5f4b4f2352282bd78341b6cc2da8f5a7bc7f00f3
[quix0rs-apt-p2p.git] / apt_dht / HTTPServer.py
1
2 from urllib import unquote_plus
3
4 from twisted.python import log
5 from twisted.internet import defer
6 from twisted.web2 import server, http, resource, channel
7 from twisted.web2 import static, http_headers, responsecode
8
9 class FileDownloader(static.File):
10     
11     def __init__(self, path, manager, defaultType="text/plain", ignoredExts=(), processors=None, indexNames=None):
12         self.manager = manager
13         super(FileDownloader, self).__init__(path, defaultType, ignoredExts, processors, indexNames)
14         
15     def renderHTTP(self, req):
16         log.msg('Got request for %s from %s' % (req.uri, req.remoteAddr))
17         resp = super(FileDownloader, self).renderHTTP(req)
18         if isinstance(resp, defer.Deferred):
19             resp.addCallback(self._renderHTTP_done, req)
20         else:
21             resp = self._renderHTTP_done(resp, req)
22         return resp
23         
24     def _renderHTTP_done(self, resp, req):
25         log.msg('Initial response to %s: %r' % (req.uri, resp))
26         
27         if self.manager:
28             path = 'http:/' + req.uri
29             if resp.code >= 200 and resp.code < 400:
30                 return self.manager.check_freshness(req, path, resp.headers.getHeader('Last-Modified'), resp)
31             
32             log.msg('Not found, trying other methods for %s' % req.uri)
33             return self.manager.get_resp(req, path)
34         
35         return resp
36
37     def createSimilarFile(self, path):
38         return self.__class__(path, self.manager, self.defaultType, self.ignoredExts,
39                               self.processors, self.indexNames[:])
40         
41         
42 class TopLevel(resource.Resource):
43     addSlash = True
44     
45     def __init__(self, directory, db, manager):
46         self.directory = directory
47         self.db = db
48         self.manager = manager
49         self.factory = None
50
51     def getHTTPFactory(self):
52         if self.factory is None:
53             self.factory = channel.HTTPFactory(server.Site(self),
54                                                **{'maxPipeline': 10, 
55                                                   'betweenRequestsTimeOut': 60})
56         return self.factory
57
58     def render(self, ctx):
59         return http.Response(
60             200,
61             {'content-type': http_headers.MimeType('text', 'html')},
62             """<html><body>
63             <h2>Statistics</h2>
64             <p>TODO: eventually some stats will be shown here.</body></html>""")
65
66     def locateChild(self, request, segments):
67         log.msg('Got HTTP request for %s from %s' % (request.uri, request.remoteAddr))
68         name = segments[0]
69         if name == '~':
70             if len(segments) != 2:
71                 log.msg('Got a malformed request from %s' % request.remoteAddr)
72                 return None, ()
73             hash = unquote_plus(segments[1])
74             files = self.db.lookupHash(hash)
75             if files:
76                 log.msg('Sharing %s with %s' % (files[0]['path'].path, request.remoteAddr))
77                 return static.File(files[0]['path'].path), ()
78             else:
79                 log.msg('Hash could not be found in database: %s' % hash)
80         
81         if request.remoteAddr.host != "127.0.0.1":
82             log.msg('Blocked illegal access to %s from %s' % (request.uri, request.remoteAddr))
83             return None, ()
84             
85         if len(name) > 1:
86             return FileDownloader(self.directory.path, self.manager), segments[0:]
87         else:
88             return self, ()
89         
90         log.msg('Got a malformed request for "%s" from %s' % (request.uri, request.remoteAddr))
91         return None, ()
92
93 if __name__ == '__builtin__':
94     # Running from twistd -y
95     t = TopLevel('/home', None)
96     t.setDirectories({'~1': '/tmp', '~2': '/var/log'})
97     factory = t.getHTTPFactory()
98     
99     # Standard twisted application Boilerplate
100     from twisted.application import service, strports
101     application = service.Application("demoserver")
102     s = strports.service('tcp:18080', factory)
103     s.setServiceParent(application)