webclient.c 38 KB

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