http.c 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393
  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, is_domain;
  91. struct hostent *hptr;
  92. /* strip http: */
  93. ptr = strchr(url, ':');
  94. if (ptr != NULL)
  95. {
  96. url = ptr + 1;
  97. }
  98. /* URL must start with double forward slashes. */
  99. if((url[0] != '/') || (url[1] != '/' )) return(NULL);
  100. url += 2; is_domain = 0;
  101. for(i = 0; ((url[i] != '\0') && (url[i] != '/')) && (i < 30); i++)
  102. {
  103. if((((host_addr[i] = url[i]) < '0') || (url[i] > '9')) && (url[i] != '.'))
  104. {
  105. if(url[i] == ':')
  106. {
  107. unsigned char w;
  108. /* allow specification of port in URL like http://www.server.net:8080/ */
  109. for(w = 0; ((w + i + 1) < 127) && (w < 5) && (url[w + i + 1] != '/') && (url[w + i + 1] != '\0'); w++)
  110. port[w] = url[w + i + 1];
  111. port[w] = '\0';
  112. rt_kprintf("HTTP: using port %s for connection\n", port);
  113. break;
  114. }
  115. else is_domain = 1;
  116. }
  117. }
  118. /* get host addr ok. */
  119. host_addr[i] = '\0';
  120. if (is_domain)
  121. {
  122. /* resolve the host name. */
  123. hptr = gethostbyname(host_addr);
  124. if(hptr == 0)
  125. {
  126. rt_kprintf("HTTP: failed to resolve domain '%s'\n", host_addr);
  127. return RT_NULL;
  128. }
  129. memcpy(&server->sin_addr, *hptr->h_addr_list, sizeof(server->sin_addr));
  130. }
  131. else
  132. {
  133. inet_aton(host_addr, (struct in_addr*)&(server->sin_addr));
  134. }
  135. /* set the port */
  136. server->sin_port = htons((int) strtol(port, NULL, 10));
  137. server->sin_family = AF_INET;
  138. while (*url != '/') url ++;
  139. return url;
  140. }
  141. //
  142. // This is the main HTTP client connect work. Makes the connection
  143. // and handles the protocol and reads the return headers. Needs
  144. // to leave the stream at the start of the real data.
  145. //
  146. static int http_connect(struct http_session* session,
  147. struct sockaddr_in * server, char *host_addr, const char * url)
  148. {
  149. int socket_handle;
  150. int peer_handle;
  151. int rc;
  152. char mimeBuffer[100];
  153. if((socket_handle = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP )) < 0)
  154. {
  155. rt_kprintf( "HTTP: SOCKET FAILED\n" );
  156. return -1;
  157. }
  158. peer_handle = connect( socket_handle, (struct sockaddr *) server, sizeof(*server));
  159. if ( peer_handle < 0 )
  160. {
  161. rt_kprintf( "HTTP: CONNECT FAILED %i\n", peer_handle );
  162. return -1;
  163. }
  164. // Needs more error checking here.....
  165. #if 0
  166. rc = send( peer_handle, _http_get, sizeof( _http_get ) - 1, 0 );
  167. rc = send( peer_handle, (void*) url, strlen( url ), 0 );
  168. rc = send( peer_handle, _http_getend, sizeof( _http_getend ) - 1, 0 );
  169. rc = send( peer_handle, _http_host, sizeof( _http_host ) - 1, 0 );
  170. rc = send( peer_handle, host_addr, strlen( host_addr ), 0 );
  171. rc = send( peer_handle, _http_endheader, sizeof( _http_endheader ) - 1, 0 ); // "\r\n"
  172. rc = send( peer_handle, _http_user_agent, sizeof( _http_user_agent ) - 1, 0 );
  173. rc = send( peer_handle, _http_endheader, sizeof( _http_endheader ) - 1, 0 );
  174. #else
  175. {
  176. rt_uint8_t *ptr, *buf;
  177. buf = rt_malloc (512);
  178. ptr = buf;
  179. rt_memcpy(ptr, _http_get, sizeof(_http_get) - 1);
  180. ptr += sizeof(_http_get) - 1;
  181. rt_memcpy(ptr, url, strlen(url));
  182. ptr += strlen(url);
  183. rt_memcpy(ptr, _http_getend, sizeof(_http_getend) - 1);
  184. ptr += sizeof(_http_getend) - 1;
  185. rt_memcpy(ptr, _http_host, sizeof(_http_host) - 1);
  186. ptr += sizeof(_http_host) - 1;
  187. rt_memcpy(ptr, host_addr, strlen(host_addr));
  188. ptr += strlen(host_addr);
  189. rt_memcpy(ptr, _http_endheader, sizeof(_http_endheader) - 1);
  190. ptr += sizeof(_http_endheader) - 1;
  191. rt_memcpy(ptr, _http_user_agent, sizeof(_http_user_agent) - 1);
  192. ptr += sizeof(_http_user_agent) - 1;
  193. rt_memcpy(ptr, _http_endheader, sizeof(_http_endheader) - 1);
  194. ptr += sizeof(_http_endheader) - 1;
  195. rc = send(peer_handle, buf,
  196. (rt_uint32_t)ptr - (rt_uint32_t)buf, 0);
  197. }
  198. #endif
  199. // We now need to read the header information
  200. while ( 1 )
  201. {
  202. int i;
  203. // read a line from the header information.
  204. rc = http_read_line( peer_handle, mimeBuffer, 100 );
  205. rt_kprintf(">> %s\n", mimeBuffer);
  206. if ( rc < 0 ) return rc;
  207. // End of headers is a blank line. exit.
  208. if ( rc == 0 ) break;
  209. if ( (rc == 1) && (mimeBuffer[0] == '\r') ) break;
  210. // Convert mimeBuffer to upper case, so we can do string comps
  211. for(i = 0; i < strlen(mimeBuffer); i++)
  212. mimeBuffer[i] = toupper(mimeBuffer[i]);
  213. if(strstr(mimeBuffer, "HTTP/1.")) // First line of header, contains status code. Check for an error code
  214. {
  215. rc = http_is_error_header(mimeBuffer);
  216. if(rc)
  217. {
  218. rt_kprintf("HTTP: status code = %d!\n", rc);
  219. return -rc;
  220. }
  221. }
  222. if(strstr(mimeBuffer, "CONTENT-LENGTH:"))
  223. {
  224. session->size = http_parse_content_length(mimeBuffer);
  225. rt_kprintf("size = %d\n", session->size);
  226. }
  227. }
  228. // We've sent the request, and read the headers. SockHandle is
  229. // now at the start of the main data read for a file io read.
  230. return peer_handle;
  231. }
  232. struct http_session* http_session_open(char* url)
  233. {
  234. int peer_handle = 0;
  235. struct sockaddr_in server;
  236. const char *get_name;
  237. char host_addr[32];
  238. struct http_session* session;
  239. session = (struct http_session*) rt_malloc(sizeof(struct http_session));
  240. if(session == RT_NULL) return RT_NULL;
  241. session->size = 0;
  242. session->position = 0;
  243. /* Check valid IP address and URL */
  244. get_name = http_resolve_address(&server, url, &host_addr[0]);
  245. if(get_name == NULL)
  246. {
  247. rt_free(session);
  248. return RT_NULL;
  249. }
  250. // Now we connect and initiate the transfer by sending a
  251. // request header to the server, and receiving the response header
  252. if((peer_handle = http_connect(session, &server, host_addr, get_name)) < 0)
  253. {
  254. rt_kprintf("HTTP: failed to connect to '%s'!\n", host_addr);
  255. rt_free(session);
  256. return RT_NULL;
  257. }
  258. // http connect returns valid socket. Save in handle list.
  259. session->socket = peer_handle;
  260. /* open successfully */
  261. return session;
  262. }
  263. rt_size_t http_session_read(struct http_session* session, rt_uint8_t *buffer, rt_size_t length)
  264. {
  265. int bytesRead = 0;
  266. int totalRead = 0;
  267. int left = length;
  268. // Read until: there is an error, we've read "size" bytes or the remote
  269. // side has closed the connection.
  270. do
  271. {
  272. bytesRead = recv(session->socket, buffer + totalRead, left, 0);
  273. if(bytesRead <= 0) break;
  274. left -= bytesRead;
  275. totalRead += bytesRead;
  276. } while(left);
  277. return totalRead;
  278. }
  279. rt_off_t http_session_seek(struct http_session* session, rt_off_t offset, int mode)
  280. {
  281. switch(mode)
  282. {
  283. case SEEK_SET:
  284. session->position = offset;
  285. break;
  286. case SEEK_CUR:
  287. session->position += offset;
  288. break;
  289. case SEEK_END:
  290. session->position = session->size + offset;
  291. break;
  292. }
  293. return session->position;
  294. }
  295. int http_session_close(struct http_session* session)
  296. {
  297. lwip_close(session->socket);
  298. rt_free(session);
  299. return 0;
  300. }
  301. #include <finsh.h>
  302. void http_test(char* url)
  303. {
  304. struct http_session* session;
  305. char buffer[80];
  306. rt_size_t length;
  307. session = http_session_open(url);
  308. if (session == RT_NULL)
  309. {
  310. rt_kprintf("open http session failed\n");
  311. return;
  312. }
  313. do
  314. {
  315. rt_memset(buffer, 0, sizeof(buffer));
  316. length = http_session_read(session, buffer, sizeof(buffer));
  317. rt_kprintf(buffer);rt_kprintf("\n");
  318. } while (length > 0);
  319. http_session_close(session);
  320. }
  321. FINSH_FUNCTION_EXPORT(http_test, http client test);