3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005, 2006 James Troup <james@nocrew.org>
6 # This program is free software; you can redistribute it and/or modify
7 # it under the terms of the GNU General Public License as published by
8 # the Free Software Foundation; either version 2 of the License, or
9 # (at your option) any later version.
11 # This program is distributed in the hope that it will be useful,
12 # but WITHOUT ANY WARRANTY; without even the implied warranty of
13 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 # GNU General Public License for more details.
16 # You should have received a copy of the GNU General Public License
17 # along with this program; if not, write to the Free Software
18 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
20 # Originally based on dinstall by Guy Maor <maor@debian.org>
22 ################################################################################
24 # Computer games don't affect kids. I mean if Pacman affected our generation as
25 # kids, we'd all run around in a darkened room munching pills and listening to
29 ################################################################################
31 import commands, errno, fcntl, os, re, shutil, stat, sys, time, tempfile, traceback
32 import apt_inst, apt_pkg
33 import dak.lib.database, dak.lib.queue, dak.lib.logging, dak.lib.utils
37 ################################################################################
39 re_valid_version = re.compile(r"^([0-9]+:)?[0-9A-Za-z\.\-\+:]+$")
40 re_valid_pkg_name = re.compile(r"^[\dA-Za-z][\dA-Za-z\+\-\.]+$")
41 re_changelog_versions = re.compile(r"^\w[-+0-9a-z.]+ \([^\(\) \t]+\)")
42 re_strip_revision = re.compile(r"-([^-]+)$")
44 ################################################################################
55 # Aliases to the real vars in the Upload class; hysterical raisins.
63 ###############################################################################
66 global Cnf, Options, Upload, changes, dsc, dsc_files, files, pkg
70 Cnf = apt_pkg.newConfiguration()
71 apt_pkg.ReadConfigFileISC(Cnf,dak.lib.utils.which_conf_file())
73 Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
74 ('h',"help","Dinstall::Options::Help"),
75 ('n',"no-action","Dinstall::Options::No-Action"),
76 ('p',"no-lock", "Dinstall::Options::No-Lock"),
77 ('s',"no-mail", "Dinstall::Options::No-Mail")]
79 for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
80 "override-distribution", "version"]:
81 Cnf["Dinstall::Options::%s" % (i)] = ""
83 changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv)
84 Options = Cnf.SubTree("Dinstall::Options")
89 Upload = dak.lib.queue.Queue(Cnf)
91 changes = Upload.pkg.changes
93 dsc_files = Upload.pkg.dsc_files
94 files = Upload.pkg.files
99 ################################################################################
101 def usage (exit_code=0):
102 print """Usage: dinstall [OPTION]... [CHANGES]...
103 -a, --automatic automatic run
104 -h, --help show this help and exit.
105 -n, --no-action don't do anything
106 -p, --no-lock don't check lockfile !! for cron.daily only !!
107 -s, --no-mail don't send any mail
108 -V, --version display the version number and exit"""
111 ################################################################################
113 def reject (str, prefix="Rejected: "):
114 global reject_message
116 reject_message += prefix + str + "\n"
118 ################################################################################
120 def copy_to_holding(filename):
123 base_filename = os.path.basename(filename)
125 dest = Cnf["Dir::Queue::Holding"] + '/' + base_filename
127 fd = os.open(dest, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0640)
130 # Shouldn't happen, but will if, for example, someone lists a
131 # file twice in the .changes.
132 if errno.errorcode[e.errno] == 'EEXIST':
133 reject("%s: already exists in holding area; can not overwrite." % (base_filename))
138 shutil.copy(filename, dest)
140 # In either case (ENOENT or EACCES) we want to remove the
141 # O_CREAT | O_EXCLed ghost file, so add the file to the list
142 # of 'in holding' even if it's not the real file.
143 if errno.errorcode[e.errno] == 'ENOENT':
144 reject("%s: can not copy to holding area: file not found." % (base_filename))
147 elif errno.errorcode[e.errno] == 'EACCES':
148 reject("%s: can not copy to holding area: read permission denied." % (base_filename))
153 in_holding[base_filename] = ""
155 ################################################################################
161 os.chdir(Cnf["Dir::Queue::Holding"])
162 for file in in_holding.keys():
163 if os.path.exists(file):
164 if file.find('/') != -1:
165 dak.lib.utils.fubar("WTF? clean_holding() got a file ('%s') with / in it!" % (file))
171 ################################################################################
174 filename = pkg.changes_file
176 # Parse the .changes field into a dictionary
178 changes.update(dak.lib.utils.parse_changes(filename))
179 except dak.lib.utils.cant_open_exc:
180 reject("%s: can't read file." % (filename))
182 except dak.lib.utils.changes_parse_error_exc, line:
183 reject("%s: parse error, can't grok: %s." % (filename, line))
186 # Parse the Files field from the .changes into another dictionary
188 files.update(dak.lib.utils.build_file_list(changes))
189 except dak.lib.utils.changes_parse_error_exc, line:
190 reject("%s: parse error, can't grok: %s." % (filename, line))
191 except dak.lib.utils.nk_format_exc, format:
192 reject("%s: unknown format '%s'." % (filename, format))
195 # Check for mandatory fields
196 for i in ("source", "binary", "architecture", "version", "distribution",
197 "maintainer", "files", "changes", "description"):
198 if not changes.has_key(i):
199 reject("%s: Missing mandatory field `%s'." % (filename, i))
200 return 0 # Avoid <undef> errors during later tests
202 # Split multi-value fields into a lower-level dictionary
203 for i in ("architecture", "distribution", "binary", "closes"):
204 o = changes.get(i, "")
211 # Fix the Maintainer: field to be RFC822/2047 compatible
213 (changes["maintainer822"], changes["maintainer2047"],
214 changes["maintainername"], changes["maintaineremail"]) = \
215 dak.lib.utils.fix_maintainer (changes["maintainer"])
216 except dak.lib.utils.ParseMaintError, msg:
217 reject("%s: Maintainer field ('%s') failed to parse: %s" \
218 % (filename, changes["maintainer"], msg))
220 # ...likewise for the Changed-By: field if it exists.
222 (changes["changedby822"], changes["changedby2047"],
223 changes["changedbyname"], changes["changedbyemail"]) = \
224 dak.lib.utils.fix_maintainer (changes.get("changed-by", ""))
225 except dak.lib.utils.ParseMaintError, msg:
226 (changes["changedby822"], changes["changedby2047"],
227 changes["changedbyname"], changes["changedbyemail"]) = \
229 reject("%s: Changed-By field ('%s') failed to parse: %s" \
230 % (filename, changes["changed-by"], msg))
232 # Ensure all the values in Closes: are numbers
233 if changes.has_key("closes"):
234 for i in changes["closes"].keys():
235 if dak.lib.queue.re_isanum.match (i) == None:
236 reject("%s: `%s' from Closes field isn't a number." % (filename, i))
239 # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
240 changes["chopversion"] = dak.lib.utils.re_no_epoch.sub('', changes["version"])
241 changes["chopversion2"] = dak.lib.utils.re_no_revision.sub('', changes["chopversion"])
243 # Check there isn't already a changes file of the same name in one
244 # of the queue directories.
245 base_filename = os.path.basename(filename)
246 for dir in [ "Accepted", "Byhand", "Done", "New" ]:
247 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+base_filename):
248 reject("%s: a file with this name already exists in the %s directory." % (base_filename, dir))
250 # Check the .changes is non-empty
252 reject("%s: nothing to do (Files field is empty)." % (base_filename))
257 ################################################################################
259 def check_distributions():
260 "Check and map the Distribution field of a .changes file."
262 # Handle suite mappings
263 for map in Cnf.ValueList("SuiteMappings"):
266 if type == "map" or type == "silent-map":
267 (source, dest) = args[1:3]
268 if changes["distribution"].has_key(source):
269 del changes["distribution"][source]
270 changes["distribution"][dest] = 1
271 if type != "silent-map":
272 reject("Mapping %s to %s." % (source, dest),"")
273 if changes.has_key("distribution-version"):
274 if changes["distribution-version"].has_key(source):
275 changes["distribution-version"][source]=dest
276 elif type == "map-unreleased":
277 (source, dest) = args[1:3]
278 if changes["distribution"].has_key(source):
279 for arch in changes["architecture"].keys():
280 if arch not in Cnf.ValueList("Suite::%s::Architectures" % (source)):
281 reject("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch),"")
282 del changes["distribution"][source]
283 changes["distribution"][dest] = 1
285 elif type == "ignore":
287 if changes["distribution"].has_key(suite):
288 del changes["distribution"][suite]
289 reject("Ignoring %s as a target suite." % (suite), "Warning: ")
290 elif type == "reject":
292 if changes["distribution"].has_key(suite):
293 reject("Uploads to %s are not accepted." % (suite))
294 elif type == "propup-version":
295 # give these as "uploaded-to(non-mapped) suites-to-add-when-upload-obsoletes"
297 # changes["distribution-version"] looks like: {'testing': 'testing-proposed-updates'}
298 if changes["distribution"].has_key(args[1]):
299 changes.setdefault("distribution-version", {})
300 for suite in args[2:]: changes["distribution-version"][suite]=suite
302 # Ensure there is (still) a target distribution
303 if changes["distribution"].keys() == []:
304 reject("no valid distribution.")
306 # Ensure target distributions exist
307 for suite in changes["distribution"].keys():
308 if not Cnf.has_key("Suite::%s" % (suite)):
309 reject("Unknown distribution `%s'." % (suite))
311 ################################################################################
313 def check_deb_ar(filename, control):
314 """Sanity check the ar of a .deb, i.e. that there is:
318 o data.tar.gz or data.tar.bz2
320 in that order, and nothing else. If the third member is a
321 data.tar.bz2, an additional check is performed for the required
322 Pre-Depends on dpkg (>= 1.10.24)."""
323 cmd = "ar t %s" % (filename)
324 (result, output) = commands.getstatusoutput(cmd)
326 reject("%s: 'ar t' invocation failed." % (filename))
327 reject(dak.lib.utils.prefix_multi_line_string(output, " [ar output:] "), "")
328 chunks = output.split('\n')
330 reject("%s: found %d chunks, expected 3." % (filename, len(chunks)))
331 if chunks[0] != "debian-binary":
332 reject("%s: first chunk is '%s', expected 'debian-binary'." % (filename, chunks[0]))
333 if chunks[1] != "control.tar.gz":
334 reject("%s: second chunk is '%s', expected 'control.tar.gz'." % (filename, chunks[1]))
335 if chunks[2] == "data.tar.bz2":
336 # Packages using bzip2 compression must have a Pre-Depends on dpkg >= 1.10.24.
337 found_needed_predep = 0
338 for parsed_dep in apt_pkg.ParseDepends(control.Find("Pre-Depends", "")):
339 for atom in parsed_dep:
340 (dep, version, constraint) = atom
341 if dep != "dpkg" or (constraint != ">=" and constraint != ">>") or \
342 len(parsed_dep) > 1: # or'ed deps don't count
344 if (constraint == ">=" and apt_pkg.VersionCompare(version, "1.10.24") < 0) or \
345 (constraint == ">>" and apt_pkg.VersionCompare(version, "1.10.23") < 0):
347 found_needed_predep = 1
348 if not found_needed_predep:
349 reject("%s: uses bzip2 compression, but doesn't Pre-Depend on dpkg (>= 1.10.24)" % (filename))
350 elif chunks[2] != "data.tar.gz":
351 reject("%s: third chunk is '%s', expected 'data.tar.gz' or 'data.tar.bz2'." % (filename, chunks[2]))
353 ################################################################################
358 archive = dak.lib.utils.where_am_i()
359 file_keys = files.keys()
361 # if reprocess is 2 we've already done this and we're checking
362 # things again for the new .orig.tar.gz.
363 # [Yes, I'm fully aware of how disgusting this is]
364 if not Options["No-Action"] and reprocess < 2:
366 os.chdir(pkg.directory)
367 for file in file_keys:
368 copy_to_holding(file)
371 # Check there isn't already a .changes or .dak file of the same name in
372 # the proposed-updates "CopyChanges" or "CopyDotDak" storage directories.
373 # [NB: this check must be done post-suite mapping]
374 base_filename = os.path.basename(pkg.changes_file)
375 dot_dak_filename = base_filename[:-8]+".dak"
376 for suite in changes["distribution"].keys():
377 copychanges = "Suite::%s::CopyChanges" % (suite)
378 if Cnf.has_key(copychanges) and \
379 os.path.exists(Cnf[copychanges]+"/"+base_filename):
380 reject("%s: a file with this name already exists in %s" \
381 % (base_filename, Cnf[copychanges]))
383 copy_dot_dak = "Suite::%s::CopyDotDak" % (suite)
384 if Cnf.has_key(copy_dot_dak) and \
385 os.path.exists(Cnf[copy_dot_dak]+"/"+dot_dak_filename):
386 reject("%s: a file with this name already exists in %s" \
387 % (dot_dak_filename, Cnf[copy_dot_dak]))
393 for file in file_keys:
394 # Ensure the file does not already exist in one of the accepted directories
395 for dir in [ "Accepted", "Byhand", "New" ]:
396 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+file):
397 reject("%s file already exists in the %s directory." % (file, dir))
398 if not dak.lib.utils.re_taint_free.match(file):
399 reject("!!WARNING!! tainted filename: '%s'." % (file))
400 # Check the file is readable
401 if os.access(file,os.R_OK) == 0:
402 # When running in -n, copy_to_holding() won't have
403 # generated the reject_message, so we need to.
404 if Options["No-Action"]:
405 if os.path.exists(file):
406 reject("Can't read `%s'. [permission denied]" % (file))
408 reject("Can't read `%s'. [file not found]" % (file))
409 files[file]["type"] = "unreadable"
411 # If it's byhand skip remaining checks
412 if files[file]["section"] == "byhand" or files[file]["section"] == "raw-installer":
413 files[file]["byhand"] = 1
414 files[file]["type"] = "byhand"
415 # Checks for a binary package...
416 elif dak.lib.utils.re_isadeb.match(file):
418 files[file]["type"] = "deb"
420 # Extract package control information
421 deb_file = dak.lib.utils.open_file(file)
423 control = apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file))
425 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type))
427 # Can't continue, none of the checks on control would work.
431 # Check for mandatory fields
432 for field in [ "Package", "Architecture", "Version" ]:
433 if control.Find(field) == None:
434 reject("%s: No %s field in control." % (file, field))
438 # Ensure the package name matches the one give in the .changes
439 if not changes["binary"].has_key(control.Find("Package", "")):
440 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")))
442 # Validate the package field
443 package = control.Find("Package")
444 if not re_valid_pkg_name.match(package):
445 reject("%s: invalid package name '%s'." % (file, package))
447 # Validate the version field
448 version = control.Find("Version")
449 if not re_valid_version.match(version):
450 reject("%s: invalid version number '%s'." % (file, version))
452 # Ensure the architecture of the .deb is one we know about.
453 default_suite = Cnf.get("Dinstall::DefaultSuite", "Unstable")
454 architecture = control.Find("Architecture")
455 if architecture not in Cnf.ValueList("Suite::%s::Architectures" % (default_suite)):
456 reject("Unknown architecture '%s'." % (architecture))
458 # Ensure the architecture of the .deb is one of the ones
459 # listed in the .changes.
460 if not changes["architecture"].has_key(architecture):
461 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, architecture))
463 # Sanity-check the Depends field
464 depends = control.Find("Depends")
466 reject("%s: Depends field is empty." % (file))
468 # Check the section & priority match those given in the .changes (non-fatal)
469 if control.Find("Section") and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
470 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ")
471 if control.Find("Priority") and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
472 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ")
474 files[file]["package"] = package
475 files[file]["architecture"] = architecture
476 files[file]["version"] = version
477 files[file]["maintainer"] = control.Find("Maintainer", "")
478 if file.endswith(".udeb"):
479 files[file]["dbtype"] = "udeb"
480 elif file.endswith(".deb"):
481 files[file]["dbtype"] = "deb"
483 reject("%s is neither a .deb or a .udeb." % (file))
484 files[file]["source"] = control.Find("Source", files[file]["package"])
485 # Get the source version
486 source = files[file]["source"]
488 if source.find("(") != -1:
489 m = dak.lib.utils.re_extract_src_version.match(source)
491 source_version = m.group(2)
492 if not source_version:
493 source_version = files[file]["version"]
494 files[file]["source package"] = source
495 files[file]["source version"] = source_version
497 # Ensure the filename matches the contents of the .deb
498 m = dak.lib.utils.re_isadeb.match(file)
500 file_package = m.group(1)
501 if files[file]["package"] != file_package:
502 reject("%s: package part of filename (%s) does not match package name in the %s (%s)." % (file, file_package, files[file]["dbtype"], files[file]["package"]))
503 epochless_version = dak.lib.utils.re_no_epoch.sub('', control.Find("Version"))
505 file_version = m.group(2)
506 if epochless_version != file_version:
507 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version))
509 file_architecture = m.group(3)
510 if files[file]["architecture"] != file_architecture:
511 reject("%s: architecture part of filename (%s) does not match package architecture in the %s (%s)." % (file, file_architecture, files[file]["dbtype"], files[file]["architecture"]))
513 # Check for existent source
514 source_version = files[file]["source version"]
515 source_package = files[file]["source package"]
516 if changes["architecture"].has_key("source"):
517 if source_version != changes["version"]:
518 reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]))
520 # Check in the SQL database
521 if not Upload.source_exists(source_package, source_version, changes["distribution"].keys()):
522 # Check in one of the other directories
523 source_epochless_version = dak.lib.utils.re_no_epoch.sub('', source_version)
524 dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version)
525 if os.path.exists(Cnf["Dir::Queue::Byhand"] + '/' + dsc_filename):
526 files[file]["byhand"] = 1
527 elif os.path.exists(Cnf["Dir::Queue::New"] + '/' + dsc_filename):
528 files[file]["new"] = 1
529 elif not os.path.exists(Cnf["Dir::Queue::Accepted"] + '/' + dsc_filename):
530 reject("no source found for %s %s (%s)." % (source_package, source_version, file))
531 # Check the version and for file overwrites
532 reject(Upload.check_binary_against_db(file),"")
534 check_deb_ar(file, control)
536 # Checks for a source package...
538 m = dak.lib.utils.re_issource.match(file)
541 files[file]["package"] = m.group(1)
542 files[file]["version"] = m.group(2)
543 files[file]["type"] = m.group(3)
545 # Ensure the source package name matches the Source filed in the .changes
546 if changes["source"] != files[file]["package"]:
547 reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]))
549 # Ensure the source version matches the version in the .changes file
550 if files[file]["type"] == "orig.tar.gz":
551 changes_version = changes["chopversion2"]
553 changes_version = changes["chopversion"]
554 if changes_version != files[file]["version"]:
555 reject("%s: should be %s according to changes file." % (file, changes_version))
557 # Ensure the .changes lists source in the Architecture field
558 if not changes["architecture"].has_key("source"):
559 reject("%s: changes file doesn't list `source' in Architecture field." % (file))
561 # Check the signature of a .dsc file
562 if files[file]["type"] == "dsc":
563 dsc["fingerprint"] = dak.lib.utils.check_signature(file, reject)
565 files[file]["architecture"] = "source"
567 # Not a binary or source package? Assume byhand...
569 files[file]["byhand"] = 1
570 files[file]["type"] = "byhand"
572 # Per-suite file checks
573 files[file]["oldfiles"] = {}
574 for suite in changes["distribution"].keys():
576 if files[file].has_key("byhand"):
579 # Handle component mappings
580 for map in Cnf.ValueList("ComponentMappings"):
581 (source, dest) = map.split()
582 if files[file]["component"] == source:
583 files[file]["original component"] = source
584 files[file]["component"] = dest
586 # Ensure the component is valid for the target suite
587 if Cnf.has_key("Suite:%s::Components" % (suite)) and \
588 files[file]["component"] not in Cnf.ValueList("Suite::%s::Components" % (suite)):
589 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite))
592 # Validate the component
593 component = files[file]["component"]
594 component_id = dak.lib.database.get_component_id(component)
595 if component_id == -1:
596 reject("file '%s' has unknown component '%s'." % (file, component))
599 # See if the package is NEW
600 if not Upload.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
601 files[file]["new"] = 1
603 # Validate the priority
604 if files[file]["priority"].find('/') != -1:
605 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]))
607 # Determine the location
608 location = Cnf["Dir::Pool"]
609 location_id = dak.lib.database.get_location_id (location, component, archive)
610 if location_id == -1:
611 reject("[INTERNAL ERROR] couldn't determine location (Component: %s, Archive: %s)" % (component, archive))
612 files[file]["location id"] = location_id
614 # Check the md5sum & size against existing files (if any)
615 files[file]["pool name"] = dak.lib.utils.poolify (changes["source"], files[file]["component"])
616 files_id = dak.lib.database.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"])
618 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file))
620 reject("md5sum and/or size mismatch on existing copy of %s." % (file))
621 files[file]["files id"] = files_id
623 # Check for packages that have moved from one component to another
624 q = Upload.projectB.query("""
625 SELECT c.name FROM binaries b, bin_associations ba, suite s, location l,
626 component c, architecture a, files f
627 WHERE b.package = '%s' AND s.suite_name = '%s'
628 AND (a.arch_string = '%s' OR a.arch_string = 'all')
629 AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
630 AND f.location = l.id AND l.component = c.id AND b.file = f.id"""
631 % (files[file]["package"], suite,
632 files[file]["architecture"]))
635 files[file]["othercomponents"] = ql[0][0]
637 # If the .changes file says it has source, it must have source.
638 if changes["architecture"].has_key("source"):
640 reject("no source found and Architecture line in changes mention source.")
642 if not has_binaries and Cnf.FindB("Dinstall::Reject::NoSourceOnly"):
643 reject("source only uploads are not supported.")
645 ###############################################################################
650 # Ensure there is source to check
651 if not changes["architecture"].has_key("source"):
656 for file in files.keys():
657 if files[file]["type"] == "dsc":
659 reject("can not process a .changes file with multiple .dsc's.")
664 # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
666 reject("source uploads must contain a dsc file")
669 # Parse the .dsc file
671 dsc.update(dak.lib.utils.parse_changes(dsc_filename, signing_rules=1))
672 except dak.lib.utils.cant_open_exc:
673 # if not -n copy_to_holding() will have done this for us...
674 if Options["No-Action"]:
675 reject("%s: can't read file." % (dsc_filename))
676 except dak.lib.utils.changes_parse_error_exc, line:
677 reject("%s: parse error, can't grok: %s." % (dsc_filename, line))
678 except dak.lib.utils.invalid_dsc_format_exc, line:
679 reject("%s: syntax error on line %s." % (dsc_filename, line))
680 # Build up the file list of files mentioned by the .dsc
682 dsc_files.update(dak.lib.utils.build_file_list(dsc, is_a_dsc=1))
683 except dak.lib.utils.no_files_exc:
684 reject("%s: no Files: field." % (dsc_filename))
686 except dak.lib.utils.changes_parse_error_exc, line:
687 reject("%s: parse error, can't grok: %s." % (dsc_filename, line))
690 # Enforce mandatory fields
691 for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
692 if not dsc.has_key(i):
693 reject("%s: missing mandatory field `%s'." % (dsc_filename, i))
696 # Validate the source and version fields
697 if not re_valid_pkg_name.match(dsc["source"]):
698 reject("%s: invalid source name '%s'." % (dsc_filename, dsc["source"]))
699 if not re_valid_version.match(dsc["version"]):
700 reject("%s: invalid version number '%s'." % (dsc_filename, dsc["version"]))
702 # Bumping the version number of the .dsc breaks extraction by stable's
703 # dpkg-source. So let's not do that...
704 if dsc["format"] != "1.0":
705 reject("%s: incompatible 'Format' version produced by a broken version of dpkg-dev 1.9.1{3,4}." % (dsc_filename))
707 # Validate the Maintainer field
709 dak.lib.utils.fix_maintainer (dsc["maintainer"])
710 except dak.lib.utils.ParseMaintError, msg:
711 reject("%s: Maintainer field ('%s') failed to parse: %s" \
712 % (dsc_filename, dsc["maintainer"], msg))
714 # Validate the build-depends field(s)
715 for field_name in [ "build-depends", "build-depends-indep" ]:
716 field = dsc.get(field_name)
718 # Check for broken dpkg-dev lossage...
719 if field.startswith("ARRAY"):
720 reject("%s: invalid %s field produced by a broken version of dpkg-dev (1.10.11)" % (dsc_filename, field_name.title()))
722 # Have apt try to parse them...
724 apt_pkg.ParseSrcDepends(field)
726 reject("%s: invalid %s field (can not be parsed by apt)." % (dsc_filename, field_name.title()))
729 # Ensure the version number in the .dsc matches the version number in the .changes
730 epochless_dsc_version = dak.lib.utils.re_no_epoch.sub('', dsc["version"])
731 changes_version = files[dsc_filename]["version"]
732 if epochless_dsc_version != files[dsc_filename]["version"]:
733 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version))
735 # Ensure there is a .tar.gz in the .dsc file
737 for f in dsc_files.keys():
738 m = dak.lib.utils.re_issource.match(f)
740 reject("%s: %s in Files field not recognised as source." % (dsc_filename, f))
742 if type == "orig.tar.gz" or type == "tar.gz":
745 reject("%s: no .tar.gz or .orig.tar.gz in 'Files' field." % (dsc_filename))
747 # Ensure source is newer than existing source in target suites
748 reject(Upload.check_source_against_db(dsc_filename),"")
750 (reject_msg, is_in_incoming) = Upload.check_dsc_against_db(dsc_filename)
751 reject(reject_msg, "")
753 if not Options["No-Action"]:
754 copy_to_holding(is_in_incoming)
755 orig_tar_gz = os.path.basename(is_in_incoming)
756 files[orig_tar_gz] = {}
757 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE]
758 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"]
759 files[orig_tar_gz]["section"] = files[dsc_filename]["section"]
760 files[orig_tar_gz]["priority"] = files[dsc_filename]["priority"]
761 files[orig_tar_gz]["component"] = files[dsc_filename]["component"]
762 files[orig_tar_gz]["type"] = "orig.tar.gz"
767 ################################################################################
769 def get_changelog_versions(source_dir):
770 """Extracts a the source package and (optionally) grabs the
771 version history out of debian/changelog for the BTS."""
773 # Find the .dsc (again)
775 for file in files.keys():
776 if files[file]["type"] == "dsc":
779 # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
783 # Create a symlink mirror of the source files in our temporary directory
784 for f in files.keys():
785 m = dak.lib.utils.re_issource.match(f)
787 src = os.path.join(source_dir, f)
788 # If a file is missing for whatever reason, give up.
789 if not os.path.exists(src):
792 if type == "orig.tar.gz" and pkg.orig_tar_gz:
794 dest = os.path.join(os.getcwd(), f)
795 os.symlink(src, dest)
797 # If the orig.tar.gz is not a part of the upload, create a symlink to the
800 dest = os.path.join(os.getcwd(), os.path.basename(pkg.orig_tar_gz))
801 os.symlink(pkg.orig_tar_gz, dest)
804 cmd = "dpkg-source -sn -x %s" % (dsc_filename)
805 (result, output) = commands.getstatusoutput(cmd)
807 reject("'dpkg-source -x' failed for %s [return code: %s]." % (dsc_filename, result))
808 reject(dak.lib.utils.prefix_multi_line_string(output, " [dpkg-source output:] "), "")
811 if not Cnf.Find("Dir::Queue::BTSVersionTrack"):
814 # Get the upstream version
815 upstr_version = dak.lib.utils.re_no_epoch.sub('', dsc["version"])
816 if re_strip_revision.search(upstr_version):
817 upstr_version = re_strip_revision.sub('', upstr_version)
819 # Ensure the changelog file exists
820 changelog_filename = "%s-%s/debian/changelog" % (dsc["source"], upstr_version)
821 if not os.path.exists(changelog_filename):
822 reject("%s: debian/changelog not found in extracted source." % (dsc_filename))
825 # Parse the changelog
826 dsc["bts changelog"] = ""
827 changelog_file = dak.lib.utils.open_file(changelog_filename)
828 for line in changelog_file.readlines():
829 m = re_changelog_versions.match(line)
831 dsc["bts changelog"] += line
832 changelog_file.close()
834 # Check we found at least one revision in the changelog
835 if not dsc["bts changelog"]:
836 reject("%s: changelog format not recognised (empty version tree)." % (dsc_filename))
838 ########################################
842 # a) there's no source
843 # or b) reprocess is 2 - we will do this check next time when orig.tar.gz is in 'files'
844 # or c) the orig.tar.gz is MIA
845 if not changes["architecture"].has_key("source") or reprocess == 2 \
846 or pkg.orig_tar_gz == -1:
849 # Create a temporary directory to extract the source into
850 if Options["No-Action"]:
851 tmpdir = tempfile.mktemp()
853 # We're in queue/holding and can create a random directory.
854 tmpdir = "%s" % (os.getpid())
857 # Move into the temporary directory
861 # Get the changelog version history
862 get_changelog_versions(cwd)
864 # Move back and cleanup the temporary tree
867 shutil.rmtree(tmpdir)
869 if errno.errorcode[e.errno] != 'EACCES':
870 dak.lib.utils.fubar("%s: couldn't remove tmp dir for source tree." % (dsc["source"]))
872 reject("%s: source tree could not be cleanly removed." % (dsc["source"]))
873 # We probably have u-r or u-w directories so chmod everything
875 cmd = "chmod -R u+rwx %s" % (tmpdir)
876 result = os.system(cmd)
878 dak.lib.utils.fubar("'%s' failed with result %s." % (cmd, result))
879 shutil.rmtree(tmpdir)
881 dak.lib.utils.fubar("%s: couldn't remove tmp dir for source tree." % (dsc["source"]))
883 ################################################################################
885 # FIXME: should be a debian specific check called from a hook
887 def check_urgency ():
888 if changes["architecture"].has_key("source"):
889 if not changes.has_key("urgency"):
890 changes["urgency"] = Cnf["Urgency::Default"]
891 if changes["urgency"] not in Cnf.ValueList("Urgency::Valid"):
892 reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ")
893 changes["urgency"] = Cnf["Urgency::Default"]
894 changes["urgency"] = changes["urgency"].lower()
896 ################################################################################
898 def check_md5sums ():
899 for file in files.keys():
901 file_handle = dak.lib.utils.open_file(file)
902 except dak.lib.utils.cant_open_exc:
906 if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
907 reject("%s: md5sum check failed." % (file))
910 actual_size = os.stat(file)[stat.ST_SIZE]
911 size = int(files[file]["size"])
912 if size != actual_size:
913 reject("%s: actual file size (%s) does not match size (%s) in .changes"
914 % (file, actual_size, size))
916 for file in dsc_files.keys():
918 file_handle = dak.lib.utils.open_file(file)
919 except dak.lib.utils.cant_open_exc:
923 if apt_pkg.md5sum(file_handle) != dsc_files[file]["md5sum"]:
924 reject("%s: md5sum check failed." % (file))
927 actual_size = os.stat(file)[stat.ST_SIZE]
928 size = int(dsc_files[file]["size"])
929 if size != actual_size:
930 reject("%s: actual file size (%s) does not match size (%s) in .dsc"
931 % (file, actual_size, size))
933 ################################################################################
935 # Sanity check the time stamps of files inside debs.
936 # [Files in the near future cause ugly warnings and extreme time
937 # travel can cause errors on extraction]
939 def check_timestamps():
941 def __init__(self, future_cutoff, past_cutoff):
943 self.future_cutoff = future_cutoff
944 self.past_cutoff = past_cutoff
947 self.future_files = {}
948 self.ancient_files = {}
950 def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
951 if MTime > self.future_cutoff:
952 self.future_files[Name] = MTime
953 if MTime < self.past_cutoff:
954 self.ancient_files[Name] = MTime
957 future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"])
958 past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"))
959 tar = Tar(future_cutoff, past_cutoff)
960 for filename in files.keys():
961 if files[filename]["type"] == "deb":
964 deb_file = dak.lib.utils.open_file(filename)
965 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz")
968 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz")
969 except SystemError, e:
970 # If we can't find a data.tar.gz, look for data.tar.bz2 instead.
971 if not re.match(r"Cannot f[ui]nd chunk data.tar.gz$", str(e)):
974 apt_inst.debExtract(deb_file,tar.callback,"data.tar.bz2")
977 future_files = tar.future_files.keys()
979 num_future_files = len(future_files)
980 future_file = future_files[0]
981 future_date = tar.future_files[future_file]
982 reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
983 % (filename, num_future_files, future_file,
984 time.ctime(future_date)))
986 ancient_files = tar.ancient_files.keys()
988 num_ancient_files = len(ancient_files)
989 ancient_file = ancient_files[0]
990 ancient_date = tar.ancient_files[ancient_file]
991 reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
992 % (filename, num_ancient_files, ancient_file,
993 time.ctime(ancient_date)))
995 reject("%s: deb contents timestamp check failed [%s: %s]" % (filename, sys.exc_type, sys.exc_value))
997 ################################################################################
998 ################################################################################
1000 # If any file of an upload has a recent mtime then chances are good
1001 # the file is still being uploaded.
1003 def upload_too_new():
1005 # Move back to the original directory to get accurate time stamps
1007 os.chdir(pkg.directory)
1008 file_list = pkg.files.keys()
1009 file_list.extend(pkg.dsc_files.keys())
1010 file_list.append(pkg.changes_file)
1011 for file in file_list:
1013 last_modified = time.time()-os.path.getmtime(file)
1014 if last_modified < int(Cnf["Dinstall::SkipTime"]):
1022 ################################################################################
1025 # changes["distribution"] may not exist in corner cases
1026 # (e.g. unreadable changes files)
1027 if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
1028 changes["distribution"] = {}
1030 (summary, short_summary) = Upload.build_summaries()
1032 # q-unapproved hax0ring
1034 "New": { "is": is_new, "process": acknowledge_new },
1035 "Byhand" : { "is": is_byhand, "process": do_byhand },
1036 "Unembargo" : { "is": is_unembargo, "process": queue_unembargo },
1037 "Embargo" : { "is": is_embargo, "process": queue_embargo },
1039 queues = [ "New", "Byhand" ]
1040 if Cnf.FindB("Dinstall::SecurityQueueHandling"):
1041 queues += [ "Unembargo", "Embargo" ]
1043 (prompt, answer) = ("", "XXX")
1044 if Options["No-Action"] or Options["Automatic"]:
1049 if reject_message.find("Rejected") != -1:
1050 if upload_too_new():
1051 print "SKIP (too new)\n" + reject_message,
1052 prompt = "[S]kip, Quit ?"
1054 print "REJECT\n" + reject_message,
1055 prompt = "[R]eject, Skip, Quit ?"
1056 if Options["Automatic"]:
1061 if queue_info[q]["is"]():
1065 print "%s for %s\n%s%s" % (
1066 queue.upper(), ", ".join(changes["distribution"].keys()),
1067 reject_message, summary),
1068 queuekey = queue[0].upper()
1069 if queuekey in "RQSA":
1071 prompt = "[D]ivert, Skip, Quit ?"
1073 prompt = "[%s]%s, Skip, Quit ?" % (queuekey, queue[1:].lower())
1074 if Options["Automatic"]:
1077 print "ACCEPT\n" + reject_message + summary,
1078 prompt = "[A]ccept, Skip, Quit ?"
1079 if Options["Automatic"]:
1082 while prompt.find(answer) == -1:
1083 answer = dak.lib.utils.our_raw_input(prompt)
1084 m = dak.lib.queue.re_default_answer.match(prompt)
1087 answer = answer[:1].upper()
1090 os.chdir (pkg.directory)
1091 Upload.do_reject(0, reject_message)
1093 accept(summary, short_summary)
1094 remove_from_unchecked()
1095 elif answer == queuekey:
1096 queue_info[queue]["process"](summary)
1097 remove_from_unchecked()
1101 def remove_from_unchecked():
1102 os.chdir (pkg.directory)
1103 for file in files.keys():
1105 os.unlink(pkg.changes_file)
1107 ################################################################################
1109 def accept (summary, short_summary):
1110 Upload.accept(summary, short_summary)
1111 Upload.check_override()
1113 ################################################################################
1115 def move_to_dir (dest, perms=0660, changesperms=0664):
1116 dak.lib.utils.move (pkg.changes_file, dest, perms=changesperms)
1117 file_keys = files.keys()
1118 for file in file_keys:
1119 dak.lib.utils.move (file, dest, perms=perms)
1121 ################################################################################
1123 def is_unembargo ():
1124 q = Upload.projectB.query(
1125 "SELECT package FROM disembargo WHERE package = '%s' AND version = '%s'" %
1126 (changes["source"], changes["version"]))
1131 if pkg.directory == Cnf["Dir::Queue::Disembargo"].rstrip("/"):
1132 if changes["architecture"].has_key("source"):
1133 if Options["No-Action"]: return 1
1135 Upload.projectB.query(
1136 "INSERT INTO disembargo (package, version) VALUES ('%s', '%s')" %
1137 (changes["source"], changes["version"]))
1142 def queue_unembargo (summary):
1143 print "Moving to UNEMBARGOED holding area."
1144 Logger.log(["Moving to unembargoed", pkg.changes_file])
1146 Upload.dump_vars(Cnf["Dir::Queue::Unembargoed"])
1147 move_to_dir(Cnf["Dir::Queue::Unembargoed"])
1148 Upload.queue_build("unembargoed", Cnf["Dir::Queue::Unembargoed"])
1150 # Check for override disparities
1151 Upload.Subst["__SUMMARY__"] = summary
1152 Upload.check_override()
1154 ################################################################################
1159 def queue_embargo (summary):
1160 print "Moving to EMBARGOED holding area."
1161 Logger.log(["Moving to embargoed", pkg.changes_file])
1163 Upload.dump_vars(Cnf["Dir::Queue::Embargoed"])
1164 move_to_dir(Cnf["Dir::Queue::Embargoed"])
1165 Upload.queue_build("embargoed", Cnf["Dir::Queue::Embargoed"])
1167 # Check for override disparities
1168 Upload.Subst["__SUMMARY__"] = summary
1169 Upload.check_override()
1171 ################################################################################
1174 for file in files.keys():
1175 if files[file].has_key("byhand"):
1179 def do_byhand (summary):
1180 print "Moving to BYHAND holding area."
1181 Logger.log(["Moving to byhand", pkg.changes_file])
1183 Upload.dump_vars(Cnf["Dir::Queue::Byhand"])
1184 move_to_dir(Cnf["Dir::Queue::Byhand"])
1186 # Check for override disparities
1187 Upload.Subst["__SUMMARY__"] = summary
1188 Upload.check_override()
1190 ################################################################################
1193 for file in files.keys():
1194 if files[file].has_key("new"):
1198 def acknowledge_new (summary):
1199 Subst = Upload.Subst
1201 print "Moving to NEW holding area."
1202 Logger.log(["Moving to new", pkg.changes_file])
1204 Upload.dump_vars(Cnf["Dir::Queue::New"])
1205 move_to_dir(Cnf["Dir::Queue::New"])
1207 if not Options["No-Mail"]:
1208 print "Sending new ack."
1209 Subst["__SUMMARY__"] = summary
1210 new_ack_message = dak.lib.utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/process-unchecked.new")
1211 dak.lib.utils.send_mail(new_ack_message)
1213 ################################################################################
1215 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1216 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1217 # Upload.check_dsc_against_db() can find the .orig.tar.gz but it will
1218 # not have processed it during it's checks of -2. If -1 has been
1219 # deleted or otherwise not checked by 'dak process-unchecked', the
1220 # .orig.tar.gz will not have been checked at all. To get round this,
1221 # we force the .orig.tar.gz into the .changes structure and reprocess
1222 # the .changes file.
1224 def process_it (changes_file):
1225 global reprocess, reject_message
1227 # Reset some globals
1230 # Some defaults in case we can't fully process the .changes file
1231 changes["maintainer2047"] = Cnf["Dinstall::MyEmailAddress"]
1232 changes["changedby2047"] = Cnf["Dinstall::MyEmailAddress"]
1235 # Absolutize the filename to avoid the requirement of being in the
1236 # same directory as the .changes file.
1237 pkg.changes_file = os.path.abspath(changes_file)
1239 # Remember where we are so we can come back after cd-ing into the
1240 # holding directory.
1241 pkg.directory = os.getcwd()
1244 # If this is the Real Thing(tm), copy things into a private
1245 # holding directory first to avoid replacable file races.
1246 if not Options["No-Action"]:
1247 os.chdir(Cnf["Dir::Queue::Holding"])
1248 copy_to_holding(pkg.changes_file)
1249 # Relativize the filename so we use the copy in holding
1250 # rather than the original...
1251 pkg.changes_file = os.path.basename(pkg.changes_file)
1252 changes["fingerprint"] = dak.lib.utils.check_signature(pkg.changes_file, reject)
1253 if changes["fingerprint"]:
1254 valid_changes_p = check_changes()
1259 check_distributions()
1261 valid_dsc_p = check_dsc()
1267 Upload.update_subst(reject_message)
1273 traceback.print_exc(file=sys.stderr)
1276 # Restore previous WD
1277 os.chdir(pkg.directory)
1279 ###############################################################################
1282 global Cnf, Options, Logger
1284 changes_files = init()
1286 # -n/--dry-run invalidates some other options which would involve things happening
1287 if Options["No-Action"]:
1288 Options["Automatic"] = ""
1290 # Ensure all the arguments we were given are .changes files
1291 for file in changes_files:
1292 if not file.endswith(".changes"):
1293 dak.lib.utils.warn("Ignoring '%s' because it's not a .changes file." % (file))
1294 changes_files.remove(file)
1296 if changes_files == []:
1297 dak.lib.utils.fubar("Need at least one .changes file as an argument.")
1299 # Check that we aren't going to clash with the daily cron job
1301 if not Options["No-Action"] and os.path.exists("%s/daily.lock" % (Cnf["Dir::Lock"])) and not Options["No-Lock"]:
1302 dak.lib.utils.fubar("Archive maintenance in progress. Try again later.")
1304 # Obtain lock if not in no-action mode and initialize the log
1306 if not Options["No-Action"]:
1307 lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
1309 fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
1311 if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
1312 dak.lib.utils.fubar("Couldn't obtain lock; assuming another 'dak process-unchecked' is already running.")
1315 Logger = Upload.Logger = dak.lib.logging.Logger(Cnf, "process-unchecked")
1317 # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1318 bcc = "X-DAK: dak process-unchecked\nX-Katie: this header is obsolete"
1319 if Cnf.has_key("Dinstall::Bcc"):
1320 Upload.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"])
1322 Upload.Subst["__BCC__"] = bcc
1325 # Sort the .changes files so that we process sourceful ones first
1326 changes_files.sort(dak.lib.utils.changes_compare)
1328 # Process the changes files
1329 for changes_file in changes_files:
1330 print "\n" + changes_file
1332 process_it (changes_file)
1334 if not Options["No-Action"]:
1337 accept_count = Upload.accept_count
1338 accept_bytes = Upload.accept_bytes
1341 if accept_count > 1:
1343 print "Accepted %d package %s, %s." % (accept_count, sets, dak.lib.utils.size_type(int(accept_bytes)))
1344 Logger.log(["total",accept_count,accept_bytes])
1346 if not Options["No-Action"]:
1349 ################################################################################
1351 if __name__ == '__main__':