Make downloaded files accessible via the HTTP server.
[quix0rs-apt-p2p.git] / apt_dht / MirrorManager.py
1
2 from bz2 import BZ2Decompressor
3 from zlib import decompressobj, MAX_WBITS
4 from gzip import FCOMMENT, FEXTRA, FHCRC, FNAME, FTEXT
5 from urlparse import urlparse
6 import os
7
8 from twisted.python import log, filepath
9 from twisted.internet import defer
10 from twisted.trial import unittest
11 from twisted.web2 import stream
12 from twisted.web2.http import splitHostPort
13
14 from AptPackages import AptPackages
15
16 aptpkg_dir='.apt-dht'
17
18 DECOMPRESS_EXTS = ['.gz', '.bz2']
19 DECOMPRESS_FILES = ['release', 'sources', 'packages']
20
21 class MirrorError(Exception):
22     """Exception raised when there's a problem with the mirror."""
23
24 class ProxyFileStream(stream.SimpleStream):
25     """Saves a stream to a file while providing a new stream."""
26     
27     def __init__(self, stream, outFile, hash, decompress = None, decFile = None):
28         """Initializes the proxy.
29         
30         @type stream: C{twisted.web2.stream.IByteStream}
31         @param stream: the input stream to read from
32         @type outFile: C{twisted.python.filepath.FilePath}
33         @param outFile: the file to write to
34         @type hash: L{Hash.HashObject}
35         @param hash: the hash object to use for the file
36         @type decompress: C{string}
37         @param decompress: also decompress the file as this type
38             (currently only '.gz' and '.bz2' are supported)
39         @type decFile: C{twisted.python.filepath.FilePath}
40         @param decFile: the file to write the decompressed data to
41         """
42         self.stream = stream
43         self.outFile = outFile.open('w')
44         self.hash = hash
45         self.hash.new()
46         self.gzfile = None
47         self.bz2file = None
48         if decompress == ".gz":
49             self.gzheader = True
50             self.gzfile = decFile.open('w')
51             self.gzdec = decompressobj(-MAX_WBITS)
52         elif decompress == ".bz2":
53             self.bz2file = decFile.open('w')
54             self.bz2dec = BZ2Decompressor()
55         self.length = self.stream.length
56         self.start = 0
57         self.doneDefer = defer.Deferred()
58
59     def _done(self):
60         """Close the output file."""
61         if not self.outFile.closed:
62             self.outFile.close()
63             self.hash.digest()
64             if self.gzfile:
65                 data_dec = self.gzdec.flush()
66                 self.gzfile.write(data_dec)
67                 self.gzfile.close()
68                 self.gzfile = None
69             if self.bz2file:
70                 self.bz2file.close()
71                 self.bz2file = None
72                 
73             self.doneDefer.callback(self.hash)
74     
75     def read(self):
76         """Read some data from the stream."""
77         if self.outFile.closed:
78             return None
79         
80         data = self.stream.read()
81         if isinstance(data, defer.Deferred):
82             data.addCallbacks(self._write, self._done)
83             return data
84         
85         self._write(data)
86         return data
87     
88     def _write(self, data):
89         """Write the stream data to the file and return it for others to use."""
90         if data is None:
91             self._done()
92             return data
93         
94         self.outFile.write(data)
95         self.hash.update(data)
96         if self.gzfile:
97             if self.gzheader:
98                 self.gzheader = False
99                 new_data = self._remove_gzip_header(data)
100                 dec_data = self.gzdec.decompress(new_data)
101             else:
102                 dec_data = self.gzdec.decompress(data)
103             self.gzfile.write(dec_data)
104         if self.bz2file:
105             dec_data = self.bz2dec.decompress(data)
106             self.bz2file.write(dec_data)
107         return data
108     
109     def _remove_gzip_header(self, data):
110         if data[:2] != '\037\213':
111             raise IOError, 'Not a gzipped file'
112         if ord(data[2]) != 8:
113             raise IOError, 'Unknown compression method'
114         flag = ord(data[3])
115         # modtime = self.fileobj.read(4)
116         # extraflag = self.fileobj.read(1)
117         # os = self.fileobj.read(1)
118
119         skip = 10
120         if flag & FEXTRA:
121             # Read & discard the extra field, if present
122             xlen = ord(data[10])
123             xlen = xlen + 256*ord(data[11])
124             skip = skip + 2 + xlen
125         if flag & FNAME:
126             # Read and discard a null-terminated string containing the filename
127             while True:
128                 if not data[skip] or data[skip] == '\000':
129                     break
130                 skip += 1
131             skip += 1
132         if flag & FCOMMENT:
133             # Read and discard a null-terminated string containing a comment
134             while True:
135                 if not data[skip] or data[skip] == '\000':
136                     break
137                 skip += 1
138             skip += 1
139         if flag & FHCRC:
140             skip += 2     # Read & discard the 16-bit header CRC
141         return data[skip:]
142
143     def close(self):
144         """Clean everything up and return None to future reads."""
145         self.length = 0
146         self._done()
147         self.stream.close()
148
149 class MirrorManager:
150     """Manages all requests for mirror objects."""
151     
152     def __init__(self, manager, cache_dir):
153         self.manager = manager
154         self.cache_dir = cache_dir
155         self.cache = filepath.FilePath(self.cache_dir)
156         self.apt_caches = {}
157     
158     def extractPath(self, url):
159         parsed = urlparse(url)
160         host, port = splitHostPort(parsed[0], parsed[1])
161         site = host + ":" + str(port)
162         path = parsed[2]
163             
164         i = max(path.rfind('/dists/'), path.rfind('/pool/'))
165         if i >= 0:
166             baseDir = path[:i]
167             path = path[i:]
168         else:
169             # Uh oh, this is not good
170             log.msg("Couldn't find a good base directory for path: %s" % (site + path))
171             baseDir = ''
172             if site in self.apt_caches:
173                 longest_match = 0
174                 for base in self.apt_caches[site]:
175                     base_match = ''
176                     for dirs in path.split('/'):
177                         if base.startswith(base_match + '/' + dirs):
178                             base_match += '/' + dirs
179                         else:
180                             break
181                     if len(base_match) > longest_match:
182                         longest_match = len(base_match)
183                         baseDir = base_match
184             log.msg("Settled on baseDir: %s" % baseDir)
185         
186         return site, baseDir, path
187         
188     def init(self, site, baseDir):
189         if site not in self.apt_caches:
190             self.apt_caches[site] = {}
191             
192         if baseDir not in self.apt_caches[site]:
193             site_cache = os.path.join(self.cache_dir, aptpkg_dir, 'mirrors', site + baseDir.replace('/', '_'))
194             self.apt_caches[site][baseDir] = AptPackages(site_cache)
195     
196     def updatedFile(self, url, file_path):
197         site, baseDir, path = self.extractPath(url)
198         self.init(site, baseDir)
199         self.apt_caches[site][baseDir].file_updated(path, file_path)
200
201     def findHash(self, url):
202         site, baseDir, path = self.extractPath(url)
203         if site in self.apt_caches and baseDir in self.apt_caches[site]:
204             return self.apt_caches[site][baseDir].findHash(path)
205         d = defer.Deferred()
206         d.errback(MirrorError("Site Not Found"))
207         return d
208     
209     def save_file(self, response, hash, url):
210         """Save a downloaded file to the cache and stream it."""
211         log.msg('Returning file: %s' % url)
212         
213         parsed = urlparse(url)
214         destFile = self.cache.preauthChild(parsed[1] + parsed[2])
215         log.msg('Saving returned %r byte file to cache: %s' % (response.stream.length, destFile.path))
216         
217         if destFile.exists():
218             log.msg('File already exists, removing: %s' % destFile.path)
219             destFile.remove()
220         else:
221             destFile.parent().makedirs()
222             
223         root, ext = os.path.splitext(destFile.basename())
224         if root.lower() in DECOMPRESS_FILES and ext.lower() in DECOMPRESS_EXTS:
225             ext = ext.lower()
226             decFile = destFile.sibling(root)
227             log.msg('Decompressing to: %s' % decFile.path)
228             if decFile.exists():
229                 log.msg('File already exists, removing: %s' % decFile.path)
230                 decFile.remove()
231         else:
232             ext = None
233             decFile = None
234             
235         orig_stream = response.stream
236         response.stream = ProxyFileStream(orig_stream, destFile, hash, ext, decFile)
237         response.stream.doneDefer.addCallback(self.save_complete, url, destFile,
238                                               response.headers.getHeader('Last-Modified'),
239                                               ext, decFile)
240         response.stream.doneDefer.addErrback(self.save_error, url)
241         return response
242
243     def save_complete(self, hash, url, destFile, modtime = None, ext = None, decFile = None):
244         """Update the modification time and AptPackages."""
245         if modtime:
246             os.utime(destFile.path, (modtime, modtime))
247             if ext:
248                 os.utime(decFile.path, (modtime, modtime))
249         
250         result = hash.verify()
251         if result or result is None:
252             if result:
253                 log.msg('Hashes match: %s' % url)
254             else:
255                 log.msg('Hashed file to %s: %s' % (hash.hexdigest(), url))
256                 
257             self.updatedFile(url, destFile.path)
258             if ext:
259                 self.updatedFile(url[:-len(ext)], decFile.path)
260                 
261             self.manager.download_complete(hash, url, destFile.path)
262         else:
263             log.msg("Hashes don't match %s != %s: %s" % (hash.hexexpected(), hash.hexdigest(), url))
264
265     def save_error(self, failure, url):
266         """An error has occurred in downloadign or saving the file."""
267         log.msg('Error occurred downloading %s' % url)
268         log.err(failure)
269         return failure
270
271 class TestMirrorManager(unittest.TestCase):
272     """Unit tests for the mirror manager."""
273     
274     timeout = 20
275     pending_calls = []
276     client = None
277     
278     def setUp(self):
279         self.client = MirrorManager('/tmp')
280         
281     def test_extractPath(self):
282         site, baseDir, path = self.client.extractPath('http://ftp.us.debian.org/debian/dists/unstable/Release')
283         self.failUnless(site == "ftp.us.debian.org:80", "no match: %s" % site)
284         self.failUnless(baseDir == "/debian", "no match: %s" % baseDir)
285         self.failUnless(path == "/dists/unstable/Release", "no match: %s" % path)
286
287         site, baseDir, path = self.client.extractPath('http://ftp.us.debian.org:16999/debian/pool/d/dpkg/dpkg_1.2.1-1.tar.gz')
288         self.failUnless(site == "ftp.us.debian.org:16999", "no match: %s" % site)
289         self.failUnless(baseDir == "/debian", "no match: %s" % baseDir)
290         self.failUnless(path == "/pool/d/dpkg/dpkg_1.2.1-1.tar.gz", "no match: %s" % path)
291
292         site, baseDir, path = self.client.extractPath('http://debian.camrdale.org/dists/unstable/Release')
293         self.failUnless(site == "debian.camrdale.org:80", "no match: %s" % site)
294         self.failUnless(baseDir == "", "no match: %s" % baseDir)
295         self.failUnless(path == "/dists/unstable/Release", "no match: %s" % path)
296
297     def verifyHash(self, found_hash, path, true_hash):
298         self.failUnless(found_hash.hexexpected() == true_hash, 
299                     "%s hashes don't match: %s != %s" % (path, found_hash.hexexpected(), true_hash))
300
301     def test_findHash(self):
302         self.packagesFile = os.popen('ls -Sr /var/lib/apt/lists/ | grep -E "_main_.*Packages$" | tail -n 1').read().rstrip('\n')
303         self.sourcesFile = os.popen('ls -Sr /var/lib/apt/lists/ | grep -E "_main_.*Sources$" | tail -n 1').read().rstrip('\n')
304         for f in os.walk('/var/lib/apt/lists').next()[2]:
305             if f[-7:] == "Release" and self.packagesFile.startswith(f[:-7]):
306                 self.releaseFile = f
307                 break
308         
309         self.client.updatedFile('http://' + self.releaseFile.replace('_','/'), 
310                                 '/var/lib/apt/lists/' + self.releaseFile)
311         self.client.updatedFile('http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') +
312                                 self.packagesFile[self.packagesFile.find('_dists_')+1:].replace('_','/'), 
313                                 '/var/lib/apt/lists/' + self.packagesFile)
314         self.client.updatedFile('http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') +
315                                 self.sourcesFile[self.sourcesFile.find('_dists_')+1:].replace('_','/'), 
316                                 '/var/lib/apt/lists/' + self.sourcesFile)
317
318         lastDefer = defer.Deferred()
319         
320         idx_hash = os.popen('grep -A 3000 -E "^SHA1:" ' + 
321                             '/var/lib/apt/lists/' + self.releaseFile + 
322                             ' | grep -E " main/binary-i386/Packages.bz2$"'
323                             ' | head -n 1 | cut -d\  -f 2').read().rstrip('\n')
324         idx_path = 'http://' + self.releaseFile.replace('_','/')[:-7] + 'main/binary-i386/Packages.bz2'
325
326         d = self.client.findHash(idx_path)
327         d.addCallback(self.verifyHash, idx_path, idx_hash)
328
329         pkg_hash = os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
330                             '/var/lib/apt/lists/' + self.packagesFile + 
331                             ' | grep -E "^SHA1:" | head -n 1' + 
332                             ' | cut -d\  -f 2').read().rstrip('\n')
333         pkg_path = 'http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') + \
334                    os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
335                             '/var/lib/apt/lists/' + self.packagesFile + 
336                             ' | grep -E "^Filename:" | head -n 1' + 
337                             ' | cut -d\  -f 2').read().rstrip('\n')
338
339         d = self.client.findHash(pkg_path)
340         d.addCallback(self.verifyHash, pkg_path, pkg_hash)
341
342         src_dir = os.popen('grep -A 30 -E "^Package: dpkg$" ' + 
343                             '/var/lib/apt/lists/' + self.sourcesFile + 
344                             ' | grep -E "^Directory:" | head -n 1' + 
345                             ' | cut -d\  -f 2').read().rstrip('\n')
346         src_hashes = os.popen('grep -A 20 -E "^Package: dpkg$" ' + 
347                             '/var/lib/apt/lists/' + self.sourcesFile + 
348                             ' | grep -A 4 -E "^Files:" | grep -E "^ " ' + 
349                             ' | cut -d\  -f 2').read().split('\n')[:-1]
350         src_paths = os.popen('grep -A 20 -E "^Package: dpkg$" ' + 
351                             '/var/lib/apt/lists/' + self.sourcesFile + 
352                             ' | grep -A 4 -E "^Files:" | grep -E "^ " ' + 
353                             ' | cut -d\  -f 4').read().split('\n')[:-1]
354
355         for i in range(len(src_hashes)):
356             src_path = 'http://' + self.releaseFile[:self.releaseFile.find('_dists_')+1].replace('_','/') + src_dir + '/' + src_paths[i]
357             d = self.client.findHash(src_path)
358             d.addCallback(self.verifyHash, src_path, src_hashes[i])
359             
360         idx_hash = os.popen('grep -A 3000 -E "^SHA1:" ' + 
361                             '/var/lib/apt/lists/' + self.releaseFile + 
362                             ' | grep -E " main/source/Sources.bz2$"'
363                             ' | head -n 1 | cut -d\  -f 2').read().rstrip('\n')
364         idx_path = 'http://' + self.releaseFile.replace('_','/')[:-7] + 'main/source/Sources.bz2'
365
366         d = self.client.findHash(idx_path)
367         d.addCallback(self.verifyHash, idx_path, idx_hash)
368
369         d.addBoth(lastDefer.callback)
370         return lastDefer
371
372     def tearDown(self):
373         for p in self.pending_calls:
374             if p.active():
375                 p.cancel()
376         self.client = None
377