3 """ Various different sanity checks
5 @contact: Debian FTP Master <ftpmaster@debian.org>
6 @copyright: (C) 2000, 2001, 2002, 2003, 2004, 2006 James Troup <james@nocrew.org>
7 @license: GNU General Public License version 2 or later
10 # This program is free software; you can redistribute it and/or modify
11 # it under the terms of the GNU General Public License as published by
12 # the Free Software Foundation; either version 2 of the License, or
13 # (at your option) any later version.
15 # This program is distributed in the hope that it will be useful,
16 # but WITHOUT ANY WARRANTY; without even the implied warranty of
17 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 # GNU General Public License for more details.
20 # You should have received a copy of the GNU General Public License
21 # along with this program; if not, write to the Free Software
22 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
24 ################################################################################
26 # And, lo, a great and menacing voice rose from the depths, and with
27 # great wrath and vehemence it's voice boomed across the
28 # land... ``hehehehehehe... that *tickles*''
31 ################################################################################
41 from daklib.dbconn import *
42 from daklib import utils
43 from daklib.config import Config
44 from daklib.dak_exceptions import InvalidDscError, ChangesUnicodeError, CantOpenError
46 ################################################################################
48 db_files = {} #: Cache of filenames as known by the database
49 waste = 0.0 #: How many bytes are "wasted" by files not referenced in database
50 excluded = {} #: List of files which are excluded from files check
53 current_time = time.time() #: now()
55 ################################################################################
57 def usage(exit_code=0):
58 print """Usage: dak check-archive MODE
59 Run various sanity checks of the archive and/or database.
61 -h, --help show this help and exit.
63 The following MODEs are available:
65 checksums - validate the checksums stored in the database
66 files - check files in the database against what's in the archive
67 dsc-syntax - validate the syntax of .dsc files in the archive
68 missing-overrides - check for missing overrides
69 source-in-one-dir - ensure the source for each package is in one directory
70 timestamps - check for future timestamps in .deb's
71 files-in-dsc - ensure each .dsc references appropriate Files
72 validate-indices - ensure files mentioned in Packages & Sources exist
73 files-not-symlinks - check files in the database aren't symlinks
74 validate-builddeps - validate build-dependencies of .dsc files in the archive
78 ################################################################################
80 def process_dir (unused, dirname, filenames):
82 Process a directory and output every files name which is not listed already
83 in the C{filenames} or global C{excluded} dictionaries.
86 @param dirname: the directory to look at
89 @param filenames: Known filenames to ignore
91 global waste, db_files, excluded
93 if dirname.find('/disks-') != -1 or dirname.find('upgrade-') != -1:
95 # hack; can't handle .changes files
96 if dirname.find('proposed-updates') != -1:
98 for name in filenames:
99 filename = os.path.abspath(os.path.join(dirname,name))
100 if os.path.isfile(filename) and not os.path.islink(filename) and not db_files.has_key(filename) and not excluded.has_key(filename):
101 waste += os.stat(filename)[stat.ST_SIZE]
102 print "%s" % (filename)
104 ################################################################################
108 Prepare the dictionary of existing filenames, then walk through the archive
109 pool/ directory to compare it.
115 print "Building list of database files..."
116 q = DBConn().session().query(PoolFile).join(Location).order_by('path', 'location')
118 print "Missing files:"
122 filename = os.path.abspath(os.path.join(f.location.path, f.filename))
123 db_files[filename] = ""
124 if os.access(filename, os.R_OK) == 0:
126 print "(last used: %s) %s" % (f.last_used, filename)
128 print "%s" % (filename)
131 filename = os.path.join(cnf["Dir::Override"], 'override.unreferenced')
132 if os.path.exists(filename):
133 f = utils.open_file(filename)
134 for filename in f.readlines():
135 filename = filename[:-1]
136 excluded[filename] = ""
138 print "Existent files not in db:"
140 os.path.walk(os.path.join(cnf["Dir::Root"], 'pool/'), process_dir, None)
143 print "%s wasted..." % (utils.size_type(waste))
145 ################################################################################
149 Parse every .dsc file in the archive and check for it's validity.
154 for src in DBConn().session().query(DBSource).order_by(DBSource.source, DBSource.version):
155 f = src.poolfile.fullpath
157 utils.parse_changes(f, signing_rules=1, dsc_file=1)
158 except InvalidDscError:
159 utils.warn("syntax error in .dsc file %s" % f)
161 except ChangesUnicodeError:
162 utils.warn("found invalid dsc file (%s), not properly utf-8 encoded" % f)
164 except CantOpenError:
165 utils.warn("missing dsc file (%s)" % f)
168 utils.warn("miscellaneous error parsing dsc file (%s): %s" % (f, str(e)))
172 utils.warn("Found %s invalid .dsc files." % (count))
174 ################################################################################
176 def check_override():
178 Check for missing overrides in stable and unstable.
180 session = DBConn().session()
182 for suite_name in [ "stable", "unstable" ]:
184 print "-" * len(suite_name)
186 suite = get_suite(suite_name)
187 q = session.execute("""
188 SELECT DISTINCT b.package FROM binaries b, bin_associations ba
189 WHERE b.id = ba.bin AND ba.suite = :suiteid AND NOT EXISTS
190 (SELECT 1 FROM override o WHERE o.suite = :suiteid AND o.package = b.package)"""
191 % {'suiteid': suite.suite_id})
193 for j in q.fetchall():
196 q = session.execute("""
197 SELECT DISTINCT s.source FROM source s, src_associations sa
198 WHERE s.id = sa.source AND sa.suite = :suiteid AND NOT EXISTS
199 (SELECT 1 FROM override o WHERE o.suite = :suiteid and o.package = s.source)"""
200 % {'suiteid': suite.suite_id})
201 for j in q.fetchall():
204 ################################################################################
207 def check_source_in_one_dir():
209 Ensure that the source files for any given package is all in one
210 directory so that 'apt-get source' works...
213 # Not the most enterprising method, but hey...
216 session = DBConn().session()
218 q = session.query(DBSource)
224 qf = session.query(PoolFile).join(Location).join(DSCFile).filter_by(source_id=s.source_id)
228 filename = os.path.join(f.location.path, f.filename)
229 path = os.path.dirname(filename)
233 first_filename = filename
234 elif first_path != path:
235 symlink = path + '/' + os.path.basename(first_filename)
236 if not os.path.exists(symlink):
238 print "WOAH, we got a live one here... %s [%s] {%s}" % (filename, s.source_id, symlink)
242 print "Found %d source packages where the source is not all in one directory." % (broken_count)
244 ################################################################################
245 def check_checksums():
249 print "Getting file information from database..."
250 q = DBConn().session().query(PoolFile)
252 print "Checking file checksums & sizes..."
254 filename = os.path.abspath(os.path.join(f.location.path, f.filename))
257 fi = utils.open_file(filename)
259 utils.warn("can't open '%s'." % (filename))
262 size = os.stat(filename)[stat.ST_SIZE]
263 if size != f.filesize:
264 utils.warn("**WARNING** size mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, size, f.filesize))
266 md5sum = apt_pkg.md5sum(fi)
267 if md5sum != f.md5sum:
268 utils.warn("**WARNING** md5sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, md5sum, f.md5sum))
271 sha1sum = apt_pkg.sha1sum(fi)
272 if sha1sum != f.sha1sum:
273 utils.warn("**WARNING** sha1sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha1sum, f.sha1sum))
276 sha256sum = apt_pkg.sha256sum(fi)
277 if sha256sum != f.sha256sum:
278 utils.warn("**WARNING** sha256sum mismatch for '%s' ('%s' [current] vs. '%s' [db])." % (filename, sha256sum, f.sha256sum))
282 ################################################################################
285 def Ent(Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
288 if MTime > current_time:
289 future_files[current_file] = MTime
290 print "%s: %s '%s','%s',%u,%u,%u,%u,%u,%u,%u" % (current_file, Kind,Name,Link,Mode,UID,GID,Size, MTime, Major, Minor)
292 def check_timestamps():
294 Check all files for timestamps in the future; common from hardware
295 (e.g. alpha) which have far-future dates as their default dates.
300 q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.deb$'))
306 filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
307 if os.access(filename, os.R_OK):
308 f = utils.open_file(filename)
309 current_file = filename
310 sys.stderr.write("Processing %s.\n" % (filename))
311 apt_inst.debExtract(f, Ent, "control.tar.gz")
313 apt_inst.debExtract(f, Ent, "data.tar.gz")
316 print "Checked %d files (out of %d)." % (count, len(db_files.keys()))
318 ################################################################################
320 def check_files_in_dsc():
322 Ensure each .dsc lists appropriate files in its Files field (according
323 to the format announced in its Format field).
327 print "Building list of database files..."
328 q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
331 print "Checking %d files..." % len(ql)
333 print "No files to check."
336 filename = os.path.abspath(os.path.join(pf.location.path + pf.filename))
339 # NB: don't enforce .dsc syntax
340 dsc = utils.parse_changes(filename, dsc_file=1)
342 utils.fubar("error parsing .dsc file '%s'." % (filename))
344 reasons = utils.check_dsc_files(filename, dsc)
352 utils.warn("Found %s invalid .dsc files." % (count))
355 ################################################################################
357 def validate_sources(suite, component):
359 Ensure files mentioned in Sources exist
361 filename = "%s/dists/%s/%s/source/Sources.gz" % (Cnf["Dir::Root"], suite, component)
362 print "Processing %s..." % (filename)
363 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
364 (fd, temp_filename) = utils.temp_filename()
365 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
367 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
369 sources = utils.open_file(temp_filename)
370 Sources = apt_pkg.ParseTagFile(sources)
371 while Sources.Step():
372 source = Sources.Section.Find('Package')
373 directory = Sources.Section.Find('Directory')
374 files = Sources.Section.Find('Files')
375 for i in files.split('\n'):
376 (md5, size, name) = i.split()
377 filename = "%s/%s/%s" % (Cnf["Dir::Root"], directory, name)
378 if not os.path.exists(filename):
379 if directory.find("potato") == -1:
380 print "W: %s missing." % (filename)
382 pool_location = utils.poolify (source, component)
383 pool_filename = "%s/%s/%s" % (Cnf["Dir::Pool"], pool_location, name)
384 if not os.path.exists(pool_filename):
385 print "E: %s missing (%s)." % (filename, pool_filename)
388 pool_filename = os.path.normpath(pool_filename)
389 filename = os.path.normpath(filename)
390 src = utils.clean_symlink(pool_filename, filename, Cnf["Dir::Root"])
391 print "Symlinking: %s -> %s" % (filename, src)
392 #os.symlink(src, filename)
394 os.unlink(temp_filename)
396 ########################################
398 def validate_packages(suite, component, architecture):
400 Ensure files mentioned in Packages exist
402 filename = "%s/dists/%s/%s/binary-%s/Packages.gz" \
403 % (Cnf["Dir::Root"], suite, component, architecture)
404 print "Processing %s..." % (filename)
405 # apt_pkg.ParseTagFile needs a real file handle and can't handle a GzipFile instance...
406 (fd, temp_filename) = utils.temp_filename()
407 (result, output) = commands.getstatusoutput("gunzip -c %s > %s" % (filename, temp_filename))
409 sys.stderr.write("Gunzip invocation failed!\n%s\n" % (output))
411 packages = utils.open_file(temp_filename)
412 Packages = apt_pkg.ParseTagFile(packages)
413 while Packages.Step():
414 filename = "%s/%s" % (Cnf["Dir::Root"], Packages.Section.Find('Filename'))
415 if not os.path.exists(filename):
416 print "W: %s missing." % (filename)
418 os.unlink(temp_filename)
420 ########################################
422 def check_indices_files_exist():
424 Ensure files mentioned in Packages & Sources exist
426 for suite in [ "stable", "testing", "unstable" ]:
427 for component in Cnf.ValueList("Suite::%s::Components" % (suite)):
428 architectures = get_suite_architectures(suite)
429 for arch in [ i.arch_string.lower() for i in architectures ]:
431 validate_sources(suite, component)
435 validate_packages(suite, component, arch)
437 ################################################################################
439 def check_files_not_symlinks():
441 Check files in the database aren't symlinks
443 print "Building list of database files... ",
445 q = DBConn().session().query(PoolFile).filter(PoolFile.filename.like('.dsc$'))
448 filename = os.path.abspath(os.path.join(pf.location.path, pf.filename))
449 if os.access(filename, os.R_OK) == 0:
450 utils.warn("%s: doesn't exist." % (filename))
452 if os.path.islink(filename):
453 utils.warn("%s: is a symlink." % (filename))
455 ################################################################################
457 def chk_bd_process_dir (unused, dirname, filenames):
458 for name in filenames:
459 if not name.endswith(".dsc"):
461 filename = os.path.abspath(dirname+'/'+name)
462 dsc = utils.parse_changes(filename, dsc_file=1)
463 for field_name in [ "build-depends", "build-depends-indep" ]:
464 field = dsc.get(field_name)
467 apt_pkg.ParseSrcDepends(field)
469 print "E: [%s] %s: %s" % (filename, field_name, field)
472 ################################################################################
474 def check_build_depends():
475 """ Validate build-dependencies of .dsc files in the archive """
477 os.path.walk(cnf["Dir::Root"], chk_bd_process_dir, None)
479 ################################################################################
482 global db_files, waste, excluded
486 Arguments = [('h',"help","Check-Archive::Options::Help")]
488 if not cnf.has_key("Check-Archive::Options::%s" % (i)):
489 cnf["Check-Archive::Options::%s" % (i)] = ""
491 args = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
493 Options = cnf.SubTree("Check-Archive::Options")
498 utils.warn("dak check-archive requires at least one argument")
501 utils.warn("dak check-archive accepts only one argument")
503 mode = args[0].lower()
508 if mode == "checksums":
510 elif mode == "files":
512 elif mode == "dsc-syntax":
514 elif mode == "missing-overrides":
516 elif mode == "source-in-one-dir":
517 check_source_in_one_dir()
518 elif mode == "timestamps":
520 elif mode == "files-in-dsc":
522 elif mode == "validate-indices":
523 check_indices_files_exist()
524 elif mode == "files-not-symlinks":
525 check_files_not_symlinks()
526 elif mode == "validate-builddeps":
527 check_build_depends()
529 utils.warn("unknown mode '%s'" % (mode))
532 ################################################################################
534 if __name__ == '__main__':