3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001, 2002 James Troup <james@nocrew.org>
5 # $Id: jennifer,v 1.30 2003-01-02 18:11:53 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 FCNTL, errno, fcntl, gzip, os, re, select, 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.30 $";
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 # Our very own version of commands.getouputstatus(), hacked to support
122 def get_status_output(cmd, status_read, status_write):
123 cmd = ['/bin/sh', '-c', cmd];
124 p2cread, p2cwrite = os.pipe();
125 c2pread, c2pwrite = os.pipe();
126 errout, errin = os.pipe();
136 for i in range(3, 256):
137 if i != status_write:
143 os.execvp(cmd[0], cmd);
149 os.dup2(c2pread, c2pwrite);
150 os.dup2(errout, errin);
152 output = status = "";
154 i, o, e = select.select([c2pwrite, errin, status_read], [], []);
157 r = os.read(fd, 8196);
159 more_data.append(fd);
160 if fd == c2pwrite or fd == errin:
162 elif fd == status_read:
165 utils.fubar("Unexpected file descriptor [%s] returned from select\n" % (fd));
167 pid, exit_status = os.waitpid(pid, 0)
169 os.close(status_write);
170 os.close(status_read);
180 return output, status, exit_status;
182 ################################################################################
184 def Dict(**dict): return dict
186 def reject (str, prefix="Rejected: "):
187 global reject_message;
189 reject_message += prefix + str + "\n";
191 ################################################################################
193 def check_signature (filename):
194 if not utils.re_taint_free.match(os.path.basename(filename)):
195 reject("!!WARNING!! tainted filename: '%s'." % (filename));
198 status_read, status_write = os.pipe();
199 cmd = "gpgv --status-fd %s --keyring %s --keyring %s %s" \
200 % (status_write, Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"], filename);
201 (output, status, exit_status) = get_status_output(cmd, status_read, status_write);
203 # Process the status-fd output
205 bad = internal_error = "";
206 for line in status.split('\n'):
210 split = line.split();
212 internal_error += "gpgv status line is malformed (< 2 atoms) ['%s'].\n" % (line);
214 (gnupg, keyword) = split[:2];
215 if gnupg != "[GNUPG:]":
216 internal_error += "gpgv status line is malformed (incorrect prefix '%s').\n" % (gnupg);
219 if keywords.has_key(keyword) and keyword != "NODATA":
220 internal_error += "found duplicate status token ('%s').\n" % (keyword);
223 keywords[keyword] = args;
225 # If we failed to parse the status-fd output, let's just whine and bail now
227 reject("internal error while performing signature check on %s." % (filename));
228 reject(internal_error, "");
229 reject("Please report the above errors to the Archive maintainers by replying to this mail.", "");
232 # Now check for obviously bad things in the processed output
233 if keywords.has_key("SIGEXPIRED"):
234 reject("key used to sign %s has expired." % (filename));
236 if keywords.has_key("KEYREVOKED"):
237 reject("key used to sign %s has been revoked." % (filename));
239 if keywords.has_key("BADSIG"):
240 reject("bad signature on %s." % (filename));
242 if keywords.has_key("ERRSIG") and not keywords.has_key("NO_PUBKEY"):
243 reject("failed to check signature on %s." % (filename));
245 if keywords.has_key("NO_PUBKEY"):
246 reject("key used to sign %s not found in keyring." % (filename));
248 if keywords.has_key("BADARMOR"):
249 reject("ascii armour of signature was corrupt in %s." % (filename));
251 if keywords.has_key("NODATA"):
252 reject("no signature found in %s." % (filename));
258 # Next check gpgv exited with a zero return code
260 reject("gpgv failed while checking %s." % (filename));
262 reject(utils.prefix_multi_line_string(status, " [GPG status-fd output:] "), "");
264 reject(utils.prefix_multi_line_string(output, " [GPG output:] "), "");
267 # Sanity check the good stuff we expect
268 if not keywords.has_key("VALIDSIG"):
269 reject("signature on %s does not appear to be valid [No VALIDSIG]." % (filename));
272 args = keywords["VALIDSIG"];
274 reject("internal error while checking signature on %s." % (filename));
277 fingerprint = args[0];
278 if not keywords.has_key("GOODSIG"):
279 reject("signature on %s does not appear to be valid [No GOODSIG]." % (filename));
281 if not keywords.has_key("SIG_ID"):
282 reject("signature on %s does not appear to be valid [No SIG_ID]." % (filename));
285 # Finally ensure there's not something we don't recognise
286 known_keywords = Dict(VALIDSIG="",SIG_ID="",GOODSIG="",BADSIG="",ERRSIG="",
287 SIGEXPIRED="",KEYREVOKED="",NO_PUBKEY="",BADARMOR="",
290 for keyword in keywords.keys():
291 if not known_keywords.has_key(keyword):
292 reject("found unknown status token '%s' from gpgv with args '%r' in %s." % (keyword, keywords[keyword], filename));
300 ################################################################################
302 def copy_to_holding(filename):
305 base_filename = os.path.basename(filename);
307 dest = Cnf["Dir::Queue::Holding"] + '/' + base_filename;
309 fd = os.open(dest, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0640);
312 # Shouldn't happen, but will if, for example, someone lists a
313 # file twice in the .changes.
314 if errno.errorcode[e.errno] == 'EEXIST':
315 reject("%s already exists in holding area; can not overwrite." % (base_filename));
320 shutil.copy(filename, dest);
322 # In either case (ENOENT or EACCES) we want to remove the
323 # O_CREAT | O_EXCLed ghost file, so add the file to the list
324 # of 'in holding' even if it's not the real file.
325 if errno.errorcode[e.errno] == 'ENOENT':
326 reject("can not copy %s to holding area: file not found." % (base_filename));
329 elif errno.errorcode[e.errno] == 'EACCES':
330 reject("can not copy %s to holding area: read permission denied." % (base_filename));
335 in_holding[base_filename] = "";
337 ################################################################################
343 os.chdir(Cnf["Dir::Queue::Holding"]);
344 for file in in_holding.keys():
345 if os.path.exists(file):
346 if file.find('/') != -1:
347 utils.fubar("WTF? clean_holding() got a file ('%s') with / in it!" % (file));
353 ################################################################################
356 filename = pkg.changes_file;
358 # Default in case we bail out
359 changes["maintainer822"] = Cnf["Dinstall::MyEmailAddress"];
360 changes["changedby822"] = Cnf["Dinstall::MyEmailAddress"];
361 changes["architecture"] = {};
363 # Parse the .changes field into a dictionary
365 changes.update(utils.parse_changes(filename));
366 except utils.cant_open_exc:
367 reject("can't read changes file '%s'." % (filename));
369 except utils.changes_parse_error_exc, line:
370 reject("error parsing changes file '%s', can't grok: %s." % (filename, line));
373 # Parse the Files field from the .changes into another dictionary
375 files.update(utils.build_file_list(changes));
376 except utils.changes_parse_error_exc, line:
377 reject("error parsing changes file '%s', can't grok: %s." % (filename, line));
378 except utils.nk_format_exc, format:
379 reject("unknown format '%s' of changes file '%s'." % (format, filename));
382 # Check for mandatory fields
383 for i in ("source", "binary", "architecture", "version", "distribution", "maintainer", "files"):
384 if not changes.has_key(i):
385 reject("Missing field `%s' in changes file." % (i));
386 return 0 # Avoid <undef> errors during later tests
388 # Split multi-value fields into a lower-level dictionary
389 for i in ("architecture", "distribution", "binary", "closes"):
390 o = changes.get(i, "")
397 # Fix the Maintainer: field to be RFC822 compatible
398 (changes["maintainer822"], changes["maintainername"], changes["maintaineremail"]) = utils.fix_maintainer (changes["maintainer"])
400 # Fix the Changed-By: field to be RFC822 compatible; if it exists.
401 (changes["changedby822"], changes["changedbyname"], changes["changedbyemail"]) = utils.fix_maintainer(changes.get("changed-by",""));
403 # Ensure all the values in Closes: are numbers
404 if changes.has_key("closes"):
405 for i in changes["closes"].keys():
406 if katie.re_isanum.match (i) == None:
407 reject("`%s' from Closes field isn't a number." % (i));
410 # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
411 changes["chopversion"] = utils.re_no_epoch.sub('', changes["version"])
412 changes["chopversion2"] = utils.re_no_revision.sub('', changes["chopversion"])
414 # Check there isn't already a changes file of the same name in one
415 # of the queue directories.
416 base_filename = os.path.basename(filename);
417 for dir in [ "Accepted", "Byhand", "Done", "New" ]:
418 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+base_filename):
419 reject("a changes file with the same name already exists in the %s directory." % (dir));
423 ################################################################################
425 def check_distributions():
426 "Check and map the Distribution field of a .changes file."
428 # Handle suite mappings
429 for map in Cnf.ValueList("SuiteMappings"):
432 if type == "map" or type == "silent-map":
433 (source, dest) = args[1:3];
434 if changes["distribution"].has_key(source):
435 del changes["distribution"][source]
436 changes["distribution"][dest] = 1;
437 if type != "silent-map":
438 reject("Mapping %s to %s." % (source, dest),"");
439 elif type == "map-unreleased":
440 (source, dest) = args[1:3];
441 if changes["distribution"].has_key(source):
442 for arch in changes["architecture"].keys():
443 if arch not in Cnf.ValueList("Suite::%s::Architectures" % (source)):
444 reject("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch),"");
445 del changes["distribution"][source];
446 changes["distribution"][dest] = 1;
448 elif type == "ignore":
450 if changes["distribution"].has_key(suite):
451 del changes["distribution"][suite];
452 reject("Ignoring %s as a target suite." % (suite), "Warning: ");
454 # Ensure there is (still) a target distribution
455 if changes["distribution"].keys() == []:
456 reject("no valid distribution.");
458 # Ensure target distributions exist
459 for suite in changes["distribution"].keys():
460 if not Cnf.has_key("Suite::%s" % (suite)):
461 reject("Unknown distribution `%s'." % (suite));
463 ################################################################################
468 archive = utils.where_am_i();
469 file_keys = files.keys();
471 # if reprocess is 2 we've already done this and we're checking
472 # things again for the new .orig.tar.gz.
473 # [Yes, I'm fully aware of how disgusting this is]
474 if not Options["No-Action"] and reprocess < 2:
476 os.chdir(pkg.directory);
477 for file in file_keys:
478 copy_to_holding(file);
483 for file in file_keys:
484 # Ensure the file does not already exist in one of the accepted directories
485 for dir in [ "Accepted", "Byhand", "New" ]:
486 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+file):
487 reject("%s file already exists in the %s directory." % (file, dir));
488 if not utils.re_taint_free.match(file):
489 reject("!!WARNING!! tainted filename: '%s'." % (file));
490 # Check the file is readable
491 if os.access(file,os.R_OK) == 0:
492 # When running in -n, copy_to_holding() won't have
493 # generated the reject_message, so we need to.
494 if Options["No-Action"]:
495 if os.path.exists(file):
496 reject("Can't read `%s'. [permission denied]" % (file));
498 reject("Can't read `%s'. [file not found]" % (file));
499 files[file]["type"] = "unreadable";
501 # If it's byhand skip remaining checks
502 if files[file]["section"] == "byhand":
503 files[file]["byhand"] = 1;
504 files[file]["type"] = "byhand";
505 # Checks for a binary package...
506 elif utils.re_isadeb.match(file) != None:
507 files[file]["type"] = "deb";
509 # Extract package control information
510 deb_file = utils.open_file(file);
512 control = apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file));
514 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
516 # Can't continue, none of the checks on control would work.
520 # Check for mandatory fields
521 for field in [ "Package", "Architecture", "Version" ]:
522 if control.Find(field) == None:
523 reject("%s: No %s field in control." % (file, field));
527 # Ensure the package name matches the one give in the .changes
528 if not changes["binary"].has_key(control.Find("Package", "")):
529 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
531 # Validate the package field
532 package = control.Find("Package");
533 if not re_valid_pkg_name.match(package):
534 reject("%s: invalid package name '%s'." % (file, package));
536 # Validate the version field
537 version = control.Find("Version");
538 if not re_valid_version.match(version):
539 reject("%s: invalid version number '%s'." % (file, version));
541 # Ensure the architecture of the .deb is one we know about.
542 default_suite = Cnf.get("Dinstall::DefaultSuite", "Unstable")
543 architecture = control.Find("Architecture");
544 if architecture not in Cnf.ValueList("Suite::%s::Architectures" % (default_suite)):
545 reject("Unknown architecture '%s'." % (architecture));
547 # Ensure the architecture of the .deb is one of the ones
548 # listed in the .changes.
549 if not changes["architecture"].has_key(architecture):
550 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, architecture));
552 # Sanity-check the Depends field
553 depends = control.Find("Depends");
555 reject("%s: Depends field is empty." % (file));
557 # Check the section & priority match those given in the .changes (non-fatal)
558 if control.Find("Section") != None and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
559 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
560 if control.Find("Priority") != None and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
561 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
563 files[file]["package"] = package;
564 files[file]["architecture"] = architecture;
565 files[file]["version"] = version;
566 files[file]["maintainer"] = control.Find("Maintainer", "");
567 if file.endswith(".udeb"):
568 files[file]["dbtype"] = "udeb";
569 elif file.endswith(".deb"):
570 files[file]["dbtype"] = "deb";
572 reject("%s is neither a .deb or a .udeb." % (file));
573 files[file]["source"] = control.Find("Source", files[file]["package"]);
574 # Get the source version
575 source = files[file]["source"];
577 if source.find("(") != -1:
578 m = utils.re_extract_src_version.match(source)
580 source_version = m.group(2)
581 if not source_version:
582 source_version = files[file]["version"];
583 files[file]["source package"] = source;
584 files[file]["source version"] = source_version;
586 # Ensure the filename matches the contents of the .deb
587 m = utils.re_isadeb.match(file);
589 file_package = m.group(1);
590 if files[file]["package"] != file_package:
591 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"]));
592 epochless_version = utils.re_no_epoch.sub('', control.Find("Version"));
594 file_version = m.group(2);
595 if epochless_version != file_version:
596 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
598 file_architecture = m.group(3);
599 if files[file]["architecture"] != file_architecture:
600 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"]));
602 # Check for existent source
603 source_version = files[file]["source version"];
604 source_package = files[file]["source package"];
605 if changes["architecture"].has_key("source"):
606 if source_version != changes["version"]:
607 reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
609 # Check in the SQL database
610 if not Katie.source_exists(source_package, source_version):
611 # Check in one of the other directories
612 source_epochless_version = utils.re_no_epoch.sub('', source_version);
613 dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
614 if os.path.exists(Cnf["Dir::Queue::Byhand"] + '/' + dsc_filename):
615 files[file]["byhand"] = 1;
616 elif os.path.exists(Cnf["Dir::Queue::New"] + '/' + dsc_filename):
617 files[file]["new"] = 1;
618 elif not os.path.exists(Cnf["Dir::Queue::Accepted"] + '/' + dsc_filename):
619 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
620 # Check the version and for file overwrites
621 reject(Katie.check_binary_against_db(file),"");
623 # Checks for a source package...
625 m = utils.re_issource.match(file);
627 files[file]["package"] = m.group(1);
628 files[file]["version"] = m.group(2);
629 files[file]["type"] = m.group(3);
631 # Ensure the source package name matches the Source filed in the .changes
632 if changes["source"] != files[file]["package"]:
633 reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
635 # Ensure the source version matches the version in the .changes file
636 if files[file]["type"] == "orig.tar.gz":
637 changes_version = changes["chopversion2"];
639 changes_version = changes["chopversion"];
640 if changes_version != files[file]["version"]:
641 reject("%s: should be %s according to changes file." % (file, changes_version));
643 # Ensure the .changes lists source in the Architecture field
644 if not changes["architecture"].has_key("source"):
645 reject("%s: changes file doesn't list `source' in Architecture field." % (file));
647 # Check the signature of a .dsc file
648 if files[file]["type"] == "dsc":
649 dsc["fingerprint"] = check_signature(file);
651 files[file]["architecture"] = "source";
653 # Not a binary or source package? Assume byhand...
655 files[file]["byhand"] = 1;
656 files[file]["type"] = "byhand";
658 # Per-suite file checks
659 files[file]["oldfiles"] = {};
660 for suite in changes["distribution"].keys():
662 if files[file].has_key("byhand"):
665 # Handle component mappings
666 for map in Cnf.ValueList("ComponentMappings"):
667 (source, dest) = map.split();
668 if files[file]["component"] == source:
669 files[file]["original component"] = source;
670 files[file]["component"] = dest;
671 # Ensure the component is valid for the target suite
672 if Cnf.has_key("Suite:%s::Components" % (suite)) and \
673 files[file]["component"] not in Cnf.ValueList("Suite::%s::Components" % (suite)):
674 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
677 # See if the package is NEW
678 if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
679 files[file]["new"] = 1;
681 # Validate the component
682 component = files[file]["component"];
683 component_id = db_access.get_component_id(component);
684 if component_id == -1:
685 reject("file '%s' has unknown component '%s'." % (file, component));
688 # Validate the priority
689 if files[file]["priority"].find('/') != -1:
690 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
692 # Determine the location
693 location = Cnf["Dir::Pool"];
694 location_id = db_access.get_location_id (location, component, archive);
695 if location_id == -1:
696 reject("[INTERNAL ERROR] couldn't determine location (Component: %s, Archive: %s)" % (component, archive));
697 files[file]["location id"] = location_id;
699 # Check the md5sum & size against existing files (if any)
700 files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
701 files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
703 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
705 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
706 files[file]["files id"] = files_id
708 # Check for packages that have moved from one component to another
709 q = Katie.projectB.query("""
710 SELECT c.name FROM binaries b, bin_associations ba, suite s, location l,
711 component c, architecture a, files f
712 WHERE b.package = '%s' AND s.suite_name = '%s'
713 AND (a.arch_string = '%s' OR a.arch_string = 'all')
714 AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
715 AND f.location = l.id AND l.component = c.id AND b.file = f.id"""
716 % (files[file]["package"], suite,
717 files[file]["architecture"]));
720 files[file]["othercomponents"] = ql[0][0];
722 # If the .changes file says it has source, it must have source.
723 if changes["architecture"].has_key("source"):
725 for file in file_keys:
726 if files[file]["type"] == "dsc":
729 reject("no source found and Architecture line in changes mention source.");
731 ###############################################################################
736 for file in files.keys():
737 # The .orig.tar.gz can disappear out from under us is it's a
738 # duplicate of one in the archive.
739 if not files.has_key(file):
741 if files[file]["type"] == "dsc":
742 # Parse the .dsc file
744 dsc.update(utils.parse_changes(file, dsc_whitespace_rules=1));
745 except utils.cant_open_exc:
746 # if not -n copy_to_holding() will have done this for us...
747 if Options["No-Action"]:
748 reject("can't read .dsc file '%s'." % (file));
749 except utils.changes_parse_error_exc, line:
750 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
751 except utils.invalid_dsc_format_exc, line:
752 reject("syntax error in .dsc file '%s', line %s." % (file, line));
753 # Build up the file list of files mentioned by the .dsc
755 dsc_files.update(utils.build_file_list(dsc, is_a_dsc=1));
756 except utils.no_files_exc:
757 reject("no Files: field in .dsc file.");
759 except utils.changes_parse_error_exc, line:
760 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
763 # Enforce mandatory fields
764 for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
765 if not dsc.has_key(i):
766 reject("Missing field `%s' in dsc file." % (i));
768 # Validate the source and version fields
769 if dsc.has_key("source") and not re_valid_pkg_name.match(dsc["source"]):
770 reject("%s: invalid source name '%s'." % (file, dsc["source"]));
771 if dsc.has_key("version") and not re_valid_version.match(dsc["version"]):
772 reject("%s: invalid version number '%s'." % (file, dsc["version"]));
774 # The dpkg maintainer from hell strikes again! Bumping the
775 # version number of the .dsc breaks extraction by stable's
777 if dsc["format"] != "1.0":
778 reject("""[dpkg-sucks] source package was produced by a broken version
779 of dpkg-dev 1.9.1{3,4}; please rebuild with >= 1.9.15 version
782 # Ensure the version number in the .dsc matches the version number in the .changes
783 epochless_dsc_version = utils.re_no_epoch.sub('', dsc.get("version"));
784 changes_version = files[file]["version"];
785 if epochless_dsc_version != files[file]["version"]:
786 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
788 # Ensure there is a .tar.gz in the .dsc file
790 for f in dsc_files.keys():
791 m = utils.re_issource.match(f);
793 reject("%s mentioned in the Files field of %s not recognised as source." % (f, file));
795 if type == "orig.tar.gz" or type == "tar.gz":
798 reject("no .tar.gz or .orig.tar.gz listed in the Files field of %s." % (file));
800 # Ensure source is newer than existing source in target suites
801 reject(Katie.check_source_against_db(file),"");
803 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
804 reject(reject_msg, "");
806 if not Options["No-Action"]:
807 copy_to_holding(is_in_incoming);
808 orig_tar_gz = os.path.basename(is_in_incoming);
809 files[orig_tar_gz] = {};
810 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
811 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
812 files[orig_tar_gz]["section"] = files[file]["section"];
813 files[orig_tar_gz]["priority"] = files[file]["priority"];
814 files[orig_tar_gz]["component"] = files[file]["component"];
815 files[orig_tar_gz]["type"] = "orig.tar.gz";
818 ################################################################################
820 # Some cunning stunt broke dpkg-source in dpkg 1.8{,.1}; detect the
821 # resulting bad source packages and reject them.
823 # Even more amusingly the fix in 1.8.1.1 didn't actually fix the
824 # problem just changed the symptoms.
827 for filename in files.keys():
828 if files[filename]["type"] == "diff.gz":
829 file = gzip.GzipFile(filename, 'r');
830 for line in file.readlines():
831 if re_bad_diff.search(line):
832 reject("[dpkg-sucks] source package was produced by a broken version of dpkg-dev 1.8.x; please rebuild with >= 1.8.3 version installed.");
835 ################################################################################
837 # FIXME: should be a debian specific check called from a hook
839 def check_urgency ():
840 if changes["architecture"].has_key("source"):
841 if not changes.has_key("urgency"):
842 changes["urgency"] = Cnf["Urgency::Default"];
843 if changes["urgency"] not in Cnf.ValueList("Urgency::Valid"):
844 reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
845 changes["urgency"] = Cnf["Urgency::Default"];
846 changes["urgency"] = changes["urgency"].lower();
848 ################################################################################
850 def check_md5sums ():
851 for file in files.keys():
853 file_handle = utils.open_file(file);
854 except utils.cant_open_exc:
858 if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
859 reject("%s: md5sum check failed." % (file));
862 actual_size = os.stat(file)[stat.ST_SIZE];
863 size = int(files[file]["size"]);
864 if size != actual_size:
865 reject("%s: actual file size (%s) does not match size (%s) in .changes"
866 % (file, actual_size, size));
868 for file in dsc_files.keys():
870 file_handle = utils.open_file(file);
871 except utils.cant_open_exc:
875 if apt_pkg.md5sum(file_handle) != dsc_files[file]["md5sum"]:
876 reject("%s: md5sum check failed." % (file));
879 actual_size = os.stat(file)[stat.ST_SIZE];
880 size = int(dsc_files[file]["size"]);
881 if size != actual_size:
882 reject("%s: actual file size (%s) does not match size (%s) in .dsc"
883 % (file, actual_size, size));
885 ################################################################################
887 # Sanity check the time stamps of files inside debs.
888 # [Files in the near future cause ugly warnings and extreme time
889 # travel can cause errors on extraction]
891 def check_timestamps():
893 def __init__(self, future_cutoff, past_cutoff):
895 self.future_cutoff = future_cutoff;
896 self.past_cutoff = past_cutoff;
899 self.future_files = {};
900 self.ancient_files = {};
902 def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
903 if MTime > self.future_cutoff:
904 self.future_files[Name] = MTime;
905 if MTime < self.past_cutoff:
906 self.ancient_files[Name] = MTime;
909 future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"]);
910 past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"));
911 tar = Tar(future_cutoff, past_cutoff);
912 for filename in files.keys():
913 if files[filename]["type"] == "deb":
916 deb_file = utils.open_file(filename);
917 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz");
919 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz");
922 future_files = tar.future_files.keys();
924 num_future_files = len(future_files);
925 future_file = future_files[0];
926 future_date = tar.future_files[future_file];
927 reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
928 % (filename, num_future_files, future_file,
929 time.ctime(future_date)));
931 ancient_files = tar.ancient_files.keys();
933 num_ancient_files = len(ancient_files);
934 ancient_file = ancient_files[0];
935 ancient_date = tar.ancient_files[ancient_file];
936 reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
937 % (filename, num_ancient_files, ancient_file,
938 time.ctime(ancient_date)));
940 reject("%s: timestamp check failed; caught %s" % (filename, sys.exc_type));
942 ################################################################################
943 ################################################################################
945 # If any file of an upload has a recent mtime then chances are good
946 # the file is still being uploaded.
948 def upload_too_new():
950 # Move back to the original directory to get accurate time stamps
952 os.chdir(pkg.directory);
953 file_list = pkg.files.keys();
954 file_list.extend(pkg.dsc_files.keys());
955 file_list.append(pkg.changes_file);
956 for file in file_list:
958 last_modified = time.time()-os.path.getmtime(file);
959 if last_modified < int(Cnf["Dinstall::SkipTime"]):
967 ################################################################################
970 # changes["distribution"] may not exist in corner cases
971 # (e.g. unreadable changes files)
972 if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
973 changes["distribution"] = {};
975 (summary, short_summary) = Katie.build_summaries();
978 for file in files.keys():
979 if files[file].has_key("byhand"):
981 elif files[file].has_key("new"):
984 (prompt, answer) = ("", "XXX")
985 if Options["No-Action"] or Options["Automatic"]:
988 if reject_message.find("Rejected") != -1:
990 print "SKIP (too new)\n" + reject_message,;
991 prompt = "[S]kip, Quit ?";
993 print "REJECT\n" + reject_message,;
994 prompt = "[R]eject, Skip, Quit ?";
995 if Options["Automatic"]:
998 print "NEW to %s\n%s%s" % (", ".join(changes["distribution"].keys()), reject_message, summary),;
999 prompt = "[N]ew, Skip, Quit ?";
1000 if Options["Automatic"]:
1003 print "BYHAND\n" + reject_message + summary,;
1004 prompt = "[B]yhand, Skip, Quit ?";
1005 if Options["Automatic"]:
1008 print "ACCEPT\n" + reject_message + summary,;
1009 prompt = "[A]ccept, Skip, Quit ?";
1010 if Options["Automatic"]:
1013 while prompt.find(answer) == -1:
1014 answer = utils.our_raw_input(prompt);
1015 m = katie.re_default_answer.match(prompt);
1017 answer = m.group(1);
1018 answer = answer[:1].upper();
1021 os.chdir (pkg.directory);
1022 Katie.do_reject(0, reject_message);
1024 accept(summary, short_summary);
1028 acknowledge_new (summary);
1032 ################################################################################
1034 def accept (summary, short_summary):
1035 Katie.accept(summary, short_summary);
1036 Katie.check_override();
1038 # Finally, remove the originals from the unchecked directory
1039 os.chdir (pkg.directory);
1040 for file in files.keys():
1042 os.unlink(pkg.changes_file);
1044 ################################################################################
1046 def do_byhand (summary):
1047 print "Moving to BYHAND holding area."
1048 Logger.log(["Moving to byhand", pkg.changes_file]);
1050 Katie.dump_vars(Cnf["Dir::Queue::Byhand"]);
1052 file_keys = files.keys();
1054 # Move all the files into the byhand directory
1055 utils.move (pkg.changes_file, Cnf["Dir::Queue::Byhand"]);
1056 for file in file_keys:
1057 utils.move (file, Cnf["Dir::Queue::Byhand"], perms=0660);
1059 # Check for override disparities
1060 Katie.Subst["__SUMMARY__"] = summary;
1061 Katie.check_override();
1063 # Finally remove the originals.
1064 os.chdir (pkg.directory);
1065 for file in file_keys:
1067 os.unlink(pkg.changes_file);
1069 ################################################################################
1071 def acknowledge_new (summary):
1072 Subst = Katie.Subst;
1074 print "Moving to NEW holding area."
1075 Logger.log(["Moving to new", pkg.changes_file]);
1077 Katie.dump_vars(Cnf["Dir::Queue::New"]);
1079 file_keys = files.keys();
1081 # Move all the files into the 'new' directory
1082 utils.move (pkg.changes_file, Cnf["Dir::Queue::New"]);
1083 for file in file_keys:
1084 utils.move (file, Cnf["Dir::Queue::New"], perms=0660);
1086 if not Options["No-Mail"]:
1087 print "Sending new ack.";
1088 Subst["__SUMMARY__"] = summary;
1089 new_ack_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/jennifer.new");
1090 utils.send_mail(new_ack_message,"");
1092 # Finally remove the originals.
1093 os.chdir (pkg.directory);
1094 for file in file_keys:
1096 os.unlink(pkg.changes_file);
1098 ################################################################################
1100 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1101 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1102 # Katie.check_dsc_against_db() can find the .orig.tar.gz but it will
1103 # not have processed it during it's checks of -2. If -1 has been
1104 # deleted or otherwise not checked by jennifer, the .orig.tar.gz will
1105 # not have been checked at all. To get round this, we force the
1106 # .orig.tar.gz into the .changes structure and reprocess the .changes
1109 def process_it (changes_file):
1110 global reprocess, reject_message;
1112 # Reset some globals
1115 reject_message = "";
1117 # Absolutize the filename to avoid the requirement of being in the
1118 # same directory as the .changes file.
1119 pkg.changes_file = os.path.abspath(changes_file);
1121 # Remember where we are so we can come back after cd-ing into the
1122 # holding directory.
1123 pkg.directory = os.getcwd();
1126 # If this is the Real Thing(tm), copy things into a private
1127 # holding directory first to avoid replacable file races.
1128 if not Options["No-Action"]:
1129 os.chdir(Cnf["Dir::Queue::Holding"]);
1130 copy_to_holding(pkg.changes_file);
1131 # Relativize the filename so we use the copy in holding
1132 # rather than the original...
1133 pkg.changes_file = os.path.basename(pkg.changes_file);
1134 changes["fingerprint"] = check_signature(pkg.changes_file);
1135 changes_valid = check_changes();
1138 check_distributions();
1145 Katie.update_subst(reject_message);
1151 traceback.print_exc(file=sys.stderr);
1154 # Restore previous WD
1155 os.chdir(pkg.directory);
1157 ###############################################################################
1160 global Cnf, Options, Logger, nmu;
1162 changes_files = init();
1164 # -n/--dry-run invalidates some other options which would involve things happening
1165 if Options["No-Action"]:
1166 Options["Automatic"] = "";
1168 # Ensure all the arguments we were given are .changes files
1169 for file in changes_files:
1170 if not file.endswith(".changes"):
1171 utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
1172 changes_files.remove(file);
1174 if changes_files == []:
1175 utils.fubar("Need at least one .changes file as an argument.");
1177 # Check that we aren't going to clash with the daily cron job
1179 if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::Root"])) and not Options["No-Lock"]:
1180 utils.fubar("Archive maintenance in progress. Try again later.");
1182 # Obtain lock if not in no-action mode and initialize the log
1184 if not Options["No-Action"]:
1185 lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1186 fcntl.lockf(lock_fd, FCNTL.F_TLOCK);
1187 Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1189 # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1190 bcc = "X-Katie: %s" % (jennifer_version);
1191 if Cnf.has_key("Dinstall::Bcc"):
1192 Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1194 Katie.Subst["__BCC__"] = bcc;
1197 # Sort the .changes files so that we process sourceful ones first
1198 changes_files.sort(utils.changes_compare);
1200 # Process the changes files
1201 for changes_file in changes_files:
1202 print "\n" + changes_file;
1204 process_it (changes_file);
1206 if not Options["No-Action"]:
1209 accept_count = Katie.accept_count;
1210 accept_bytes = Katie.accept_bytes;
1213 if accept_count > 1:
1215 print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)));
1216 Logger.log(["total",accept_count,accept_bytes]);
1218 if not Options["No-Action"]:
1221 ################################################################################
1223 if __name__ == '__main__':