webclient.c 37 KB

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