3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001, 2002, 2003 James Troup <james@nocrew.org>
5 # $Id: jennifer,v 1.39 2003-10-14 19:16:16 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 errno, fcntl, gzip, os, re, shutil, stat, sys, time, 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\+\-\.]+$");
45 ################################################################################
48 jennifer_version = "$Revision: 1.39 $";
58 # Aliases to the real vars in the Katie class; hysterical raisins.
66 ###############################################################################
69 global Cnf, Options, Katie, changes, dsc, dsc_files, files, pkg;
73 Cnf = apt_pkg.newConfiguration();
74 apt_pkg.ReadConfigFileISC(Cnf,utils.which_conf_file());
76 Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
77 ('h',"help","Dinstall::Options::Help"),
78 ('n',"no-action","Dinstall::Options::No-Action"),
79 ('p',"no-lock", "Dinstall::Options::No-Lock"),
80 ('s',"no-mail", "Dinstall::Options::No-Mail"),
81 ('V',"version","Dinstall::Options::Version")];
83 for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
84 "override-distribution", "version"]:
85 Cnf["Dinstall::Options::%s" % (i)] = "";
87 changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
88 Options = Cnf.SubTree("Dinstall::Options")
92 elif Options["Version"]:
93 print "jennifer %s" % (jennifer_version);
96 Katie = katie.Katie(Cnf);
98 changes = Katie.pkg.changes;
100 dsc_files = Katie.pkg.dsc_files;
101 files = Katie.pkg.files;
104 return changes_files;
106 ################################################################################
108 def usage (exit_code=0):
109 print """Usage: dinstall [OPTION]... [CHANGES]...
110 -a, --automatic automatic run
111 -h, --help show this help and exit.
112 -n, --no-action don't do anything
113 -p, --no-lock don't check lockfile !! for cron.daily only !!
114 -s, --no-mail don't send any mail
115 -V, --version display the version number and exit"""
118 ################################################################################
120 def reject (str, prefix="Rejected: "):
121 global reject_message;
123 reject_message += prefix + str + "\n";
125 ################################################################################
127 def copy_to_holding(filename):
130 base_filename = os.path.basename(filename);
132 dest = Cnf["Dir::Queue::Holding"] + '/' + base_filename;
134 fd = os.open(dest, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0640);
137 # Shouldn't happen, but will if, for example, someone lists a
138 # file twice in the .changes.
139 if errno.errorcode[e.errno] == 'EEXIST':
140 reject("%s already exists in holding area; can not overwrite." % (base_filename));
145 shutil.copy(filename, dest);
147 # In either case (ENOENT or EACCES) we want to remove the
148 # O_CREAT | O_EXCLed ghost file, so add the file to the list
149 # of 'in holding' even if it's not the real file.
150 if errno.errorcode[e.errno] == 'ENOENT':
151 reject("can not copy %s to holding area: file not found." % (base_filename));
154 elif errno.errorcode[e.errno] == 'EACCES':
155 reject("can not copy %s to holding area: read permission denied." % (base_filename));
160 in_holding[base_filename] = "";
162 ################################################################################
168 os.chdir(Cnf["Dir::Queue::Holding"]);
169 for file in in_holding.keys():
170 if os.path.exists(file):
171 if file.find('/') != -1:
172 utils.fubar("WTF? clean_holding() got a file ('%s') with / in it!" % (file));
178 ################################################################################
181 filename = pkg.changes_file;
183 # Default in case we bail out
184 changes["maintainer822"] = Cnf["Dinstall::MyEmailAddress"];
185 changes["changedby822"] = Cnf["Dinstall::MyEmailAddress"];
186 changes["architecture"] = {};
188 # Parse the .changes field into a dictionary
190 changes.update(utils.parse_changes(filename));
191 except utils.cant_open_exc:
192 reject("can't read changes file '%s'." % (filename));
194 except utils.changes_parse_error_exc, line:
195 reject("error parsing changes file '%s', can't grok: %s." % (filename, line));
198 # Parse the Files field from the .changes into another dictionary
200 files.update(utils.build_file_list(changes));
201 except utils.changes_parse_error_exc, line:
202 reject("error parsing changes file '%s', can't grok: %s." % (filename, line));
203 except utils.nk_format_exc, format:
204 reject("unknown format '%s' of changes file '%s'." % (format, filename));
207 # Check for mandatory fields
208 for i in ("source", "binary", "architecture", "version", "distribution", "maintainer", "files"):
209 if not changes.has_key(i):
210 reject("Missing field `%s' in changes file." % (i));
211 return 0 # Avoid <undef> errors during later tests
213 # Split multi-value fields into a lower-level dictionary
214 for i in ("architecture", "distribution", "binary", "closes"):
215 o = changes.get(i, "")
222 # Fix the Maintainer: field to be RFC822 compatible
223 (changes["maintainer822"], changes["maintainername"], changes["maintaineremail"]) = utils.fix_maintainer (changes["maintainer"])
225 # Fix the Changed-By: field to be RFC822 compatible; if it exists.
226 (changes["changedby822"], changes["changedbyname"], changes["changedbyemail"]) = utils.fix_maintainer(changes.get("changed-by",""));
228 # Ensure all the values in Closes: are numbers
229 if changes.has_key("closes"):
230 for i in changes["closes"].keys():
231 if katie.re_isanum.match (i) == None:
232 reject("`%s' from Closes field isn't a number." % (i));
235 # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
236 changes["chopversion"] = utils.re_no_epoch.sub('', changes["version"])
237 changes["chopversion2"] = utils.re_no_revision.sub('', changes["chopversion"])
239 # Check there isn't already a changes file of the same name in one
240 # of the queue directories.
241 base_filename = os.path.basename(filename);
242 for dir in [ "Accepted", "Byhand", "Done", "New" ]:
243 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+base_filename):
244 reject("%s: a file with this name already exists in the %s directory." % (base_filename, dir));
248 ################################################################################
250 def check_distributions():
251 "Check and map the Distribution field of a .changes file."
253 # Handle suite mappings
254 for map in Cnf.ValueList("SuiteMappings"):
257 if type == "map" or type == "silent-map":
258 (source, dest) = args[1:3];
259 if changes["distribution"].has_key(source):
260 del changes["distribution"][source]
261 changes["distribution"][dest] = 1;
262 if type != "silent-map":
263 reject("Mapping %s to %s." % (source, dest),"");
264 elif type == "map-unreleased":
265 (source, dest) = args[1:3];
266 if changes["distribution"].has_key(source):
267 for arch in changes["architecture"].keys():
268 if arch not in Cnf.ValueList("Suite::%s::Architectures" % (source)):
269 reject("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch),"");
270 del changes["distribution"][source];
271 changes["distribution"][dest] = 1;
273 elif type == "ignore":
275 if changes["distribution"].has_key(suite):
276 del changes["distribution"][suite];
277 reject("Ignoring %s as a target suite." % (suite), "Warning: ");
279 # Ensure there is (still) a target distribution
280 if changes["distribution"].keys() == []:
281 reject("no valid distribution.");
283 # Ensure target distributions exist
284 for suite in changes["distribution"].keys():
285 if not Cnf.has_key("Suite::%s" % (suite)):
286 reject("Unknown distribution `%s'." % (suite));
288 ################################################################################
293 archive = utils.where_am_i();
294 file_keys = files.keys();
296 # if reprocess is 2 we've already done this and we're checking
297 # things again for the new .orig.tar.gz.
298 # [Yes, I'm fully aware of how disgusting this is]
299 if not Options["No-Action"] and reprocess < 2:
301 os.chdir(pkg.directory);
302 for file in file_keys:
303 copy_to_holding(file);
310 for file in file_keys:
311 # Ensure the file does not already exist in one of the accepted directories
312 for dir in [ "Accepted", "Byhand", "New" ]:
313 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+file):
314 reject("%s file already exists in the %s directory." % (file, dir));
315 if not utils.re_taint_free.match(file):
316 reject("!!WARNING!! tainted filename: '%s'." % (file));
317 # Check the file is readable
318 if os.access(file,os.R_OK) == 0:
319 # When running in -n, copy_to_holding() won't have
320 # generated the reject_message, so we need to.
321 if Options["No-Action"]:
322 if os.path.exists(file):
323 reject("Can't read `%s'. [permission denied]" % (file));
325 reject("Can't read `%s'. [file not found]" % (file));
326 files[file]["type"] = "unreadable";
328 # If it's byhand skip remaining checks
329 if files[file]["section"] == "byhand":
330 files[file]["byhand"] = 1;
331 files[file]["type"] = "byhand";
332 # Checks for a binary package...
333 elif utils.re_isadeb.match(file) != None:
335 files[file]["type"] = "deb";
337 # Extract package control information
338 deb_file = utils.open_file(file);
340 control = apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file));
342 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
344 # Can't continue, none of the checks on control would work.
348 # Check for mandatory fields
349 for field in [ "Package", "Architecture", "Version" ]:
350 if control.Find(field) == None:
351 reject("%s: No %s field in control." % (file, field));
355 # Ensure the package name matches the one give in the .changes
356 if not changes["binary"].has_key(control.Find("Package", "")):
357 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
359 # Validate the package field
360 package = control.Find("Package");
361 if not re_valid_pkg_name.match(package):
362 reject("%s: invalid package name '%s'." % (file, package));
364 # Validate the version field
365 version = control.Find("Version");
366 if not re_valid_version.match(version):
367 reject("%s: invalid version number '%s'." % (file, version));
369 # Ensure the architecture of the .deb is one we know about.
370 default_suite = Cnf.get("Dinstall::DefaultSuite", "Unstable")
371 architecture = control.Find("Architecture");
372 if architecture not in Cnf.ValueList("Suite::%s::Architectures" % (default_suite)):
373 reject("Unknown architecture '%s'." % (architecture));
375 # Ensure the architecture of the .deb is one of the ones
376 # listed in the .changes.
377 if not changes["architecture"].has_key(architecture):
378 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, architecture));
380 # Sanity-check the Depends field
381 depends = control.Find("Depends");
383 reject("%s: Depends field is empty." % (file));
385 # Check the section & priority match those given in the .changes (non-fatal)
386 if control.Find("Section") != None and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
387 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
388 if control.Find("Priority") != None and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
389 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
391 files[file]["package"] = package;
392 files[file]["architecture"] = architecture;
393 files[file]["version"] = version;
394 files[file]["maintainer"] = control.Find("Maintainer", "");
395 if file.endswith(".udeb"):
396 files[file]["dbtype"] = "udeb";
397 elif file.endswith(".deb"):
398 files[file]["dbtype"] = "deb";
400 reject("%s is neither a .deb or a .udeb." % (file));
401 files[file]["source"] = control.Find("Source", files[file]["package"]);
402 # Get the source version
403 source = files[file]["source"];
405 if source.find("(") != -1:
406 m = utils.re_extract_src_version.match(source)
408 source_version = m.group(2)
409 if not source_version:
410 source_version = files[file]["version"];
411 files[file]["source package"] = source;
412 files[file]["source version"] = source_version;
414 # Ensure the filename matches the contents of the .deb
415 m = utils.re_isadeb.match(file);
417 file_package = m.group(1);
418 if files[file]["package"] != file_package:
419 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"]));
420 epochless_version = utils.re_no_epoch.sub('', control.Find("Version"));
422 file_version = m.group(2);
423 if epochless_version != file_version:
424 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
426 file_architecture = m.group(3);
427 if files[file]["architecture"] != file_architecture:
428 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"]));
430 # Check for existent source
431 source_version = files[file]["source version"];
432 source_package = files[file]["source package"];
433 if changes["architecture"].has_key("source"):
434 if source_version != changes["version"]:
435 reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
437 # Check in the SQL database
438 if not Katie.source_exists(source_package, source_version, changes["distribution"].keys()):
439 # Check in one of the other directories
440 source_epochless_version = utils.re_no_epoch.sub('', source_version);
441 dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
442 if os.path.exists(Cnf["Dir::Queue::Byhand"] + '/' + dsc_filename):
443 files[file]["byhand"] = 1;
444 elif os.path.exists(Cnf["Dir::Queue::New"] + '/' + dsc_filename):
445 files[file]["new"] = 1;
446 elif not os.path.exists(Cnf["Dir::Queue::Accepted"] + '/' + dsc_filename):
447 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
448 # Check the version and for file overwrites
449 reject(Katie.check_binary_against_db(file),"");
451 # Checks for a source package...
453 m = utils.re_issource.match(file);
456 files[file]["package"] = m.group(1);
457 files[file]["version"] = m.group(2);
458 files[file]["type"] = m.group(3);
460 # Ensure the source package name matches the Source filed in the .changes
461 if changes["source"] != files[file]["package"]:
462 reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
464 # Ensure the source version matches the version in the .changes file
465 if files[file]["type"] == "orig.tar.gz":
466 changes_version = changes["chopversion2"];
468 changes_version = changes["chopversion"];
469 if changes_version != files[file]["version"]:
470 reject("%s: should be %s according to changes file." % (file, changes_version));
472 # Ensure the .changes lists source in the Architecture field
473 if not changes["architecture"].has_key("source"):
474 reject("%s: changes file doesn't list `source' in Architecture field." % (file));
476 # Check the signature of a .dsc file
477 if files[file]["type"] == "dsc":
478 dsc["fingerprint"] = utils.check_signature(file, reject);
480 files[file]["architecture"] = "source";
482 # Not a binary or source package? Assume byhand...
484 files[file]["byhand"] = 1;
485 files[file]["type"] = "byhand";
487 # Per-suite file checks
488 files[file]["oldfiles"] = {};
489 for suite in changes["distribution"].keys():
491 if files[file].has_key("byhand"):
494 # Handle component mappings
495 for map in Cnf.ValueList("ComponentMappings"):
496 (source, dest) = map.split();
497 if files[file]["component"] == source:
498 files[file]["original component"] = source;
499 files[file]["component"] = dest;
500 # Ensure the component is valid for the target suite
501 if Cnf.has_key("Suite:%s::Components" % (suite)) and \
502 files[file]["component"] not in Cnf.ValueList("Suite::%s::Components" % (suite)):
503 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
506 # See if the package is NEW
507 if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
508 files[file]["new"] = 1;
510 # Validate the component
511 component = files[file]["component"];
512 component_id = db_access.get_component_id(component);
513 if component_id == -1:
514 reject("file '%s' has unknown component '%s'." % (file, component));
517 # Validate the priority
518 if files[file]["priority"].find('/') != -1:
519 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
521 # Determine the location
522 location = Cnf["Dir::Pool"];
523 location_id = db_access.get_location_id (location, component, archive);
524 if location_id == -1:
525 reject("[INTERNAL ERROR] couldn't determine location (Component: %s, Archive: %s)" % (component, archive));
526 files[file]["location id"] = location_id;
528 # Check the md5sum & size against existing files (if any)
529 files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
530 files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
532 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
534 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
535 files[file]["files id"] = files_id
537 # Check for packages that have moved from one component to another
538 q = Katie.projectB.query("""
539 SELECT c.name FROM binaries b, bin_associations ba, suite s, location l,
540 component c, architecture a, files f
541 WHERE b.package = '%s' AND s.suite_name = '%s'
542 AND (a.arch_string = '%s' OR a.arch_string = 'all')
543 AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
544 AND f.location = l.id AND l.component = c.id AND b.file = f.id"""
545 % (files[file]["package"], suite,
546 files[file]["architecture"]));
549 files[file]["othercomponents"] = ql[0][0];
551 # If the .changes file says it has source, it must have source.
552 if changes["architecture"].has_key("source"):
554 reject("no source found and Architecture line in changes mention source.");
556 if not has_binaries and Cnf.FindB("Dinstall::Reject::NoSourceOnly"):
557 reject("source only uploads are not supported.");
559 ###############################################################################
564 for file in files.keys():
565 # The .orig.tar.gz can disappear out from under us is it's a
566 # duplicate of one in the archive.
567 if not files.has_key(file):
569 if files[file]["type"] == "dsc":
570 # Parse the .dsc file
572 dsc.update(utils.parse_changes(file, dsc_whitespace_rules=1));
573 except utils.cant_open_exc:
574 # if not -n copy_to_holding() will have done this for us...
575 if Options["No-Action"]:
576 reject("can't read .dsc file '%s'." % (file));
577 except utils.changes_parse_error_exc, line:
578 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
579 except utils.invalid_dsc_format_exc, line:
580 reject("syntax error in .dsc file '%s', line %s." % (file, line));
581 # Build up the file list of files mentioned by the .dsc
583 dsc_files.update(utils.build_file_list(dsc, is_a_dsc=1));
584 except utils.no_files_exc:
585 reject("no Files: field in .dsc file.");
587 except utils.changes_parse_error_exc, line:
588 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
591 # Enforce mandatory fields
592 for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
593 if not dsc.has_key(i):
594 reject("Missing field `%s' in dsc file." % (i));
596 # Validate the source and version fields
597 if dsc.has_key("source") and not re_valid_pkg_name.match(dsc["source"]):
598 reject("%s: invalid source name '%s'." % (file, dsc["source"]));
599 if dsc.has_key("version") and not re_valid_version.match(dsc["version"]):
600 reject("%s: invalid version number '%s'." % (file, dsc["version"]));
602 # Bumping the version number of the .dsc breaks extraction by stable's
603 # dpkg-source. So let's not do that...
604 if dsc["format"] != "1.0":
605 reject("%s: incompatible 'Format' version produced by a broken version of dpkg-dev 1.9.1{3,4}." % (file));
607 # Validate the build-depends field(s)
608 for field_name in [ "build-depends", "build-depends-indep" ]:
609 field = dsc.get(field_name);
611 # Check for broken dpkg-dev lossage...
612 if field.find("ARRAY") == 0:
613 reject("%s: invalid %s field produced by a broken version of dpkg-dev (1.10.11)" % (file, field_name.title()));
615 # Have apt try to parse them...
617 apt_pkg.ParseSrcDepends(field);
619 reject("%s: invalid %s field (can not be parsed by apt)." % (file, field_name.title()));
622 # Ensure the version number in the .dsc matches the version number in the .changes
623 epochless_dsc_version = utils.re_no_epoch.sub('', dsc.get("version"));
624 changes_version = files[file]["version"];
625 if epochless_dsc_version != files[file]["version"]:
626 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
628 # Ensure there is a .tar.gz in the .dsc file
630 for f in dsc_files.keys():
631 m = utils.re_issource.match(f);
633 reject("%s mentioned in the Files field of %s not recognised as source." % (f, file));
635 if type == "orig.tar.gz" or type == "tar.gz":
638 reject("no .tar.gz or .orig.tar.gz listed in the Files field of %s." % (file));
640 # Ensure source is newer than existing source in target suites
641 reject(Katie.check_source_against_db(file),"");
643 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
644 reject(reject_msg, "");
646 if not Options["No-Action"]:
647 copy_to_holding(is_in_incoming);
648 orig_tar_gz = os.path.basename(is_in_incoming);
649 files[orig_tar_gz] = {};
650 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
651 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
652 files[orig_tar_gz]["section"] = files[file]["section"];
653 files[orig_tar_gz]["priority"] = files[file]["priority"];
654 files[orig_tar_gz]["component"] = files[file]["component"];
655 files[orig_tar_gz]["type"] = "orig.tar.gz";
658 ################################################################################
660 # dpkg-source broke .diff.gz generation in dpkg 1.8.x; detect the
661 # resulting bad source packages and reject them.
664 for filename in files.keys():
665 if files[filename]["type"] == "diff.gz":
666 file = gzip.GzipFile(filename, 'r');
667 for line in file.readlines():
668 if re_bad_diff.search(line):
669 reject("%s: invalid .diff.gz produced by a broken version of dpkg-dev 1.8.x." % (filename));
672 ################################################################################
674 # FIXME: should be a debian specific check called from a hook
676 def check_urgency ():
677 if changes["architecture"].has_key("source"):
678 if not changes.has_key("urgency"):
679 changes["urgency"] = Cnf["Urgency::Default"];
680 if changes["urgency"] not in Cnf.ValueList("Urgency::Valid"):
681 reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
682 changes["urgency"] = Cnf["Urgency::Default"];
683 changes["urgency"] = changes["urgency"].lower();
685 ################################################################################
687 def check_md5sums ():
688 for file in files.keys():
690 file_handle = utils.open_file(file);
691 except utils.cant_open_exc:
695 if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
696 reject("%s: md5sum check failed." % (file));
699 actual_size = os.stat(file)[stat.ST_SIZE];
700 size = int(files[file]["size"]);
701 if size != actual_size:
702 reject("%s: actual file size (%s) does not match size (%s) in .changes"
703 % (file, actual_size, size));
705 for file in dsc_files.keys():
707 file_handle = utils.open_file(file);
708 except utils.cant_open_exc:
712 if apt_pkg.md5sum(file_handle) != dsc_files[file]["md5sum"]:
713 reject("%s: md5sum check failed." % (file));
716 actual_size = os.stat(file)[stat.ST_SIZE];
717 size = int(dsc_files[file]["size"]);
718 if size != actual_size:
719 reject("%s: actual file size (%s) does not match size (%s) in .dsc"
720 % (file, actual_size, size));
722 ################################################################################
724 # Sanity check the time stamps of files inside debs.
725 # [Files in the near future cause ugly warnings and extreme time
726 # travel can cause errors on extraction]
728 def check_timestamps():
730 def __init__(self, future_cutoff, past_cutoff):
732 self.future_cutoff = future_cutoff;
733 self.past_cutoff = past_cutoff;
736 self.future_files = {};
737 self.ancient_files = {};
739 def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
740 if MTime > self.future_cutoff:
741 self.future_files[Name] = MTime;
742 if MTime < self.past_cutoff:
743 self.ancient_files[Name] = MTime;
746 future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"]);
747 past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"));
748 tar = Tar(future_cutoff, past_cutoff);
749 for filename in files.keys():
750 if files[filename]["type"] == "deb":
753 deb_file = utils.open_file(filename);
754 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz");
756 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz");
759 future_files = tar.future_files.keys();
761 num_future_files = len(future_files);
762 future_file = future_files[0];
763 future_date = tar.future_files[future_file];
764 reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
765 % (filename, num_future_files, future_file,
766 time.ctime(future_date)));
768 ancient_files = tar.ancient_files.keys();
770 num_ancient_files = len(ancient_files);
771 ancient_file = ancient_files[0];
772 ancient_date = tar.ancient_files[ancient_file];
773 reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
774 % (filename, num_ancient_files, ancient_file,
775 time.ctime(ancient_date)));
777 reject("%s: deb contents timestamp check failed [%s: %s]" % (filename, sys.exc_type, sys.exc_value));
779 ################################################################################
780 ################################################################################
782 # If any file of an upload has a recent mtime then chances are good
783 # the file is still being uploaded.
785 def upload_too_new():
787 # Move back to the original directory to get accurate time stamps
789 os.chdir(pkg.directory);
790 file_list = pkg.files.keys();
791 file_list.extend(pkg.dsc_files.keys());
792 file_list.append(pkg.changes_file);
793 for file in file_list:
795 last_modified = time.time()-os.path.getmtime(file);
796 if last_modified < int(Cnf["Dinstall::SkipTime"]):
804 ################################################################################
807 # changes["distribution"] may not exist in corner cases
808 # (e.g. unreadable changes files)
809 if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
810 changes["distribution"] = {};
812 (summary, short_summary) = Katie.build_summaries();
815 for file in files.keys():
816 if files[file].has_key("byhand"):
818 elif files[file].has_key("new"):
821 (prompt, answer) = ("", "XXX")
822 if Options["No-Action"] or Options["Automatic"]:
825 if reject_message.find("Rejected") != -1:
827 print "SKIP (too new)\n" + reject_message,;
828 prompt = "[S]kip, Quit ?";
830 print "REJECT\n" + reject_message,;
831 prompt = "[R]eject, Skip, Quit ?";
832 if Options["Automatic"]:
835 print "NEW to %s\n%s%s" % (", ".join(changes["distribution"].keys()), reject_message, summary),;
836 prompt = "[N]ew, Skip, Quit ?";
837 if Options["Automatic"]:
840 print "BYHAND\n" + reject_message + summary,;
841 prompt = "[B]yhand, Skip, Quit ?";
842 if Options["Automatic"]:
845 print "ACCEPT\n" + reject_message + summary,;
846 prompt = "[A]ccept, Skip, Quit ?";
847 if Options["Automatic"]:
850 while prompt.find(answer) == -1:
851 answer = utils.our_raw_input(prompt);
852 m = katie.re_default_answer.match(prompt);
855 answer = answer[:1].upper();
858 os.chdir (pkg.directory);
859 Katie.do_reject(0, reject_message);
861 accept(summary, short_summary);
865 acknowledge_new (summary);
869 ################################################################################
871 def accept (summary, short_summary):
872 Katie.accept(summary, short_summary);
873 Katie.check_override();
875 # Finally, remove the originals from the unchecked directory
876 os.chdir (pkg.directory);
877 for file in files.keys():
879 os.unlink(pkg.changes_file);
881 ################################################################################
883 def do_byhand (summary):
884 print "Moving to BYHAND holding area."
885 Logger.log(["Moving to byhand", pkg.changes_file]);
887 Katie.dump_vars(Cnf["Dir::Queue::Byhand"]);
889 file_keys = files.keys();
891 # Move all the files into the byhand directory
892 utils.move (pkg.changes_file, Cnf["Dir::Queue::Byhand"]);
893 for file in file_keys:
894 utils.move (file, Cnf["Dir::Queue::Byhand"], perms=0660);
896 # Check for override disparities
897 Katie.Subst["__SUMMARY__"] = summary;
898 Katie.check_override();
900 # Finally remove the originals.
901 os.chdir (pkg.directory);
902 for file in file_keys:
904 os.unlink(pkg.changes_file);
906 ################################################################################
908 def acknowledge_new (summary):
911 print "Moving to NEW holding area."
912 Logger.log(["Moving to new", pkg.changes_file]);
914 Katie.dump_vars(Cnf["Dir::Queue::New"]);
916 file_keys = files.keys();
918 # Move all the files into the 'new' directory
919 utils.move (pkg.changes_file, Cnf["Dir::Queue::New"]);
920 for file in file_keys:
921 utils.move (file, Cnf["Dir::Queue::New"], perms=0660);
923 if not Options["No-Mail"]:
924 print "Sending new ack.";
925 Subst["__SUMMARY__"] = summary;
926 new_ack_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/jennifer.new");
927 utils.send_mail(new_ack_message);
929 # Finally remove the originals.
930 os.chdir (pkg.directory);
931 for file in file_keys:
933 os.unlink(pkg.changes_file);
935 ################################################################################
937 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
938 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
939 # Katie.check_dsc_against_db() can find the .orig.tar.gz but it will
940 # not have processed it during it's checks of -2. If -1 has been
941 # deleted or otherwise not checked by jennifer, the .orig.tar.gz will
942 # not have been checked at all. To get round this, we force the
943 # .orig.tar.gz into the .changes structure and reprocess the .changes
946 def process_it (changes_file):
947 global reprocess, reject_message;
954 # Absolutize the filename to avoid the requirement of being in the
955 # same directory as the .changes file.
956 pkg.changes_file = os.path.abspath(changes_file);
958 # Remember where we are so we can come back after cd-ing into the
960 pkg.directory = os.getcwd();
963 # If this is the Real Thing(tm), copy things into a private
964 # holding directory first to avoid replacable file races.
965 if not Options["No-Action"]:
966 os.chdir(Cnf["Dir::Queue::Holding"]);
967 copy_to_holding(pkg.changes_file);
968 # Relativize the filename so we use the copy in holding
969 # rather than the original...
970 pkg.changes_file = os.path.basename(pkg.changes_file);
971 changes["fingerprint"] = utils.check_signature(pkg.changes_file, reject);
972 changes_valid = check_changes();
975 check_distributions();
982 Katie.update_subst(reject_message);
988 traceback.print_exc(file=sys.stderr);
991 # Restore previous WD
992 os.chdir(pkg.directory);
994 ###############################################################################
997 global Cnf, Options, Logger, nmu;
999 changes_files = init();
1001 # -n/--dry-run invalidates some other options which would involve things happening
1002 if Options["No-Action"]:
1003 Options["Automatic"] = "";
1005 # Ensure all the arguments we were given are .changes files
1006 for file in changes_files:
1007 if not file.endswith(".changes"):
1008 utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
1009 changes_files.remove(file);
1011 if changes_files == []:
1012 utils.fubar("Need at least one .changes file as an argument.");
1014 # Check that we aren't going to clash with the daily cron job
1016 if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::Root"])) and not Options["No-Lock"]:
1017 utils.fubar("Archive maintenance in progress. Try again later.");
1019 # Obtain lock if not in no-action mode and initialize the log
1021 if not Options["No-Action"]:
1022 lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1024 fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB);
1026 if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
1027 utils.fubar("Couldn't obtain lock; assuming another jennifer is already running.");
1030 Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1032 # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1033 bcc = "X-Katie: %s" % (jennifer_version);
1034 if Cnf.has_key("Dinstall::Bcc"):
1035 Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1037 Katie.Subst["__BCC__"] = bcc;
1040 # Sort the .changes files so that we process sourceful ones first
1041 changes_files.sort(utils.changes_compare);
1043 # Process the changes files
1044 for changes_file in changes_files:
1045 print "\n" + changes_file;
1047 process_it (changes_file);
1049 if not Options["No-Action"]:
1052 accept_count = Katie.accept_count;
1053 accept_bytes = Katie.accept_bytes;
1056 if accept_count > 1:
1058 print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)));
1059 Logger.log(["total",accept_count,accept_bytes]);
1061 if not Options["No-Action"]:
1064 ################################################################################
1066 if __name__ == '__main__':