$28
1 Introduction
A Web proxy is a program that acts as a middleman between a Web browser and an end server. Instead of contacting the end server directly to get a Web page, the browser contacts the proxy, which forwards the request on to the end server. When the end server replies to the proxy, the proxy sends the reply on to the browser. Proxies are useful for many purposes. Sometimes proxies are used in firewalls, so that browsers behind a firewall can only contact a server beyond the firewall via the proxy. Proxies can also act as anonymizers: by stripping requests of all identifying information, a proxy can make the browser anonymous to Web servers. Proxies can even be used to cache web objects by storing local copies of objects from servers then responding to future requests by reading them out of its cache rather than by communicating again with remote servers. Inthislab,youwillwriteasimpleHTTPproxythatcacheswebobjects. Forthefirstpartofthelab,youwill set up the proxy to accept incoming connections, read and parse requests, forward requests to web servers, read the servers’ responses, and forward those responses to the corresponding clients. This first part will involve learning about basic HTTP operation and how to use sockets to write programs that communicate overnetworkconnections. Inthesecondpart,youwillupgradeyourproxytodealwithmultipleconcurrent connections. This will introduce you to dealing with concurrency, a crucial systems concept. In the third and last part, you will add caching to your proxy using a simple main memory cache of recently accessed web content.
2 Logistics
This is an individual project.
1
3 Handoutinstructions
SITE-SPECIFIC:Insertaparagraphherethatexplainshowtheinstructorwillhandout the proxylab-handout.tar filetothestudents.
Copy the handout file to a protected directory on the Linux machine where you plan to do your work, and then issue the following command:
linux tar xvf proxylab-handout.tar
This will generate a handout directory called proxylab-handout. The README file describes the various files.
4 PartI:Implementingasequentialwebproxy
ThefirststepisimplementingabasicsequentialproxythathandlesHTTP/1.0GETrequests. Otherrequests type, such as POST, are strictly optional. When started, your proxy should listen for incoming connections on a port whose number will be specified on the command line. Once a connection is established, your proxy should read the entirety of the request from the client and parse the request. It should determine whether the client has sent a valid HTTP request; ifso,itcanthenestablishitsownconnectiontotheappropriatewebserverthenrequesttheobjecttheclient specified. Finally, your proxy should read the server’s response and forward it to the client.
4.1 HTTP/1.0GETrequests
When an end user enters a URL such as http://www.cmu.edu/hub/index.html into the address bar of a web browser, the browser will send anHTTP request to the proxy that begins with aline that might resemble the following:
GET http://www.cmu.edu/hub/index.html HTTP/1.1
Inthatcase,theproxyshouldparsetherequestintoatleastthefollowingfields: thehostname,www.cmu.edu; and the path or query and everything following it, /hub/index.html. That way, the proxy can determinethatitshouldopenaconnectionto www.cmu.edu andsendanHTTPrequestofitsownstartingwith a line of the following form:
GET /hub/index.html HTTP/1.0
NotethatalllinesinanHTTPrequestendwithacarriagereturn, ‘\r’,followedbyanewline, ‘\n’. Also important is that every HTTP request is terminated by an empty line: "\r\n".
2
You should notice in the above example that the web browser’s request line ends with HTTP/1.1, while theproxy’srequestlineendswith HTTP/1.0. ModernwebbrowserswillgenerateHTTP/1.1requests,but your proxy should handle them and forward them as HTTP/1.0 requests. It is important to consider that HTTP requests, even just the subset of HTTP/1.0 GET requests, can be incredibly complicated. The textbook describes certain details of HTTP transactions, but you should refer to RFC 1945 for the complete HTTP/1.0 specification. Ideally your HTTP request parser will be fully robust according to the relevant sections of RFC 1945, except for one detail: while the specification allows for multiline request fields, your proxy is not required to properly handle them. Of course, your proxy should never prematurely abort due to a malformed request.
4.2 Requestheaders
TheimportantrequestheadersforthislabaretheHost,User-Agent,Connection,andProxy-Connection headers:
• Always send a Host header. While this behavior is technically not sanctioned by the HTTP/1.0 specification, it is necessary to coax sensible responses out of certain Web servers, especially those that use virtual hosting. The Host header describes the hostname of the end server. For example, to access http://www. cmu.edu/hub/index.html, your proxy would send the following header:
Host: www.cmu.edu
It is possible that web browsers will attach their own Host headers to their HTTP requests. If that is the case, your proxy should use the same Host header as the browser. • You may choose to always send the following User-Agent header:
User-Agent: Mozilla/5.0 (X11; Linux x86_64; rv:10.0.3) Gecko/20120305 Firefox/10.0.3
The header is provided on two separate lines because it does not fit as a single line in the writeup, but your proxy should send the header as a single line. The User-Agent header identifies the client (in terms of parameters such as the operating system and browser), and web servers often use the identifying information to manipulate the content they serve. Sending this particular User-Agent: string may improve, in content and diversity, the material that you get back during simple telnet-style testing. • Always send the following Connection header:
Connection: close
• Always send the following Proxy-Connection header:
3
Proxy-Connection: close
The Connection and Proxy-Connection headers are used to specify whether a connection will be kept alive after the first request/response exchange is completed. It is perfectly acceptable (and suggested) to have your proxy open a new connection for each request. Specifying close as the value of these headers alerts web servers that your proxy intends to close connections after the first request/response exchange.
For your convenience, the values of the described User-Agent header is provided to you as a string constant in proxy.c. Finally, if a browser sends any additional request headers as part of an HTTP request, your proxy should forward them unchanged.
4.3 Portnumbers
Therearetwosignificantclassesofportnumbersforthislab: HTTPrequestportsandyourproxy’slistening port. The HTTP request port is an optional field in the URL of an HTTP request. That is, the URL may be of the form, http://www.cmu.edu:8080/hub/index.html, in which case your proxy should connect to the host www.cmu.edu on port 8080 instead of the default HTTP port, which is port 80. Your proxy must properly function whether or not the port number is included in the URL. The listening port is the port on which your proxy should listen for incoming connections. Your proxy should accept a command line argument specifying the listening port number for your proxy. For example, with the following command, your proxy should listen for connections on port 15213:
linux ./proxy 15213
You may select any non-privileged listening port (greater than 1,024 and less than 65,536) as long as it is not used by other processes. Since each proxy must use a unique listening port and many people will simultaneously be working on each machine, the script port-for-user.pl is provided to help you pick your own personal port number. Use it to generate port number based on your user ID:
linux ./port-for-user.pl droh droh: 45806
The port, p, returned by port-for-user.pl is always an even number. So if you need an additional port number, say for the Tiny server, you can safely use ports p and p + 1. Please don’t pick your own random port. If you do, you run the risk of interfering with another user.
4
5 PartII:Dealingwithmultipleconcurrentrequests
Once you have a working sequential proxy, you should alter it to simultaneously handle multiple requests. Thesimplestwaytoimplementaconcurrentserveristospawnanewthreadtohandleeachnewconnection request. Other designs are also possible, such as the prethreaded server described in Section 12.5.5 of your textbook.
• Note that your threads should run in detached mode to avoid memory leaks. • The open clientfd and open listenfd functions described in the CS:APP3e textbook are based on the modern and protocol-independent getaddrinfo function, and thus are thread safe.
6 PartIII:Cachingwebobjects
For the final part of the lab, you will add a cache to your proxy that stores recently-used Web objects in memory. HTTP actually defines a fairly complex model by which web servers can give instructions as to how the objects they serve should be cached and clients can specify how caches should be used on their behalf. However, your proxy will adopt a simplified approach. Whenyourproxyreceivesawebobjectfromaserver,itshouldcacheitinmemoryasittransmitstheobject totheclient. Ifanotherclientrequeststhesameobjectfromthesameserver, yourproxyneednotreconnect to the server; it can simply resend the cached object. Obviously, if your proxy were to cache every object that is ever requested, it would require an unlimited amount of memory. Moreover, because some web objects are larger than others, it might be the case that one giant object will consume the entire cache, preventing other objects from being cached at all. To avoid those problems, your proxy should have both a maximum cache size and a maximum cache object size.
6.1 Maximumcachesize
The entirety of your proxy’s cache should have the following maximum size:
MAX_CACHE_SIZE = 1 MiB
Whencalculatingthesizeofitscache,yourproxymustonlycountbytesusedtostoretheactualwebobjects; any extraneous bytes, including metadata, should be ignored.
6.2 Maximumobjectsize
Your proxy should only cache web objects that do not exceed the following maximum size:
MAX_OBJECT_SIZE = 100 KiB
5
For your convenience, both size limits are provided as macros in proxy.c. The easiest way to implement a correct cache is to allocate a buffer for each active connection and accumulatedataasitisreceivedfromtheserver. Ifthesizeofthebuffereverexceedsthemaximumobjectsize,the buffer can be discarded. If the entirety of the web server’s response is read before the maximum object size is exceeded, then the object can be cached. Using this scheme, the maximum amount of data your proxy will ever use for web objects is the following, where T is the maximum number of active connections:
MAX_CACHE_SIZE + T * MAX_OBJECT_SIZE
6.3 Evictionpolicy
Yourproxy’scacheshouldemployanevictionpolicythatapproximatesaleast-recently-used(LRU)eviction policy. It doesn’t have to be strictly LRU, but it should be something reasonably close. Note that both reading an object and writing it count as using the object.
6.4 Synchronization
Accesses to the cache must be thread-safe, and ensuring that cache access is free of race conditions will likelybethemoreinterestingaspectofthispartofthelab. Asamatteroffact,thereisaspecialrequirement thatmultiplethreadsmustbeabletosimultaneouslyreadfromthecache. Ofcourse,onlyonethreadshould be permitted to write to the cache at a time, but that restriction must not exist for readers. As such, protecting accesses to the cache with one large exclusive lock is not an acceptable solution. You may want to explore options such as partitioning the cache, using Pthreads readers-writers locks, or using semaphores to implement your own readers-writers solution. In either case, the fact that you don’t have to implement a strictly LRU eviction policy will give you some flexibility in supporting multiple readers.
7 Evaluation
This assignment will be graded out of a total of 70 points: • BasicCorrectness: 40 points for basic proxy operation (autograded) • Concurrency: 15 points for handling concurrent requests (autograded) • Cache: 15 points for a working cache (autograded)
7.1 Autograding
Your handout materials include an autograder, called driver.sh, that your instructor will use to assign scores for BasicCorrectness, Concurrency, and Cache. From the proxylab-handout directory:
linux ./driver.sh
6
You must run the driver on a Linux machine.
7.2 Robustness
As always, you must deliver a program that is robust to errors and even malformed or malicious input. Servers are typically long-running processes, and web proxies are no exception. Think carefully about how long-running processes should react to different types of errors. For many kinds of errors, it is certainly inappropriate for your proxy to immediately exit. Robustness implies other requirements as well, including invulnerability to error cases like segmentation faults and a lack of memory leaks and file descriptor leaks.
8 Testinganddebugging
Besides the simple autograder, you will not have any sample inputs or a test program to test your implementation. Youwillhavetocomeupwithyourowntestsandperhapsevenyourowntestingharnesstohelp youdebugyourcodeanddecidewhenyouhaveacorrectimplementation. Thisisavaluableskillinthereal world, where exact operating conditions are rarely known and reference solutions are often unavailable. Fortunatelytherearemanytoolsyoucanusetodebugandtestyourproxy. Besuretoexerciseallcodepaths and test a representative set of inputs, including base cases, typical cases, and edge cases.
8.1 Tinywebserver
YourhandoutdirectorythesourcecodefortheCS:APPTinywebserver. Whilenotaspowerfulasthttpd, the CS:APP Tiny web server will be easy for you to modify as you see fit. It’s also a reasonable starting point for your proxy code. And it’s the server that the driver code uses to fetch pages.
8.2 telnet
As described in your textbook (11.5.3), you can use telnet to open a connection to your proxy and send it HTTP requests.
8.3 curl
You can use curl to generate HTTP requests to any server, including your own proxy. It is an extremely useful debugging tool. For example, if your proxy and Tiny are both running on the local machine, Tiny is listening on port 15213, and proxy is listening on port 15214, then you can request a page from Tiny via your proxy using the following curl command:
linux curl -v --proxy http://localhost:15214 http://localhost:15213/home.html * About to connect() to proxy localhost port 15214 (#0) * Trying 127.0.0.1... connected
7
* Connected to localhost (127.0.0.1) port 15214 (#0) GET http://localhost:15213/home.html HTTP/1.1 User-Agent: curl/7.19.7 (x86_64-redhat-linux-gnu)... Host: localhost:15213 Accept: */* Proxy-Connection: Keep-Alive * HTTP 1.0, assume close after body < HTTP/1.0 200 OK < Server: Tiny Web Server < Content-length: 120 < Content-type: text/html < <html <head<titletest</title</head <body <img align="middle" src="godzilla.gif" Dave O’Hallaron </body </html * Closing connection #0
8.4 netcat
netcat, also known as nc, is a versatile network utility. You can use netcat just like telnet, to open connections to servers. Hence, imagining that your proxy were running on catshark using port 12345 you can do something like the following to manually test your proxy:
sh nc catshark.ics.cs.cmu.edu 12345 GET http://www.cmu.edu/hub/index.html HTTP/1.0
HTTP/1.1 200 OK ...
In addition to being able to connect to Web servers, netcat can also operate as a server itself. With the following command, you can run netcat as a server listening on port 12345:
sh nc -l 12345
Once you have set up a netcat server, you can generate a request to a phony object on it through your proxy, and you will be able to inspect the exact request that your proxy sent to netcat.
8.5 Webbrowsers
EventuallyyoushouldtestyourproxyusingthemostrecentversionofMozillaFirefox. VisitingAbout Firefox will automatically update your browser to the most recent version.
8
To configure Firefox to work with a proxy, visit
PreferencesAdvancedNetworkSettings
ItwillbeveryexcitingtoseeyourproxyworkingthrougharealWebbrowser. Althoughthefunctionalityof yourproxywillbelimited,youwillnoticethatyouareabletobrowsethevastmajorityofwebsitesthrough your proxy. AnimportantcaveatisthatyoumustbeverycarefulwhentestingcachingusingaWebbrowser. Allmodern Web browsers have caches of their own, which you should disable before attempting to test your proxy’s cache.
9 Handininstructions
The provided Makefile includes functionality to build your final handin file. Issue the following command from your working directory:
linux make handin
The output is the file ../proxylab-handin.tar, which you can then handin.
SITE-SPECIFIC: Insert a paragraph here that tells each student how to hand in their proxylab-handin.tar solutionfile.
• Chapters 10-12 of the textbook contains useful information on system-level I/O, network programming, HTTP protocols, and concurrent programming. • RFC1945(http://www.ietf.org/rfc/rfc1945.txt)isthecompletespecificationforthe HTTP/1.0 protocol.
10 Hints • As discussed in Section 10.11 of your textbook, using standard I/O functions for socket input and output is a problem. Instead, we recommend that you use the Robust I/O (RIO) package, which is provided in the csapp.c file in the handout directory. • The error-handling functions provide in csapp.c are not appropriate for your proxy because once a server begins accepting connections, it is not supposed to terminate. You’ll need to modify them or write your own. • You are free to modify the files in the handout directory any way you like. For example, for the sake of good modularity, you might implement your cache functions as a library in files called cache.c and cache.h. Of course, adding new files will require you to update the provided Makefile.
9
• AsdiscussedintheAsideonpage964oftheCS:APP3etext,yourproxymustignoreSIGPIPEsignals and should deal gracefully with write operations that return EPIPE errors. • Sometimes, calling read to receive bytes from a socket that has been prematurely closed will cause read to return -1 with errno set to ECONNRESET. Your proxy should not terminate due to this error either. • Remember that not all content on the web is ASCII text. Much of the content on the web is binary data, such as images and video. Ensure that you account for binary data when selecting and using functions for network I/O. • Forward all requests as HTTP/1.0 even if the original request was HTTP/1.1.
Good luck!