3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004 James Troup <james@nocrew.org>
5 # $Id: jennifer,v 1.46 2004-04-01 17:14:25 troup Exp $
7 # This program is free software; you can redistribute it and/or modify
8 # it under the terms of the GNU General Public License as published by
9 # the Free Software Foundation; either version 2 of the License, or
10 # (at your option) any later version.
12 # This program is distributed in the hope that it will be useful,
13 # but WITHOUT ANY WARRANTY; without even the implied warranty of
14 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 # GNU General Public License for more details.
17 # You should have received a copy of the GNU General Public License
18 # along with this program; if not, write to the Free Software
19 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
21 # Originally based on dinstall by Guy Maor <maor@debian.org>
23 ################################################################################
25 # Computer games don't affect kids. I mean if Pacman affected our generation as
26 # kids, we'd all run around in a darkened room munching pills and listening to
30 ################################################################################
32 import commands, errno, fcntl, os, re, shutil, stat, sys, time, tempfile, traceback;
33 import apt_inst, apt_pkg;
34 import db_access, katie, logging, utils;
38 ################################################################################
40 re_bad_diff = re.compile("^[\-\+][\-\+][\-\+] /dev/null");
41 re_is_changes = re.compile(r"(.+?)_(.+?)_(.+?)\.changes$");
42 re_valid_version = re.compile(r"^([0-9]+:)?[0-9A-Za-z\.\-\+:]+$");
43 re_valid_pkg_name = re.compile(r"^[\dA-Za-z][\dA-Za-z\+\-\.]+$");
44 re_changelog_versions = re.compile(r"^\w[-+0-9a-z.]+ \([^\(\) \t]+\)");
45 re_strip_revision = re.compile(r"-([^-]+)$");
47 ################################################################################
50 jennifer_version = "$Revision: 1.46 $";
60 # Aliases to the real vars in the Katie class; hysterical raisins.
68 ###############################################################################
71 global Cnf, Options, Katie, changes, dsc, dsc_files, files, pkg;
75 Cnf = apt_pkg.newConfiguration();
76 apt_pkg.ReadConfigFileISC(Cnf,utils.which_conf_file());
78 Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
79 ('h',"help","Dinstall::Options::Help"),
80 ('n',"no-action","Dinstall::Options::No-Action"),
81 ('p',"no-lock", "Dinstall::Options::No-Lock"),
82 ('s',"no-mail", "Dinstall::Options::No-Mail"),
83 ('V',"version","Dinstall::Options::Version")];
85 for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
86 "override-distribution", "version"]:
87 Cnf["Dinstall::Options::%s" % (i)] = "";
89 changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
90 Options = Cnf.SubTree("Dinstall::Options")
94 elif Options["Version"]:
95 print "jennifer %s" % (jennifer_version);
98 Katie = katie.Katie(Cnf);
100 changes = Katie.pkg.changes;
102 dsc_files = Katie.pkg.dsc_files;
103 files = Katie.pkg.files;
106 return changes_files;
108 ################################################################################
110 def usage (exit_code=0):
111 print """Usage: dinstall [OPTION]... [CHANGES]...
112 -a, --automatic automatic run
113 -h, --help show this help and exit.
114 -n, --no-action don't do anything
115 -p, --no-lock don't check lockfile !! for cron.daily only !!
116 -s, --no-mail don't send any mail
117 -V, --version display the version number and exit"""
120 ################################################################################
122 def reject (str, prefix="Rejected: "):
123 global reject_message;
125 reject_message += prefix + str + "\n";
127 ################################################################################
129 def copy_to_holding(filename):
132 base_filename = os.path.basename(filename);
134 dest = Cnf["Dir::Queue::Holding"] + '/' + base_filename;
136 fd = os.open(dest, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0640);
139 # Shouldn't happen, but will if, for example, someone lists a
140 # file twice in the .changes.
141 if errno.errorcode[e.errno] == 'EEXIST':
142 reject("%s: already exists in holding area; can not overwrite." % (base_filename));
147 shutil.copy(filename, dest);
149 # In either case (ENOENT or EACCES) we want to remove the
150 # O_CREAT | O_EXCLed ghost file, so add the file to the list
151 # of 'in holding' even if it's not the real file.
152 if errno.errorcode[e.errno] == 'ENOENT':
153 reject("%s: can not copy to holding area: file not found." % (base_filename));
156 elif errno.errorcode[e.errno] == 'EACCES':
157 reject("%s: can not copy to holding area: read permission denied." % (base_filename));
162 in_holding[base_filename] = "";
164 ################################################################################
170 os.chdir(Cnf["Dir::Queue::Holding"]);
171 for file in in_holding.keys():
172 if os.path.exists(file):
173 if file.find('/') != -1:
174 utils.fubar("WTF? clean_holding() got a file ('%s') with / in it!" % (file));
180 ################################################################################
183 filename = pkg.changes_file;
185 # Default in case we bail out
186 changes["maintainer822"] = Cnf["Dinstall::MyEmailAddress"];
187 changes["changedby822"] = Cnf["Dinstall::MyEmailAddress"];
188 changes["architecture"] = {};
190 # Parse the .changes field into a dictionary
192 changes.update(utils.parse_changes(filename));
193 except utils.cant_open_exc:
194 reject("%s: can't read file." % (filename));
196 except utils.changes_parse_error_exc, line:
197 reject("%s: parse error, can't grok: %s." % (filename, line));
200 # Parse the Files field from the .changes into another dictionary
202 files.update(utils.build_file_list(changes));
203 except utils.changes_parse_error_exc, line:
204 reject("%s: parse error, can't grok: %s." % (filename, line));
205 except utils.nk_format_exc, format:
206 reject("%s: unknown format '%s'." % (filename, format));
209 # Check for mandatory fields
210 for i in ("source", "binary", "architecture", "version", "distribution", "maintainer", "files"):
211 if not changes.has_key(i):
212 reject("%s: Missing mandatory field `%s'." % (filename, i));
213 return 0 # Avoid <undef> errors during later tests
215 # Split multi-value fields into a lower-level dictionary
216 for i in ("architecture", "distribution", "binary", "closes"):
217 o = changes.get(i, "")
224 # Fix the Maintainer: field to be RFC822 compatible
225 (changes["maintainer822"], changes["maintainername"], changes["maintaineremail"]) = utils.fix_maintainer (changes["maintainer"])
227 # Fix the Changed-By: field to be RFC822 compatible; if it exists.
228 (changes["changedby822"], changes["changedbyname"], changes["changedbyemail"]) = utils.fix_maintainer(changes.get("changed-by",""));
230 # Ensure all the values in Closes: are numbers
231 if changes.has_key("closes"):
232 for i in changes["closes"].keys():
233 if katie.re_isanum.match (i) == None:
234 reject("%s: `%s' from Closes field isn't a number." % (filename, i));
237 # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
238 changes["chopversion"] = utils.re_no_epoch.sub('', changes["version"])
239 changes["chopversion2"] = utils.re_no_revision.sub('', changes["chopversion"])
241 # Check there isn't already a changes file of the same name in one
242 # of the queue directories.
243 base_filename = os.path.basename(filename);
244 for dir in [ "Accepted", "Byhand", "Done", "New" ]:
245 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+base_filename):
246 reject("%s: a file with this name already exists in the %s directory." % (base_filename, dir));
248 # Check the .changes is non-empty
250 reject("%s: nothing to do (Files field is empty)." % (base_filename))
255 ################################################################################
257 def check_distributions():
258 "Check and map the Distribution field of a .changes file."
260 # Handle suite mappings
261 for map in Cnf.ValueList("SuiteMappings"):
264 if type == "map" or type == "silent-map":
265 (source, dest) = args[1:3];
266 if changes["distribution"].has_key(source):
267 del changes["distribution"][source]
268 changes["distribution"][dest] = 1;
269 if type != "silent-map":
270 reject("Mapping %s to %s." % (source, dest),"");
271 elif type == "map-unreleased":
272 (source, dest) = args[1:3];
273 if changes["distribution"].has_key(source):
274 for arch in changes["architecture"].keys():
275 if arch not in Cnf.ValueList("Suite::%s::Architectures" % (source)):
276 reject("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch),"");
277 del changes["distribution"][source];
278 changes["distribution"][dest] = 1;
280 elif type == "ignore":
282 if changes["distribution"].has_key(suite):
283 del changes["distribution"][suite];
284 reject("Ignoring %s as a target suite." % (suite), "Warning: ");
286 # Ensure there is (still) a target distribution
287 if changes["distribution"].keys() == []:
288 reject("no valid distribution.");
290 # Ensure target distributions exist
291 for suite in changes["distribution"].keys():
292 if not Cnf.has_key("Suite::%s" % (suite)):
293 reject("Unknown distribution `%s'." % (suite));
295 ################################################################################
300 archive = utils.where_am_i();
301 file_keys = files.keys();
303 # if reprocess is 2 we've already done this and we're checking
304 # things again for the new .orig.tar.gz.
305 # [Yes, I'm fully aware of how disgusting this is]
306 if not Options["No-Action"] and reprocess < 2:
308 os.chdir(pkg.directory);
309 for file in file_keys:
310 copy_to_holding(file);
317 for file in file_keys:
318 # Ensure the file does not already exist in one of the accepted directories
319 for dir in [ "Accepted", "Byhand", "New" ]:
320 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+file):
321 reject("%s file already exists in the %s directory." % (file, dir));
322 if not utils.re_taint_free.match(file):
323 reject("!!WARNING!! tainted filename: '%s'." % (file));
324 # Check the file is readable
325 if os.access(file,os.R_OK) == 0:
326 # When running in -n, copy_to_holding() won't have
327 # generated the reject_message, so we need to.
328 if Options["No-Action"]:
329 if os.path.exists(file):
330 reject("Can't read `%s'. [permission denied]" % (file));
332 reject("Can't read `%s'. [file not found]" % (file));
333 files[file]["type"] = "unreadable";
335 # If it's byhand skip remaining checks
336 if files[file]["section"] == "byhand":
337 files[file]["byhand"] = 1;
338 files[file]["type"] = "byhand";
339 # Checks for a binary package...
340 elif utils.re_isadeb.match(file):
342 files[file]["type"] = "deb";
344 # Extract package control information
345 deb_file = utils.open_file(file);
347 control = apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file));
349 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
351 # Can't continue, none of the checks on control would work.
355 # Check for mandatory fields
356 for field in [ "Package", "Architecture", "Version" ]:
357 if control.Find(field) == None:
358 reject("%s: No %s field in control." % (file, field));
362 # Ensure the package name matches the one give in the .changes
363 if not changes["binary"].has_key(control.Find("Package", "")):
364 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
366 # Validate the package field
367 package = control.Find("Package");
368 if not re_valid_pkg_name.match(package):
369 reject("%s: invalid package name '%s'." % (file, package));
371 # Validate the version field
372 version = control.Find("Version");
373 if not re_valid_version.match(version):
374 reject("%s: invalid version number '%s'." % (file, version));
376 # Ensure the architecture of the .deb is one we know about.
377 default_suite = Cnf.get("Dinstall::DefaultSuite", "Unstable")
378 architecture = control.Find("Architecture");
379 if architecture not in Cnf.ValueList("Suite::%s::Architectures" % (default_suite)):
380 reject("Unknown architecture '%s'." % (architecture));
382 # Ensure the architecture of the .deb is one of the ones
383 # listed in the .changes.
384 if not changes["architecture"].has_key(architecture):
385 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, architecture));
387 # Sanity-check the Depends field
388 depends = control.Find("Depends");
390 reject("%s: Depends field is empty." % (file));
392 # Check the section & priority match those given in the .changes (non-fatal)
393 if control.Find("Section") and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
394 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
395 if control.Find("Priority") and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
396 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
398 files[file]["package"] = package;
399 files[file]["architecture"] = architecture;
400 files[file]["version"] = version;
401 files[file]["maintainer"] = control.Find("Maintainer", "");
402 if file.endswith(".udeb"):
403 files[file]["dbtype"] = "udeb";
404 elif file.endswith(".deb"):
405 files[file]["dbtype"] = "deb";
407 reject("%s is neither a .deb or a .udeb." % (file));
408 files[file]["source"] = control.Find("Source", files[file]["package"]);
409 # Get the source version
410 source = files[file]["source"];
412 if source.find("(") != -1:
413 m = utils.re_extract_src_version.match(source);
415 source_version = m.group(2);
416 if not source_version:
417 source_version = files[file]["version"];
418 files[file]["source package"] = source;
419 files[file]["source version"] = source_version;
421 # Ensure the filename matches the contents of the .deb
422 m = utils.re_isadeb.match(file);
424 file_package = m.group(1);
425 if files[file]["package"] != file_package:
426 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"]));
427 epochless_version = utils.re_no_epoch.sub('', control.Find("Version"));
429 file_version = m.group(2);
430 if epochless_version != file_version:
431 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
433 file_architecture = m.group(3);
434 if files[file]["architecture"] != file_architecture:
435 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"]));
437 # Check for existent source
438 source_version = files[file]["source version"];
439 source_package = files[file]["source package"];
440 if changes["architecture"].has_key("source"):
441 if source_version != changes["version"]:
442 reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
444 # Check in the SQL database
445 if not Katie.source_exists(source_package, source_version, changes["distribution"].keys()):
446 # Check in one of the other directories
447 source_epochless_version = utils.re_no_epoch.sub('', source_version);
448 dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
449 if os.path.exists(Cnf["Dir::Queue::Byhand"] + '/' + dsc_filename):
450 files[file]["byhand"] = 1;
451 elif os.path.exists(Cnf["Dir::Queue::New"] + '/' + dsc_filename):
452 files[file]["new"] = 1;
453 elif not os.path.exists(Cnf["Dir::Queue::Accepted"] + '/' + dsc_filename):
454 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
455 # Check the version and for file overwrites
456 reject(Katie.check_binary_against_db(file),"");
458 # Checks for a source package...
460 m = utils.re_issource.match(file);
463 files[file]["package"] = m.group(1);
464 files[file]["version"] = m.group(2);
465 files[file]["type"] = m.group(3);
467 # Ensure the source package name matches the Source filed in the .changes
468 if changes["source"] != files[file]["package"]:
469 reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
471 # Ensure the source version matches the version in the .changes file
472 if files[file]["type"] == "orig.tar.gz":
473 changes_version = changes["chopversion2"];
475 changes_version = changes["chopversion"];
476 if changes_version != files[file]["version"]:
477 reject("%s: should be %s according to changes file." % (file, changes_version));
479 # Ensure the .changes lists source in the Architecture field
480 if not changes["architecture"].has_key("source"):
481 reject("%s: changes file doesn't list `source' in Architecture field." % (file));
483 # Check the signature of a .dsc file
484 if files[file]["type"] == "dsc":
485 dsc["fingerprint"] = utils.check_signature(file, reject);
487 files[file]["architecture"] = "source";
489 # Not a binary or source package? Assume byhand...
491 files[file]["byhand"] = 1;
492 files[file]["type"] = "byhand";
494 # Per-suite file checks
495 files[file]["oldfiles"] = {};
496 for suite in changes["distribution"].keys():
498 if files[file].has_key("byhand"):
501 # Handle component mappings
502 for map in Cnf.ValueList("ComponentMappings"):
503 (source, dest) = map.split();
504 if files[file]["component"] == source:
505 files[file]["original component"] = source;
506 files[file]["component"] = dest;
507 # Ensure the component is valid for the target suite
508 if Cnf.has_key("Suite:%s::Components" % (suite)) and \
509 files[file]["component"] not in Cnf.ValueList("Suite::%s::Components" % (suite)):
510 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
513 # See if the package is NEW
514 if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
515 files[file]["new"] = 1;
517 # Validate the component
518 component = files[file]["component"];
519 component_id = db_access.get_component_id(component);
520 if component_id == -1:
521 reject("file '%s' has unknown component '%s'." % (file, component));
524 # Validate the priority
525 if files[file]["priority"].find('/') != -1:
526 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
528 # Determine the location
529 location = Cnf["Dir::Pool"];
530 location_id = db_access.get_location_id (location, component, archive);
531 if location_id == -1:
532 reject("[INTERNAL ERROR] couldn't determine location (Component: %s, Archive: %s)" % (component, archive));
533 files[file]["location id"] = location_id;
535 # Check the md5sum & size against existing files (if any)
536 files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
537 files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
539 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
541 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
542 files[file]["files id"] = files_id
544 # Check for packages that have moved from one component to another
545 q = Katie.projectB.query("""
546 SELECT c.name FROM binaries b, bin_associations ba, suite s, location l,
547 component c, architecture a, files f
548 WHERE b.package = '%s' AND s.suite_name = '%s'
549 AND (a.arch_string = '%s' OR a.arch_string = 'all')
550 AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
551 AND f.location = l.id AND l.component = c.id AND b.file = f.id"""
552 % (files[file]["package"], suite,
553 files[file]["architecture"]));
556 files[file]["othercomponents"] = ql[0][0];
558 # If the .changes file says it has source, it must have source.
559 if changes["architecture"].has_key("source"):
561 reject("no source found and Architecture line in changes mention source.");
563 if not has_binaries and Cnf.FindB("Dinstall::Reject::NoSourceOnly"):
564 reject("source only uploads are not supported.");
566 ###############################################################################
571 # Ensure there is source to check
572 if not changes["architecture"].has_key("source"):
577 for file in files.keys():
578 if files[file]["type"] == "dsc":
580 reject("can not process a .changes file with multiple .dsc's.");
585 # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
589 # Parse the .dsc file
591 dsc.update(utils.parse_changes(dsc_filename, dsc_whitespace_rules=1));
592 except utils.cant_open_exc:
593 # if not -n copy_to_holding() will have done this for us...
594 if Options["No-Action"]:
595 reject("%s: can't read file." % (dsc_filename));
596 except utils.changes_parse_error_exc, line:
597 reject("%s: parse error, can't grok: %s." % (dsc_filename, line));
598 except utils.invalid_dsc_format_exc, line:
599 reject("%s: syntax error on line %s." % (dsc_filename, line));
600 # Build up the file list of files mentioned by the .dsc
602 dsc_files.update(utils.build_file_list(dsc, is_a_dsc=1));
603 except utils.no_files_exc:
604 reject("%s: no Files: field." % (dsc_filename));
606 except utils.changes_parse_error_exc, line:
607 reject("%s: parse error, can't grok: %s." % (dsc_filename, line));
610 # Enforce mandatory fields
611 for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
612 if not dsc.has_key(i):
613 reject("%s: missing mandatory field `%s'." % (dsc_filename, i));
615 # Validate the source and version fields
616 if dsc.has_key("source") and not re_valid_pkg_name.match(dsc["source"]):
617 reject("%s: invalid source name '%s'." % (dsc_filename, dsc["source"]));
618 if dsc.has_key("version") and not re_valid_version.match(dsc["version"]):
619 reject("%s: invalid version number '%s'." % (dsc_filename, dsc["version"]));
621 # Bumping the version number of the .dsc breaks extraction by stable's
622 # dpkg-source. So let's not do that...
623 if dsc["format"] != "1.0":
624 reject("%s: incompatible 'Format' version produced by a broken version of dpkg-dev 1.9.1{3,4}." % (dsc_filename));
626 # Validate the build-depends field(s)
627 for field_name in [ "build-depends", "build-depends-indep" ]:
628 field = dsc.get(field_name);
630 # Check for broken dpkg-dev lossage...
631 if field.startswith("ARRAY"):
632 reject("%s: invalid %s field produced by a broken version of dpkg-dev (1.10.11)" % (dsc_filename, field_name.title()));
634 # Have apt try to parse them...
636 apt_pkg.ParseSrcDepends(field);
638 reject("%s: invalid %s field (can not be parsed by apt)." % (dsc_filename, field_name.title()));
641 # Ensure the version number in the .dsc matches the version number in the .changes
642 epochless_dsc_version = utils.re_no_epoch.sub('', dsc.get("version"));
643 changes_version = files[dsc_filename]["version"];
644 if epochless_dsc_version != files[dsc_filename]["version"]:
645 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
647 # Ensure there is a .tar.gz in the .dsc file
649 for f in dsc_files.keys():
650 m = utils.re_issource.match(f);
652 reject("%s: %s in Files field not recognised as source." % (dsc_filename, f));
654 if type == "orig.tar.gz" or type == "tar.gz":
657 reject("%s: no .tar.gz or .orig.tar.gz in 'Files' field." % (dsc_filename));
659 # Ensure source is newer than existing source in target suites
660 reject(Katie.check_source_against_db(dsc_filename),"");
662 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(dsc_filename);
663 reject(reject_msg, "");
665 if not Options["No-Action"]:
666 copy_to_holding(is_in_incoming);
667 orig_tar_gz = os.path.basename(is_in_incoming);
668 files[orig_tar_gz] = {};
669 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
670 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
671 files[orig_tar_gz]["section"] = files[dsc_filename]["section"];
672 files[orig_tar_gz]["priority"] = files[dsc_filename]["priority"];
673 files[orig_tar_gz]["component"] = files[dsc_filename]["component"];
674 files[orig_tar_gz]["type"] = "orig.tar.gz";
677 ################################################################################
679 def get_changelog_versions(source_dir):
680 """Extracts a the source package and (optionally) grabs the
681 version history out of debian/changelog for the BTS."""
683 # Find the .dsc (again)
685 for file in files.keys():
686 if files[file]["type"] == "dsc":
689 # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
693 # Create a symlink mirror of the source files in our temporary directory
694 for f in files.keys():
695 m = utils.re_issource.match(f);
697 src = os.path.join(source_dir, f);
698 # If a file is missing for whatever reason, give up.
699 if not os.path.exists(src):
702 if type == "orig.tar.gz" and pkg.orig_tar_gz:
705 dest = os.path.join(os.getcwd(), f);
706 os.symlink(src, dest);
708 # If the orig.tar.gz is not a part of the upload, create a symlink to the
711 dest = os.path.join(os.getcwd(), os.path.basename(pkg.orig_tar_gz));
712 os.symlink(pkg.orig_tar_gz, dest);
715 cmd = "dpkg-source -sn -x %s" % (dsc_filename);
716 (result, output) = commands.getstatusoutput(cmd);
718 reject("'dpkg-source -x' failed for %s [return code: %s]." % (dsc_filename, result));
719 reject(utils.prefix_multi_line_string(output, " [dpkg-source output:] "), "");
722 if not Cnf.Find("Dir::Queue::BTSVersionTrack"):
725 # Get the upstream version
726 upstr_version = utils.re_no_epoch.sub('', dsc["version"]);
727 if re_strip_revision.search(upstr_version):
728 upstr_version = re_strip_revision.sub('', upstr_version);
730 # Ensure the changelog file exists
731 changelog_filename = "%s-%s/debian/changelog" % (dsc["source"], upstr_version);
732 if not os.path.exists(changelog_filename):
733 reject("%s: debian/changelog not found in extracted source." % (dsc_filename));
736 # Parse the changelog
737 dsc["bts changelog"] = "";
738 changelog_file = utils.open_file(changelog_filename);
739 for line in changelog_file.readlines():
740 m = re_changelog_versions.match(line);
742 dsc["bts changelog"] += line;
743 changelog_file.close();
745 # Check we found at least one revision in the changelog
746 if not dsc["bts changelog"]:
747 reject("%s: changelog format not recognised (empty version tree)." % (dsc_filename));
749 ########################################
753 # a) there's no source
754 # or b) reprocess is 2 - we will do this check next time when orig.tar.gz is in 'files'
755 # or c) the orig.tar.gz is MIA
756 if not changes["architecture"].has_key("source") or reprocess == 2 \
757 or pkg.orig_tar_gz == -1:
760 # Create a temporary directory to extract the source into
761 if Options["No-Action"]:
762 tmpdir = tempfile.mktemp();
764 # We're in queue/holding and can create a random directory.
765 tmpdir = "%s" % (os.getpid());
768 # Move into the temporary directory
772 # Get the changelog version history
773 get_changelog_versions(cwd);
775 # Move back and cleanup the temporary tree
777 shutil.rmtree(tmpdir);
779 ################################################################################
781 # FIXME: should be a debian specific check called from a hook
783 def check_urgency ():
784 if changes["architecture"].has_key("source"):
785 if not changes.has_key("urgency"):
786 changes["urgency"] = Cnf["Urgency::Default"];
787 if changes["urgency"] not in Cnf.ValueList("Urgency::Valid"):
788 reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
789 changes["urgency"] = Cnf["Urgency::Default"];
790 changes["urgency"] = changes["urgency"].lower();
792 ################################################################################
794 def check_md5sums ():
795 for file in files.keys():
797 file_handle = utils.open_file(file);
798 except utils.cant_open_exc:
802 if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
803 reject("%s: md5sum check failed." % (file));
806 actual_size = os.stat(file)[stat.ST_SIZE];
807 size = int(files[file]["size"]);
808 if size != actual_size:
809 reject("%s: actual file size (%s) does not match size (%s) in .changes"
810 % (file, actual_size, size));
812 for file in dsc_files.keys():
814 file_handle = utils.open_file(file);
815 except utils.cant_open_exc:
819 if apt_pkg.md5sum(file_handle) != dsc_files[file]["md5sum"]:
820 reject("%s: md5sum check failed." % (file));
823 actual_size = os.stat(file)[stat.ST_SIZE];
824 size = int(dsc_files[file]["size"]);
825 if size != actual_size:
826 reject("%s: actual file size (%s) does not match size (%s) in .dsc"
827 % (file, actual_size, size));
829 ################################################################################
831 # Sanity check the time stamps of files inside debs.
832 # [Files in the near future cause ugly warnings and extreme time
833 # travel can cause errors on extraction]
835 def check_timestamps():
837 def __init__(self, future_cutoff, past_cutoff):
839 self.future_cutoff = future_cutoff;
840 self.past_cutoff = past_cutoff;
843 self.future_files = {};
844 self.ancient_files = {};
846 def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
847 if MTime > self.future_cutoff:
848 self.future_files[Name] = MTime;
849 if MTime < self.past_cutoff:
850 self.ancient_files[Name] = MTime;
853 future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"]);
854 past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"));
855 tar = Tar(future_cutoff, past_cutoff);
856 for filename in files.keys():
857 if files[filename]["type"] == "deb":
860 deb_file = utils.open_file(filename);
861 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz");
863 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz");
866 future_files = tar.future_files.keys();
868 num_future_files = len(future_files);
869 future_file = future_files[0];
870 future_date = tar.future_files[future_file];
871 reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
872 % (filename, num_future_files, future_file,
873 time.ctime(future_date)));
875 ancient_files = tar.ancient_files.keys();
877 num_ancient_files = len(ancient_files);
878 ancient_file = ancient_files[0];
879 ancient_date = tar.ancient_files[ancient_file];
880 reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
881 % (filename, num_ancient_files, ancient_file,
882 time.ctime(ancient_date)));
884 reject("%s: deb contents timestamp check failed [%s: %s]" % (filename, sys.exc_type, sys.exc_value));
886 ################################################################################
887 ################################################################################
889 # If any file of an upload has a recent mtime then chances are good
890 # the file is still being uploaded.
892 def upload_too_new():
894 # Move back to the original directory to get accurate time stamps
896 os.chdir(pkg.directory);
897 file_list = pkg.files.keys();
898 file_list.extend(pkg.dsc_files.keys());
899 file_list.append(pkg.changes_file);
900 for file in file_list:
902 last_modified = time.time()-os.path.getmtime(file);
903 if last_modified < int(Cnf["Dinstall::SkipTime"]):
911 ################################################################################
914 # changes["distribution"] may not exist in corner cases
915 # (e.g. unreadable changes files)
916 if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
917 changes["distribution"] = {};
919 (summary, short_summary) = Katie.build_summaries();
922 for file in files.keys():
923 if files[file].has_key("byhand"):
925 elif files[file].has_key("new"):
928 (prompt, answer) = ("", "XXX")
929 if Options["No-Action"] or Options["Automatic"]:
932 if reject_message.find("Rejected") != -1:
934 print "SKIP (too new)\n" + reject_message,;
935 prompt = "[S]kip, Quit ?";
937 print "REJECT\n" + reject_message,;
938 prompt = "[R]eject, Skip, Quit ?";
939 if Options["Automatic"]:
942 print "NEW to %s\n%s%s" % (", ".join(changes["distribution"].keys()), reject_message, summary),;
943 prompt = "[N]ew, Skip, Quit ?";
944 if Options["Automatic"]:
947 print "BYHAND\n" + reject_message + summary,;
948 prompt = "[B]yhand, Skip, Quit ?";
949 if Options["Automatic"]:
952 print "ACCEPT\n" + reject_message + summary,;
953 prompt = "[A]ccept, Skip, Quit ?";
954 if Options["Automatic"]:
957 while prompt.find(answer) == -1:
958 answer = utils.our_raw_input(prompt);
959 m = katie.re_default_answer.match(prompt);
962 answer = answer[:1].upper();
965 os.chdir (pkg.directory);
966 Katie.do_reject(0, reject_message);
968 accept(summary, short_summary);
972 acknowledge_new (summary);
976 ################################################################################
978 def accept (summary, short_summary):
979 Katie.accept(summary, short_summary);
980 Katie.check_override();
982 # Finally, remove the originals from the unchecked directory
983 os.chdir (pkg.directory);
984 for file in files.keys():
986 os.unlink(pkg.changes_file);
988 ################################################################################
990 def do_byhand (summary):
991 print "Moving to BYHAND holding area."
992 Logger.log(["Moving to byhand", pkg.changes_file]);
994 Katie.dump_vars(Cnf["Dir::Queue::Byhand"]);
996 file_keys = files.keys();
998 # Move all the files into the byhand directory
999 utils.move (pkg.changes_file, Cnf["Dir::Queue::Byhand"]);
1000 for file in file_keys:
1001 utils.move (file, Cnf["Dir::Queue::Byhand"], perms=0660);
1003 # Check for override disparities
1004 Katie.Subst["__SUMMARY__"] = summary;
1005 Katie.check_override();
1007 # Finally remove the originals.
1008 os.chdir (pkg.directory);
1009 for file in file_keys:
1011 os.unlink(pkg.changes_file);
1013 ################################################################################
1015 def acknowledge_new (summary):
1016 Subst = Katie.Subst;
1018 print "Moving to NEW holding area."
1019 Logger.log(["Moving to new", pkg.changes_file]);
1021 Katie.dump_vars(Cnf["Dir::Queue::New"]);
1023 file_keys = files.keys();
1025 # Move all the files into the 'new' directory
1026 utils.move (pkg.changes_file, Cnf["Dir::Queue::New"]);
1027 for file in file_keys:
1028 utils.move (file, Cnf["Dir::Queue::New"], perms=0660);
1030 if not Options["No-Mail"]:
1031 print "Sending new ack.";
1032 Subst["__SUMMARY__"] = summary;
1033 new_ack_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/jennifer.new");
1034 utils.send_mail(new_ack_message);
1036 # Finally remove the originals.
1037 os.chdir (pkg.directory);
1038 for file in file_keys:
1040 os.unlink(pkg.changes_file);
1042 ################################################################################
1044 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1045 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1046 # Katie.check_dsc_against_db() can find the .orig.tar.gz but it will
1047 # not have processed it during it's checks of -2. If -1 has been
1048 # deleted or otherwise not checked by jennifer, the .orig.tar.gz will
1049 # not have been checked at all. To get round this, we force the
1050 # .orig.tar.gz into the .changes structure and reprocess the .changes
1053 def process_it (changes_file):
1054 global reprocess, reject_message;
1056 # Reset some globals
1059 reject_message = "";
1061 # Absolutize the filename to avoid the requirement of being in the
1062 # same directory as the .changes file.
1063 pkg.changes_file = os.path.abspath(changes_file);
1065 # Remember where we are so we can come back after cd-ing into the
1066 # holding directory.
1067 pkg.directory = os.getcwd();
1070 # If this is the Real Thing(tm), copy things into a private
1071 # holding directory first to avoid replacable file races.
1072 if not Options["No-Action"]:
1073 os.chdir(Cnf["Dir::Queue::Holding"]);
1074 copy_to_holding(pkg.changes_file);
1075 # Relativize the filename so we use the copy in holding
1076 # rather than the original...
1077 pkg.changes_file = os.path.basename(pkg.changes_file);
1078 changes["fingerprint"] = utils.check_signature(pkg.changes_file, reject);
1079 changes_valid = check_changes();
1082 check_distributions();
1089 Katie.update_subst(reject_message);
1095 traceback.print_exc(file=sys.stderr);
1098 # Restore previous WD
1099 os.chdir(pkg.directory);
1101 ###############################################################################
1104 global Cnf, Options, Logger;
1106 changes_files = init();
1108 # -n/--dry-run invalidates some other options which would involve things happening
1109 if Options["No-Action"]:
1110 Options["Automatic"] = "";
1112 # Ensure all the arguments we were given are .changes files
1113 for file in changes_files:
1114 if not file.endswith(".changes"):
1115 utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
1116 changes_files.remove(file);
1118 if changes_files == []:
1119 utils.fubar("Need at least one .changes file as an argument.");
1121 # Check that we aren't going to clash with the daily cron job
1123 if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::Root"])) and not Options["No-Lock"]:
1124 utils.fubar("Archive maintenance in progress. Try again later.");
1126 # Obtain lock if not in no-action mode and initialize the log
1128 if not Options["No-Action"]:
1129 lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1131 fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB);
1133 if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
1134 utils.fubar("Couldn't obtain lock; assuming another jennifer is already running.");
1137 Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1139 # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1140 bcc = "X-Katie: %s" % (jennifer_version);
1141 if Cnf.has_key("Dinstall::Bcc"):
1142 Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1144 Katie.Subst["__BCC__"] = bcc;
1147 # Sort the .changes files so that we process sourceful ones first
1148 changes_files.sort(utils.changes_compare);
1150 # Process the changes files
1151 for changes_file in changes_files:
1152 print "\n" + changes_file;
1154 process_it (changes_file);
1156 if not Options["No-Action"]:
1159 accept_count = Katie.accept_count;
1160 accept_bytes = Katie.accept_bytes;
1163 if accept_count > 1:
1165 print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)));
1166 Logger.log(["total",accept_count,accept_bytes]);
1168 if not Options["No-Action"]:
1171 ################################################################################
1173 if __name__ == '__main__':