My blog has been moved to

Monday, April 05, 2010

simple http proxy server in 100 lines

I guess a simple proxy server should have been an example in Qt Network module. What I mean of course a real proxy server based on Qt, not about using a proxy server via QNetworkProxy class. After all, there are other more complex examples like the torrent client and Google suggest (yeah, blame me for the latter). As a matter of fact, there are e.g. a gazillion proxy servers written in Python.

Look no more. I posted an example in the X2 repository, under the directory network/webproxy. The code is written for clarity and not for performance. In fact, fancy error handling is even omitted (minimalism rulez!). There is no support for pipelining, or in-memory cache, or per-connection thread, or even secure connection via https. I leave them as exercises for the curious readers.

If we focus on things which work, here they are: asynchronous socket handling, different request methods (GET/PUT/POST/HEAD), persistent connection aka keep alive, and even Flash and HTML 5 video streaming. Yes, you can still watch YouTube or Vimeo if you hook your browser into this little proxy. For a few hours of hacking and 92 lines of code (as reported by sloccount) and certain ways to abuse QObject, I could not be more happier.

There will be two other offspring examples based on this one. So stay tuned. Meanwhile let's just hope nobody would ask me for a colorful UML diagram for this snippet...

PS: Special thanks to Jan Erik for his feedback and review.


milot said...
This comment has been removed by the author.
Unknown said...

Thanks for example - some features was considerable.
Few questions:
1) is it possible, that first line in request headers from client will be so long (4000+ bytes with long url), that readAll in WebProxy::processQuery() will return string without "\r\n"?
2) Is that possible/dangerous: POST request from client with long body will call WebProxy::processQuery() more than once, because readyRead will be emited more than once?

Unknown said...

So questions are because I didn't tested this proxy code, and can't be sure what is more correct - proxy code or my assumptions.