PageRenderTime 58ms CodeModel.GetById 17ms RepoModel.GetById 1ms app.codeStats 0ms

/miniupnpc/miniwget.c

https://github.com/miniupnp/miniupnp
C | 578 lines | 495 code | 21 blank | 62 comment | 133 complexity | ed2f987c4b1f0b2fd96bf7cd94ba71f6 MD5 | raw file
Possible License(s): BSD-3-Clause
  1. /* $Id: miniwget.c,v 1.61 2014/02/05 17:27:48 nanard Exp $ */
  2. /* Project : miniupnp
  3. * Website : http://miniupnp.free.fr/
  4. * Author : Thomas Bernard
  5. * Copyright (c) 2005-2014 Thomas Bernard
  6. * This software is subject to the conditions detailed in the
  7. * LICENCE file provided in this distribution. */
  8. #include <stdio.h>
  9. #include <stdlib.h>
  10. #include <string.h>
  11. #include <ctype.h>
  12. #ifdef _WIN32
  13. #include <winsock2.h>
  14. #include <ws2tcpip.h>
  15. #include <io.h>
  16. #define MAXHOSTNAMELEN 64
  17. #define MIN(x,y) (((x)<(y))?(x):(y))
  18. #define snprintf _snprintf
  19. #define socklen_t int
  20. #ifndef strncasecmp
  21. #if defined(_MSC_VER) && (_MSC_VER >= 1400)
  22. #define strncasecmp _memicmp
  23. #else /* defined(_MSC_VER) && (_MSC_VER >= 1400) */
  24. #define strncasecmp memicmp
  25. #endif /* defined(_MSC_VER) && (_MSC_VER >= 1400) */
  26. #endif /* #ifndef strncasecmp */
  27. #else /* #ifdef _WIN32 */
  28. #include <unistd.h>
  29. #include <sys/param.h>
  30. #if defined(__amigaos__) && !defined(__amigaos4__)
  31. #define socklen_t int
  32. #else /* #if defined(__amigaos__) && !defined(__amigaos4__) */
  33. #include <sys/select.h>
  34. #endif /* #else defined(__amigaos__) && !defined(__amigaos4__) */
  35. #include <sys/socket.h>
  36. #include <netinet/in.h>
  37. #include <arpa/inet.h>
  38. #include <net/if.h>
  39. #include <netdb.h>
  40. #define closesocket close
  41. #endif /* #else _WIN32 */
  42. #if defined(__sun) || defined(sun)
  43. #define MIN(x,y) (((x)<(y))?(x):(y))
  44. #endif
  45. #ifdef __GNU__
  46. #define MAXHOSTNAMELEN 64
  47. #endif
  48. #include "miniupnpcstrings.h"
  49. #include "miniwget.h"
  50. #include "connecthostport.h"
  51. #include "receivedata.h"
  52. #ifndef MAXHOSTNAMELEN
  53. #define MAXHOSTNAMELEN 64
  54. #endif
  55. /*
  56. * Read a HTTP response from a socket.
  57. * Process Content-Length and Transfer-encoding headers.
  58. * return a pointer to the content buffer, which length is saved
  59. * to the length parameter.
  60. */
  61. void *
  62. getHTTPResponse(int s, int * size)
  63. {
  64. char buf[2048];
  65. int n;
  66. int endofheaders = 0;
  67. int chunked = 0;
  68. int content_length = -1;
  69. unsigned int chunksize = 0;
  70. unsigned int bytestocopy = 0;
  71. /* buffers : */
  72. char * header_buf;
  73. unsigned int header_buf_len = 2048;
  74. unsigned int header_buf_used = 0;
  75. char * content_buf;
  76. unsigned int content_buf_len = 2048;
  77. unsigned int content_buf_used = 0;
  78. char chunksize_buf[32];
  79. unsigned int chunksize_buf_index;
  80. header_buf = malloc(header_buf_len);
  81. content_buf = malloc(content_buf_len);
  82. chunksize_buf[0] = '\0';
  83. chunksize_buf_index = 0;
  84. while((n = receivedata(s, buf, 2048, 5000, NULL)) > 0)
  85. {
  86. if(endofheaders == 0)
  87. {
  88. int i;
  89. int linestart=0;
  90. int colon=0;
  91. int valuestart=0;
  92. if(header_buf_used + n > header_buf_len) {
  93. header_buf = realloc(header_buf, header_buf_used + n);
  94. header_buf_len = header_buf_used + n;
  95. }
  96. memcpy(header_buf + header_buf_used, buf, n);
  97. header_buf_used += n;
  98. /* search for CR LF CR LF (end of headers)
  99. * recognize also LF LF */
  100. i = 0;
  101. while(i < ((int)header_buf_used-1) && (endofheaders == 0)) {
  102. if(header_buf[i] == '\r') {
  103. i++;
  104. if(header_buf[i] == '\n') {
  105. i++;
  106. if(i < (int)header_buf_used && header_buf[i] == '\r') {
  107. i++;
  108. if(i < (int)header_buf_used && header_buf[i] == '\n') {
  109. endofheaders = i+1;
  110. }
  111. }
  112. }
  113. } else if(header_buf[i] == '\n') {
  114. i++;
  115. if(header_buf[i] == '\n') {
  116. endofheaders = i+1;
  117. }
  118. }
  119. i++;
  120. }
  121. if(endofheaders == 0)
  122. continue;
  123. /* parse header lines */
  124. for(i = 0; i < endofheaders - 1; i++) {
  125. if(colon <= linestart && header_buf[i]==':')
  126. {
  127. colon = i;
  128. while(i < (endofheaders-1)
  129. && (header_buf[i+1] == ' ' || header_buf[i+1] == '\t'))
  130. i++;
  131. valuestart = i + 1;
  132. }
  133. /* detecting end of line */
  134. else if(header_buf[i]=='\r' || header_buf[i]=='\n')
  135. {
  136. if(colon > linestart && valuestart > colon)
  137. {
  138. #ifdef DEBUG
  139. printf("header='%.*s', value='%.*s'\n",
  140. colon-linestart, header_buf+linestart,
  141. i-valuestart, header_buf+valuestart);
  142. #endif
  143. if(0==strncasecmp(header_buf+linestart, "content-length", colon-linestart))
  144. {
  145. content_length = atoi(header_buf+valuestart);
  146. #ifdef DEBUG
  147. printf("Content-Length: %d\n", content_length);
  148. #endif
  149. }
  150. else if(0==strncasecmp(header_buf+linestart, "transfer-encoding", colon-linestart)
  151. && 0==strncasecmp(header_buf+valuestart, "chunked", 7))
  152. {
  153. #ifdef DEBUG
  154. printf("chunked transfer-encoding!\n");
  155. #endif
  156. chunked = 1;
  157. }
  158. }
  159. while((i < (int)header_buf_used) && (header_buf[i]=='\r' || header_buf[i] == '\n'))
  160. i++;
  161. linestart = i;
  162. colon = linestart;
  163. valuestart = 0;
  164. }
  165. }
  166. /* copy the remaining of the received data back to buf */
  167. n = header_buf_used - endofheaders;
  168. memcpy(buf, header_buf + endofheaders, n);
  169. /* if(headers) */
  170. }
  171. if(endofheaders)
  172. {
  173. /* content */
  174. if(chunked)
  175. {
  176. int i = 0;
  177. while(i < n)
  178. {
  179. if(chunksize == 0)
  180. {
  181. /* reading chunk size */
  182. if(chunksize_buf_index == 0) {
  183. /* skipping any leading CR LF */
  184. if(i<n && buf[i] == '\r') i++;
  185. if(i<n && buf[i] == '\n') i++;
  186. }
  187. while(i<n && isxdigit(buf[i])
  188. && chunksize_buf_index < (sizeof(chunksize_buf)-1))
  189. {
  190. chunksize_buf[chunksize_buf_index++] = buf[i];
  191. chunksize_buf[chunksize_buf_index] = '\0';
  192. i++;
  193. }
  194. while(i<n && buf[i] != '\r' && buf[i] != '\n')
  195. i++; /* discarding chunk-extension */
  196. if(i<n && buf[i] == '\r') i++;
  197. if(i<n && buf[i] == '\n') {
  198. unsigned int j;
  199. for(j = 0; j < chunksize_buf_index; j++) {
  200. if(chunksize_buf[j] >= '0'
  201. && chunksize_buf[j] <= '9')
  202. chunksize = (chunksize << 4) + (chunksize_buf[j] - '0');
  203. else
  204. chunksize = (chunksize << 4) + ((chunksize_buf[j] | 32) - 'a' + 10);
  205. }
  206. chunksize_buf[0] = '\0';
  207. chunksize_buf_index = 0;
  208. i++;
  209. } else {
  210. /* not finished to get chunksize */
  211. continue;
  212. }
  213. #ifdef DEBUG
  214. printf("chunksize = %u (%x)\n", chunksize, chunksize);
  215. #endif
  216. if(chunksize == 0)
  217. {
  218. #ifdef DEBUG
  219. printf("end of HTTP content - %d %d\n", i, n);
  220. /*printf("'%.*s'\n", n-i, buf+i);*/
  221. #endif
  222. goto end_of_stream;
  223. }
  224. }
  225. bytestocopy = ((int)chunksize < (n - i))?chunksize:(unsigned int)(n - i);
  226. if((content_buf_used + bytestocopy) > content_buf_len)
  227. {
  228. if(content_length >= (int)(content_buf_used + bytestocopy)) {
  229. content_buf_len = content_length;
  230. } else {
  231. content_buf_len = content_buf_used + bytestocopy;
  232. }
  233. content_buf = (char *)realloc((void *)content_buf,
  234. content_buf_len);
  235. }
  236. memcpy(content_buf + content_buf_used, buf + i, bytestocopy);
  237. content_buf_used += bytestocopy;
  238. i += bytestocopy;
  239. chunksize -= bytestocopy;
  240. }
  241. }
  242. else
  243. {
  244. /* not chunked */
  245. if(content_length > 0
  246. && (int)(content_buf_used + n) > content_length) {
  247. /* skipping additional bytes */
  248. n = content_length - content_buf_used;
  249. }
  250. if(content_buf_used + n > content_buf_len)
  251. {
  252. if(content_length >= (int)(content_buf_used + n)) {
  253. content_buf_len = content_length;
  254. } else {
  255. content_buf_len = content_buf_used + n;
  256. }
  257. content_buf = (char *)realloc((void *)content_buf,
  258. content_buf_len);
  259. }
  260. memcpy(content_buf + content_buf_used, buf, n);
  261. content_buf_used += n;
  262. }
  263. }
  264. /* use the Content-Length header value if available */
  265. if(content_length > 0 && (int)content_buf_used >= content_length)
  266. {
  267. #ifdef DEBUG
  268. printf("End of HTTP content\n");
  269. #endif
  270. break;
  271. }
  272. }
  273. end_of_stream:
  274. free(header_buf); header_buf = NULL;
  275. *size = content_buf_used;
  276. if(content_buf_used == 0)
  277. {
  278. free(content_buf);
  279. content_buf = NULL;
  280. }
  281. return content_buf;
  282. }
  283. /* miniwget3() :
  284. * do all the work.
  285. * Return NULL if something failed. */
  286. static void *
  287. miniwget3(const char * host,
  288. unsigned short port, const char * path,
  289. int * size, char * addr_str, int addr_str_len,
  290. const char * httpversion, unsigned int scope_id)
  291. {
  292. char buf[2048];
  293. int s;
  294. int n;
  295. int len;
  296. int sent;
  297. void * content;
  298. *size = 0;
  299. s = connecthostport(host, port, scope_id);
  300. if(s < 0)
  301. return NULL;
  302. /* get address for caller ! */
  303. if(addr_str)
  304. {
  305. struct sockaddr_storage saddr;
  306. socklen_t saddrlen;
  307. saddrlen = sizeof(saddr);
  308. if(getsockname(s, (struct sockaddr *)&saddr, &saddrlen) < 0)
  309. {
  310. perror("getsockname");
  311. }
  312. else
  313. {
  314. #if defined(__amigaos__) && !defined(__amigaos4__)
  315. /* using INT WINAPI WSAAddressToStringA(LPSOCKADDR, DWORD, LPWSAPROTOCOL_INFOA, LPSTR, LPDWORD);
  316. * But his function make a string with the port : nn.nn.nn.nn:port */
  317. /* if(WSAAddressToStringA((SOCKADDR *)&saddr, sizeof(saddr),
  318. NULL, addr_str, (DWORD *)&addr_str_len))
  319. {
  320. printf("WSAAddressToStringA() failed : %d\n", WSAGetLastError());
  321. }*/
  322. /* the following code is only compatible with ip v4 addresses */
  323. strncpy(addr_str, inet_ntoa(((struct sockaddr_in *)&saddr)->sin_addr), addr_str_len);
  324. #else
  325. #if 0
  326. if(saddr.sa_family == AF_INET6) {
  327. inet_ntop(AF_INET6,
  328. &(((struct sockaddr_in6 *)&saddr)->sin6_addr),
  329. addr_str, addr_str_len);
  330. } else {
  331. inet_ntop(AF_INET,
  332. &(((struct sockaddr_in *)&saddr)->sin_addr),
  333. addr_str, addr_str_len);
  334. }
  335. #endif
  336. /* getnameinfo return ip v6 address with the scope identifier
  337. * such as : 2a01:e35:8b2b:7330::%4281128194 */
  338. n = getnameinfo((const struct sockaddr *)&saddr, saddrlen,
  339. addr_str, addr_str_len,
  340. NULL, 0,
  341. NI_NUMERICHOST | NI_NUMERICSERV);
  342. if(n != 0) {
  343. #ifdef _WIN32
  344. fprintf(stderr, "getnameinfo() failed : %d\n", n);
  345. #else
  346. fprintf(stderr, "getnameinfo() failed : %s\n", gai_strerror(n));
  347. #endif
  348. }
  349. #endif
  350. }
  351. #ifdef DEBUG
  352. printf("address miniwget : %s\n", addr_str);
  353. #endif
  354. }
  355. len = snprintf(buf, sizeof(buf),
  356. "GET %s HTTP/%s\r\n"
  357. "Host: %s:%d\r\n"
  358. "Connection: Close\r\n"
  359. "User-Agent: " OS_STRING ", UPnP/1.0, MiniUPnPc/" MINIUPNPC_VERSION_STRING "\r\n"
  360. "\r\n",
  361. path, httpversion, host, port);
  362. sent = 0;
  363. /* sending the HTTP request */
  364. while(sent < len)
  365. {
  366. n = send(s, buf+sent, len-sent, 0);
  367. if(n < 0)
  368. {
  369. perror("send");
  370. closesocket(s);
  371. return NULL;
  372. }
  373. else
  374. {
  375. sent += n;
  376. }
  377. }
  378. content = getHTTPResponse(s, size);
  379. closesocket(s);
  380. return content;
  381. }
  382. /* miniwget2() :
  383. * Call miniwget3(); retry with HTTP/1.1 if 1.0 fails. */
  384. static void *
  385. miniwget2(const char * host,
  386. unsigned short port, const char * path,
  387. int * size, char * addr_str, int addr_str_len,
  388. unsigned int scope_id)
  389. {
  390. char * respbuffer;
  391. #if 1
  392. respbuffer = miniwget3(host, port, path, size,
  393. addr_str, addr_str_len, "1.1", scope_id);
  394. #else
  395. respbuffer = miniwget3(host, port, path, size,
  396. addr_str, addr_str_len, "1.0", scope_id);
  397. if (*size == 0)
  398. {
  399. #ifdef DEBUG
  400. printf("Retrying with HTTP/1.1\n");
  401. #endif
  402. free(respbuffer);
  403. respbuffer = miniwget3(host, port, path, size,
  404. addr_str, addr_str_len, "1.1", scope_id);
  405. }
  406. #endif
  407. return respbuffer;
  408. }
  409. /* parseURL()
  410. * arguments :
  411. * url : source string not modified
  412. * hostname : hostname destination string (size of MAXHOSTNAMELEN+1)
  413. * port : port (destination)
  414. * path : pointer to the path part of the URL
  415. *
  416. * Return values :
  417. * 0 - Failure
  418. * 1 - Success */
  419. int
  420. parseURL(const char * url,
  421. char * hostname, unsigned short * port,
  422. char * * path, unsigned int * scope_id)
  423. {
  424. char * p1, *p2, *p3;
  425. if(!url)
  426. return 0;
  427. p1 = strstr(url, "://");
  428. if(!p1)
  429. return 0;
  430. p1 += 3;
  431. if( (url[0]!='h') || (url[1]!='t')
  432. ||(url[2]!='t') || (url[3]!='p'))
  433. return 0;
  434. memset(hostname, 0, MAXHOSTNAMELEN + 1);
  435. if(*p1 == '[')
  436. {
  437. /* IP v6 : http://[2a00:1450:8002::6a]/path/abc */
  438. char * scope;
  439. scope = strchr(p1, '%');
  440. p2 = strchr(p1, ']');
  441. if(p2 && scope && scope < p2 && scope_id) {
  442. /* parse scope */
  443. #ifdef IF_NAMESIZE
  444. char tmp[IF_NAMESIZE];
  445. int l;
  446. scope++;
  447. /* "%25" is just '%' in URL encoding */
  448. if(scope[0] == '2' && scope[1] == '5')
  449. scope += 2; /* skip "25" */
  450. l = p2 - scope;
  451. if(l >= IF_NAMESIZE)
  452. l = IF_NAMESIZE - 1;
  453. memcpy(tmp, scope, l);
  454. tmp[l] = '\0';
  455. *scope_id = if_nametoindex(tmp);
  456. if(*scope_id == 0) {
  457. *scope_id = (unsigned int)strtoul(tmp, NULL, 10);
  458. }
  459. #else
  460. /* under windows, scope is numerical */
  461. char tmp[8];
  462. int l;
  463. scope++;
  464. /* "%25" is just '%' in URL encoding */
  465. if(scope[0] == '2' && scope[1] == '5')
  466. scope += 2; /* skip "25" */
  467. l = p2 - scope;
  468. if(l >= sizeof(tmp))
  469. l = sizeof(tmp) - 1;
  470. memcpy(tmp, scope, l);
  471. tmp[l] = '\0';
  472. *scope_id = (unsigned int)strtoul(tmp, NULL, 10);
  473. #endif
  474. }
  475. p3 = strchr(p1, '/');
  476. if(p2 && p3)
  477. {
  478. p2++;
  479. strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1)));
  480. if(*p2 == ':')
  481. {
  482. *port = 0;
  483. p2++;
  484. while( (*p2 >= '0') && (*p2 <= '9'))
  485. {
  486. *port *= 10;
  487. *port += (unsigned short)(*p2 - '0');
  488. p2++;
  489. }
  490. }
  491. else
  492. {
  493. *port = 80;
  494. }
  495. *path = p3;
  496. return 1;
  497. }
  498. }
  499. p2 = strchr(p1, ':');
  500. p3 = strchr(p1, '/');
  501. if(!p3)
  502. return 0;
  503. if(!p2 || (p2>p3))
  504. {
  505. strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p3-p1)));
  506. *port = 80;
  507. }
  508. else
  509. {
  510. strncpy(hostname, p1, MIN(MAXHOSTNAMELEN, (int)(p2-p1)));
  511. *port = 0;
  512. p2++;
  513. while( (*p2 >= '0') && (*p2 <= '9'))
  514. {
  515. *port *= 10;
  516. *port += (unsigned short)(*p2 - '0');
  517. p2++;
  518. }
  519. }
  520. *path = p3;
  521. return 1;
  522. }
  523. void *
  524. miniwget(const char * url, int * size, unsigned int scope_id)
  525. {
  526. unsigned short port;
  527. char * path;
  528. /* protocol://host:port/chemin */
  529. char hostname[MAXHOSTNAMELEN+1];
  530. *size = 0;
  531. if(!parseURL(url, hostname, &port, &path, &scope_id))
  532. return NULL;
  533. #ifdef DEBUG
  534. printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n",
  535. hostname, port, path, scope_id);
  536. #endif
  537. return miniwget2(hostname, port, path, size, 0, 0, scope_id);
  538. }
  539. void *
  540. miniwget_getaddr(const char * url, int * size,
  541. char * addr, int addrlen, unsigned int scope_id)
  542. {
  543. unsigned short port;
  544. char * path;
  545. /* protocol://host:port/path */
  546. char hostname[MAXHOSTNAMELEN+1];
  547. *size = 0;
  548. if(addr)
  549. addr[0] = '\0';
  550. if(!parseURL(url, hostname, &port, &path, &scope_id))
  551. return NULL;
  552. #ifdef DEBUG
  553. printf("parsed url : hostname='%s' port=%hu path='%s' scope_id=%u\n",
  554. hostname, port, path, scope_id);
  555. #endif
  556. return miniwget2(hostname, port, path, size, addr, addrlen, scope_id);
  557. }