http.c 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  1. /*
  2. * http client for RT-Thread
  3. */
  4. #include "http.h"
  5. #include <dfs_posix.h>
  6. #include <lwip/sockets.h>
  7. #include <lwip/netdb.h>
  8. const char _http_get[] = "GET %s HTTP/1.0\r\nHost: %s:%d\r\nUser-Agent: RT-Thread HTTP Agent\r\n\r\n";
  9. const char _shoutcast_get[] = "GET %s HTTP/1.0\r\nHost: %s:%d\r\nUser-Agent: RT-Thread HTTP Agent\r\nIcy-MetaData: 1\r\nConnection: close\r\n\r\n";
  10. extern long int strtol(const char *nptr, char **endptr, int base);
  11. //
  12. // This function will parse the Content-Length header line and return the file size
  13. //
  14. int http_parse_content_length(char *mime_buf)
  15. {
  16. char *line;
  17. line = strstr(mime_buf, "CONTENT-LENGTH:");
  18. line += strlen("CONTENT-LENGTH:");
  19. // Advance past any whitepace characters
  20. while((*line == ' ') || (*line == '\t')) line++;
  21. return (int)strtol(line, RT_NULL, 10);
  22. }
  23. //
  24. // This function will parse the initial response header line and return 0 for a "200 OK",
  25. // or return the error code in the event of an error (such as 404 - not found)
  26. //
  27. int http_is_error_header(char *mime_buf)
  28. {
  29. char *line;
  30. int i;
  31. int code;
  32. line = strstr(mime_buf, "HTTP/1.");
  33. line += strlen("HTTP/1.");
  34. // Advance past minor protocol version number
  35. line++;
  36. // Advance past any whitespace characters
  37. while((*line == ' ') || (*line == '\t')) line++;
  38. // Terminate string after status code
  39. for(i = 0; ((line[i] != ' ') && (line[i] != '\t')); i++);
  40. line[i] = '\0';
  41. code = (int)strtol(line, RT_NULL, 10);
  42. if( code == 200 )
  43. return 0;
  44. else
  45. return code;
  46. }
  47. int shoutcast_is_error_header(char *mime_buf)
  48. {
  49. char *line;
  50. int i;
  51. int code;
  52. line = strstr(mime_buf, "ICY");
  53. line += strlen("ICY");
  54. // Advance past minor protocol version number
  55. line++;
  56. // Advance past any whitespace characters
  57. while((*line == ' ') || (*line == '\t')) line++;
  58. // Terminate string after status code
  59. for(i = 0; ((line[i] != ' ') && (line[i] != '\t')); i++);
  60. line[i] = '\0';
  61. code = (int)strtol(line, RT_NULL, 10);
  62. if( code == 200 )
  63. return 0;
  64. else
  65. return code;
  66. }
  67. //
  68. // When a request has been sent, we can expect mime headers to be
  69. // before the data. We need to read exactly to the end of the headers
  70. // and no more data. This readline reads a single char at a time.
  71. //
  72. int http_read_line( int socket, char * buffer, int size )
  73. {
  74. char * ptr = buffer;
  75. int count = 0;
  76. int rc;
  77. // Keep reading until we fill the buffer.
  78. while ( count < size )
  79. {
  80. rc = recv( socket, ptr, 1, 0 );
  81. if ( rc <= 0 ) return rc;
  82. if ((*ptr == '\n'))
  83. {
  84. ptr ++;
  85. count++;
  86. break;
  87. }
  88. // increment after check for cr. Don't want to count the cr.
  89. count++;
  90. ptr++;
  91. }
  92. // Terminate string
  93. *ptr = '\0';
  94. // return how many bytes read.
  95. return count;
  96. }
  97. //
  98. // Before we can connect we need to parse the server address and optional
  99. // port from the url provided. the format of "url" as passed to this function
  100. // is "//192.168.0.1:8080/blah.elf" where "192.168.0.1" can be either an IP
  101. // or a domain name and ":8080" is the optional port to connect to, default
  102. // port is 80.
  103. //
  104. // This function will return a filename string for use in GET
  105. // requests, and fill the structure pointed to by *server with the
  106. // correct values.
  107. //
  108. const char *http_resolve_address( struct sockaddr_in *server, const char * url, char *host_addr)
  109. {
  110. char *ptr;
  111. char port[6] = "80"; /* default port of 80(HTTP) */
  112. int i = 0, is_domain;
  113. struct hostent *hptr;
  114. /* strip http: */
  115. ptr = strchr(url, ':');
  116. if (ptr != NULL)
  117. {
  118. url = ptr + 1;
  119. }
  120. /* URL must start with double forward slashes. */
  121. if((url[0] != '/') || (url[1] != '/' )) return(NULL);
  122. url += 2; is_domain = 0;
  123. for(i = 0; ((url[i] != '\0') && (url[i] != '/')) && (i < 30); i++)
  124. {
  125. if((((host_addr[i] = url[i]) < '0') || (url[i] > '9')) && (url[i] != '.'))
  126. {
  127. if(url[i] == ':')
  128. {
  129. unsigned char w;
  130. /* allow specification of port in URL like http://www.server.net:8080/ */
  131. for(w = 0; ((w + i + 1) < 127) && (w < 5) && (url[w + i + 1] != '/') && (url[w + i + 1] != '\0'); w++)
  132. port[w] = url[w + i + 1];
  133. port[w] = '\0';
  134. break;
  135. }
  136. else is_domain = 1;
  137. }
  138. }
  139. /* get host addr ok. */
  140. host_addr[i] = '\0';
  141. if (is_domain)
  142. {
  143. /* resolve the host name. */
  144. hptr = gethostbyname(host_addr);
  145. if(hptr == 0)
  146. {
  147. rt_kprintf("HTTP: failed to resolve domain '%s'\n", host_addr);
  148. return RT_NULL;
  149. }
  150. memcpy(&server->sin_addr, *hptr->h_addr_list, sizeof(server->sin_addr));
  151. }
  152. else
  153. {
  154. inet_aton(host_addr, (struct in_addr*)&(server->sin_addr));
  155. }
  156. /* set the port */
  157. server->sin_port = htons((int) strtol(port, NULL, 10));
  158. server->sin_family = AF_INET;
  159. while (*url != '/') url ++;
  160. return url;
  161. }
  162. //
  163. // This is the main HTTP client connect work. Makes the connection
  164. // and handles the protocol and reads the return headers. Needs
  165. // to leave the stream at the start of the real data.
  166. //
  167. static int http_connect(struct http_session* session,
  168. struct sockaddr_in * server, char *host_addr, const char * url)
  169. {
  170. int socket_handle;
  171. int peer_handle;
  172. int rc;
  173. char mimeBuffer[100];
  174. if((socket_handle = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP )) < 0)
  175. {
  176. rt_kprintf( "HTTP: SOCKET FAILED\n" );
  177. return -1;
  178. }
  179. peer_handle = connect( socket_handle, (struct sockaddr *) server, sizeof(*server));
  180. if ( peer_handle < 0 )
  181. {
  182. rt_kprintf( "HTTP: CONNECT FAILED %i\n", peer_handle );
  183. return -1;
  184. }
  185. {
  186. char *buf;
  187. rt_uint32_t length;
  188. buf = rt_malloc (512);
  189. length = rt_snprintf(buf, 512, _http_get, url, host_addr, server->sin_port);
  190. rc = send(peer_handle, buf, length, 0);
  191. rt_kprintf("HTTP request:\n%s", buf);
  192. /* release buffer */
  193. rt_free(buf);
  194. }
  195. // We now need to read the header information
  196. while ( 1 )
  197. {
  198. int i;
  199. // read a line from the header information.
  200. rc = http_read_line( peer_handle, mimeBuffer, 100 );
  201. rt_kprintf(">> %s\n", mimeBuffer);
  202. if ( rc < 0 ) return rc;
  203. // End of headers is a blank line. exit.
  204. if (rc == 0) break;
  205. if ((rc == 2) && (mimeBuffer[0] == '\r')) break;
  206. // Convert mimeBuffer to upper case, so we can do string comps
  207. for(i = 0; i < strlen(mimeBuffer); i++)
  208. mimeBuffer[i] = toupper(mimeBuffer[i]);
  209. if(strstr(mimeBuffer, "HTTP/1.")) // First line of header, contains status code. Check for an error code
  210. {
  211. rc = http_is_error_header(mimeBuffer);
  212. if(rc)
  213. {
  214. rt_kprintf("HTTP: status code = %d!\n", rc);
  215. return -rc;
  216. }
  217. }
  218. if(strstr(mimeBuffer, "CONTENT-LENGTH:"))
  219. {
  220. session->size = http_parse_content_length(mimeBuffer);
  221. rt_kprintf("size = %d\n", session->size);
  222. }
  223. }
  224. // We've sent the request, and read the headers. SockHandle is
  225. // now at the start of the main data read for a file io read.
  226. return peer_handle;
  227. }
  228. struct http_session* http_session_open(char* url)
  229. {
  230. int peer_handle = 0;
  231. struct sockaddr_in server;
  232. const char *get_name;
  233. char host_addr[32];
  234. struct http_session* session;
  235. session = (struct http_session*) rt_malloc(sizeof(struct http_session));
  236. if(session == RT_NULL) return RT_NULL;
  237. session->size = 0;
  238. session->position = 0;
  239. /* Check valid IP address and URL */
  240. get_name = http_resolve_address(&server, url, &host_addr[0]);
  241. if(get_name == NULL)
  242. {
  243. rt_free(session);
  244. return RT_NULL;
  245. }
  246. // Now we connect and initiate the transfer by sending a
  247. // request header to the server, and receiving the response header
  248. if((peer_handle = http_connect(session, &server, host_addr, get_name)) < 0)
  249. {
  250. rt_kprintf("HTTP: failed to connect to '%s'!\n", host_addr);
  251. rt_free(session);
  252. return RT_NULL;
  253. }
  254. // http connect returns valid socket. Save in handle list.
  255. session->socket = peer_handle;
  256. /* open successfully */
  257. return session;
  258. }
  259. rt_size_t http_session_read(struct http_session* session, rt_uint8_t *buffer, rt_size_t length)
  260. {
  261. int bytesRead = 0;
  262. int totalRead = 0;
  263. int left = length;
  264. // Read until: there is an error, we've read "size" bytes or the remote
  265. // side has closed the connection.
  266. do
  267. {
  268. bytesRead = recv(session->socket, buffer + totalRead, left, 0);
  269. if(bytesRead <= 0) break;
  270. left -= bytesRead;
  271. totalRead += bytesRead;
  272. } while(left);
  273. return totalRead;
  274. }
  275. rt_off_t http_session_seek(struct http_session* session, rt_off_t offset, int mode)
  276. {
  277. switch(mode)
  278. {
  279. case SEEK_SET:
  280. session->position = offset;
  281. break;
  282. case SEEK_CUR:
  283. session->position += offset;
  284. break;
  285. case SEEK_END:
  286. session->position = session->size + offset;
  287. break;
  288. }
  289. return session->position;
  290. }
  291. int http_session_close(struct http_session* session)
  292. {
  293. lwip_close(session->socket);
  294. rt_free(session);
  295. return 0;
  296. }
  297. //
  298. // This is the main HTTP client connect work. Makes the connection
  299. // and handles the protocol and reads the return headers. Needs
  300. // to leave the stream at the start of the real data.
  301. //
  302. static int shoutcast_connect(struct shoutcast_session* session,
  303. struct sockaddr_in* server, char *host_addr, const char * url)
  304. {
  305. int socket_handle;
  306. int peer_handle;
  307. int rc;
  308. char mimeBuffer[100];
  309. if((socket_handle = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP )) < 0)
  310. {
  311. rt_kprintf( "ICY: SOCKET FAILED\n" );
  312. return -1;
  313. }
  314. peer_handle = connect( socket_handle, (struct sockaddr *) server, sizeof(*server));
  315. if ( peer_handle < 0 )
  316. {
  317. rt_kprintf( "ICY: CONNECT FAILED %i\n", peer_handle );
  318. return -1;
  319. }
  320. {
  321. char *buf;
  322. rt_uint32_t length;
  323. buf = rt_malloc (512);
  324. length = rt_snprintf(buf, 512, _shoutcast_get, url, host_addr, server->sin_port);
  325. rc = send(peer_handle, buf, length, 0);
  326. rt_kprintf("SHOUTCAST request:\n%s", buf);
  327. /* release buffer */
  328. rt_free(buf);
  329. }
  330. /* read the header information */
  331. while ( 1 )
  332. {
  333. // read a line from the header information.
  334. rc = http_read_line(peer_handle, mimeBuffer, 100);
  335. rt_kprintf(">>%s", mimeBuffer);
  336. if ( rc < 0 ) return rc;
  337. // End of headers is a blank line. exit.
  338. if (rc == 0) break;
  339. if ((rc == 2) && (mimeBuffer[0] == '\r')) break;
  340. if(strstr(mimeBuffer, "ICY")) // First line of header, contains status code. Check for an error code
  341. {
  342. rc = shoutcast_is_error_header(mimeBuffer);
  343. if(rc)
  344. {
  345. rt_kprintf("ICY: status code = %d!\n", rc);
  346. return -rc;
  347. }
  348. }
  349. if (strstr(mimeBuffer, "HTTP/1."))
  350. {
  351. rc = http_is_error_header(mimeBuffer);
  352. if(rc)
  353. {
  354. rt_kprintf("HTTP: status code = %d!\n", rc);
  355. return -rc;
  356. }
  357. }
  358. if (strstr(mimeBuffer, "icy-name:"))
  359. {
  360. /* get name */
  361. char* name;
  362. name = mimeBuffer + strlen("icy-name:");
  363. session->station_name = rt_strdup(name);
  364. rt_kprintf("station name: %s\n", session->station_name);
  365. }
  366. if (strstr(mimeBuffer, "icy-br:"))
  367. {
  368. /* get bitrate */
  369. session->bitrate = strtol(mimeBuffer + strlen("icy-br:"), RT_NULL, 10);
  370. rt_kprintf("bitrate: %d\n", session->bitrate);
  371. }
  372. if (strstr(mimeBuffer, "icy-metaint:"))
  373. {
  374. /* get metaint */
  375. session->metaint = strtol(mimeBuffer + strlen("icy-metaint:"), RT_NULL, 10);
  376. rt_kprintf("metaint: %d\n", session->metaint);
  377. }
  378. if (strstr(mimeBuffer, "content-type:"))
  379. {
  380. /* check content-type */
  381. if (strstr(mimeBuffer, "content-type: audio/mpeg") == RT_NULL)
  382. {
  383. rt_kprintf("ICY content is not audio/mpeg.\n");
  384. return -1;
  385. }
  386. }
  387. if (strstr(mimeBuffer, "Content-Type:"))
  388. {
  389. /* check content-type */
  390. if (strstr(mimeBuffer, "Content-Type: audio/mpeg") == RT_NULL)
  391. {
  392. rt_kprintf("ICY content is not audio/mpeg.\n");
  393. return -1;
  394. }
  395. }
  396. }
  397. // We've sent the request, and read the headers. SockHandle is
  398. // now at the start of the main data read for a file io read.
  399. return peer_handle;
  400. }
  401. struct shoutcast_session* shoutcast_session_open(char* url)
  402. {
  403. int peer_handle = 0;
  404. struct sockaddr_in server;
  405. const char *get_name;
  406. char host_addr[32];
  407. struct shoutcast_session* session;
  408. session = (struct shoutcast_session*) rt_malloc(sizeof(struct shoutcast_session));
  409. if(session == RT_NULL) return RT_NULL;
  410. session->metaint = 0;
  411. session->current_meta_chunk = 0;
  412. session->bitrate = 0;
  413. session->station_name = RT_NULL;
  414. /* Check valid IP address and URL */
  415. get_name = http_resolve_address(&server, url, &host_addr[0]);
  416. if(get_name == NULL)
  417. {
  418. rt_free(session);
  419. return RT_NULL;
  420. }
  421. // Now we connect and initiate the transfer by sending a
  422. // request header to the server, and receiving the response header
  423. if((peer_handle = shoutcast_connect(session, &server, host_addr, get_name)) < 0)
  424. {
  425. rt_kprintf("SHOUTCAST: failed to connect to '%s'!\n", host_addr);
  426. if (session->station_name != RT_NULL)
  427. rt_free(session->station_name);
  428. rt_free(session);
  429. return RT_NULL;
  430. }
  431. // http connect returns valid socket. Save in handle list.
  432. session->socket = peer_handle;
  433. /* open successfully */
  434. return session;
  435. }
  436. rt_size_t shoutcast_session_read(struct shoutcast_session* session, rt_uint8_t *buffer, rt_size_t length)
  437. {
  438. int bytesRead = 0;
  439. int totalRead = 0;
  440. int left = length;
  441. // Read until: there is an error, we've read "size" bytes or the remote
  442. // side has closed the connection.
  443. do
  444. {
  445. bytesRead = recv(session->socket, buffer + totalRead, left, 0);
  446. if(bytesRead <= 0)
  447. {
  448. rt_kprintf("no data on recv, len %d,err %d\n", bytesRead,
  449. lwip_get_error(session->socket));
  450. break;
  451. }
  452. left -= bytesRead;
  453. totalRead += bytesRead;
  454. } while(left);
  455. /* handle meta */
  456. if (session->current_meta_chunk + totalRead >= session->metaint)
  457. {
  458. int meta_length, next_chunk_length;
  459. // rt_kprintf("c: %d, total: %d\n", session->current_meta_chunk, totalRead);
  460. /* get the length of meta data */
  461. meta_length = buffer[session->metaint - session->current_meta_chunk] * 16;
  462. next_chunk_length = totalRead - (session->metaint - session->current_meta_chunk) -
  463. (meta_length + 1);
  464. // rt_kprintf("l: %d, n: %d\n", meta_length, next_chunk_length);
  465. /* skip meta data */
  466. memmove(&buffer[session->metaint - session->current_meta_chunk],
  467. &buffer[session->metaint - session->current_meta_chunk + meta_length + 1],
  468. next_chunk_length);
  469. /* set new current meta chunk */
  470. session->current_meta_chunk = next_chunk_length;
  471. totalRead = totalRead - (meta_length + 1);
  472. // rt_kprintf("total: %d\n", totalRead);
  473. }
  474. else
  475. {
  476. session->current_meta_chunk += totalRead;
  477. }
  478. return totalRead;
  479. }
  480. rt_off_t shoutcast_session_seek(struct shoutcast_session* session, rt_off_t offset, int mode)
  481. {
  482. /* not support seek yet */
  483. return 0;
  484. }
  485. int shoutcast_session_close(struct shoutcast_session* session)
  486. {
  487. lwip_close(session->socket);
  488. if (session->station_name != RT_NULL)
  489. rt_free(session->station_name);
  490. rt_free(session);
  491. return 0;
  492. }
  493. #include <finsh.h>
  494. void http_test(char* url)
  495. {
  496. struct http_session* session;
  497. char buffer[80];
  498. rt_size_t length;
  499. session = http_session_open(url);
  500. if (session == RT_NULL)
  501. {
  502. rt_kprintf("open http session failed\n");
  503. return;
  504. }
  505. do
  506. {
  507. rt_memset(buffer, 0, sizeof(buffer));
  508. length = http_session_read(session, (rt_uint8_t*)buffer, sizeof(buffer));
  509. rt_kprintf(buffer);rt_kprintf("\n");
  510. } while (length > 0);
  511. http_session_close(session);
  512. }
  513. FINSH_FUNCTION_EXPORT(http_test, http client test);
  514. void shoutcast_test(char* url)
  515. {
  516. struct shoutcast_session* session;
  517. session = shoutcast_session_open(url);
  518. if (session == RT_NULL)
  519. {
  520. rt_kprintf("open shoutcast session failed\n");
  521. return;
  522. }
  523. shoutcast_session_close(session);
  524. }
  525. FINSH_FUNCTION_EXPORT(shoutcast_test, shoutcast client test);