webclient.c 36 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439
  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. int webclient_send_header(struct webclient_session *session, int method,
  272. const char *header, size_t header_sz)
  273. {
  274. int rc = WEBCLIENT_OK;
  275. unsigned char *header_buffer = RT_NULL, *header_ptr;
  276. RT_ASSERT(session);
  277. if (header == RT_NULL)
  278. {
  279. header_buffer = web_malloc(session->header_sz);
  280. if (header_buffer == RT_NULL)
  281. {
  282. LOG_E("send header failed, no memory for header buffer!");
  283. rc = -WEBCLIENT_NOMEM;
  284. goto __exit;
  285. }
  286. header_ptr = header_buffer;
  287. header_ptr += rt_snprintf((char *) header_ptr,
  288. session->header_sz - (header_ptr - header_buffer),
  289. "GET %s HTTP/1.1\r\n",
  290. session->request ? session->request : "/");
  291. header_ptr += rt_snprintf((char *) header_ptr,
  292. session->header_sz - (header_ptr - header_buffer),
  293. "Host: %s\r\n", session->host);
  294. header_ptr += rt_snprintf((char *) header_ptr,
  295. session->header_sz - (header_ptr - header_buffer),
  296. "User-Agent: RT-Thread HTTP Agent\r\n\r\n");
  297. webclient_write(session, header_buffer, header_ptr - header_buffer);
  298. }
  299. else
  300. {
  301. if (method != WEBCLIENT_USER_METHOD)
  302. {
  303. header_buffer = web_malloc(session->header_sz);
  304. if (header_buffer == RT_NULL)
  305. {
  306. LOG_E("send header failed, no memory for header buffer!");
  307. rc = -WEBCLIENT_NOMEM;
  308. goto __exit;
  309. }
  310. header_ptr = header_buffer;
  311. if (strstr(header, "HTTP/1.") == RT_NULL)
  312. {
  313. if (method == WEBCLIENT_GET)
  314. header_ptr += rt_snprintf((char *) header_ptr,
  315. session->header_sz
  316. - (header_ptr - header_buffer),
  317. "GET %s HTTP/1.1\r\n",
  318. session->request ? session->request : "/");
  319. else if (method == WEBCLIENT_POST)
  320. header_ptr += rt_snprintf((char *) header_ptr,
  321. session->header_sz
  322. - (header_ptr - header_buffer),
  323. "POST %s HTTP/1.1\r\n",
  324. session->request ? session->request : "/");
  325. }
  326. if (strstr(header, "Host:") == RT_NULL)
  327. {
  328. header_ptr += rt_snprintf((char *) header_ptr,
  329. session->header_sz - (header_ptr - header_buffer),
  330. "Host: %s\r\n", session->host);
  331. }
  332. if (strstr(header, "User-Agent:") == RT_NULL)
  333. {
  334. header_ptr += rt_snprintf((char *) header_ptr,
  335. session->header_sz - (header_ptr - header_buffer),
  336. "User-Agent: RT-Thread HTTP Agent\r\n");
  337. }
  338. if (strstr(header, "Accept: ") == RT_NULL)
  339. {
  340. header_ptr += rt_snprintf((char *) header_ptr,
  341. session->header_sz - (header_ptr - header_buffer),
  342. "Accept: */*\r\n");
  343. }
  344. if ((session->header_sz - (header_ptr - header_buffer))
  345. < (int) header_sz + 3)
  346. {
  347. LOG_E("send header failed, not enough header buffer size(%d)!", session->header_sz);
  348. rc = -WEBCLIENT_NOBUFFER;
  349. goto __exit;
  350. }
  351. /* append user's header */
  352. memcpy(header_ptr, header, header_sz);
  353. header_ptr += header_sz;
  354. header_ptr += rt_snprintf((char *) header_ptr,
  355. session->header_sz - (header_ptr - header_buffer),
  356. "\r\n");
  357. webclient_write(session, header_buffer, header_ptr - header_buffer);
  358. }
  359. else
  360. {
  361. webclient_write(session, (unsigned char *) header, header_sz);
  362. }
  363. }
  364. __exit:
  365. if(header_buffer)
  366. {
  367. web_free(header_buffer);
  368. }
  369. return rc;
  370. }
  371. /**
  372. * resolve server response data.
  373. *
  374. * @param session http session
  375. *
  376. * @return <0: resolve response data failed
  377. * =0: success
  378. */
  379. int webclient_handle_response(struct webclient_session *session)
  380. {
  381. int rc = WEBCLIENT_OK;
  382. char *mime_buffer, *mime_ptr;
  383. RT_ASSERT(session);
  384. /* set content length of session */
  385. session->content_length = -1;
  386. mime_buffer = (char *) web_malloc(session->resp_sz + 1);
  387. if (!mime_buffer)
  388. {
  389. LOG_E("handle response failed, no memory for mime buffer!");
  390. return -WEBCLIENT_NOMEM;
  391. }
  392. /* We now need to read the header information */
  393. while (1)
  394. {
  395. int i;
  396. /* read a line from the header information. */
  397. rc = webclient_read_line(session, mime_buffer, session->resp_sz);
  398. if (rc < 0)
  399. break;
  400. /* set terminal charater */
  401. mime_buffer[rc] = '\0';
  402. /* End of headers is a blank line. exit. */
  403. if (rc == 0)
  404. break;
  405. if ((rc == 2) && (mime_buffer[0] == '\r'))
  406. break;
  407. mime_ptr = webclient_header_skip_prefix(mime_buffer, "HTTP/1.");
  408. if (mime_ptr != RT_NULL)
  409. {
  410. mime_ptr += 1;
  411. while (*mime_ptr && (*mime_ptr == ' ' || *mime_ptr == '\t'))
  412. mime_ptr++;
  413. /* Terminate string after status code */
  414. for (i = 0; ((mime_ptr[i] != ' ') && (mime_ptr[i] != '\t')); i++);
  415. mime_ptr[i] = '\0';
  416. session->response = (int) strtol(mime_ptr, RT_NULL, 10);
  417. }
  418. mime_ptr = webclient_header_skip_prefix(mime_buffer, "Last-Modified:");
  419. if (mime_ptr != RT_NULL)
  420. {
  421. session->last_modified = web_strdup(mime_ptr);
  422. }
  423. mime_ptr = webclient_header_skip_prefix(mime_buffer, "Transfer-Encoding: ");
  424. if (mime_ptr != RT_NULL)
  425. {
  426. session->transfer_encoding = web_strdup(mime_ptr);
  427. }
  428. mime_ptr = webclient_header_skip_prefix(mime_buffer, "Content-Type:");
  429. if (mime_ptr != RT_NULL)
  430. {
  431. session->content_type = web_strdup(mime_ptr);
  432. }
  433. mime_ptr = webclient_header_skip_prefix(mime_buffer, "Content-Length:");
  434. if (mime_ptr != RT_NULL)
  435. {
  436. session->content_length = (int) strtol(mime_ptr, RT_NULL, 10);
  437. }
  438. mime_ptr = webclient_header_skip_prefix(mime_buffer, "Location: ");
  439. if (mime_ptr != RT_NULL)
  440. {
  441. session->location = web_strdup(mime_ptr);
  442. }
  443. mime_ptr = webclient_header_skip_prefix(mime_buffer, "Content-Range:");
  444. if (mime_ptr != RT_NULL)
  445. {
  446. char *ptr = RT_NULL;
  447. int totle_length;
  448. mime_ptr = webclient_header_skip_prefix(mime_ptr, "bytes");
  449. while (*mime_ptr == ' ')
  450. mime_ptr++;
  451. session->position = atoi(mime_ptr);
  452. ptr = strstr(mime_ptr, "/");
  453. if (ptr)
  454. {
  455. ptr ++;
  456. /* The total length of the get data */
  457. totle_length = atoi(ptr);
  458. //TODO: process total length
  459. }
  460. }
  461. }
  462. session->content_length_remainder =
  463. (session->content_length) ? (size_t) session->content_length : 0xFFFFFFFF;
  464. if (session->transfer_encoding && strcmp(session->transfer_encoding, "chunked") == 0)
  465. {
  466. /* chunk mode, we should get the first chunk size */
  467. webclient_read_line(session, mime_buffer, session->resp_sz);
  468. session->chunk_sz = strtol(mime_buffer, RT_NULL, 16);
  469. session->chunk_offset = 0;
  470. }
  471. /* release buffer */
  472. if(mime_buffer)
  473. {
  474. web_free(mime_buffer);
  475. }
  476. if (rc < 0)
  477. {
  478. return rc;
  479. }
  480. return session->response;
  481. }
  482. #ifdef WEBCLIENT_USING_TLS
  483. /**
  484. * create and initialize https session.
  485. *
  486. * @param session http session
  487. * @param URI the input server URI address
  488. *
  489. * @return <0: create failed, no memory or other errors
  490. * =0: success
  491. */
  492. static int webclient_open_tls(struct webclient_session *session, const char *URI)
  493. {
  494. int tls_ret = 0;
  495. const char *pers = "webclient";
  496. RT_ASSERT(session);
  497. session->tls_session = (MbedTLSSession *) web_calloc(1, sizeof(MbedTLSSession));
  498. if (session->tls_session == RT_NULL)
  499. {
  500. return -WEBCLIENT_NOMEM;
  501. }
  502. session->tls_session->buffer_len = session->resp_sz;
  503. session->tls_session->buffer = web_malloc(session->tls_session->buffer_len);
  504. if(session->tls_session->buffer == RT_NULL)
  505. {
  506. LOG_E("no memory for tls_session buffer!");
  507. return -WEBCLIENT_ERROR;
  508. }
  509. if((tls_ret = mbedtls_client_init(session->tls_session, (void *)pers, strlen(pers))) < 0)
  510. {
  511. LOG_E("initialize https client failed return: -0x%x.", -tls_ret);
  512. return -WEBCLIENT_ERROR;
  513. }
  514. return WEBCLIENT_OK;
  515. }
  516. #endif
  517. /**
  518. * connect to http server.
  519. *
  520. * @param session http session
  521. * @param URI the input server URI address
  522. *
  523. * @return <0: connect failed or other error
  524. * =0: connect success
  525. */
  526. int webclient_connect(struct webclient_session *session, const char *URI)
  527. {
  528. int rc = WEBCLIENT_OK;
  529. int socket_handle;
  530. struct timeval timeout;
  531. struct addrinfo *res = RT_NULL;
  532. char *request;
  533. RT_ASSERT(session);
  534. RT_ASSERT(URI);
  535. /* initialize the socket of session */
  536. session->socket = -1;
  537. timeout.tv_sec = WEBCLIENT_DEFAULT_TIMEO;
  538. timeout.tv_usec = 0;
  539. if(strncmp(URI, "https://", 8) == 0)
  540. {
  541. #ifdef WEBCLIENT_USING_TLS
  542. if(webclient_open_tls(session, URI) < 0)
  543. {
  544. LOG_E("connect failed, https client open URI(%s) failed!", URI);
  545. return -WEBCLIENT_ERROR;
  546. }
  547. #else
  548. LOG_E("not support https connect, please enable webclient https configure!");
  549. rc = -WEBCLIENT_ERROR;
  550. goto __exit;
  551. #endif
  552. }
  553. /* Check valid IP address and URL */
  554. rc = webclient_resolve_address(session, &res, URI, &request);
  555. if (rc != WEBCLIENT_OK)
  556. {
  557. LOG_E("connect failed, resolve address error.");
  558. goto __exit;
  559. }
  560. if (!res)
  561. {
  562. rc = -WEBCLIENT_ERROR;
  563. goto __exit;
  564. }
  565. /* copy host address */
  566. if (*request)
  567. {
  568. session->request = web_strdup(request);
  569. }
  570. #ifdef WEBCLIENT_USING_TLS
  571. if(session->tls_session)
  572. {
  573. int tls_ret = 0;
  574. if((tls_ret = mbedtls_client_context(session->tls_session)) < 0)
  575. {
  576. LOG_E("connect failed, https client context return: -0x%x", -tls_ret);
  577. return -WEBCLIENT_ERROR;
  578. }
  579. if((tls_ret = mbedtls_client_connect(session->tls_session)) < 0)
  580. {
  581. LOG_E("connect failed, https client connect return: -0x%x", -tls_ret);
  582. rc = -WEBCLIENT_CONNECT_FAILED;
  583. goto __exit;
  584. }
  585. socket_handle = session->tls_session->server_fd.fd;
  586. /* set recv timeout option */
  587. setsockopt(socket_handle, SOL_SOCKET, SO_RCVTIMEO, (void*) &timeout,
  588. sizeof(timeout));
  589. setsockopt(socket_handle, SOL_SOCKET, SO_SNDTIMEO, (void*) &timeout,
  590. sizeof(timeout));
  591. session->socket = socket_handle;
  592. rc = WEBCLIENT_OK;
  593. goto __exit;
  594. }
  595. #endif
  596. {
  597. socket_handle = socket(res->ai_family, SOCK_STREAM, IPPROTO_TCP);
  598. if (socket_handle < 0)
  599. {
  600. LOG_E("connect failed, create socket(%d) error.", socket_handle);
  601. rc = -WEBCLIENT_NOSOCKET;
  602. goto __exit;
  603. }
  604. /* set receive and send timeout option */
  605. setsockopt(socket_handle, SOL_SOCKET, SO_RCVTIMEO, (void *) &timeout,
  606. sizeof(timeout));
  607. setsockopt(socket_handle, SOL_SOCKET, SO_SNDTIMEO, (void *) &timeout,
  608. sizeof(timeout));
  609. if (connect(socket_handle, res->ai_addr, res->ai_addrlen) != 0)
  610. {
  611. /* connect failed */
  612. LOG_E("connect failed, connect socket(%d) error.", socket_handle);
  613. rc = -WEBCLIENT_CONNECT_FAILED;
  614. goto __exit;
  615. }
  616. session->socket = socket_handle;
  617. }
  618. __exit:
  619. if (res)
  620. {
  621. freeaddrinfo(res);
  622. }
  623. return rc;
  624. }
  625. struct webclient_session *webclient_create(size_t header_sz, size_t resp_sz)
  626. {
  627. struct webclient_session *session;
  628. /* create session */
  629. session = (struct webclient_session *) web_calloc(1, sizeof(struct webclient_session));
  630. if (session == RT_NULL)
  631. {
  632. LOG_E("webclient create failed, no memory for session!");
  633. return RT_NULL;
  634. }
  635. session->header_sz = header_sz;
  636. session->resp_sz = resp_sz;
  637. return session;
  638. }
  639. int webclient_get(struct webclient_session *session, const char *URI, const char *header)
  640. {
  641. int rc = WEBCLIENT_OK;
  642. RT_ASSERT(session);
  643. RT_ASSERT(URI);
  644. rc = webclient_connect(session, URI);
  645. if (rc != WEBCLIENT_OK)
  646. {
  647. /* connect to webclient server failed. */
  648. goto __exit;
  649. }
  650. rc = webclient_send_header(session, WEBCLIENT_GET, header, strlen(header));
  651. if (rc != WEBCLIENT_OK)
  652. {
  653. /* send header to webclient server failed. */
  654. goto __exit;
  655. }
  656. /* handle the response header of webclient server */
  657. rc = webclient_handle_response(session);
  658. if (rc > 0)
  659. {
  660. /* relocation */
  661. if ((session->response == 302 || session->response == 301) && session->location)
  662. {
  663. char *location = web_strdup(session->location);
  664. if (location)
  665. {
  666. webclient_close(session);
  667. rc = webclient_get(session, location, header);
  668. if (rc != WEBCLIENT_OK)
  669. {
  670. goto __exit;
  671. }
  672. web_free(location);
  673. return session->response;
  674. }
  675. }
  676. else if (session->response != 200)
  677. {
  678. LOG_E("get failed, handle response(%d) error!", session->response);
  679. goto __exit;
  680. }
  681. }
  682. __exit:
  683. if (rc < 0)
  684. {
  685. return rc;
  686. }
  687. return session->response;
  688. }
  689. int webclient_get_position(struct webclient_session *session, const char *URI, int position)
  690. {
  691. char *range_header = RT_NULL;
  692. int rc = WEBCLIENT_OK;
  693. RT_ASSERT(session);
  694. RT_ASSERT(URI);
  695. rc = webclient_connect(session, URI);
  696. if (rc != WEBCLIENT_OK)
  697. {
  698. /* connect to webclient server failed. */
  699. goto __exit;
  700. }
  701. range_header = (char *) web_malloc(session->header_sz);
  702. if (range_header == RT_NULL)
  703. {
  704. LOG_E("open position failed, no memory for range header!");
  705. rc = -WEBCLIENT_NOMEM;
  706. goto __exit;
  707. }
  708. /* splice header*/
  709. rt_snprintf(range_header, session->header_sz - 1,
  710. "Range: bytes=%d-\r\n", position);
  711. rc = webclient_send_header(session, WEBCLIENT_GET, range_header, strlen(range_header));
  712. if (rc != WEBCLIENT_OK)
  713. {
  714. /* send header to webclient server failed. */
  715. goto __exit;
  716. }
  717. /* handle the response header of webclient server */
  718. rc = webclient_handle_response(session);
  719. if (rc > 0)
  720. {
  721. /* relocation */
  722. if ((session->response == 302 || session->response == 301) && session->location)
  723. {
  724. char *location = web_strdup(session->location);
  725. if (location)
  726. {
  727. webclient_close(session);
  728. rc = webclient_get_position(session, location, position);
  729. if (rc != WEBCLIENT_OK)
  730. {
  731. goto __exit;
  732. }
  733. web_free(location);
  734. return session->response;
  735. }
  736. }
  737. else if (session->response != 206)
  738. {
  739. LOG_E("get failed, handle response(%d) error!", session->response);
  740. goto __exit;
  741. }
  742. }
  743. __exit:
  744. if (range_header)
  745. {
  746. web_free(range_header);
  747. }
  748. if (rc < 0)
  749. {
  750. return rc;
  751. }
  752. return session->response;
  753. }
  754. int webclient_post_header(struct webclient_session *session, const char *URI, const char *header)
  755. {
  756. int rc = WEBCLIENT_OK;
  757. RT_ASSERT(session);
  758. RT_ASSERT(URI);
  759. if(header == RT_NULL)
  760. {
  761. LOG_E("http post request input header data cannot be empty!");
  762. return RT_NULL;
  763. }
  764. rc = webclient_connect(session, URI);
  765. if (rc != WEBCLIENT_OK)
  766. {
  767. /* connect to webclient server failed. */
  768. goto __exit;
  769. }
  770. rc = webclient_send_header(session, WEBCLIENT_POST, header, strlen(header));
  771. if (rc != WEBCLIENT_OK)
  772. {
  773. /* send header to webclient server failed. */
  774. goto __exit;
  775. }
  776. __exit:
  777. return rc;
  778. }
  779. int webclient_post(struct webclient_session *session, const char *URI,
  780. const char *header, const char *post_data)
  781. {
  782. int rc = WEBCLIENT_OK;
  783. RT_ASSERT(session);
  784. RT_ASSERT(URI);
  785. RT_ASSERT(post_data);
  786. rc = webclient_post_header(session, URI, header);
  787. if (rc != WEBCLIENT_OK)
  788. {
  789. goto __exit;
  790. }
  791. webclient_write(session, (const unsigned char *)post_data, strlen(post_data));
  792. rc = webclient_handle_response(session);
  793. if (rc > 0)
  794. {
  795. if (session->response != 200)
  796. {
  797. LOG_E("post failed, handle response(%d) error.", session->response);
  798. goto __exit;
  799. }
  800. }
  801. __exit:
  802. if (rc < 0)
  803. {
  804. return rc;
  805. }
  806. return session->response;
  807. }
  808. /**
  809. * set receive and send data timeout.
  810. *
  811. * @param session http session
  812. * @param millisecond timeout millisecond
  813. *
  814. * @return 0: set timeout success
  815. */
  816. int webclient_set_timeout(struct webclient_session *session, int millisecond)
  817. {
  818. struct timeval timeout;
  819. int second = rt_tick_from_millisecond(millisecond) / 1000;
  820. RT_ASSERT(session);
  821. timeout.tv_sec = second;
  822. timeout.tv_usec = 0;
  823. /* set recv timeout option */
  824. setsockopt(session->socket, SOL_SOCKET, SO_RCVTIMEO,
  825. (void *) &timeout, sizeof(timeout));
  826. setsockopt(session->socket, SOL_SOCKET, SO_SNDTIMEO,
  827. (void *) &timeout, sizeof(timeout));
  828. return 0;
  829. }
  830. static int webclient_next_chunk(struct webclient_session *session)
  831. {
  832. char line[64];
  833. int length;
  834. RT_ASSERT(session);
  835. length = webclient_read_line(session, line, sizeof(line));
  836. if (length)
  837. {
  838. if (strcmp(line, "\r\n") == 0)
  839. {
  840. length = webclient_read_line(session, line, sizeof(line));
  841. if (length <= 0)
  842. {
  843. closesocket(session->socket);
  844. session->socket = -1;
  845. return length;
  846. }
  847. }
  848. }
  849. else
  850. {
  851. closesocket(session->socket);
  852. session->socket = -1;
  853. return length;
  854. }
  855. session->chunk_sz = strtol(line, RT_NULL, 16);
  856. session->chunk_offset = 0;
  857. if (session->chunk_sz == 0)
  858. {
  859. /* end of chunks */
  860. closesocket(session->socket);
  861. session->socket = -1;
  862. }
  863. return session->chunk_sz;
  864. }
  865. /**
  866. * read data from http server.
  867. *
  868. * @param session http session
  869. * @param buffer read buffer
  870. * @param length the maximum of read buffer size
  871. *
  872. * @return <0: read data error
  873. * =0: http server disconnect
  874. * >0: successfully read data length
  875. */
  876. int webclient_read(struct webclient_session *session, unsigned char *buffer, size_t length)
  877. {
  878. int bytes_read = 0;
  879. int total_read = 0;
  880. int left;
  881. RT_ASSERT(session);
  882. if (session->socket < 0)
  883. {
  884. return -WEBCLIENT_DISCONNECT;
  885. }
  886. if (length == 0)
  887. {
  888. return 0;
  889. }
  890. /* which is transfered as chunk mode */
  891. if (session->chunk_sz)
  892. {
  893. if ((int) length > (session->chunk_sz - session->chunk_offset))
  894. {
  895. length = session->chunk_sz - session->chunk_offset;
  896. }
  897. bytes_read = webclient_recv(session, buffer, length, 0);
  898. if (bytes_read <= 0)
  899. {
  900. if (errno == EWOULDBLOCK || errno == EAGAIN)
  901. {
  902. /* recv timeout */
  903. return -WEBCLIENT_TIMEOUT;
  904. }
  905. else
  906. {
  907. closesocket(session->socket);
  908. session->socket = -1;
  909. return 0;
  910. }
  911. }
  912. session->chunk_offset += bytes_read;
  913. if (session->chunk_offset >= session->chunk_sz)
  914. {
  915. webclient_next_chunk(session);
  916. }
  917. return bytes_read;
  918. }
  919. if (session->content_length > 0)
  920. {
  921. if (length > session->content_length_remainder)
  922. {
  923. length = session->content_length_remainder;
  924. }
  925. if (length == 0)
  926. {
  927. return 0;
  928. }
  929. }
  930. /*
  931. * Read until: there is an error, we've read "size" bytes or the remote
  932. * side has closed the connection.
  933. */
  934. left = length;
  935. do
  936. {
  937. bytes_read = webclient_recv(session, buffer + total_read, left, 0);
  938. if (bytes_read <= 0)
  939. {
  940. #ifdef WEBCLIENT_USING_TLS
  941. if(session->tls_session && bytes_read == MBEDTLS_ERR_SSL_WANT_READ)
  942. continue;
  943. #endif
  944. LOG_E("receive data error(%d).", bytes_read);
  945. if (total_read)
  946. {
  947. break;
  948. }
  949. else
  950. {
  951. if (errno == EWOULDBLOCK || errno == EAGAIN)
  952. {
  953. /* recv timeout */
  954. LOG_E("receive data timeout.");
  955. return -WEBCLIENT_TIMEOUT;
  956. }
  957. else
  958. {
  959. closesocket(session->socket);
  960. session->socket = -1;
  961. return 0;
  962. }
  963. }
  964. }
  965. left -= bytes_read;
  966. total_read += bytes_read;
  967. }
  968. while (left);
  969. if (session->content_length > 0)
  970. {
  971. session->content_length_remainder -= total_read;
  972. }
  973. return total_read;
  974. }
  975. /**
  976. * write data to http server.
  977. *
  978. * @param session http session
  979. * @param buffer write buffer
  980. * @param length write buffer size
  981. *
  982. * @return <0: write data error
  983. * =0: http server disconnect
  984. * >0: successfully write data length
  985. */
  986. int webclient_write(struct webclient_session *session, const unsigned char *buffer, size_t length)
  987. {
  988. int bytes_write = 0;
  989. int total_write = 0;
  990. int left = length;
  991. RT_ASSERT(session);
  992. if (session->socket < 0)
  993. {
  994. return -WEBCLIENT_DISCONNECT;
  995. }
  996. if(length == 0)
  997. {
  998. return 0;
  999. }
  1000. /* send all of data on the buffer. */
  1001. do
  1002. {
  1003. bytes_write = webclient_send(session, buffer + total_write, left, 0);
  1004. if (bytes_write <= 0)
  1005. {
  1006. #ifdef WEBCLIENT_USING_TLS
  1007. if(session->tls_session && bytes_write == MBEDTLS_ERR_SSL_WANT_WRITE)
  1008. continue;
  1009. #endif
  1010. if (errno == EWOULDBLOCK || errno == EAGAIN)
  1011. {
  1012. /* send timeout */
  1013. if (total_write)
  1014. {
  1015. return total_write;
  1016. }
  1017. continue;
  1018. /* TODO: whether return the TIMEOUT
  1019. * return -WEBCLIENT_TIMEOUT; */
  1020. }
  1021. else
  1022. {
  1023. closesocket(session->socket);
  1024. session->socket = -1;
  1025. if (total_write == 0)
  1026. {
  1027. return -WEBCLIENT_DISCONNECT;
  1028. }
  1029. break;
  1030. }
  1031. }
  1032. left -= bytes_write;
  1033. total_write += bytes_write;
  1034. }
  1035. while (left);
  1036. return total_write;
  1037. }
  1038. /**
  1039. * close a webclient client session.
  1040. *
  1041. * @param session http client session
  1042. *
  1043. * @return 0: close success
  1044. */
  1045. int webclient_close(struct webclient_session *session)
  1046. {
  1047. RT_ASSERT(session);
  1048. #ifdef WEBCLIENT_USING_TLS
  1049. if(session->tls_session)
  1050. {
  1051. mbedtls_client_close(session->tls_session);
  1052. }
  1053. else
  1054. {
  1055. if (session->socket >= 0)
  1056. {
  1057. closesocket(session->socket);
  1058. session->socket = -1;
  1059. }
  1060. }
  1061. #else
  1062. if (session->socket >= 0)
  1063. {
  1064. closesocket(session->socket);
  1065. session->socket = -1;
  1066. }
  1067. #endif
  1068. if(session->transfer_encoding)
  1069. web_free(session->transfer_encoding);
  1070. if(session->content_type)
  1071. web_free(session->content_type);
  1072. if(session->last_modified)
  1073. web_free(session->last_modified);
  1074. if(session->host)
  1075. web_free(session->host);
  1076. if(session->request)
  1077. web_free(session->request);
  1078. if(session->location)
  1079. web_free(session->location);
  1080. if(session)
  1081. {
  1082. web_free(session);
  1083. session = RT_NULL;
  1084. }
  1085. return 0;
  1086. }
  1087. int webclient_response(struct webclient_session *session, void **response)
  1088. {
  1089. unsigned char *buf_ptr;
  1090. unsigned char *response_buf = 0;
  1091. int length, total_read = 0;
  1092. RT_ASSERT(session);
  1093. RT_ASSERT(response);
  1094. /* initialize response */
  1095. *response = RT_NULL;
  1096. /* not content length field kind */
  1097. if (session->content_length < 0)
  1098. {
  1099. size_t result_sz;
  1100. total_read = 0;
  1101. while (1)
  1102. {
  1103. unsigned char *new_resp = RT_NULL;
  1104. result_sz = total_read + session->resp_sz;
  1105. new_resp = web_realloc(response_buf, result_sz + 1);
  1106. if (new_resp == RT_NULL)
  1107. {
  1108. LOG_E("no memory for realloc new response buffer!");
  1109. break;
  1110. }
  1111. response_buf = new_resp;
  1112. buf_ptr = (unsigned char *) response_buf + total_read;
  1113. /* read result */
  1114. length = webclient_read(session, buf_ptr, result_sz - total_read);
  1115. if (length <= 0)
  1116. break;
  1117. total_read += length;
  1118. }
  1119. }
  1120. else
  1121. {
  1122. int result_sz;
  1123. result_sz = session->content_length;
  1124. response_buf = web_malloc(result_sz + 1);
  1125. if (!response_buf)
  1126. {
  1127. return -WEBCLIENT_NOMEM;
  1128. }
  1129. buf_ptr = (unsigned char *) response_buf;
  1130. for (total_read = 0; total_read < result_sz;)
  1131. {
  1132. length = webclient_read(session, buf_ptr, result_sz - total_read);
  1133. if (length <= 0)
  1134. break;
  1135. buf_ptr += length;
  1136. total_read += length;
  1137. }
  1138. }
  1139. if ((total_read == 0) && (response_buf != 0))
  1140. {
  1141. web_free(response_buf);
  1142. response_buf = RT_NULL;
  1143. }
  1144. if (response_buf)
  1145. {
  1146. *response = response_buf;
  1147. *(response_buf + total_read) = '\0';
  1148. }
  1149. return total_read;
  1150. }
  1151. int webclient_request(const char *URI, const char *header, const char *post_data, unsigned char **result)
  1152. {
  1153. struct webclient_session *session;
  1154. int rc = WEBCLIENT_OK;
  1155. int totle_length;
  1156. RT_ASSERT(URI);
  1157. if(post_data && header == RT_NULL)
  1158. {
  1159. LOG_E("request post failed, post input header cannot be empty.");
  1160. return -WEBCLIENT_ERROR;
  1161. }
  1162. if(post_data == RT_NULL && result == RT_NULL)
  1163. {
  1164. LOG_E("request get failed, get response data cannot be empty.");
  1165. return -WEBCLIENT_ERROR;
  1166. }
  1167. if(post_data == RT_NULL)
  1168. {
  1169. session = webclient_create(WEBCLIENT_HEADER_BUFSZ, WEBCLIENT_RESPONSE_BUFSZ);
  1170. if(session == RT_NULL)
  1171. {
  1172. rc = -WEBCLIENT_NOMEM;
  1173. goto __exit;
  1174. }
  1175. if(webclient_get(session, URI, header) != 200)
  1176. {
  1177. rc = -WEBCLIENT_ERROR;
  1178. goto __exit;
  1179. }
  1180. totle_length = webclient_response(session, (void **)result);
  1181. if(totle_length <= 0)
  1182. {
  1183. rc = -WEBCLIENT_ERROR;
  1184. goto __exit;
  1185. }
  1186. }
  1187. else
  1188. {
  1189. session = webclient_create(WEBCLIENT_HEADER_BUFSZ, WEBCLIENT_RESPONSE_BUFSZ);
  1190. if(session == RT_NULL)
  1191. {
  1192. rc = -WEBCLIENT_NOMEM;
  1193. goto __exit;
  1194. }
  1195. if(webclient_post(session, URI, header, post_data) != 200)
  1196. {
  1197. rc = -WEBCLIENT_ERROR;
  1198. goto __exit;
  1199. }
  1200. }
  1201. __exit:
  1202. if(session)
  1203. {
  1204. webclient_close(session);
  1205. session = RT_NULL;
  1206. }
  1207. if(rc < 0)
  1208. {
  1209. return rc;
  1210. }
  1211. return totle_length;
  1212. }