Reputation: 37068
I'm on the last major hurdle of writing a basic proxy server in C.
I've got my server successfully receiving requests from the browser, then successfully sending them to the host, wherever they are. And I'm successfully receiving responses from the host! Except, here's what I get when I try to connect to Google through the server:
Rcvd message from server:
----
HTTP/1.1 200 OK
Date: Thu, 15 Mar 2012 20:35:11 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Set-Cookie: PREF=ID=83a7c2e6675a9a9f:FF=0:TM=1331843711:LM=1331843711:S=7I7RIVV1B-HxhWJR; expires=Sat, 15-Mar-2014 20:35:11 GMT; path=/; domain=.google.com
Set-Cookie: NID=57=KvqnXtYNkJZBryXL5zzhG5eH8Or2_PDWDqT_kU35PvOro_mAFiLiTSjPHOnWWxxm3R0vKYnzEeVkAPFKK366lZiNZGpjhO2-II5OeZQnWe09H-jZdePsrN-SnBdQ2ENT; expires=Fri, 14-Sep-2012 20:35:11 GMT; path=/; domain=.google.com; HttpOnly
P3P: CP="This is not a P3P policy! See http://www.google.com/support/accounts/bin/answer.py?hl=en&answer=151657 for more info."
Server: gws
X-XSS-Protection: 1; mode=block
X-Frame-Options: SAMEORIGIN
Transfer-Encoding: chunked
1000
<!doctype html><html itemscope itemtype="http://schema.org/WebPage"><head><meta http-equiv="content-type" content="text/html; charset=UTF-8"><meta name="description" content="Search the world's information, including webpages, images, videos and more. Goo
you see how it cuts off? Because of "Transfer-Encoding: chunked". Now how do I get the server to continue sending me the rest of the chunks? Because after that first one, it stops. Do I need to put read() inside a while loop, and say to continue reading and forwarding to the client as long as there's something to read?
EDIT:
Okay, here is my present code. This makes one initial read of the server's response (on socket named "sock"), writes it to the client ("newsock"), then enters a while loop to continue reading more server responses and sending them to the client. i have not tested this form of the code just yet. do you see any blatant problems besides some error-checking gaps?
/*WRITING SERVER RESPONSE TO CLIENT*/
char buffer2[1024];
n = read(sock, buffer2, 1024 );
if ( n < 1 )
{
perror( "read() failed" );
return EXIT_FAILURE;
}
else
{
buffer2[n] = '\0';
printf( "Rcvd message from server: \n\n----\n\n%s\n\n----\n\n", buffer2 );
}
n = write( newsock, buffer2, strlen( buffer2 ) );
while((n = read(sock, buffer2, 1024 )) >= 1)
{
buffer2[n] = '\0';
printf( "Rcvd message from server: \n\n----\n\n%s\n\n----\n\n", buffer2 );
n = write( newsock, buffer2, strlen( buffer2 ) );
}
Upvotes: 2
Views: 2541
Reputation: 186
You can't use strlen to get the size of your buffer, strlen is only for getting the size of a string, you're probably reading some binary data, because there is not only text going through your proxy (images...). Try using instead the value returned by read, which is the number of bytes actually read.
And ending your string by '\n' becomes useless.
Upvotes: 1