3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001 James Troup <james@nocrew.org>
5 # $Id: jennifer,v 1.1 2002-02-12 23:08:07 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, string, sys, time, traceback;
33 import apt_inst, apt_pkg;
34 import db_access, katie, logging, utils;
37 from string import lower;
39 ################################################################################
41 re_bad_diff = re.compile("^[\-\+][\-\+][\-\+] /dev/null");
42 re_is_changes = re.compile (r"(.+?)_(.+?)_(.+?)\.changes$");
44 ################################################################################
47 jennifer_version = "$Revision: 1.1 $";
57 # Aliases to the real vars in the Katie class; hysterical raisins.
65 ###############################################################################
68 global Cnf, Options, Katie, changes, dsc, dsc_files, files, pkg;
72 Cnf = apt_pkg.newConfiguration();
73 apt_pkg.ReadConfigFileISC(Cnf,utils.which_conf_file());
75 Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
76 ('h',"help","Dinstall::Options::Help"),
77 ('n',"no-action","Dinstall::Options::No-Action"),
78 ('p',"no-lock", "Dinstall::Options::No-Lock"),
79 ('s',"no-mail", "Dinstall::Options::No-Mail"),
80 ('V',"version","Dinstall::Options::Version")];
82 for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
83 "override-distribution", "version"]:
84 Cnf["Dinstall::Options::%s" % (i)] = "";
86 changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
87 Options = Cnf.SubTree("Dinstall::Options")
89 Katie = katie.Katie(Cnf);
91 changes = Katie.pkg.changes;
93 dsc_files = Katie.pkg.dsc_files;
94 files = Katie.pkg.files;
99 #########################################################################################
101 def usage (exit_code=0):
102 print """Usage: dinstall [OPTION]... [CHANGES]...
103 -a, --automatic automatic run
104 -h, --help show this help and exit.
105 -n, --no-action don't do anything
106 -p, --no-lock don't check lockfile !! for cron.daily only !!
107 -s, --no-mail don't send any mail
108 -V, --version display the version number and exit"""
111 #########################################################################################
113 # Our very own version of commands.getouputstatus(), hacked to support
115 def get_status_output(cmd, status_read, status_write):
116 cmd = ['/bin/sh', '-c', cmd];
117 p2cread, p2cwrite = os.pipe();
118 c2pread, c2pwrite = os.pipe();
119 errout, errin = os.pipe();
129 for i in range(3, 256):
130 if i != status_write:
136 os.execvp(cmd[0], cmd);
142 os.dup2(c2pread, c2pwrite);
143 os.dup2(errout, errin);
145 output = status = "";
147 i, o, e = select.select([c2pwrite, errin, status_read], [], []);
150 r = os.read(fd, 8196);
152 more_data.append(fd);
153 if fd == c2pwrite or fd == errin:
155 elif fd == status_read:
158 utils.fubar("Unexpected file descriptor [%s] returned from select\n" % (fd));
160 pid, exit_status = os.waitpid(pid, 0)
162 os.close(status_write);
163 os.close(status_read);
171 return output, status, exit_status;
173 #########################################################################################
175 def Dict(**dict): return dict
177 def prefix_multi_line_string(str, prefix):
179 for line in string.split(str, '\n'):
180 line = string.strip(line);
182 out = out + "%s %s\n" % (prefix, line);
183 # Strip trailing new line
188 def reject (str, prefix="Rejected: "):
189 global reject_message;
191 reject_message = reject_message + prefix + str + "\n";
193 #########################################################################################
195 def check_signature (filename):
196 if not utils.re_taint_free.match(os.path.basename(filename)):
197 reject("!!WARNING!! tainted filename: '%s'." % (filename));
200 status_read, status_write = os.pipe();
201 cmd = "gpgv --status-fd %s --keyring %s --keyring %s %s" \
202 % (status_write, Cnf["Dinstall::PGPKeyring"], Cnf["Dinstall::GPGKeyring"], filename);
203 (output, status, exit_status) = get_status_output(cmd, status_read, status_write);
205 # Process the status-fd output
207 bad = internal_error = "";
208 for line in string.split(status, '\n'):
209 line = string.strip(line);
212 split = string.split(line);
214 internal_error = internal_error + "gpgv status line is malformed (< 2 atoms) ['%s'].\n" % (line);
216 (gnupg, keyword) = split[:2];
217 if gnupg != "[GNUPG:]":
218 internal_error = internal_error + "gpgv status line is malformed (incorrect prefix '%s').\n" % (gnupg);
221 if keywords.has_key(keyword) and keyword != "NODATA":
222 internal_error = internal_error + "found duplicate status token ('%s')." % (keyword);
225 keywords[keyword] = args;
227 # If we failed to parse the status-fd output, let's just whine and bail now
229 reject("internal error while performing signature check on %s." % (filename));
230 reject(internal_error, "");
231 reject("Please report the above errors to the Archive maintainers by replying to this mail.", "");
234 # Now check for obviously bad things in the processed output
235 if keywords.has_key("SIGEXPIRED"):
236 reject("key used to sign %s has expired." % (filename));
238 if keywords.has_key("KEYREVOKED"):
239 reject("key used to sign %s has been revoked." % (filename));
241 if keywords.has_key("BADSIG"):
242 reject("bad signature on %s." % (filename));
244 if keywords.has_key("ERRSIG") and not keywords.has_key("NO_PUBKEY"):
245 reject("failed to check signature on %s." % (filename));
247 if keywords.has_key("NO_PUBKEY"):
248 reject("key used to sign %s not found in keyring." % (filename));
250 if keywords.has_key("BADARMOR"):
251 reject("ascii armour of signature was corrupt in %s." % (filename));
253 if keywords.has_key("NODATA"):
254 reject("no signature found in %s." % (filename));
260 # Next check gpgv exited with a zero return code
262 reject("gpgv failed while checking %s." % (filename));
263 if string.strip(status):
264 reject(prefix_multi_line_string(status, " [GPG status-fd output:]"), "");
266 reject(prefix_multi_line_string(output, " [GPG output:]"), "");
269 # Sanity check the good stuff we expect
270 if not keywords.has_key("VALIDSIG"):
271 reject("signature on %s does not appear to be valid [No VALIDSIG]." % (filename));
274 args = keywords["VALIDSIG"];
276 reject("internal error while checking signature on %s." % (filename));
279 fingerprint = args[0];
280 if not keywords.has_key("GOODSIG"):
281 reject("signature on %s does not appear to be valid [No GOODSIG]." % (filename));
283 if not keywords.has_key("SIG_ID"):
284 reject("signature on %s does not appear to be valid [No SIG_ID]." % (filename));
287 # Finally ensure there's not something we don't recognise
288 known_keywords = Dict(VALIDSIG="",SIG_ID="",GOODSIG="",BADSIG="",ERRSIG="",
289 SIGEXPIRED="",KEYREVOKED="",NO_PUBKEY="",BADARMOR="",
292 for keyword in keywords.keys():
293 if not known_keywords.has_key(keyword):
294 reject("found unknown status token '%s' from gpgv with args '%s' in %s." % (keyword, repr(keywords[keyword]), filename));
302 ################################################################################
304 def copy_to_holding(filename):
307 base_filename = os.path.basename(filename);
309 dest = Cnf["Dir::QueueHoldingDir"] + '/' + base_filename;
311 fd = os.open(dest, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0640);
314 # Shouldn't happen, but will if, for example, someone lists a
315 # file twice in the .changes.
316 if errno.errorcode[e.errno] == 'EEXIST':
317 reject("%s already exists in holding area; can not overwrite." % (base_filename));
322 shutil.copy(filename, dest);
324 # In either case (ENOENT or EPERM) we want to remove the
325 # O_CREAT | O_EXCLed ghost file, so add the file to the list
326 # of 'in holding' even if it's not the real file.
327 if errno.errorcode[e.errno] == 'ENOENT':
328 reject("can not copy %s to holding area: file not found." % (base_filename));
331 elif errno.errorcode[e.errno] == 'EACCES':
332 reject("can not copy %s to holding area: read permission denied." % (base_filename));
337 in_holding[base_filename] = "";
340 ################################################################################
346 os.chdir(Cnf["Dir::QueueHoldingDir"]);
347 for file in in_holding.keys():
348 if os.path.exists(file):
349 if string.find(file, '/') != -1:
350 utils.fubar("WTF? clean_holding() got a file ('%s') with / in it!" % (file));
356 ################################################################################
359 filename = pkg.changes_file;
361 # Default in case we bail out
362 changes["maintainer822"] = Cnf["Dinstall::MyEmailAddress"];
363 changes["changedby822"] = Cnf["Dinstall::MyEmailAddress"];
364 changes["architecture"] = {};
366 # Parse the .changes field into a dictionary
368 changes.update(utils.parse_changes(filename, 0));
369 except utils.cant_open_exc:
370 reject("can't read changes file '%s'." % (filename));
372 except utils.changes_parse_error_exc, line:
373 reject("error parsing changes file '%s', can't grok: %s." % (filename, line));
376 # Parse the Files field from the .changes into another dictionary
378 files.update(utils.build_file_list(changes, ""));
379 except utils.changes_parse_error_exc, line:
380 reject("error parsing changes file '%s', can't grok: %s." % (filename, line));
381 except utils.nk_format_exc, format:
382 reject("unknown format '%s' of changes file '%s'." % (format, filename));
385 # Check for mandatory fields
386 for i in ("source", "binary", "architecture", "version", "distribution", "maintainer", "files"):
387 if not changes.has_key(i):
388 reject("Missing field `%s' in changes file." % (i));
389 return 0 # Avoid <undef> errors during later tests
391 # Split multi-value fields into a lower-level dictionary
392 for i in ("architecture", "distribution", "binary", "closes"):
393 o = changes.get(i, "")
397 for j in string.split(o):
400 # Fix the Maintainer: field to be RFC822 compatible
401 (changes["maintainer822"], changes["maintainername"], changes["maintaineremail"]) = utils.fix_maintainer (changes["maintainer"])
403 # Fix the Changed-By: field to be RFC822 compatible; if it exists.
404 (changes["changedby822"], changes["changedbyname"], changes["changedbyemail"]) = utils.fix_maintainer(changes.get("changed-by",""));
406 # Ensure all the values in Closes: are numbers
407 if changes.has_key("closes"):
408 for i in changes["closes"].keys():
409 if katie.re_isanum.match (i) == None:
410 reject("`%s' from Closes field isn't a number." % (i));
412 # Ensure there is a target distribution
413 if changes["distribution"].keys() == []:
414 reject("huh? Distribution field is empty in changes file.");
416 # Map frozen to unstable if frozen doesn't exist
417 if changes["distribution"].has_key("frozen") and not Cnf.has_key("Suite::Frozen"):
418 del changes["distribution"]["frozen"]
419 changes["distribution"]["unstable"] = 1;
420 reject("Mapping frozen to unstable.","");
422 # Map testing to unstable
423 if changes["distribution"].has_key("testing"):
424 if len(changes["distribution"].keys()) > 1:
425 del changes["distribution"]["testing"];
426 reject("Ignoring testing as a target suite.", "Warning: ");
428 reject("invalid distribution 'testing'.");
430 # Ensure target distributions exist
431 for i in changes["distribution"].keys():
432 if not Cnf.has_key("Suite::%s" % (i)):
433 reject("Unknown distribution `%s'." % (i));
435 # Map unreleased arches from stable to unstable
436 if changes["distribution"].has_key("stable"):
437 for i in changes["architecture"].keys():
438 if not Cnf.has_key("Suite::Stable::Architectures::%s" % (i)):
439 reject("Mapping stable to unstable for unreleased arch %s." % (i),"");
440 del changes["distribution"]["stable"];
441 changes["distribution"]["unstable"] = 1;
444 # Map arches not being released from frozen to unstable
445 if changes["distribution"].has_key("frozen"):
446 for i in changes["architecture"].keys():
447 if not Cnf.has_key("Suite::Frozen::Architectures::%s" % (i)):
448 reject("Mapping frozen to unstable for non-releasing arch `%s'." % (i),"");
449 del changes["distribution"]["frozen"]
450 changes["distribution"]["unstable"] = 1;
452 # Map stable uploads to proposed-updates
453 if changes["distribution"].has_key("stable"):
454 reject("Mapping stable to updates.","");
455 del changes["distribution"]["stable"];
456 changes["distribution"]["proposed-updates"] = 1;
458 # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
459 changes["chopversion"] = utils.re_no_epoch.sub('', changes["version"])
460 changes["chopversion2"] = utils.re_no_revision.sub('', changes["chopversion"])
462 # Ensure the changes filename matches it's contents.
464 base_filename = os.path.basename(filename);
465 m = re_is_changes.match(base_filename);
466 # source package name
468 file_source = m.group(1);
469 if changes["source"] != file_source:
470 reject("package name part of changes filename (%s) does not match source field (%s) in the changes file." % (file_source, changes["source"]));
472 file_version = m.group(2);
473 if changes["chopversion"] != file_version:
474 reject("version part of changes filename (%s) does not match version field (%s) in the changes file." % (file_version, changes["chopversion"]));
476 reject("invalid changes filename '%s'." % (filename));
478 # But ... we can't check architecture because there's no
479 # established policy or practice on how to handle
480 # multi-architecture uploads. Instead we check what we can and
481 # reject if there's a changes file of the same name already in one
482 # of the queue directories.
483 for dir in [ "Accepted", "Byhand", "Done", "New" ]:
484 if os.path.exists(Cnf["Dir::Queue%sDir" % (dir) ]+'/'+base_filename):
485 reject("a changes file with the same name exists in the %s directory." % (dir));
489 ################################################################################
494 archive = utils.where_am_i();
495 file_keys = files.keys();
497 # if reprocess is 2 we've already done this and we're checking
498 # things again for the new .orig.tar.gz.
499 # [Yes, I'm fully aware of how disgusting this is]
500 if not Options["No-Action"] and reprocess < 2:
502 os.chdir(pkg.directory);
503 for file in file_keys:
504 copy_to_holding(file);
509 for file in file_keys:
510 # Ensure the file does not already exist in one of the accepted directories
511 for dir in [ "Accepted", "Byhand", "New" ]:
512 if os.path.exists(Cnf["Dir::Queue%sDir" % (dir) ]+'/'+file):
513 reject("%s file already exists in the %s directory." % (file, dir));
514 if not utils.re_taint_free.match(file):
515 reject("!!WARNING!! tainted filename: '%s'." % (file));
516 # Check the file is readable
517 if os.access(file,os.R_OK) == 0:
518 # When running in -n, copy_to_holding() won't have
519 # generated the reject_message, so we need to.
520 if Options["No-Action"]:
521 if os.path.exists(file):
522 reject("Can't read `%s'. [permission denied]" % (file));
524 reject("Can't read `%s'. [file not found]" % (file));
525 files[file]["type"] = "unreadable";
527 # If it's byhand skip remaining checks
528 if files[file]["section"] == "byhand":
529 files[file]["byhand"] = 1;
530 files[file]["type"] = "byhand";
531 # Checks for a binary package...
532 elif utils.re_isadeb.match(file) != None:
533 files[file]["type"] = "deb";
535 # Extract package control information
537 control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(file)));
539 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
540 # Can't continue, none of the checks on control would work.
543 # Check for mandatory fields
544 for field in [ "Package", "Architecture", "Version" ]:
545 if control.Find(field) == None:
546 reject("%s: No %s field in control." % (file, field));
548 # Ensure the package name matches the one give in the .changes
549 if not changes["binary"].has_key(control.Find("Package", "")):
550 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
552 # Ensure the architecture of the .deb is one we know about.
553 if not Cnf.has_key("Suite::Unstable::Architectures::%s" % (control.Find("Architecture", ""))):
554 reject("Unknown architecture '%s'." % (control.Find("Architecture", "")));
556 # Ensure the architecture of the .deb is one of the ones
557 # listed in the .changes.
558 if not changes["architecture"].has_key(control.Find("Architecture", "")):
559 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, control.Find("Architecture", "")));
561 # Check the section & priority match those given in the .changes (non-fatal)
562 if control.Find("Section") != None and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
563 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
564 if control.Find("Priority") != None and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
565 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
567 files[file]["package"] = control.Find("Package");
568 files[file]["architecture"] = control.Find("Architecture");
569 files[file]["version"] = control.Find("Version");
570 files[file]["maintainer"] = control.Find("Maintainer", "");
571 if file[-5:] == ".udeb":
572 files[file]["dbtype"] = "udeb";
573 elif file[-4:] == ".deb":
574 files[file]["dbtype"] = "deb";
576 reject("%s is neither a .deb or a .udeb." % (file));
577 files[file]["source"] = control.Find("Source", "");
578 if files[file]["source"] == "":
579 files[file]["source"] = files[file]["package"];
580 # Get the source version
581 source = files[file]["source"];
583 if string.find(source, "(") != -1:
584 m = utils.re_extract_src_version.match(source)
586 source_version = m.group(2)
587 if not source_version:
588 source_version = files[file]["version"];
589 files[file]["source package"] = source;
590 files[file]["source version"] = source_version;
592 # Ensure the filename matches the contents of the .deb
593 m = utils.re_isadeb.match(file);
595 file_package = m.group(1);
596 if files[file]["package"] != file_package:
597 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"]));
598 epochless_version = utils.re_no_epoch.sub('', control.Find("Version", ""))
600 file_version = m.group(2);
601 if epochless_version != file_version:
602 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
604 file_architecture = m.group(3);
605 if files[file]["architecture"] != file_architecture:
606 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"]));
608 # Check for existent source
609 source_version = files[file]["source version"];
610 source_package = files[file]["source package"];
611 if changes["architecture"].has_key("source"):
612 if source_version != changes["version"]:
613 reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
615 # Check in the SQL database
616 if not Katie.source_exists(source_package, source_version):
617 # Check in one of the other directories
618 source_epochless_version = utils.re_no_epoch.sub('', source_version);
619 dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
620 if os.path.exists(Cnf["Dir::QueueByhandDir"] + '/' + dsc_filename):
621 files[file]["byhand"] = 1;
622 elif os.path.exists(Cnf["Dir::QueueNewDir"] + '/' + dsc_filename):
623 files[file]["new"] = 1;
624 elif not os.path.exists(Cnf["Dir::QueueAcceptedDir"] + '/' + dsc_filename):
625 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
627 # Checks for a source package...
629 m = utils.re_issource.match(file);
631 files[file]["package"] = m.group(1);
632 files[file]["version"] = m.group(2);
633 files[file]["type"] = m.group(3);
635 # Ensure the source package name matches the Source filed in the .changes
636 if changes["source"] != files[file]["package"]:
637 reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
639 # Ensure the source version matches the version in the .changes file
640 if files[file]["type"] == "orig.tar.gz":
641 changes_version = changes["chopversion2"];
643 changes_version = changes["chopversion"];
644 if changes_version != files[file]["version"]:
645 reject("%s: should be %s according to changes file." % (file, changes_version));
647 # Ensure the .changes lists source in the Architecture field
648 if not changes["architecture"].has_key("source"):
649 reject("%s: changes file doesn't list `source' in Architecture field." % (file));
651 # Check the signature of a .dsc file
652 if files[file]["type"] == "dsc":
653 dsc["fingerprint"] = check_signature(file);
655 files[file]["architecture"] = "source";
657 # Not a binary or source package? Assume byhand...
659 files[file]["byhand"] = 1;
660 files[file]["type"] = "byhand";
662 # Per-suite file checks
663 files[file]["oldfiles"] = {};
664 for suite in changes["distribution"].keys():
666 if files[file].has_key("byhand"):
669 # Ensure the component is valid for the target suite
670 if Cnf.has_key("Suite:%s::Components" % (suite)) and not Cnf.has_key("Suite::%s::Components::%s" % (suite, files[file]["component"])):
671 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
674 # See if the package is NEW
675 if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
676 files[file]["new"] = 1;
678 if files[file]["type"] == "deb":
679 reject(Katie.check_binaries_against_db(file, suite));
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 string.find(files[file]["priority"],'/') != -1:
690 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
692 # Check the md5sum & size against existing files (if any)
693 location = Cnf["Dir::PoolDir"];
694 files[file]["location id"] = db_access.get_location_id (location, component, archive);
696 files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
697 files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
699 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
701 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
702 files[file]["files id"] = files_id
704 # Check for packages that have moved from one component to another
705 if files[file]["oldfiles"].has_key(suite) and files[file]["oldfiles"][suite]["name"] != files[file]["component"]:
706 files[file]["othercomponents"] = files[file]["oldfiles"][suite]["name"];
708 ###############################################################################
713 for file in files.keys():
714 if files[file]["type"] == "dsc":
715 # Parse the .dsc file
717 dsc.update(utils.parse_changes(file, 1));
718 except utils.cant_open_exc:
719 # if not -n copy_to_holding() will have done this for us...
720 if Options["No-Action"]:
721 reject("can't read .dsc file '%s'." % (file));
722 except utils.changes_parse_error_exc, line:
723 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
724 except utils.invalid_dsc_format_exc, line:
725 reject("syntax error in .dsc file '%s', line %s." % (file, line));
726 # Build up the file list of files mentioned by the .dsc
728 dsc_files.update(utils.build_file_list(dsc, 1));
729 except utils.no_files_exc:
730 reject("no Files: field in .dsc file.");
732 except utils.changes_parse_error_exc, line:
733 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
736 # Enforce mandatory fields
737 for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
738 if not dsc.has_key(i):
739 reject("Missing field `%s' in dsc file." % (i));
741 # The dpkg maintainer from hell strikes again! Bumping the
742 # version number of the .dsc breaks extraction by stable's
744 if dsc["format"] != "1.0":
745 reject("""[dpkg-sucks] source package was produced by a broken version
746 of dpkg-dev 1.9.1{3,4}; please rebuild with >= 1.9.15 version
749 # Ensure the version number in the .dsc matches the version number in the .changes
750 epochless_dsc_version = utils.re_no_epoch.sub('', dsc.get("version"));
751 changes_version = files[file]["version"];
752 if epochless_dsc_version != files[file]["version"]:
753 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
755 # Ensure source is newer than existing source in target suites
756 reject(Katie.check_source_against_db(file));
758 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
761 if not Options["No-Action"]:
762 copy_to_holding(is_in_incoming);
763 orig_tar_gz = os.path.basename(is_in_incoming);
764 files[orig_tar_gz] = {};
765 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
766 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
767 files[orig_tar_gz]["section"] = files[file]["section"];
768 files[orig_tar_gz]["priority"] = files[file]["priority"];
769 files[orig_tar_gz]["component"] = files[file]["component"];
770 files[orig_tar_gz]["type"] = "orig.tar.gz";
773 ################################################################################
775 # Some cunning stunt broke dpkg-source in dpkg 1.8{,.1}; detect the
776 # resulting bad source packages and reject them.
778 # Even more amusingly the fix in 1.8.1.1 didn't actually fix the
779 # problem just changed the symptoms.
782 for filename in files.keys():
783 if files[filename]["type"] == "diff.gz":
784 file = gzip.GzipFile(filename, 'r');
785 for line in file.readlines():
786 if re_bad_diff.search(line):
787 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.");
790 ################################################################################
792 # FIXME: should be a debian specific check called from a hook
794 def check_urgency ():
795 if changes["architecture"].has_key("source"):
796 if not changes.has_key("urgency"):
797 changes["urgency"] = Cnf["Urgency::Default"];
798 if not Cnf.has_key("Urgency::Valid::%s" % changes["urgency"]):
799 reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
800 changes["urgency"] = Cnf["Urgency::Default"];
801 changes["urgency"] = lower(changes["urgency"]);
803 ################################################################################
805 def check_md5sums ():
806 for file in files.keys():
808 file_handle = utils.open_file(file);
809 except utils.cant_open_exc:
812 if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
813 reject("md5sum check failed for %s." % (file));
815 ################################################################################
817 # Sanity check the time stamps of files inside debs.
818 # [Files in the near future cause ugly warnings and extreme time
819 # travel can causes errors on extraction]
821 def check_timestamps():
823 def __init__(self, future_cutoff, past_cutoff):
825 self.future_cutoff = future_cutoff;
826 self.past_cutoff = past_cutoff;
829 self.future_files = {};
830 self.ancient_files = {};
832 def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
833 if MTime > self.future_cutoff:
834 self.future_files[Name] = MTime;
835 if MTime < self.past_cutoff:
836 self.ancient_files[Name] = MTime;
839 future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"]);
840 past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"));
841 tar = Tar(future_cutoff, past_cutoff);
842 for filename in files.keys():
843 if files[filename]["type"] == "deb":
846 deb_file = utils.open_file(filename);
847 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz");
849 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz");
851 future_files = tar.future_files.keys();
853 num_future_files = len(future_files);
854 future_file = future_files[0];
855 future_date = tar.future_files[future_file];
856 reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
857 % (filename, num_future_files, future_file,
858 time.ctime(future_date)));
860 ancient_files = tar.ancient_files.keys();
862 num_ancient_files = len(ancient_files);
863 ancient_file = ancient_files[0];
864 ancient_date = tar.ancient_files[ancient_file];
865 reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
866 % (filename, num_ancient_files, ancient_file,
867 time.ctime(ancient_date)));
869 reject("%s: timestamp check failed; caught %s" % (filename, sys.exc_type));
872 ################################################################################
873 ################################################################################
875 # If any file of an upload has a recent mtime then chances are good
876 # the file is still being uploaded.
878 def upload_too_new():
879 file_list = pkg.files.keys();
880 file_list.extend(pkg.dsc_files.keys());
881 file_list.append(pkg.changes_file);
882 for file in file_list:
884 last_modified = time.time()-os.path.getmtime(pkg.changes_file);
885 if last_modified < int(Cnf["Dinstall::SkipTime"]):
892 # changes["distribution"] may not exist in corner cases
893 # (e.g. unreadable changes files)
894 if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
895 changes["distribution"] = {};
897 (summary, short_summary) = Katie.build_summaries();
900 for file in files.keys():
901 if files[file].has_key("byhand"):
903 elif files[file].has_key("new"):
906 (prompt, answer) = ("", "XXX")
907 if Options["No-Action"] or Options["Automatic"]:
910 if string.find(reject_message, "Rejected") != -1:
912 print "SKIP (too new)\n" + reject_message,;
913 prompt = "[S]kip, Quit ?";
915 print "REJECT\n" + reject_message,;
916 prompt = "[R]eject, Skip, Quit ?";
917 if Options["Automatic"]:
920 print "NEW to %s\n%s%s" % (string.join(changes["distribution"].keys(), ", "), reject_message, summary),;
921 prompt = "[N]ew, Skip, Quit ?";
922 if Options["Automatic"]:
925 print "BYHAND\n" + reject_message + summary,;
926 prompt = "[B]yhand, Skip, Quit ?";
927 if Options["Automatic"]:
930 print "ACCEPT\n" + reject_message + summary,;
931 prompt = "[A]ccept, Skip, Quit ?";
932 if Options["Automatic"]:
935 while string.find(prompt, answer) == -1:
937 answer = utils.our_raw_input()
938 m = katie.re_default_answer.match(prompt)
941 answer = string.upper(answer[:1])
944 os.chdir (pkg.directory);
945 Katie.do_reject(0, reject_message);
947 accept(summary, short_summary);
951 acknowledge_new (summary);
955 ################################################################################
957 def accept (summary, short_summary):
958 Katie.accept(summary, short_summary);
960 # Check for override disparities
961 if not Cnf["Dinstall::Options::No-Mail"]:
962 Katie.check_override();
964 # Finally, remove the originals from the unchecked directory
965 os.chdir (pkg.directory);
966 for file in files.keys():
968 os.unlink(pkg.changes_file);
970 ################################################################################
972 def do_byhand (summary):
973 print "Moving to BYHAND holding area."
975 Katie.dump_vars(Cnf["Dir::QueueByhandDir"]);
977 file_keys = files.keys();
979 # Move all the files into the accepted directory
980 utils.move (pkg.changes_file, Cnf["Dir::QueueByhandDir"]);
981 for file in file_keys:
982 utils.move (file, Cnf["Dir::QueueByhandDir"]);
984 # Check for override disparities
985 if not Cnf["Dinstall::Options::No-Mail"]:
986 Katie.Subst["__SUMMARY__"] = summary;
987 Katie.check_override();
989 # Finally remove the originals.
990 os.chdir (pkg.directory);
991 for file in file_keys:
993 os.unlink(pkg.changes_file);
995 ################################################################################
997 def acknowledge_new (summary):
1000 print "Moving to NEW holding area."
1002 Katie.dump_vars(Cnf["Dir::QueueNewDir"]);
1004 file_keys = files.keys();
1006 # Move all the files into the accepted directory
1007 utils.move (pkg.changes_file, Cnf["Dir::QueueNewDir"]);
1008 for file in file_keys:
1009 utils.move (file, Cnf["Dir::QueueNewDir"]);
1011 if not Options["No-Mail"]:
1012 print "Sending new ack.";
1013 Subst["__SUMMARY__"] = summary;
1014 new_ack_message = utils.TemplateSubst(Subst,open(Cnf["Dir::TemplatesDir"]+"/jennifer.new","r").read());
1015 utils.send_mail(new_ack_message,"");
1017 # Finally remove the originals.
1018 os.chdir (pkg.directory);
1019 for file in file_keys:
1021 os.unlink(pkg.changes_file);
1023 ################################################################################
1025 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1026 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1027 # dsccheckdistrib() can find the .orig.tar.gz but it will not have
1028 # processed it during it's checks of -2. If -1 has been deleted or
1029 # otherwise not checked by jennifer, the .orig.tar.gz will not have been
1030 # checked at all. To get round this, we force the .orig.tar.gz into
1031 # the .changes structure and reprocess the .changes file.
1033 def process_it (changes_file):
1034 global reprocess, reject_message;
1036 # Reset some globals
1039 reject_message = "";
1041 # Absolutize the filename to avoid the requirement of being in the
1042 # same directory as the .changes file.
1043 pkg.changes_file = os.path.abspath(changes_file);
1045 # Remember where we are so we can come back after cd-ing into the
1046 # holding directory.
1047 pkg.directory = os.getcwd();
1050 # If this is the Real Thing(tm), copy things into a private
1051 # holding directory first to avoid replacable file races.
1052 if not Options["No-Action"]:
1053 os.chdir(Cnf["Dir::QueueHoldingDir"]);
1054 copy_to_holding(pkg.changes_file);
1055 # Relativize the filename so we use the copy in holding
1056 # rather than the original...
1057 pkg.changes_file = os.path.basename(pkg.changes_file);
1058 changes["fingerprint"] = check_signature(pkg.changes_file);
1059 changes_valid = check_changes();
1068 Katie.update_subst(reject_message);
1074 traceback.print_exc(file=sys.stdout);
1077 # Restore previous WD
1078 os.chdir(pkg.directory);
1080 ###############################################################################
1083 global Cnf, Options, Logger, nmu;
1085 changes_files = init();
1090 if Options["Version"]:
1091 print "jennifer %s" % (jennifer_version);
1094 # -n/--dry-run invalidates some other options which would involve things happening
1095 if Options["No-Action"]:
1096 Options["Automatic"] = "";
1098 # Ensure all the arguments we were given are .changes files
1099 for file in changes_files:
1100 if file[-8:] != ".changes":
1101 utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
1102 changes_files.remove(file);
1104 if changes_files == []:
1105 utils.fubar("Need at least one .changes file as an argument.");
1107 # Check that we aren't going to clash with the daily cron job
1109 if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::RootDir"])) and not Options["No-Lock"]:
1110 utils.fubar("Archive maintenance in progress. Try again later.");
1112 # Obtain lock if not in no-action mode and initialize the log
1114 if not Options["No-Action"]:
1115 lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1116 fcntl.lockf(lock_fd, FCNTL.F_TLOCK);
1117 Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1119 # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1120 bcc = "X-Katie: %s" % (jennifer_version);
1121 if Cnf.has_key("Dinstall::Bcc"):
1122 Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1124 Katie.Subst["__BCC__"] = bcc;
1127 # Sort the .changes files so that we process sourceful ones first
1128 changes_files.sort(utils.changes_compare);
1130 # Process the changes files
1131 for changes_file in changes_files:
1132 print "\n" + changes_file;
1134 process_it (changes_file);
1136 if not Options["No-Action"]:
1139 accept_count = Katie.accept_count;
1140 accept_bytes = Katie.accept_bytes;
1143 if accept_count > 1:
1145 sys.stderr.write("Accepted %d package %s, %s.\n" % (accept_count, sets, utils.size_type(int(accept_bytes))));
1146 Logger.log(["total",accept_count,accept_bytes]);
1148 if not Options["No-Action"]:
1151 ################################################################################
1153 if __name__ == '__main__':