http.c 16.2 KB
Newer Older
B
bernard.xiong 已提交
1 2 3
/*
 * http client for RT-Thread
 */
4 5
#include "http.h"

B
bernard.xiong 已提交
6 7 8 9 10
#include <dfs_posix.h>

#include <lwip/sockets.h>
#include <lwip/netdb.h>

11
const char _http_get[] = "GET %s HTTP/1.0\r\nHost: %s:%d\r\nUser-Agent: RT-Thread HTTP Agent\r\n\r\n";
B
bernard.xiong 已提交
12 13
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";

B
bernard.xiong 已提交
14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
extern long int strtol(const char *nptr, char **endptr, int base);

//
// This function will parse the Content-Length header line and return the file size
//
int http_parse_content_length(char *mime_buf)
{
	char *line;

	line = strstr(mime_buf, "CONTENT-LENGTH:");
	line += strlen("CONTENT-LENGTH:");

	// Advance past any whitepace characters
	while((*line == ' ') || (*line == '\t')) line++;

	return (int)strtol(line, RT_NULL, 10);
}

//
// This function will parse the initial response header line and return 0 for a "200 OK",
// or return the error code in the event of an error (such as 404 - not found)
//
int http_is_error_header(char *mime_buf)
{
	char *line;
	int i;
	int code;

	line = strstr(mime_buf, "HTTP/1.");
	line += strlen("HTTP/1.");

	// Advance past minor protocol version number
	line++;

	// Advance past any whitespace characters
	while((*line == ' ') || (*line == '\t')) line++;

	// Terminate string after status code
	for(i = 0; ((line[i] != ' ') && (line[i] != '\t')); i++);
	line[i] = '\0';

	code = (int)strtol(line, RT_NULL, 10);
	if( code == 200 )
		return 0;
	else
		return code;
}

B
bernard.xiong 已提交
62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
int shoutcast_is_error_header(char *mime_buf)
{
	char *line;
	int i;
	int code;

	line = strstr(mime_buf, "ICY");
	line += strlen("ICY");

	// Advance past minor protocol version number
	line++;

	// Advance past any whitespace characters
	while((*line == ' ') || (*line == '\t')) line++;

	// Terminate string after status code
	for(i = 0; ((line[i] != ' ') && (line[i] != '\t')); i++);
	line[i] = '\0';

	code = (int)strtol(line, RT_NULL, 10);
	if( code == 200 )
		return 0;
	else
		return code;
}

B
bernard.xiong 已提交
88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104
//
// When a request has been sent, we can expect mime headers to be
// before the data.  We need to read exactly to the end of the headers
// and no more data.  This readline reads a single char at a time.
//
int http_read_line( int socket, char * buffer, int size )
{
	char * ptr = buffer;
	int count = 0;
	int rc;

	// Keep reading until we fill the buffer.
	while ( count < size )
	{
		rc = recv( socket, ptr, 1, 0 );
		if ( rc <= 0 ) return rc;

B
bernard.xiong 已提交
105 106 107 108 109 110
		if ((*ptr == '\n'))
		{
			ptr ++;
			count++;
			break;
		}
B
bernard.xiong 已提交
111 112 113 114 115 116 117 118 119 120 121 122 123

		// increment after check for cr.  Don't want to count the cr.
		count++;
		ptr++;
	}

	// Terminate string
	*ptr = '\0';

	// return how many bytes read.
	return count;
}

124 125 126 127 128 129 130 131 132 133
/*
 * resolve server address
 * @param server the server sockaddress
 * @param url the input URL address, for example, http://www.rt-thread.org/index.html
 * @param host_addr the buffer pointer to save server host address
 * @param request the pointer to point the request url, for example, /index.html
 *
 * @return 0 on resolve server address OK, others failed
 */
int http_resolve_address(struct sockaddr_in *server, const char * url, char *host_addr, char** request)
B
bernard.xiong 已提交
134
{
B
bernard.xiong 已提交
135
	char *ptr;
B
bernard.xiong 已提交
136
	char port[6] = "80"; /* default port of 80(HTTP) */
137 138
	int i = 0, is_domain;
	struct hostent *hptr;
B
bernard.xiong 已提交
139 140

	/* strip http: */
B
bernard.xiong 已提交
141 142
	ptr = strchr(url, ':');
	if (ptr != NULL)
B
bernard.xiong 已提交
143
	{
B
bernard.xiong 已提交
144
		url = ptr + 1;
B
bernard.xiong 已提交
145 146
	}

B
bernard.xiong 已提交
147
	/* URL must start with double forward slashes. */
148
	if((url[0] != '/') || (url[1] != '/' )) return -1;
B
bernard.xiong 已提交
149

150
	url += 2; is_domain = 0;
151 152 153
	i = 0;
	/* allow specification of port in URL like http://www.server.net:8080/ */
	while (*url)
B
bernard.xiong 已提交
154
	{
155 156
		if (*url == '/') break;
		if (*url == ':')
B
bernard.xiong 已提交
157
		{
158 159 160 161 162 163 164 165
			unsigned char w;
			for (w = 0; w < 5 && url[w] != '/' && url[w] != '\0'; w ++)
				port[w] = url[w + 1];
			
			/* get port ok */
			port[w] = '\0';
			url += w + 1;
			break;
B
bernard.xiong 已提交
166
		}
167 168 169

		host_addr[i++] = *url;
		url ++;
B
bernard.xiong 已提交
170
	}
171 172
	*request = (char*)url;

173 174
	/* get host addr ok. */
	host_addr[i] = '\0';
B
bernard.xiong 已提交
175

176
	if (is_domain)
177 178
	{
		/* resolve the host name. */
179 180
		hptr = gethostbyname(host_addr);
		if(hptr == 0)
181 182
		{
			rt_kprintf("HTTP: failed to resolve domain '%s'\n", host_addr);
183
			return -1;
184
		}
185 186 187 188 189
		memcpy(&server->sin_addr, *hptr->h_addr_list, sizeof(server->sin_addr));
	}
	else
	{
		inet_aton(host_addr, (struct in_addr*)&(server->sin_addr));
190
	}
191 192
	/* set the port */
	server->sin_port = htons((int) strtol(port, NULL, 10));
B
bernard.xiong 已提交
193 194
	server->sin_family = AF_INET;

195
	return 0;
B
bernard.xiong 已提交
196 197 198 199 200 201 202 203
}

//
// This is the main HTTP client connect work.  Makes the connection
// and handles the protocol and reads the return headers.  Needs
// to leave the stream at the start of the real data.
//
static int http_connect(struct http_session* session,
204
    struct sockaddr_in * server, char *host_addr, const char *url)
B
bernard.xiong 已提交
205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223
{
	int socket_handle;
	int peer_handle;
	int rc;
	char mimeBuffer[100];

	if((socket_handle = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP )) < 0)
	{
		rt_kprintf( "HTTP: SOCKET FAILED\n" );
		return -1;
	}

	peer_handle = connect( socket_handle, (struct sockaddr *) server, sizeof(*server));
	if ( peer_handle < 0 )
	{
		rt_kprintf( "HTTP: CONNECT FAILED %i\n", peer_handle );
		return -1;
	}

224
	{
225 226
		char *buf;
		rt_uint32_t length;
227 228

		buf = rt_malloc (512);
229 230 231 232 233
		if (*url)
			length = rt_snprintf(buf, 512, _http_get, url, host_addr, server->sin_port);
		else
			length = rt_snprintf(buf, 512, _http_get, "/", host_addr, server->sin_port);
		
234 235 236 237 238
		rc = send(peer_handle, buf, length, 0);
		rt_kprintf("HTTP request:\n%s", buf);
		
		/* release buffer */
		rt_free(buf);
239
	}
B
bernard.xiong 已提交
240 241 242 243 244 245 246 247

	// We now need to read the header information
	while ( 1 )
	{
		int i;

		// read a line from the header information.
		rc = http_read_line( peer_handle, mimeBuffer, 100 );
B
bernard.xiong 已提交
248
		rt_kprintf(">> %s\n", mimeBuffer);
B
bernard.xiong 已提交
249 250 251 252

		if ( rc < 0 ) return rc;

		// End of headers is a blank line.  exit.
B
bernard.xiong 已提交
253 254
		if (rc == 0) break;
		if ((rc == 2) && (mimeBuffer[0] == '\r')) break;
B
bernard.xiong 已提交
255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285

		// Convert mimeBuffer to upper case, so we can do string comps
		for(i = 0; i < strlen(mimeBuffer); i++)
			mimeBuffer[i] = toupper(mimeBuffer[i]);

		if(strstr(mimeBuffer, "HTTP/1.")) // First line of header, contains status code. Check for an error code
		{
			rc = http_is_error_header(mimeBuffer);
			if(rc)
			{
				rt_kprintf("HTTP: status code = %d!\n", rc);
				return -rc;
			}
		}

		if(strstr(mimeBuffer, "CONTENT-LENGTH:"))
		{
			session->size = http_parse_content_length(mimeBuffer);
			rt_kprintf("size = %d\n", session->size);
		}
	}

	// We've sent the request, and read the headers.  SockHandle is
	// now at the start of the main data read for a file io read.
	return peer_handle;
}

struct http_session* http_session_open(char* url)
{
	int peer_handle = 0;
	struct sockaddr_in server;
286
	char *request, host_addr[32];
B
bernard.xiong 已提交
287 288
	struct http_session* session;

289
    session = (struct http_session*) rt_malloc(sizeof(struct http_session));
B
bernard.xiong 已提交
290 291 292 293 294 295
	if(session == RT_NULL) return RT_NULL;

	session->size = 0;
	session->position = 0;

	/* Check valid IP address and URL */
296
	if(http_resolve_address(&server, url, &host_addr[0], &request) != 0)
B
bernard.xiong 已提交
297 298 299 300 301 302 303
	{
		rt_free(session);
		return RT_NULL;
	}

	// Now we connect and initiate the transfer by sending a
	// request header to the server, and receiving the response header
304
	if((peer_handle = http_connect(session, &server, host_addr, request)) < 0)
B
bernard.xiong 已提交
305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365
	{
        rt_kprintf("HTTP: failed to connect to '%s'!\n", host_addr);
		rt_free(session);
		return RT_NULL;
	}

	// http connect returns valid socket.  Save in handle list.
	session->socket = peer_handle;

	/* open successfully */
	return session;
}

rt_size_t http_session_read(struct http_session* session, rt_uint8_t *buffer, rt_size_t length)
{
	int bytesRead = 0;
	int totalRead = 0;
	int left = length;

	// Read until: there is an error, we've read "size" bytes or the remote
	//             side has closed the connection.
	do
	{
		bytesRead = recv(session->socket, buffer + totalRead, left, 0);
		if(bytesRead <= 0) break;

		left -= bytesRead;
		totalRead += bytesRead;
	} while(left);

	return totalRead;
}

rt_off_t http_session_seek(struct http_session* session, rt_off_t offset, int mode)
{
	switch(mode)
	{
	case SEEK_SET:
		session->position = offset;
		break;

	case SEEK_CUR:
		session->position += offset;
		break;

	case SEEK_END:
		session->position = session->size + offset;
		break;
	}

	return session->position;
}

int http_session_close(struct http_session* session)
{
   	lwip_close(session->socket);
	rt_free(session);

	return 0;
}

B
bernard.xiong 已提交
366 367 368 369 370 371
//
// This is the main HTTP client connect work.  Makes the connection
// and handles the protocol and reads the return headers.  Needs
// to leave the stream at the start of the real data.
//
static int shoutcast_connect(struct shoutcast_session* session,
372
    struct sockaddr_in* server, char* host_addr, const char* url)
B
bernard.xiong 已提交
373 374 375 376
{
	int socket_handle;
	int peer_handle;
	int rc;
377
	char mimeBuffer[256];
B
bernard.xiong 已提交
378 379 380 381 382 383 384 385 386 387 388 389 390 391 392

	if((socket_handle = socket( PF_INET, SOCK_STREAM, IPPROTO_TCP )) < 0)
	{
		rt_kprintf( "ICY: SOCKET FAILED\n" );
		return -1;
	}

	peer_handle = connect( socket_handle, (struct sockaddr *) server, sizeof(*server));
	if ( peer_handle < 0 )
	{
		rt_kprintf( "ICY: CONNECT FAILED %i\n", peer_handle );
		return -1;
	}

	{
393
		char *buf;
B
bernard.xiong 已提交
394 395 396
		rt_uint32_t length;

		buf = rt_malloc (512);
397 398 399 400
		if (*url)
			length = rt_snprintf(buf, 512, _shoutcast_get, url, host_addr, server->sin_port);
		else
			length = rt_snprintf(buf, 512, _shoutcast_get, "/", host_addr, server->sin_port);
B
bernard.xiong 已提交
401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468

		rc = send(peer_handle, buf, length, 0);
		rt_kprintf("SHOUTCAST request:\n%s", buf);
		
		/* release buffer */
		rt_free(buf);
	}

	/* read the header information */
	while ( 1 )
	{
		// read a line from the header information.
		rc = http_read_line(peer_handle, mimeBuffer, 100);
		rt_kprintf(">>%s", mimeBuffer);

		if ( rc < 0 ) return rc;

		// End of headers is a blank line.  exit.
		if (rc == 0) break;
		if ((rc == 2) && (mimeBuffer[0] == '\r')) break;

		if(strstr(mimeBuffer, "ICY")) // First line of header, contains status code. Check for an error code
		{
			rc = shoutcast_is_error_header(mimeBuffer);
			if(rc)
			{
				rt_kprintf("ICY: status code = %d!\n", rc);
				return -rc;
			}
		}
		
		if (strstr(mimeBuffer, "HTTP/1."))
		{
			rc = http_is_error_header(mimeBuffer);
			if(rc)
			{
				rt_kprintf("HTTP: status code = %d!\n", rc);
				return -rc;
			}
		}

		if (strstr(mimeBuffer, "icy-name:"))
		{
			/* get name */
			char* name;

			name = mimeBuffer + strlen("icy-name:");
			session->station_name = rt_strdup(name);
			rt_kprintf("station name: %s\n", session->station_name);
		}

		if (strstr(mimeBuffer, "icy-br:"))
		{
			/* get bitrate */
			session->bitrate = strtol(mimeBuffer + strlen("icy-br:"), RT_NULL, 10);
			rt_kprintf("bitrate: %d\n", session->bitrate);
		}

		if (strstr(mimeBuffer, "icy-metaint:"))
		{
			/* get metaint */
			session->metaint = strtol(mimeBuffer + strlen("icy-metaint:"), RT_NULL, 10);
			rt_kprintf("metaint: %d\n", session->metaint);
		}
		
		if (strstr(mimeBuffer, "content-type:"))
		{
			/* check content-type */
469
			if (strstr(mimeBuffer, "audio/mpeg") == RT_NULL)
B
bernard.xiong 已提交
470 471 472 473 474 475 476 477 478
			{
				rt_kprintf("ICY content is not audio/mpeg.\n");
				return -1;
			}
		}

		if (strstr(mimeBuffer, "Content-Type:"))
		{
			/* check content-type */
479
			if (strstr(mimeBuffer, "audio/mpeg") == RT_NULL)
B
bernard.xiong 已提交
480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495
			{
				rt_kprintf("ICY content is not audio/mpeg.\n");
				return -1;
			}
		}
	}

	// We've sent the request, and read the headers.  SockHandle is
	// now at the start of the main data read for a file io read.
	return peer_handle;
}

struct shoutcast_session* shoutcast_session_open(char* url)
{
	int peer_handle = 0;
	struct sockaddr_in server;
496
	char *request, host_addr[32];
B
bernard.xiong 已提交
497 498 499 500 501 502 503 504 505 506 507
	struct shoutcast_session* session;

    session = (struct shoutcast_session*) rt_malloc(sizeof(struct shoutcast_session));
	if(session == RT_NULL) return RT_NULL;

	session->metaint = 0;
	session->current_meta_chunk = 0;
	session->bitrate = 0;
	session->station_name = RT_NULL;

	/* Check valid IP address and URL */
508
	if(http_resolve_address(&server, url, &host_addr[0], &request) != 0)
B
bernard.xiong 已提交
509 510 511 512 513 514 515
	{
		rt_free(session);
		return RT_NULL;
	}

	// Now we connect and initiate the transfer by sending a
	// request header to the server, and receiving the response header
516
	if((peer_handle = shoutcast_connect(session, &server, host_addr, request)) < 0)
B
bernard.xiong 已提交
517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
	{
        rt_kprintf("SHOUTCAST: failed to connect to '%s'!\n", host_addr);
		if (session->station_name != RT_NULL)
			rt_free(session->station_name);
		rt_free(session);
		return RT_NULL;
	}

	// http connect returns valid socket.  Save in handle list.
	session->socket = peer_handle;

	/* open successfully */
	return session;
}

rt_size_t shoutcast_session_read(struct shoutcast_session* session, rt_uint8_t *buffer, rt_size_t length)
{
	int bytesRead = 0;
	int totalRead = 0;
	int left = length;
537
	static rt_uint32_t first_meta_size = 0;
B
bernard.xiong 已提交
538 539 540 541 542 543

	// Read until: there is an error, we've read "size" bytes or the remote
	//             side has closed the connection.
	do
	{
		bytesRead = recv(session->socket, buffer + totalRead, left, 0);
544 545 546 547 548 549
		if(bytesRead <= 0) 
		{
			rt_kprintf("no data on recv, len %d,err %d\n", bytesRead, 
				lwip_get_error(session->socket));
			break;
		}
B
bernard.xiong 已提交
550 551 552 553 554 555

		left -= bytesRead;
		totalRead += bytesRead;
	} while(left);

	/* handle meta */
556
	if (first_meta_size > 0)
B
bernard.xiong 已提交
557
	{
558 559
		/* skip meta data */
		memmove(&buffer[0], &buffer[first_meta_size], totalRead - first_meta_size);
B
bernard.xiong 已提交
560

561
		// rt_kprintf("remove meta: len %d\n", first_meta_size);
B
bernard.xiong 已提交
562

563 564 565
		totalRead = totalRead - first_meta_size;
		first_meta_size = 0;
		session->current_meta_chunk = totalRead;
B
bernard.xiong 已提交
566
	}
567
	else
B
bernard.xiong 已提交
568
	{
569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605
		if (session->current_meta_chunk + totalRead == session->metaint)
		{
			rt_uint8_t meta_data;
			recv(session->socket, &meta_data, 1, 0);
		
			/* remove meta data in next packet */
			first_meta_size = meta_data * 16;
			session->current_meta_chunk = 0;

			// rt_kprintf("get meta: len %d\n", first_meta_size);
		}
		else if (session->current_meta_chunk + totalRead > session->metaint)
		{
			int meta_length, next_chunk_length;

			// rt_kprintf("c: %d, total: %d, m: %d\n", session->current_meta_chunk, totalRead, session->metaint);

			/* get the length of meta data */
			meta_length = buffer[session->metaint - session->current_meta_chunk] * 16;
			next_chunk_length = totalRead - (session->metaint - session->current_meta_chunk) - 
				(meta_length + 1);

			// rt_kprintf("l: %d, n: %d\n", meta_length, next_chunk_length);

			/* skip meta data */
			memmove(&buffer[session->metaint - session->current_meta_chunk], 
				&buffer[session->metaint - session->current_meta_chunk + meta_length + 1],
				next_chunk_length);

			/* set new current meta chunk */
			session->current_meta_chunk = next_chunk_length;
			totalRead = totalRead - (meta_length + 1);
		}
		else 
		{
			session->current_meta_chunk += totalRead;
		}
B
bernard.xiong 已提交
606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626
	}

	return totalRead;
}

rt_off_t shoutcast_session_seek(struct shoutcast_session* session, rt_off_t offset, int mode)
{
	/* not support seek yet */
	return 0;
}

int shoutcast_session_close(struct shoutcast_session* session)
{
   	lwip_close(session->socket);
	if (session->station_name != RT_NULL)
		rt_free(session->station_name);
	rt_free(session);

	return 0;
}

B
bernard.xiong 已提交
627 628 629 630
#include <finsh.h>
void http_test(char* url)
{
	struct http_session* session;
B
bernard.xiong 已提交
631
	char buffer[80];
B
bernard.xiong 已提交
632 633 634 635 636 637 638 639 640
	rt_size_t length;

	session = http_session_open(url);
	if (session == RT_NULL)
	{
		rt_kprintf("open http session failed\n");
		return;
	}

641
	do
B
bernard.xiong 已提交
642 643
	{
		rt_memset(buffer, 0, sizeof(buffer));
644
		length = http_session_read(session, (rt_uint8_t*)buffer, sizeof(buffer));
B
bernard.xiong 已提交
645

B
bernard.xiong 已提交
646
		rt_kprintf(buffer);rt_kprintf("\n");
B
bernard.xiong 已提交
647 648 649 650 651
	} while (length > 0);

	http_session_close(session);
}
FINSH_FUNCTION_EXPORT(http_test, http client test);
B
bernard.xiong 已提交
652 653 654 655 656 657 658 659 660 661 662 663 664 665 666

void shoutcast_test(char* url)
{
	struct shoutcast_session* session;

	session = shoutcast_session_open(url);
	if (session == RT_NULL)
	{
		rt_kprintf("open shoutcast session failed\n");
		return;
	}

	shoutcast_session_close(session);
}
FINSH_FUNCTION_EXPORT(shoutcast_test, shoutcast client test);
667