Skip to main content Link Menu Expand (external link) Document Search Copy Copied

Proxy

Implement handle_proxy_request to proxy HTTP requests to another HTTP server. We’ve already handled the connection setup code for you. You should read and understand it, but you don’t need to modify it.

Here’s what is already implemented.

  • We use the value of the --proxy command line argument, which contains the address and port number of the upstream HTTP server. These two values are stored in the global variables server_proxy_hostname and server_proxy_port.
  • We do a DNS lookup of the server proxy hostname, which will look up the IP address of the hostname (check out gethostbyname)).
  • We create a network socket and connect it to the IP address that we get from DNS. Check out socket and connect.
  • htons is used to set the socket’s port number (integers in memory on x86 are little-endian, whereas network stuff expects big-endian). Also note that HTTP is a SOCK_STREAM protocol.

Here’s what you need to take care of.

  • Wait for new data on both sockets (the HTTP client fd, and the target HTTP server fd). When data arrives, you should immediately read it to a buffer and then write it to the other socket. You are essentially maintaining 2-way communication between the HTTP client and the target HTTP server. Your proxy must support multiple requests/responses.
    • This is more tricky than writing to a file or reading from stdin, since you do not know which side of the 2-way stream will write data first, or whether they will write more data after receiving a response. In proxy mode, you will find that multiple HTTP requests/responses are sent within the same connection, unlike your HTTP server which only needs to support one request/response per connection.
    • You should use pthreads for this task. Consider using two threads to facilitate the two-way communication, one from A to B and the other from B to A.
    • Do not use select, fcntl, or the like. We used to recommend this approach in previous semesters, but we’ve found this method to be too confusing.
  • If either of the sockets closes, communication cannot continue, so you should close both sockets to terminate the connection.

After finishing this part, all Proxy tests should pass on the autograder.