http.c 9.2 KB

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