webclient.c 37 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487
  1. /*
  2. * Copyright (c) 2006-2018, 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. */
  16. #include <string.h>
  17. #include <sys/time.h>
  18. #include <webclient.h>
  19. /* support both enable and disable "SAL_USING_POSIX" */
  20. #if defined(RT_USING_SAL)
  21. #include <netdb.h>
  22. #include <sys/socket.h>
  23. #else
  24. #include <lwip/netdb.h>
  25. #include <lwip/sockets.h>
  26. #endif /* RT_USING_SAL */
  27. /* default receive or send timeout */
  28. #define WEBCLIENT_DEFAULT_TIMEO 6
  29. extern long int strtol(const char *nptr, char **endptr, int base);
  30. static int webclient_send(struct webclient_session* session, const unsigned char *buffer, size_t len, int flag)
  31. {
  32. #ifdef WEBCLIENT_USING_TLS
  33. if(session->tls_session)
  34. {
  35. return mbedtls_client_write(session->tls_session, buffer, len);
  36. }
  37. #endif
  38. return send(session->socket, buffer, len, flag);
  39. }
  40. static int webclient_recv(struct webclient_session* session, unsigned char *buffer, size_t len, int flag)
  41. {
  42. #ifdef WEBCLIENT_USING_TLS
  43. if(session->tls_session)
  44. {
  45. return mbedtls_client_read(session->tls_session, buffer, len);
  46. }
  47. #endif
  48. return recv(session->socket, buffer, len, flag);
  49. }
  50. static int webclient_read_line(struct webclient_session *session, char *buffer, int size)
  51. {
  52. int rc, count = 0;
  53. char ch = 0, last_ch = 0;
  54. RT_ASSERT(session);
  55. RT_ASSERT(buffer);
  56. /* Keep reading until we fill the buffer. */
  57. while (count < size)
  58. {
  59. rc = webclient_recv(session, (unsigned char *) &ch, 1, 0);
  60. #ifdef WEBCLIENT_USING_TLS
  61. if(session->tls_session && rc == MBEDTLS_ERR_SSL_WANT_READ)
  62. continue;
  63. #endif
  64. if (rc <= 0)
  65. return rc;
  66. if (ch == '\n' && last_ch == '\r')
  67. break;
  68. buffer[count++] = ch;
  69. last_ch = ch;
  70. }
  71. if (count > size)
  72. {
  73. LOG_E("read line failed. The line data length is out of buffer size(%d)!", count);
  74. return -WEBCLIENT_ERROR;
  75. }
  76. return count;
  77. }
  78. /**
  79. * resolve server address
  80. *
  81. * @param session http session
  82. * @param res the server address information
  83. * @param url the input server URI address
  84. * @param request the pointer to point the request url, for example, /index.html
  85. *
  86. * @return 0 on resolve server address OK, others failed
  87. *
  88. * URL example:
  89. * http://www.rt-thread.org/
  90. * http://192.168.1.1:80/index.htm
  91. * http://[fe80::1]/index.html
  92. * http://[fe80::1]:80/index.html
  93. */
  94. static int webclient_resolve_address(struct webclient_session *session, struct addrinfo **res,
  95. const char *url, char **request)
  96. {
  97. int rc = WEBCLIENT_OK;
  98. char *ptr;
  99. char port_str[6] = "80"; /* default port of 80(http) */
  100. const char *host_addr = 0;
  101. int url_len, host_addr_len = 0;
  102. RT_ASSERT(res);
  103. RT_ASSERT(request);
  104. url_len = rt_strlen(url);
  105. /* strip protocol(http or https) */
  106. if (strncmp(url, "http://", 7) == 0)
  107. {
  108. host_addr = url + 7;
  109. }
  110. else if (strncmp(url, "https://", 8) == 0)
  111. {
  112. rt_strncpy(port_str, "443", 4);
  113. host_addr = url + 8;
  114. }
  115. else
  116. {
  117. rc = -WEBCLIENT_ERROR;
  118. goto __exit;
  119. }
  120. /* ipv6 address */
  121. if (host_addr[0] == '[')
  122. {
  123. host_addr += 1;
  124. ptr = rt_strstr(host_addr, "]");
  125. if (!ptr)
  126. {
  127. rc = -WEBCLIENT_ERROR;
  128. goto __exit;
  129. }
  130. host_addr_len = ptr - host_addr;
  131. ptr = rt_strstr(host_addr + host_addr_len, "/");
  132. if (!ptr)
  133. {
  134. rc = -WEBCLIENT_ERROR;
  135. goto __exit;
  136. }
  137. else if (ptr != (host_addr + host_addr_len + 1))
  138. {
  139. int port_len = ptr - host_addr - host_addr_len - 2;
  140. rt_strncpy(port_str, host_addr + host_addr_len + 2, port_len);
  141. port_str[port_len] = '\0';
  142. }
  143. *request = (char *) ptr;
  144. }
  145. else /* ipv4 or domain. */
  146. {
  147. char *port_ptr;
  148. ptr = rt_strstr(host_addr, "/");
  149. if (!ptr)
  150. {
  151. rc = -WEBCLIENT_ERROR;
  152. goto __exit;
  153. }
  154. host_addr_len = ptr - host_addr;
  155. *request = (char *) ptr;
  156. /* resolve port */
  157. port_ptr = rt_strstr(host_addr, ":");
  158. if (port_ptr && port_ptr < ptr)
  159. {
  160. int port_len = ptr - port_ptr - 1;
  161. rt_strncpy(port_str, port_ptr + 1, port_len);
  162. port_str[port_len] = '\0';
  163. host_addr_len = port_ptr - host_addr;
  164. }
  165. }
  166. if ((host_addr_len < 1) || (host_addr_len > url_len))
  167. {
  168. rc = -WEBCLIENT_ERROR;
  169. goto __exit;
  170. }
  171. /* get host address ok. */
  172. {
  173. char *host_addr_new = web_malloc(host_addr_len + 1);
  174. if (!host_addr_new)
  175. {
  176. rc = -WEBCLIENT_ERROR;
  177. goto __exit;
  178. }
  179. memcpy(host_addr_new, host_addr, host_addr_len);
  180. host_addr_new[host_addr_len] = '\0';
  181. session->host = host_addr_new;
  182. #ifdef WEBCLIENT_USING_TLS
  183. if(session->tls_session)
  184. session->tls_session->host = web_strdup(host_addr_new);
  185. #endif
  186. }
  187. LOG_D("host address: %s , port: %s", session->host, port_str);
  188. /* resolve the host name. */
  189. {
  190. struct addrinfo hint;
  191. int ret;
  192. rt_memset(&hint, 0, sizeof(hint));
  193. #ifdef WEBCLIENT_USING_TLS
  194. if(session->tls_session)
  195. {
  196. session->tls_session->port = web_strdup(port_str);
  197. ret = getaddrinfo(session->tls_session->host, port_str, &hint, res);
  198. if (ret != 0)
  199. {
  200. LOG_E("getaddrinfo err: %d '%s'", ret, session->host);
  201. rc = -WEBCLIENT_ERROR;
  202. }
  203. goto __exit;
  204. }
  205. #endif
  206. ret = getaddrinfo(session->host, port_str, &hint, res);
  207. if (ret != 0)
  208. {
  209. LOG_E("getaddrinfo err: %d '%s'.", ret, session->host);
  210. rc = -WEBCLIENT_ERROR;
  211. goto __exit;
  212. }
  213. }
  214. __exit:
  215. if (rc != WEBCLIENT_OK)
  216. {
  217. if (session->host)
  218. {
  219. web_free(session->host);
  220. session->host = RT_NULL;
  221. }
  222. if (*res)
  223. {
  224. freeaddrinfo(*res);
  225. *res = RT_NULL;
  226. }
  227. }
  228. return rc;
  229. }
  230. #ifdef WEBCLIENT_USING_TLS
  231. /**
  232. * create and initialize https session.
  233. *
  234. * @param session webclient session
  235. * @param URI input server URI address
  236. *
  237. * @return <0: create failed, no memory or other errors
  238. * =0: success
  239. */
  240. static int webclient_open_tls(struct webclient_session *session, const char *URI)
  241. {
  242. int tls_ret = 0;
  243. const char *pers = "webclient";
  244. RT_ASSERT(session);
  245. session->tls_session = (MbedTLSSession *) web_calloc(1, sizeof(MbedTLSSession));
  246. if (session->tls_session == RT_NULL)
  247. {
  248. return -WEBCLIENT_NOMEM;
  249. }
  250. session->tls_session->buffer_len = WEBCLIENT_RESPONSE_BUFSZ;
  251. session->tls_session->buffer = web_malloc(session->tls_session->buffer_len);
  252. if(session->tls_session->buffer == RT_NULL)
  253. {
  254. LOG_E("no memory for tls_session buffer!");
  255. return -WEBCLIENT_ERROR;
  256. }
  257. if((tls_ret = mbedtls_client_init(session->tls_session, (void *)pers, strlen(pers))) < 0)
  258. {
  259. LOG_E("initialize https client failed return: -0x%x.", -tls_ret);
  260. return -WEBCLIENT_ERROR;
  261. }
  262. return WEBCLIENT_OK;
  263. }
  264. #endif
  265. /**
  266. * connect to http server.
  267. *
  268. * @param session webclient session
  269. * @param URI the input server URI address
  270. *
  271. * @return <0: connect failed or other error
  272. * =0: connect success
  273. */
  274. static int webclient_connect(struct webclient_session *session, const char *URI)
  275. {
  276. int rc = WEBCLIENT_OK;
  277. int socket_handle;
  278. struct timeval timeout;
  279. struct addrinfo *res = RT_NULL;
  280. char *req_url;
  281. RT_ASSERT(session);
  282. RT_ASSERT(URI);
  283. /* initialize the socket of session */
  284. session->socket = -1;
  285. timeout.tv_sec = WEBCLIENT_DEFAULT_TIMEO;
  286. timeout.tv_usec = 0;
  287. if (strncmp(URI, "https://", 8) == 0)
  288. {
  289. #ifdef WEBCLIENT_USING_TLS
  290. if(webclient_open_tls(session, URI) < 0)
  291. {
  292. LOG_E("connect failed, https client open URI(%s) failed!", URI);
  293. return -WEBCLIENT_ERROR;
  294. }
  295. #else
  296. LOG_E("not support https connect, please enable webclient https configure!");
  297. rc = -WEBCLIENT_ERROR;
  298. goto __exit;
  299. #endif
  300. }
  301. /* Check valid IP address and URL */
  302. rc = webclient_resolve_address(session, &res, URI, &req_url);
  303. if (rc != WEBCLIENT_OK)
  304. {
  305. LOG_E("connect failed, resolve address error(%d).", rc);
  306. goto __exit;
  307. }
  308. if (!res)
  309. {
  310. rc = -WEBCLIENT_ERROR;
  311. goto __exit;
  312. }
  313. /* copy host address */
  314. if (*req_url)
  315. {
  316. session->req_url = web_strdup(req_url);
  317. }
  318. #ifdef WEBCLIENT_USING_TLS
  319. if (session->tls_session)
  320. {
  321. int tls_ret = 0;
  322. if ((tls_ret = mbedtls_client_context(session->tls_session)) < 0)
  323. {
  324. LOG_E("connect failed, https client context return: -0x%x", -tls_ret);
  325. return -WEBCLIENT_ERROR;
  326. }
  327. if ((tls_ret = mbedtls_client_connect(session->tls_session)) < 0)
  328. {
  329. LOG_E("connect failed, https client connect return: -0x%x", -tls_ret);
  330. rc = -WEBCLIENT_CONNECT_FAILED;
  331. goto __exit;
  332. }
  333. socket_handle = session->tls_session->server_fd.fd;
  334. /* set recv timeout option */
  335. setsockopt(socket_handle, SOL_SOCKET, SO_RCVTIMEO, (void*) &timeout,
  336. sizeof(timeout));
  337. setsockopt(socket_handle, SOL_SOCKET, SO_SNDTIMEO, (void*) &timeout,
  338. sizeof(timeout));
  339. session->socket = socket_handle;
  340. rc = WEBCLIENT_OK;
  341. goto __exit;
  342. }
  343. #endif
  344. {
  345. socket_handle = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
  346. if (socket_handle < 0)
  347. {
  348. LOG_E("connect failed, create socket(%d) error.", socket_handle);
  349. rc = -WEBCLIENT_NOSOCKET;
  350. goto __exit;
  351. }
  352. /* set receive and send timeout option */
  353. setsockopt(socket_handle, SOL_SOCKET, SO_RCVTIMEO, (void *) &timeout,
  354. sizeof(timeout));
  355. setsockopt(socket_handle, SOL_SOCKET, SO_SNDTIMEO, (void *) &timeout,
  356. sizeof(timeout));
  357. if (connect(socket_handle, res->ai_addr, res->ai_addrlen) != 0)
  358. {
  359. /* connect failed */
  360. LOG_E("connect failed, connect socket(%d) error.", socket_handle);
  361. rc = -WEBCLIENT_CONNECT_FAILED;
  362. goto __exit;
  363. }
  364. session->socket = socket_handle;
  365. }
  366. __exit:
  367. if (res)
  368. {
  369. freeaddrinfo(res);
  370. }
  371. return rc;
  372. }
  373. /**
  374. * add fields data to request header data.
  375. *
  376. * @param session webclient session
  377. * @param fmt fields format
  378. *
  379. * @return >0: data length of successfully added
  380. * <0: not enough header buffer size
  381. */
  382. int webclient_header_fields_add(struct webclient_session *session, const char *fmt, ...)
  383. {
  384. rt_int32_t length;
  385. va_list args;
  386. RT_ASSERT(session);
  387. RT_ASSERT(session->header->buffer);
  388. va_start(args, fmt);
  389. length = rt_vsnprintf(session->header->buffer + session->header->length,
  390. session->header->size - session->header->length, fmt, args);
  391. if (length < 0)
  392. {
  393. LOG_E("add fields header data failed, return length(%d) error.", length);
  394. return -WEBCLIENT_ERROR;
  395. }
  396. va_end(args);
  397. session->header->length += length;
  398. /* check header size */
  399. if (session->header->length >= session->header->size)
  400. {
  401. LOG_E("not enough header buffer size(%d)!", session->header->size);
  402. return -WEBCLIENT_ERROR;
  403. }
  404. return length;
  405. }
  406. /**
  407. * get fields information from request/response header data.
  408. *
  409. * @param session webclient session
  410. * @param fields fields keyword
  411. *
  412. * @return = NULL: get fields data failed
  413. * != NULL: success get fields data
  414. */
  415. const char *webclient_header_fields_get(struct webclient_session *session, const char *fields)
  416. {
  417. char *resp_buf = RT_NULL;
  418. size_t resp_buf_len = 0;
  419. RT_ASSERT(session);
  420. RT_ASSERT(session->header->buffer);
  421. resp_buf = session->header->buffer;
  422. while (resp_buf_len < session->header->length)
  423. {
  424. if (rt_strstr(resp_buf, fields))
  425. {
  426. char *mime_ptr = RT_NULL;
  427. /* jump space */
  428. mime_ptr = rt_strstr(resp_buf, ":");
  429. if (mime_ptr != NULL)
  430. {
  431. mime_ptr += 1;
  432. while (*mime_ptr && (*mime_ptr == ' ' || *mime_ptr == '\t'))
  433. mime_ptr++;
  434. return mime_ptr;
  435. }
  436. }
  437. if (*resp_buf == '\0')
  438. break;
  439. resp_buf += rt_strlen(resp_buf) + 1;
  440. resp_buf_len += rt_strlen(resp_buf) + 1;
  441. }
  442. return RT_NULL;
  443. }
  444. /**
  445. * get http response status code.
  446. *
  447. * @param session webclient session
  448. *
  449. * @return response status code
  450. */
  451. int webclient_resp_status_get(struct webclient_session *session)
  452. {
  453. RT_ASSERT(session);
  454. return session->resp_status;
  455. }
  456. /**
  457. * get http response data content length.
  458. *
  459. * @param session webclient session
  460. *
  461. * @return response content length
  462. */
  463. int webclient_content_length_get(struct webclient_session *session)
  464. {
  465. RT_ASSERT(session);
  466. return session->content_length;
  467. }
  468. static int webclient_send_header(struct webclient_session *session, int method)
  469. {
  470. int rc = WEBCLIENT_OK;
  471. char *header = RT_NULL;
  472. RT_ASSERT(session);
  473. header = session->header->buffer;
  474. if (session->header->length == 0)
  475. {
  476. /* use default header data */
  477. if (webclient_header_fields_add(session, "GET %s HTTP/1.1\r\n", session->req_url) < 0)
  478. return -WEBCLIENT_NOMEM;
  479. if (webclient_header_fields_add(session, "Host: %s\r\n", session->host) < 0)
  480. return -WEBCLIENT_NOMEM;
  481. if (webclient_header_fields_add(session, "User-Agent: RT-Thread HTTP Agent\r\n\r\n") < 0)
  482. return -WEBCLIENT_NOMEM;
  483. webclient_write(session, (unsigned char *) session->header->buffer, session->header->length);
  484. }
  485. else
  486. {
  487. if (method != WEBCLIENT_USER_METHOD)
  488. {
  489. /* check and add fields header data */
  490. if (memcmp(header, "HTTP/1.", rt_strlen("HTTP/1.")))
  491. {
  492. char *header_buffer = RT_NULL;
  493. int length = 0;
  494. header_buffer = web_strdup(session->header->buffer);
  495. if (header_buffer == RT_NULL)
  496. {
  497. LOG_E("no memory for header buffer!");
  498. rc = -WEBCLIENT_NOMEM;
  499. goto __exit;
  500. }
  501. /* splice http request header data */
  502. if (method == WEBCLIENT_GET)
  503. length = rt_snprintf(session->header->buffer, session->header->size, "GET %s HTTP/1.1\r\n%s",
  504. session->req_url ? session->req_url : "/", header_buffer);
  505. else if (method == WEBCLIENT_POST)
  506. length = rt_snprintf(session->header->buffer, session->header->size, "POST %s HTTP/1.1\r\n%s",
  507. session->req_url ? session->req_url : "/", header_buffer);
  508. session->header->length = length;
  509. web_free(header_buffer);
  510. }
  511. if (memcmp(header, "Host:", rt_strlen("Host:")))
  512. {
  513. if (webclient_header_fields_add(session, "Host: %s\r\n", session->host) < 0)
  514. return -WEBCLIENT_NOMEM;
  515. }
  516. if (memcmp(header, "User-Agent:", rt_strlen("User-Agent:")))
  517. {
  518. if (webclient_header_fields_add(session, "User-Agent: RT-Thread HTTP Agent\r\n") < 0)
  519. return -WEBCLIENT_NOMEM;
  520. }
  521. if (memcmp(header, "Accept:", rt_strlen("Accept:")))
  522. {
  523. if (webclient_header_fields_add(session, "Accept: */*\r\n") < 0)
  524. return -WEBCLIENT_NOMEM;
  525. }
  526. /* header data end */
  527. rt_snprintf(session->header->buffer + session->header->length, session->header->size, "\r\n");
  528. session->header->length += 2;
  529. /* check header size */
  530. if (session->header->length > session->header->size)
  531. {
  532. LOG_E("send header failed, not enough header buffer size(%d)!", session->header->size);
  533. rc = -WEBCLIENT_NOBUFFER;
  534. goto __exit;
  535. }
  536. webclient_write(session, (unsigned char *) session->header->buffer, session->header->length);
  537. }
  538. else
  539. {
  540. webclient_write(session, (unsigned char *) session->header->buffer, session->header->length);
  541. }
  542. }
  543. __exit:
  544. return rc;
  545. }
  546. /**
  547. * resolve server response data.
  548. *
  549. * @param session webclient session
  550. *
  551. * @return <0: resolve response data failed
  552. * =0: success
  553. */
  554. int webclient_handle_response(struct webclient_session *session)
  555. {
  556. int rc = WEBCLIENT_OK;
  557. char *mime_buffer = RT_NULL;
  558. char *mime_ptr = RT_NULL;
  559. const char *transfer_encoding;
  560. int i;
  561. RT_ASSERT(session);
  562. /* clean header buffer and size */
  563. rt_memset(session->header->buffer, 0x00, session->header->size);
  564. session->header->length = 0;
  565. /* We now need to read the header information */
  566. while (1)
  567. {
  568. mime_buffer = session->header->buffer + session->header->length;
  569. /* read a line from the header information. */
  570. rc = webclient_read_line(session, mime_buffer, session->header->size - session->header->length);
  571. if (rc < 0)
  572. break;
  573. /* End of headers is a blank line. exit. */
  574. if (rc == 0)
  575. break;
  576. if ((rc == 1) && (mime_buffer[0] == '\r'))
  577. {
  578. mime_buffer[0] = '\0';
  579. break;
  580. }
  581. /* set terminal charater */
  582. mime_buffer[rc - 1] = '\0';
  583. session->header->length += rc;
  584. if (session->header->length >= session->header->size)
  585. {
  586. LOG_E("not enough header buffer size(%d)!", session->header->size);
  587. return -WEBCLIENT_NOMEM;
  588. }
  589. }
  590. /* get HTTP status code */
  591. mime_ptr = web_strdup(session->header->buffer);
  592. if (mime_ptr == RT_NULL)
  593. {
  594. LOG_E("no memory for get http status code buffer!");
  595. return -WEBCLIENT_NOMEM;
  596. }
  597. if (rt_strstr(mime_ptr, "HTTP/1."))
  598. {
  599. char *ptr = mime_ptr;
  600. ptr += rt_strlen("HTTP/1.x");
  601. while (*ptr && (*ptr == ' ' || *ptr == '\t'))
  602. ptr++;
  603. /* Terminate string after status code */
  604. for (i = 0; ((ptr[i] != ' ') && (ptr[i] != '\t')); i++);
  605. ptr[i] = '\0';
  606. session->resp_status = (int) strtol(ptr, RT_NULL, 10);
  607. }
  608. /* get content length */
  609. if (webclient_header_fields_get(session, "Content-Length") != RT_NULL)
  610. {
  611. session->content_length = atoi(webclient_header_fields_get(session, "Content-Length"));
  612. }
  613. session->content_remainder = session->content_length ? (size_t) session->content_length : 0xFFFFFFFF;
  614. transfer_encoding = webclient_header_fields_get(session, "Transfer-Encoding");
  615. if (transfer_encoding && rt_strcmp(transfer_encoding, "chunked") == 0)
  616. {
  617. char line[16];
  618. /* chunk mode, we should get the first chunk size */
  619. webclient_read_line(session, line, session->header->size);
  620. session->chunk_sz = strtol(line, RT_NULL, 16);
  621. session->chunk_offset = 0;
  622. }
  623. if (mime_ptr)
  624. {
  625. web_free(mime_ptr);
  626. }
  627. if (rc < 0)
  628. {
  629. return rc;
  630. }
  631. return session->resp_status;
  632. }
  633. /**
  634. * create webclient session, set maximum header and response size
  635. *
  636. * @param header_sz maximum send header size
  637. * @param resp_sz maximum response data size
  638. *
  639. * @return webclient session structure
  640. */
  641. struct webclient_session *webclient_session_create(size_t header_sz)
  642. {
  643. struct webclient_session *session;
  644. /* create session */
  645. session = (struct webclient_session *) web_calloc(1, sizeof(struct webclient_session));
  646. if (session == RT_NULL)
  647. {
  648. LOG_E("webclient create failed, no memory for webclient session!");
  649. return RT_NULL;
  650. }
  651. session->content_length = -1;
  652. session->header = (struct webclient_header *) web_calloc(1, sizeof(struct webclient_header));
  653. if (session->header == RT_NULL)
  654. {
  655. LOG_E("webclient create failed, no memory for session header!");
  656. web_free(session);
  657. session = RT_NULL;
  658. return RT_NULL;
  659. }
  660. session->header->size = header_sz;
  661. session->header->buffer = (char *) web_malloc(header_sz);
  662. if (session->header->buffer == RT_NULL)
  663. {
  664. LOG_E("webclient create failed, no memory for session header buffer!");
  665. web_free(session->header);
  666. web_free(session);
  667. session = RT_NULL;
  668. return RT_NULL;
  669. }
  670. return session;
  671. }
  672. /**
  673. * send GET request to http server and get response header.
  674. *
  675. * @param session webclient session
  676. * @param URI input server URI address
  677. * @param header GET request header
  678. * = NULL: use default header data
  679. * != NULL: use custom header data
  680. *
  681. * @return <0: send GET request failed
  682. * >0: response http status code
  683. */
  684. int webclient_get(struct webclient_session *session, const char *URI)
  685. {
  686. int rc = WEBCLIENT_OK;
  687. int resp_status = 0;
  688. RT_ASSERT(session);
  689. RT_ASSERT(URI);
  690. rc = webclient_connect(session, URI);
  691. if (rc != WEBCLIENT_OK)
  692. {
  693. /* connect to webclient server failed. */
  694. return rc;
  695. }
  696. rc = webclient_send_header(session, WEBCLIENT_GET);
  697. if (rc != WEBCLIENT_OK)
  698. {
  699. /* send header to webclient server failed. */
  700. return rc;
  701. }
  702. /* handle the response header of webclient server */
  703. resp_status = webclient_handle_response(session);
  704. if (resp_status > 0)
  705. {
  706. const char *location = webclient_header_fields_get(session, "Location");
  707. /* relocation */
  708. if ((resp_status == 302 || resp_status == 301) && location)
  709. {
  710. webclient_close(session);
  711. return webclient_get(session, location);
  712. }
  713. else if (resp_status != 200)
  714. {
  715. LOG_E("get failed, handle response(%d) error!", resp_status);
  716. return resp_status;
  717. }
  718. }
  719. return resp_status;
  720. }
  721. /**
  722. * http breakpoint resume.
  723. *
  724. * @param session webclient session
  725. * @param URI input server URI address
  726. * @param position last downloaded position
  727. *
  728. * @return <0: send GET request failed
  729. * >0: response http status code
  730. */
  731. int webclient_get_position(struct webclient_session *session, const char *URI, int position)
  732. {
  733. int rc = WEBCLIENT_OK;
  734. int resp_status = 0;
  735. RT_ASSERT(session);
  736. RT_ASSERT(URI);
  737. rc = webclient_connect(session, URI);
  738. if (rc != WEBCLIENT_OK)
  739. {
  740. return rc;
  741. }
  742. /* splice header*/
  743. if (webclient_header_fields_add(session, "Range: bytes=%d-\r\n", position) <= 0)
  744. {
  745. rc = -WEBCLIENT_ERROR;
  746. return rc;
  747. }
  748. rc = webclient_send_header(session, WEBCLIENT_GET);
  749. if (rc != WEBCLIENT_OK)
  750. {
  751. return rc;
  752. }
  753. /* handle the response header of webclient server */
  754. resp_status = webclient_handle_response(session);
  755. if (resp_status > 0)
  756. {
  757. const char *location = webclient_header_fields_get(session, "Location");
  758. /* relocation */
  759. if ((resp_status == 302 || resp_status == 301) && location)
  760. {
  761. webclient_close(session);
  762. return webclient_get_position(session, location, position);
  763. }
  764. else if (resp_status != 206)
  765. {
  766. LOG_E("get failed, handle response(%d) error!", resp_status);
  767. return resp_status;
  768. }
  769. }
  770. return resp_status;
  771. }
  772. /**
  773. * send POST request to server and get response header data.
  774. *
  775. * @param session webclient session
  776. * @param URI input server URI address
  777. * @param header POST request header, can't be empty
  778. * @param post_data data sent to the server
  779. * = NULL: just connect server and send header
  780. * != NULL: send header and body data, resolve response data
  781. *
  782. * @return <0: send POST request failed
  783. * =0: send POST header success
  784. * >0: response http status code
  785. */
  786. int webclient_post(struct webclient_session *session, const char *URI, const char *post_data)
  787. {
  788. int rc = WEBCLIENT_OK;
  789. int resp_status = 0;
  790. RT_ASSERT(session);
  791. RT_ASSERT(URI);
  792. rc = webclient_connect(session, URI);
  793. if (rc != WEBCLIENT_OK)
  794. {
  795. /* connect to webclient server failed. */
  796. return rc;
  797. }
  798. rc = webclient_send_header(session, WEBCLIENT_POST);
  799. if (rc != WEBCLIENT_OK)
  800. {
  801. /* send header to webclient server failed. */
  802. return rc;
  803. }
  804. if (post_data)
  805. {
  806. webclient_write(session, (unsigned char *) post_data, rt_strlen(post_data));
  807. /* resolve response data, get http status code */
  808. resp_status = webclient_handle_response(session);
  809. if (resp_status != 200)
  810. {
  811. LOG_E("post failed, handle response(%d) error.", resp_status);
  812. return resp_status;
  813. }
  814. }
  815. return resp_status;
  816. }
  817. /**
  818. * set receive and send data timeout.
  819. *
  820. * @param session http session
  821. * @param millisecond timeout millisecond
  822. *
  823. * @return 0: set timeout success
  824. */
  825. int webclient_set_timeout(struct webclient_session *session, int millisecond)
  826. {
  827. struct timeval timeout;
  828. int second = rt_tick_from_millisecond(millisecond) / 1000;
  829. RT_ASSERT(session);
  830. timeout.tv_sec = second;
  831. timeout.tv_usec = 0;
  832. /* set recv timeout option */
  833. setsockopt(session->socket, SOL_SOCKET, SO_RCVTIMEO,
  834. (void *) &timeout, sizeof(timeout));
  835. setsockopt(session->socket, SOL_SOCKET, SO_SNDTIMEO,
  836. (void *) &timeout, sizeof(timeout));
  837. return 0;
  838. }
  839. static int webclient_next_chunk(struct webclient_session *session)
  840. {
  841. char line[64];
  842. int length;
  843. RT_ASSERT(session);
  844. length = webclient_read_line(session, line, sizeof(line));
  845. if (length > 0)
  846. {
  847. if (rt_strcmp(line, "\r") == 0)
  848. {
  849. length = webclient_read_line(session, line, sizeof(line));
  850. if (length <= 0)
  851. {
  852. closesocket(session->socket);
  853. session->socket = -1;
  854. return length;
  855. }
  856. }
  857. }
  858. else
  859. {
  860. closesocket(session->socket);
  861. session->socket = -1;
  862. return length;
  863. }
  864. session->chunk_sz = strtol(line, RT_NULL, 16);
  865. session->chunk_offset = 0;
  866. if (session->chunk_sz == 0)
  867. {
  868. /* end of chunks */
  869. closesocket(session->socket);
  870. session->socket = -1;
  871. }
  872. return session->chunk_sz;
  873. }
  874. /**
  875. * read data from http server.
  876. *
  877. * @param session http session
  878. * @param buffer read buffer
  879. * @param length the maximum of read buffer size
  880. *
  881. * @return <0: read data error
  882. * =0: http server disconnect
  883. * >0: successfully read data length
  884. */
  885. int webclient_read(struct webclient_session *session, unsigned char *buffer, size_t length)
  886. {
  887. int bytes_read = 0;
  888. int total_read = 0;
  889. int left;
  890. RT_ASSERT(session);
  891. if (session->socket < 0)
  892. {
  893. return -WEBCLIENT_DISCONNECT;
  894. }
  895. if (length == 0)
  896. {
  897. return 0;
  898. }
  899. /* which is transfered as chunk mode */
  900. if (session->chunk_sz)
  901. {
  902. if ((int) length > (session->chunk_sz - session->chunk_offset))
  903. {
  904. length = session->chunk_sz - session->chunk_offset;
  905. }
  906. bytes_read = webclient_recv(session, buffer, length, 0);
  907. if (bytes_read <= 0)
  908. {
  909. if (errno == EWOULDBLOCK || errno == EAGAIN)
  910. {
  911. /* recv timeout */
  912. return -WEBCLIENT_TIMEOUT;
  913. }
  914. else
  915. {
  916. closesocket(session->socket);
  917. session->socket = -1;
  918. return 0;
  919. }
  920. }
  921. session->chunk_offset += bytes_read;
  922. if (session->chunk_offset >= session->chunk_sz)
  923. {
  924. webclient_next_chunk(session);
  925. }
  926. return bytes_read;
  927. }
  928. if (session->content_length > 0)
  929. {
  930. if (length > session->content_remainder)
  931. {
  932. length = session->content_remainder;
  933. }
  934. if (length == 0)
  935. {
  936. return 0;
  937. }
  938. }
  939. /*
  940. * Read until: there is an error, we've read "size" bytes or the remote
  941. * side has closed the connection.
  942. */
  943. left = length;
  944. do
  945. {
  946. bytes_read = webclient_recv(session, buffer + total_read, left, 0);
  947. if (bytes_read <= 0)
  948. {
  949. #ifdef WEBCLIENT_USING_TLS
  950. if(session->tls_session && bytes_read == MBEDTLS_ERR_SSL_WANT_READ)
  951. continue;
  952. #endif
  953. LOG_E("receive data error(%d).", bytes_read);
  954. if (total_read)
  955. {
  956. break;
  957. }
  958. else
  959. {
  960. if (errno == EWOULDBLOCK || errno == EAGAIN)
  961. {
  962. /* recv timeout */
  963. LOG_E("receive data timeout.");
  964. return -WEBCLIENT_TIMEOUT;
  965. }
  966. else
  967. {
  968. closesocket(session->socket);
  969. session->socket = -1;
  970. return 0;
  971. }
  972. }
  973. }
  974. left -= bytes_read;
  975. total_read += bytes_read;
  976. }
  977. while (left);
  978. if (session->content_length > 0)
  979. {
  980. session->content_remainder -= total_read;
  981. }
  982. return total_read;
  983. }
  984. /**
  985. * write data to http server.
  986. *
  987. * @param session http session
  988. * @param buffer write buffer
  989. * @param length write buffer size
  990. *
  991. * @return <0: write data error
  992. * =0: http server disconnect
  993. * >0: successfully write data length
  994. */
  995. int webclient_write(struct webclient_session *session, const unsigned char *buffer, size_t length)
  996. {
  997. int bytes_write = 0;
  998. int total_write = 0;
  999. int left = length;
  1000. RT_ASSERT(session);
  1001. if (session->socket < 0)
  1002. {
  1003. return -WEBCLIENT_DISCONNECT;
  1004. }
  1005. if (length == 0)
  1006. {
  1007. return 0;
  1008. }
  1009. /* send all of data on the buffer. */
  1010. do
  1011. {
  1012. bytes_write = webclient_send(session, buffer + total_write, left, 0);
  1013. if (bytes_write <= 0)
  1014. {
  1015. #ifdef WEBCLIENT_USING_TLS
  1016. if(session->tls_session && bytes_write == MBEDTLS_ERR_SSL_WANT_WRITE)
  1017. continue;
  1018. #endif
  1019. if (errno == EWOULDBLOCK || errno == EAGAIN)
  1020. {
  1021. /* send timeout */
  1022. if (total_write)
  1023. {
  1024. return total_write;
  1025. }
  1026. continue;
  1027. /* TODO: whether return the TIMEOUT
  1028. * return -WEBCLIENT_TIMEOUT; */
  1029. }
  1030. else
  1031. {
  1032. closesocket(session->socket);
  1033. session->socket = -1;
  1034. if (total_write == 0)
  1035. {
  1036. return -WEBCLIENT_DISCONNECT;
  1037. }
  1038. break;
  1039. }
  1040. }
  1041. left -= bytes_write;
  1042. total_write += bytes_write;
  1043. }
  1044. while (left);
  1045. return total_write;
  1046. }
  1047. /**
  1048. * close a webclient client session.
  1049. *
  1050. * @param session http client session
  1051. *
  1052. * @return 0: close success
  1053. */
  1054. int webclient_close(struct webclient_session *session)
  1055. {
  1056. RT_ASSERT(session);
  1057. #ifdef WEBCLIENT_USING_TLS
  1058. if (session->tls_session)
  1059. {
  1060. mbedtls_client_close(session->tls_session);
  1061. }
  1062. else
  1063. {
  1064. if (session->socket >= 0)
  1065. {
  1066. closesocket(session->socket);
  1067. session->socket = -1;
  1068. }
  1069. }
  1070. #else
  1071. if (session->socket >= 0)
  1072. {
  1073. closesocket(session->socket);
  1074. session->socket = -1;
  1075. }
  1076. #endif
  1077. if (session->host)
  1078. {
  1079. web_free(session->host);
  1080. }
  1081. if (session->req_url)
  1082. {
  1083. web_free(session->req_url);
  1084. }
  1085. if (session->header && session->header->buffer)
  1086. {
  1087. web_free(session->header->buffer);
  1088. }
  1089. if (session->header)
  1090. {
  1091. web_free(session->header);
  1092. }
  1093. if (session)
  1094. {
  1095. web_free(session);
  1096. session = RT_NULL;
  1097. }
  1098. return 0;
  1099. }
  1100. /**
  1101. * get wenclient request response data.
  1102. *
  1103. * @param session wenclient session
  1104. * @param response response buffer address
  1105. *
  1106. * @return response data size
  1107. */
  1108. int webclient_response(struct webclient_session *session, unsigned char **response)
  1109. {
  1110. unsigned char *buf_ptr;
  1111. unsigned char *response_buf = 0;
  1112. int length, total_read = 0;
  1113. RT_ASSERT(session);
  1114. RT_ASSERT(response);
  1115. /* initialize response */
  1116. *response = RT_NULL;
  1117. /* not content length field kind */
  1118. if (session->content_length < 0)
  1119. {
  1120. size_t result_sz;
  1121. total_read = 0;
  1122. while (1)
  1123. {
  1124. unsigned char *new_resp = RT_NULL;
  1125. result_sz = total_read + WEBCLIENT_RESPONSE_BUFSZ;
  1126. new_resp = web_realloc(response_buf, result_sz + 1);
  1127. if (new_resp == RT_NULL)
  1128. {
  1129. LOG_E("no memory for realloc new response buffer!");
  1130. break;
  1131. }
  1132. response_buf = new_resp;
  1133. buf_ptr = (unsigned char *) response_buf + total_read;
  1134. /* read result */
  1135. length = webclient_read(session, buf_ptr, result_sz - total_read);
  1136. if (length <= 0)
  1137. break;
  1138. total_read += length;
  1139. }
  1140. }
  1141. else
  1142. {
  1143. int result_sz;
  1144. result_sz = session->content_length;
  1145. response_buf = web_malloc(result_sz + 1);
  1146. if (!response_buf)
  1147. {
  1148. return -WEBCLIENT_NOMEM;
  1149. }
  1150. buf_ptr = (unsigned char *) response_buf;
  1151. for (total_read = 0; total_read < result_sz;)
  1152. {
  1153. length = webclient_read(session, buf_ptr, result_sz - total_read);
  1154. if (length <= 0)
  1155. break;
  1156. buf_ptr += length;
  1157. total_read += length;
  1158. }
  1159. }
  1160. if ((total_read == 0) && (response_buf != 0))
  1161. {
  1162. web_free(response_buf);
  1163. response_buf = RT_NULL;
  1164. }
  1165. if (response_buf)
  1166. {
  1167. *response = response_buf;
  1168. *(response_buf + total_read) = '\0';
  1169. }
  1170. return total_read;
  1171. }
  1172. /**
  1173. * send request(GET/POST) to server and get response data.
  1174. *
  1175. * @param URI input server address
  1176. * @param header send header data
  1177. * = NULL: use default header data, must be GET request
  1178. * != NULL: user custom header data, GET or POST request
  1179. * @param post_data data sent to the server
  1180. * = NULL: it is GET request
  1181. * != NULL: it is POST request
  1182. * @param response response buffer address
  1183. *
  1184. * @return <0: request failed
  1185. * >=0: response buffer size
  1186. */
  1187. int webclient_request(const char *URI, const char *header, const char *post_data, unsigned char **response)
  1188. {
  1189. struct webclient_session *session;
  1190. int rc = WEBCLIENT_OK;
  1191. int totle_length;
  1192. RT_ASSERT(URI);
  1193. if (post_data && header == RT_NULL)
  1194. {
  1195. LOG_E("request post failed, post input header cannot be empty.");
  1196. return -WEBCLIENT_ERROR;
  1197. }
  1198. if (post_data == RT_NULL && response == RT_NULL)
  1199. {
  1200. LOG_E("request get failed, get response data cannot be empty.");
  1201. return -WEBCLIENT_ERROR;
  1202. }
  1203. if (post_data == RT_NULL)
  1204. {
  1205. session = webclient_session_create(WEBCLIENT_HEADER_BUFSZ);
  1206. if (session == RT_NULL)
  1207. {
  1208. rc = -WEBCLIENT_NOMEM;
  1209. goto __exit;
  1210. }
  1211. if (header != RT_NULL)
  1212. {
  1213. rt_strncpy(session->header->buffer, header, rt_strlen(header));
  1214. }
  1215. if (webclient_get(session, URI) != 200)
  1216. {
  1217. rc = -WEBCLIENT_ERROR;
  1218. goto __exit;
  1219. }
  1220. totle_length = webclient_response(session, response);
  1221. if (totle_length <= 0)
  1222. {
  1223. rc = -WEBCLIENT_ERROR;
  1224. goto __exit;
  1225. }
  1226. }
  1227. else
  1228. {
  1229. session = webclient_session_create(WEBCLIENT_HEADER_BUFSZ);
  1230. if (session == RT_NULL)
  1231. {
  1232. rc = -WEBCLIENT_NOMEM;
  1233. goto __exit;
  1234. }
  1235. if (header != RT_NULL)
  1236. {
  1237. rt_strncpy(session->header->buffer, header, rt_strlen(header));
  1238. }
  1239. if (webclient_post(session, URI, post_data) != 200)
  1240. {
  1241. rc = -WEBCLIENT_ERROR;
  1242. goto __exit;
  1243. }
  1244. }
  1245. if (header != RT_NULL)
  1246. {
  1247. rt_strncpy(session->header->buffer, header, rt_strlen(header));
  1248. }
  1249. __exit:
  1250. if (session)
  1251. {
  1252. webclient_close(session);
  1253. session = RT_NULL;
  1254. }
  1255. if (rc < 0)
  1256. {
  1257. return rc;
  1258. }
  1259. return totle_length;
  1260. }