I need to build an HTTP Proxy Server that handle GET method.
I am able to establish an connection from Client(web brownser) to Proxy Server and Proxy is Sending Reformatted header to Server and retrieve the reponse.
But the proxy is not receiving entire data.
My code is as follows:
main(int argc,char **argv)
{
//Server binds to particular port
//Waiting for connection");
for(;;)
{
//Connect to client
handle_connection(connfd,&cli_addr);
close(connfd);
}
}
void handle_connection(int connfd, struct sockaddr_in *cli_addr)
{
struct sockaddr_in host_addr;
char buffer[BUFFSIZE];
int rfd,n;
char** http_args;
url* requested_url;
struct hostent *hp;
bzero(buffer, BUFFSIZE);
if ((rfd = read(connfd,buffer,BUFFSIZE)) < 0 ) {
perror("Error reading from socket.");
return;
}
buffer[rfd]='\0';
split_line( (char*)buffer, (char**)http_args,2);
requested_url = parse_request(http_args[1]);
//Printing
printf("\nCommand: %s\n", http_args[0]);
printf("Url: %s\n", http_args[1]);
printf("proto: %d\n",requested_url->proto);
printf("port: %d\n",requested_url->port);
printf("host: %s\n",requested_url->host);
printf("File: %s\n",requested_url->file);
if((strcmp(http_args[0],"GET"))!=0)
{
printf("here");
http_error_messages(connfd, http_args[0], 501, "Not Implemented","Proxy does not implement this method");
return;
}
//Connection to request made to server on rfd
sprintf(buffer, "%s %s HTTP/1.%d\r\nHost: %s:80\r\n\r\n"
, http_args[0], requested_url->file, requested_url->proto, requested_url->host);
printf("In the Server %s",buffer);
//printf("In the Server %s",get_header);
n = write(rfd,buffer,sizeof(buffer));
shutdown(rfd,2);
char buff[MAXLINE];
while((n = read(rfd, buff, MAXLINE)) > 0) {
write(connfd, buff, MAXLINE);
printf("%s",buff);
}
if(n<0)
{
perror("Error in reading");
}
shutdown(rfd,1);
shutdown(connfd,2);
close(rfd);
}
On TCP sockets you’ll need to call
read()repeatedly until the expected terminating character (\n?) is read, or the required number of bytes has been read.read()can return partial or no data, depending on how TCP packets get segmented/buffered/messed with.