http.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391
  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 ";
  9. const char _http_host[] = "Host: ";
  10. const char _http_getend[] = " HTTP/1.0\r\n";
  11. const char _http_user_agent[] = "User-Agent: RT-Thread HTTP Agent\r\n";
  12. const char _http_endheader[] = "\r\n";
  13. extern long int strtol(const char *nptr, char **endptr, int base);
  14. //
  15. // This function will parse the Content-Length header line and return the file size
  16. //
  17. int http_parse_content_length(char *mime_buf)
  18. {
  19. char *line;
  20. line = strstr(mime_buf, "CONTENT-LENGTH:");
  21. line += strlen("CONTENT-LENGTH:");
  22. // Advance past any whitepace characters
  23. while((*line == ' ') || (*line == '\t')) line++;
  24. return (int)strtol(line, RT_NULL, 10);
  25. }
  26. //
  27. // This function will parse the initial response header line and return 0 for a "200 OK",
  28. // or return the error code in the event of an error (such as 404 - not found)
  29. //
  30. int http_is_error_header(char *mime_buf)
  31. {
  32. char *line;
  33. int i;
  34. int code;
  35. line = strstr(mime_buf, "HTTP/1.");
  36. line += strlen("HTTP/1.");
  37. // Advance past minor protocol version number
  38. line++;
  39. // Advance past any whitespace characters
  40. while((*line == ' ') || (*line == '\t')) line++;
  41. // Terminate string after status code
  42. for(i = 0; ((line[i] != ' ') && (line[i] != '\t')); i++);
  43. line[i] = '\0';
  44. code = (int)strtol(line, RT_NULL, 10);
  45. if( code == 200 )
  46. return 0;
  47. else
  48. return code;
  49. }
  50. //
  51. // When a request has been sent, we can expect mime headers to be
  52. // before the data. We need to read exactly to the end of the headers
  53. // and no more data. This readline reads a single char at a time.
  54. //
  55. int http_read_line( int socket, char * buffer, int size )
  56. {
  57. char * ptr = buffer;
  58. int count = 0;
  59. int rc;
  60. // Keep reading until we fill the buffer.
  61. while ( count < size )
  62. {
  63. rc = recv( socket, ptr, 1, 0 );
  64. if ( rc <= 0 ) return rc;
  65. if ( (*ptr == '\n') ) break;
  66. // increment after check for cr. Don't want to count the cr.
  67. count++;
  68. ptr++;
  69. }
  70. // Terminate string
  71. *ptr = '\0';
  72. // return how many bytes read.
  73. return count;
  74. }
  75. //
  76. // Before we can connect we need to parse the server address and optional
  77. // port from the url provided. the format of "url" as passed to this function
  78. // is "//192.168.0.1:8080/blah.elf" where "192.168.0.1" can be either an IP
  79. // or a domain name and ":8080" is the optional port to connect to, default
  80. // port is 80.
  81. //
  82. // This function will return a filename string for use in GET
  83. // requests, and fill the structure pointed to by *server with the
  84. // correct values.
  85. //
  86. const char *http_resolve_address( struct sockaddr_in *server, const char * url, char *host_addr)
  87. {
  88. char *ptr;
  89. char port[6] = "80"; /* default port of 80(HTTP) */
  90. int i = 0, rv, is_domain;
  91. /* strip http: */
  92. ptr = strchr(url, ':');
  93. if (ptr != NULL)
  94. {
  95. url = ptr + 1;
  96. }
  97. /* URL must start with double forward slashes. */
  98. if((url[0] != '/') || (url[1] != '/' )) return(NULL);
  99. url += 2; is_domain = 0;
  100. for(i = 0; ((url[i] != '\0') && (url[i] != '/')) && (i < 30); i++)
  101. {
  102. if((((host_addr[i] = url[i]) < '0') || (url[i] > '9')) && (url[i] != '.'))
  103. {
  104. if(url[i] == ':')
  105. {
  106. unsigned char w;
  107. /* allow specification of port in URL like http://www.server.net:8080/ */
  108. for(w = 0; ((w + i + 1) < 127) && (w < 5) && (url[w + i + 1] != '/') && (url[w + i + 1] != '\0'); w++)
  109. port[w] = url[w + i + 1];
  110. port[w] = '\0';
  111. rt_kprintf("HTTP: using port %s for connection\n", port);
  112. break;
  113. }
  114. else is_domain = 1;
  115. }
  116. }
  117. /* get host addr ok. */
  118. host_addr[i] = '\0';
  119. inet_aton(host_addr, (struct in_addr*)&(server->sin_addr));
  120. if (!is_domain)
  121. {
  122. /* set the port */
  123. server->sin_port = htons((int) strtol(port, NULL, 10));
  124. }
  125. else
  126. {
  127. /* resolve the host name. */
  128. rv = dns_gethostbyname(host_addr, &server->sin_addr, RT_NULL, RT_NULL);
  129. if(rv != 0)
  130. {
  131. rt_kprintf("HTTP: failed to resolve domain '%s'\n", host_addr);
  132. return RT_NULL;
  133. }
  134. }
  135. server->sin_family = AF_INET;
  136. while (*url != '/') url ++;
  137. return url;
  138. }
  139. //
  140. // This is the main HTTP client connect work. Makes the connection
  141. // and handles the protocol and reads the return headers. Needs
  142. // to leave the stream at the start of the real data.
  143. //
  144. static int http_connect(struct http_session* session,
  145. struct sockaddr_in * server, char *host_addr, const char * url)
  146. {
  147. int socket_handle;
  148. int peer_handle;
  149. int rc;
  150. char mimeBuffer[100];
  151. if((socket_handle = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP )) < 0)
  152. {
  153. rt_kprintf( "HTTP: SOCKET FAILED\n" );
  154. return -1;
  155. }
  156. peer_handle = connect( socket_handle, (struct sockaddr *) server, sizeof(*server));
  157. if ( peer_handle < 0 )
  158. {
  159. rt_kprintf( "HTTP: CONNECT FAILED %i\n", peer_handle );
  160. return -1;
  161. }
  162. // Needs more error checking here.....
  163. #if 0
  164. rc = send( peer_handle, _http_get, sizeof( _http_get ) - 1, 0 );
  165. rc = send( peer_handle, (void*) url, strlen( url ), 0 );
  166. rc = send( peer_handle, _http_getend, sizeof( _http_getend ) - 1, 0 );
  167. rc = send( peer_handle, _http_host, sizeof( _http_host ) - 1, 0 );
  168. rc = send( peer_handle, host_addr, strlen( host_addr ), 0 );
  169. rc = send( peer_handle, _http_endheader, sizeof( _http_endheader ) - 1, 0 ); // "\r\n"
  170. rc = send( peer_handle, _http_user_agent, sizeof( _http_user_agent ) - 1, 0 );
  171. rc = send( peer_handle, _http_endheader, sizeof( _http_endheader ) - 1, 0 );
  172. #else
  173. {
  174. rt_uint8_t *ptr, *buf;
  175. buf = rt_malloc (512);
  176. ptr = buf;
  177. rt_memcpy(ptr, _http_get, sizeof(_http_get) - 1);
  178. ptr += sizeof(_http_get) - 1;
  179. rt_memcpy(ptr, url, strlen(url));
  180. ptr += strlen(url);
  181. rt_memcpy(ptr, _http_getend, sizeof(_http_getend) - 1);
  182. ptr += sizeof(_http_getend) - 1;
  183. rt_memcpy(ptr, _http_host, sizeof(_http_host) - 1);
  184. ptr += sizeof(_http_host) - 1;
  185. rt_memcpy(ptr, host_addr, strlen(host_addr));
  186. ptr += strlen(host_addr);
  187. rt_memcpy(ptr, _http_endheader, sizeof(_http_endheader) - 1);
  188. ptr += sizeof(_http_endheader) - 1;
  189. rt_memcpy(ptr, _http_user_agent, sizeof(_http_user_agent) - 1);
  190. ptr += sizeof(_http_user_agent) - 1;
  191. rt_memcpy(ptr, _http_endheader, sizeof(_http_endheader) - 1);
  192. ptr += sizeof(_http_endheader) - 1;
  193. rc = send(peer_handle, buf,
  194. (rt_uint32_t)ptr - (rt_uint32_t)buf, 0);
  195. }
  196. #endif
  197. // We now need to read the header information
  198. while ( 1 )
  199. {
  200. int i;
  201. // read a line from the header information.
  202. rc = http_read_line( peer_handle, mimeBuffer, 100 );
  203. rt_kprintf(">> %s\n", mimeBuffer);
  204. if ( rc < 0 ) return rc;
  205. // End of headers is a blank line. exit.
  206. if ( rc == 0 ) break;
  207. if ( (rc == 1) && (mimeBuffer[0] == '\r') ) break;
  208. // Convert mimeBuffer to upper case, so we can do string comps
  209. for(i = 0; i < strlen(mimeBuffer); i++)
  210. mimeBuffer[i] = toupper(mimeBuffer[i]);
  211. if(strstr(mimeBuffer, "HTTP/1.")) // First line of header, contains status code. Check for an error code
  212. {
  213. rc = http_is_error_header(mimeBuffer);
  214. if(rc)
  215. {
  216. rt_kprintf("HTTP: status code = %d!\n", rc);
  217. return -rc;
  218. }
  219. }
  220. if(strstr(mimeBuffer, "CONTENT-LENGTH:"))
  221. {
  222. session->size = http_parse_content_length(mimeBuffer);
  223. rt_kprintf("size = %d\n", session->size);
  224. }
  225. }
  226. // We've sent the request, and read the headers. SockHandle is
  227. // now at the start of the main data read for a file io read.
  228. return peer_handle;
  229. }
  230. struct http_session* http_session_open(char* url)
  231. {
  232. int peer_handle = 0;
  233. struct sockaddr_in server;
  234. const char *get_name;
  235. char host_addr[32];
  236. struct http_session* session;
  237. session = (struct http_session*) rt_malloc(sizeof(struct http_session));
  238. if(session == RT_NULL) return RT_NULL;
  239. session->size = 0;
  240. session->position = 0;
  241. /* Check valid IP address and URL */
  242. get_name = http_resolve_address(&server, url, &host_addr[0]);
  243. if(get_name == NULL)
  244. {
  245. rt_free(session);
  246. return RT_NULL;
  247. }
  248. // Now we connect and initiate the transfer by sending a
  249. // request header to the server, and receiving the response header
  250. if((peer_handle = http_connect(session, &server, host_addr, get_name)) < 0)
  251. {
  252. rt_kprintf("HTTP: failed to connect to '%s'!\n", host_addr);
  253. rt_free(session);
  254. return RT_NULL;
  255. }
  256. // http connect returns valid socket. Save in handle list.
  257. session->socket = peer_handle;
  258. /* open successfully */
  259. return session;
  260. }
  261. rt_size_t http_session_read(struct http_session* session, rt_uint8_t *buffer, rt_size_t length)
  262. {
  263. int bytesRead = 0;
  264. int totalRead = 0;
  265. int left = length;
  266. // Read until: there is an error, we've read "size" bytes or the remote
  267. // side has closed the connection.
  268. do
  269. {
  270. bytesRead = recv(session->socket, buffer + totalRead, left, 0);
  271. if(bytesRead <= 0) break;
  272. left -= bytesRead;
  273. totalRead += bytesRead;
  274. } while(left);
  275. return totalRead;
  276. }
  277. rt_off_t http_session_seek(struct http_session* session, rt_off_t offset, int mode)
  278. {
  279. switch(mode)
  280. {
  281. case SEEK_SET:
  282. session->position = offset;
  283. break;
  284. case SEEK_CUR:
  285. session->position += offset;
  286. break;
  287. case SEEK_END:
  288. session->position = session->size + offset;
  289. break;
  290. }
  291. return session->position;
  292. }
  293. int http_session_close(struct http_session* session)
  294. {
  295. lwip_close(session->socket);
  296. rt_free(session);
  297. return 0;
  298. }
  299. #include <finsh.h>
  300. void http_test(char* url)
  301. {
  302. struct http_session* session;
  303. char buffer[80];
  304. rt_size_t length;
  305. session = http_session_open(url);
  306. if (session == RT_NULL)
  307. {
  308. rt_kprintf("open http session failed\n");
  309. return;
  310. }
  311. do
  312. {
  313. rt_memset(buffer, 0, sizeof(buffer));
  314. length = http_session_read(session, buffer, sizeof(buffer));
  315. rt_kprintf(buffer);rt_kprintf("\n");
  316. } while (length > 0);
  317. http_session_close(session);
  318. }
  319. FINSH_FUNCTION_EXPORT(http_test, http client test);