3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001 James Troup <james@nocrew.org>
5 # $Id: jennifer,v 1.9 2002-03-14 14:12:04 ajt 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.9 $";
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 # Check there isn't already a changes file of the same name in one
463 # of the queue directories.
464 base_filename = os.path.basename(filename);
465 for dir in [ "Accepted", "Byhand", "Done", "New" ]:
466 if os.path.exists(Cnf["Dir::Queue%sDir" % (dir) ]+'/'+base_filename):
467 reject("a changes file with the same name already exists in the %s directory." % (dir));
471 ################################################################################
476 archive = utils.where_am_i();
477 file_keys = files.keys();
479 # if reprocess is 2 we've already done this and we're checking
480 # things again for the new .orig.tar.gz.
481 # [Yes, I'm fully aware of how disgusting this is]
482 if not Options["No-Action"] and reprocess < 2:
484 os.chdir(pkg.directory);
485 for file in file_keys:
486 copy_to_holding(file);
491 for file in file_keys:
492 # Ensure the file does not already exist in one of the accepted directories
493 for dir in [ "Accepted", "Byhand", "New" ]:
494 if os.path.exists(Cnf["Dir::Queue%sDir" % (dir) ]+'/'+file):
495 reject("%s file already exists in the %s directory." % (file, dir));
496 if not utils.re_taint_free.match(file):
497 reject("!!WARNING!! tainted filename: '%s'." % (file));
498 # Check the file is readable
499 if os.access(file,os.R_OK) == 0:
500 # When running in -n, copy_to_holding() won't have
501 # generated the reject_message, so we need to.
502 if Options["No-Action"]:
503 if os.path.exists(file):
504 reject("Can't read `%s'. [permission denied]" % (file));
506 reject("Can't read `%s'. [file not found]" % (file));
507 files[file]["type"] = "unreadable";
509 # If it's byhand skip remaining checks
510 if files[file]["section"] == "byhand":
511 files[file]["byhand"] = 1;
512 files[file]["type"] = "byhand";
513 # Checks for a binary package...
514 elif utils.re_isadeb.match(file) != None:
515 files[file]["type"] = "deb";
517 # Extract package control information
519 control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(file)));
521 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
522 # Can't continue, none of the checks on control would work.
525 # Check for mandatory fields
526 for field in [ "Package", "Architecture", "Version" ]:
527 if control.Find(field) == None:
528 reject("%s: No %s field in control." % (file, field));
530 # Ensure the package name matches the one give in the .changes
531 if not changes["binary"].has_key(control.Find("Package", "")):
532 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
534 # Ensure the architecture of the .deb is one we know about.
535 if not Cnf.has_key("Suite::Unstable::Architectures::%s" % (control.Find("Architecture", ""))):
536 reject("Unknown architecture '%s'." % (control.Find("Architecture", "")));
538 # Ensure the architecture of the .deb is one of the ones
539 # listed in the .changes.
540 if not changes["architecture"].has_key(control.Find("Architecture", "")):
541 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, control.Find("Architecture", "")));
543 # Check the section & priority match those given in the .changes (non-fatal)
544 if control.Find("Section") != None and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
545 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
546 if control.Find("Priority") != None and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
547 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
549 files[file]["package"] = control.Find("Package");
550 files[file]["architecture"] = control.Find("Architecture");
551 files[file]["version"] = control.Find("Version");
552 files[file]["maintainer"] = control.Find("Maintainer", "");
553 if file[-5:] == ".udeb":
554 files[file]["dbtype"] = "udeb";
555 elif file[-4:] == ".deb":
556 files[file]["dbtype"] = "deb";
558 reject("%s is neither a .deb or a .udeb." % (file));
559 files[file]["source"] = control.Find("Source", "");
560 if files[file]["source"] == "":
561 files[file]["source"] = files[file]["package"];
562 # Get the source version
563 source = files[file]["source"];
565 if string.find(source, "(") != -1:
566 m = utils.re_extract_src_version.match(source)
568 source_version = m.group(2)
569 if not source_version:
570 source_version = files[file]["version"];
571 files[file]["source package"] = source;
572 files[file]["source version"] = source_version;
574 # Ensure the filename matches the contents of the .deb
575 m = utils.re_isadeb.match(file);
577 file_package = m.group(1);
578 if files[file]["package"] != file_package:
579 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"]));
580 epochless_version = utils.re_no_epoch.sub('', control.Find("Version", ""))
582 file_version = m.group(2);
583 if epochless_version != file_version:
584 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
586 file_architecture = m.group(3);
587 if files[file]["architecture"] != file_architecture:
588 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"]));
590 # Check for existent source
591 source_version = files[file]["source version"];
592 source_package = files[file]["source package"];
593 if changes["architecture"].has_key("source"):
594 if source_version != changes["version"]:
595 reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
597 # Check in the SQL database
598 if not Katie.source_exists(source_package, source_version):
599 # Check in one of the other directories
600 source_epochless_version = utils.re_no_epoch.sub('', source_version);
601 dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
602 if os.path.exists(Cnf["Dir::QueueByhandDir"] + '/' + dsc_filename):
603 files[file]["byhand"] = 1;
604 elif os.path.exists(Cnf["Dir::QueueNewDir"] + '/' + dsc_filename):
605 files[file]["new"] = 1;
606 elif not os.path.exists(Cnf["Dir::QueueAcceptedDir"] + '/' + dsc_filename):
607 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
609 # Checks for a source package...
611 m = utils.re_issource.match(file);
613 files[file]["package"] = m.group(1);
614 files[file]["version"] = m.group(2);
615 files[file]["type"] = m.group(3);
617 # Ensure the source package name matches the Source filed in the .changes
618 if changes["source"] != files[file]["package"]:
619 reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
621 # Ensure the source version matches the version in the .changes file
622 if files[file]["type"] == "orig.tar.gz":
623 changes_version = changes["chopversion2"];
625 changes_version = changes["chopversion"];
626 if changes_version != files[file]["version"]:
627 reject("%s: should be %s according to changes file." % (file, changes_version));
629 # Ensure the .changes lists source in the Architecture field
630 if not changes["architecture"].has_key("source"):
631 reject("%s: changes file doesn't list `source' in Architecture field." % (file));
633 # Check the signature of a .dsc file
634 if files[file]["type"] == "dsc":
635 dsc["fingerprint"] = check_signature(file);
637 files[file]["architecture"] = "source";
639 # Not a binary or source package? Assume byhand...
641 files[file]["byhand"] = 1;
642 files[file]["type"] = "byhand";
644 # Per-suite file checks
645 files[file]["oldfiles"] = {};
646 for suite in changes["distribution"].keys():
648 if files[file].has_key("byhand"):
651 # Ensure the component is valid for the target suite
652 if Cnf.has_key("Suite:%s::Components" % (suite)) and not Cnf.has_key("Suite::%s::Components::%s" % (suite, files[file]["component"])):
653 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
656 # See if the package is NEW
657 if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
658 files[file]["new"] = 1;
660 if files[file]["type"] == "deb":
661 reject(Katie.check_binaries_against_db(file, suite),"");
663 # Validate the component
664 component = files[file]["component"];
665 component_id = db_access.get_component_id(component);
666 if component_id == -1:
667 reject("file '%s' has unknown component '%s'." % (file, component));
670 # Validate the priority
671 if string.find(files[file]["priority"],'/') != -1:
672 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
674 # Check the md5sum & size against existing files (if any)
675 location = Cnf["Dir::PoolDir"];
676 files[file]["location id"] = db_access.get_location_id (location, component, archive);
678 files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
679 files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
681 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
683 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
684 files[file]["files id"] = files_id
686 # Check for packages that have moved from one component to another
687 if files[file]["oldfiles"].has_key(suite) and files[file]["oldfiles"][suite]["name"] != files[file]["component"]:
688 files[file]["othercomponents"] = files[file]["oldfiles"][suite]["name"];
690 # If the .changes file says it has source, it must have source.
691 if changes["architecture"].has_key("source"):
693 for file in file_keys:
694 if files[file]["type"] == "dsc":
697 reject("no source found and Architecture line in changes mention source.");
699 ###############################################################################
704 for file in files.keys():
705 if files[file]["type"] == "dsc":
706 # Parse the .dsc file
708 dsc.update(utils.parse_changes(file, 1));
709 except utils.cant_open_exc:
710 # if not -n copy_to_holding() will have done this for us...
711 if Options["No-Action"]:
712 reject("can't read .dsc file '%s'." % (file));
713 except utils.changes_parse_error_exc, line:
714 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
715 except utils.invalid_dsc_format_exc, line:
716 reject("syntax error in .dsc file '%s', line %s." % (file, line));
717 # Build up the file list of files mentioned by the .dsc
719 dsc_files.update(utils.build_file_list(dsc, 1));
720 except utils.no_files_exc:
721 reject("no Files: field in .dsc file.");
723 except utils.changes_parse_error_exc, line:
724 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
727 # Enforce mandatory fields
728 for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
729 if not dsc.has_key(i):
730 reject("Missing field `%s' in dsc file." % (i));
732 # The dpkg maintainer from hell strikes again! Bumping the
733 # version number of the .dsc breaks extraction by stable's
735 if dsc["format"] != "1.0":
736 reject("""[dpkg-sucks] source package was produced by a broken version
737 of dpkg-dev 1.9.1{3,4}; please rebuild with >= 1.9.15 version
740 # Ensure the version number in the .dsc matches the version number in the .changes
741 epochless_dsc_version = utils.re_no_epoch.sub('', dsc.get("version"));
742 changes_version = files[file]["version"];
743 if epochless_dsc_version != files[file]["version"]:
744 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
746 # Ensure source is newer than existing source in target suites
747 reject(Katie.check_source_against_db(file),"");
749 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
750 reject(reject_msg, "");
752 if not Options["No-Action"]:
753 copy_to_holding(is_in_incoming);
754 orig_tar_gz = os.path.basename(is_in_incoming);
755 files[orig_tar_gz] = {};
756 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
757 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
758 files[orig_tar_gz]["section"] = files[file]["section"];
759 files[orig_tar_gz]["priority"] = files[file]["priority"];
760 files[orig_tar_gz]["component"] = files[file]["component"];
761 files[orig_tar_gz]["type"] = "orig.tar.gz";
764 ################################################################################
766 # Some cunning stunt broke dpkg-source in dpkg 1.8{,.1}; detect the
767 # resulting bad source packages and reject them.
769 # Even more amusingly the fix in 1.8.1.1 didn't actually fix the
770 # problem just changed the symptoms.
773 for filename in files.keys():
774 if files[filename]["type"] == "diff.gz":
775 file = gzip.GzipFile(filename, 'r');
776 for line in file.readlines():
777 if re_bad_diff.search(line):
778 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.");
781 ################################################################################
783 # FIXME: should be a debian specific check called from a hook
785 def check_urgency ():
786 if changes["architecture"].has_key("source"):
787 if not changes.has_key("urgency"):
788 changes["urgency"] = Cnf["Urgency::Default"];
789 if not Cnf.has_key("Urgency::Valid::%s" % changes["urgency"]):
790 reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
791 changes["urgency"] = Cnf["Urgency::Default"];
792 changes["urgency"] = lower(changes["urgency"]);
794 ################################################################################
796 def check_md5sums ():
797 for file in files.keys():
799 file_handle = utils.open_file(file);
800 except utils.cant_open_exc:
803 if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
804 reject("md5sum check failed for %s." % (file));
806 ################################################################################
808 # Sanity check the time stamps of files inside debs.
809 # [Files in the near future cause ugly warnings and extreme time
810 # travel can causes errors on extraction]
812 def check_timestamps():
814 def __init__(self, future_cutoff, past_cutoff):
816 self.future_cutoff = future_cutoff;
817 self.past_cutoff = past_cutoff;
820 self.future_files = {};
821 self.ancient_files = {};
823 def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
824 if MTime > self.future_cutoff:
825 self.future_files[Name] = MTime;
826 if MTime < self.past_cutoff:
827 self.ancient_files[Name] = MTime;
830 future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"]);
831 past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"));
832 tar = Tar(future_cutoff, past_cutoff);
833 for filename in files.keys():
834 if files[filename]["type"] == "deb":
837 deb_file = utils.open_file(filename);
838 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz");
840 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz");
842 future_files = tar.future_files.keys();
844 num_future_files = len(future_files);
845 future_file = future_files[0];
846 future_date = tar.future_files[future_file];
847 reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
848 % (filename, num_future_files, future_file,
849 time.ctime(future_date)));
851 ancient_files = tar.ancient_files.keys();
853 num_ancient_files = len(ancient_files);
854 ancient_file = ancient_files[0];
855 ancient_date = tar.ancient_files[ancient_file];
856 reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
857 % (filename, num_ancient_files, ancient_file,
858 time.ctime(ancient_date)));
860 reject("%s: timestamp check failed; caught %s" % (filename, sys.exc_type));
863 ################################################################################
864 ################################################################################
866 # If any file of an upload has a recent mtime then chances are good
867 # the file is still being uploaded.
869 def upload_too_new():
870 file_list = pkg.files.keys();
871 file_list.extend(pkg.dsc_files.keys());
872 file_list.append(pkg.changes_file);
873 for file in file_list:
875 last_modified = time.time()-os.path.getmtime(pkg.changes_file);
876 if last_modified < int(Cnf["Dinstall::SkipTime"]):
883 # changes["distribution"] may not exist in corner cases
884 # (e.g. unreadable changes files)
885 if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
886 changes["distribution"] = {};
888 (summary, short_summary) = Katie.build_summaries();
891 for file in files.keys():
892 if files[file].has_key("byhand"):
894 elif files[file].has_key("new"):
897 (prompt, answer) = ("", "XXX")
898 if Options["No-Action"] or Options["Automatic"]:
901 if string.find(reject_message, "Rejected") != -1:
903 print "SKIP (too new)\n" + reject_message,;
904 prompt = "[S]kip, Quit ?";
906 print "REJECT\n" + reject_message,;
907 prompt = "[R]eject, Skip, Quit ?";
908 if Options["Automatic"]:
911 print "NEW to %s\n%s%s" % (string.join(changes["distribution"].keys(), ", "), reject_message, summary),;
912 prompt = "[N]ew, Skip, Quit ?";
913 if Options["Automatic"]:
916 print "BYHAND\n" + reject_message + summary,;
917 prompt = "[B]yhand, Skip, Quit ?";
918 if Options["Automatic"]:
921 print "ACCEPT\n" + reject_message + summary,;
922 prompt = "[A]ccept, Skip, Quit ?";
923 if Options["Automatic"]:
926 while string.find(prompt, answer) == -1:
927 answer = utils.our_raw_input(prompt);
928 m = katie.re_default_answer.match(prompt);
931 answer = string.upper(answer[:1]);
934 os.chdir (pkg.directory);
935 Katie.do_reject(0, reject_message);
937 accept(summary, short_summary);
941 acknowledge_new (summary);
945 ################################################################################
947 def accept (summary, short_summary):
948 Katie.accept(summary, short_summary);
950 # Check for override disparities
951 if not Cnf["Dinstall::Options::No-Mail"]:
952 Katie.check_override();
954 # Finally, remove the originals from the unchecked directory
955 os.chdir (pkg.directory);
956 for file in files.keys():
958 os.unlink(pkg.changes_file);
960 ################################################################################
962 def do_byhand (summary):
963 print "Moving to BYHAND holding area."
964 Logger.log(["Moving to byhand", pkg.changes_file]);
966 Katie.dump_vars(Cnf["Dir::QueueByhandDir"]);
968 file_keys = files.keys();
970 # Move all the files into the byhand directory
971 utils.move (pkg.changes_file, Cnf["Dir::QueueByhandDir"]);
972 for file in file_keys:
973 utils.move (file, Cnf["Dir::QueueByhandDir"], perms=0660);
975 # Check for override disparities
976 if not Cnf["Dinstall::Options::No-Mail"]:
977 Katie.Subst["__SUMMARY__"] = summary;
978 Katie.check_override();
980 # Finally remove the originals.
981 os.chdir (pkg.directory);
982 for file in file_keys:
984 os.unlink(pkg.changes_file);
986 ################################################################################
988 def acknowledge_new (summary):
991 print "Moving to NEW holding area."
992 Logger.log(["Moving to new", pkg.changes_file]);
994 Katie.dump_vars(Cnf["Dir::QueueNewDir"]);
996 file_keys = files.keys();
998 # Move all the files into the accepted directory
999 utils.move (pkg.changes_file, Cnf["Dir::QueueNewDir"]);
1000 for file in file_keys:
1001 utils.move (file, Cnf["Dir::QueueNewDir"], perms=0660);
1003 if not Options["No-Mail"]:
1004 print "Sending new ack.";
1005 Subst["__SUMMARY__"] = summary;
1006 new_ack_message = utils.TemplateSubst(Subst,open(Cnf["Dir::TemplatesDir"]+"/jennifer.new","r").read());
1007 utils.send_mail(new_ack_message,"");
1009 # Finally remove the originals.
1010 os.chdir (pkg.directory);
1011 for file in file_keys:
1013 os.unlink(pkg.changes_file);
1015 ################################################################################
1017 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1018 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1019 # Katie.check_dsc_against_db() can find the .orig.tar.gz but it will
1020 # not have processed it during it's checks of -2. If -1 has been
1021 # deleted or otherwise not checked by jennifer, the .orig.tar.gz will
1022 # not have been checked at all. To get round this, we force the
1023 # .orig.tar.gz into the .changes structure and reprocess the .changes
1026 def process_it (changes_file):
1027 global reprocess, reject_message;
1029 # Reset some globals
1032 reject_message = "";
1034 # Absolutize the filename to avoid the requirement of being in the
1035 # same directory as the .changes file.
1036 pkg.changes_file = os.path.abspath(changes_file);
1038 # Remember where we are so we can come back after cd-ing into the
1039 # holding directory.
1040 pkg.directory = os.getcwd();
1043 # If this is the Real Thing(tm), copy things into a private
1044 # holding directory first to avoid replacable file races.
1045 if not Options["No-Action"]:
1046 os.chdir(Cnf["Dir::QueueHoldingDir"]);
1047 copy_to_holding(pkg.changes_file);
1048 # Relativize the filename so we use the copy in holding
1049 # rather than the original...
1050 pkg.changes_file = os.path.basename(pkg.changes_file);
1051 changes["fingerprint"] = check_signature(pkg.changes_file);
1052 changes_valid = check_changes();
1061 Katie.update_subst(reject_message);
1067 traceback.print_exc(file=sys.stderr);
1070 # Restore previous WD
1071 os.chdir(pkg.directory);
1073 ###############################################################################
1076 global Cnf, Options, Logger, nmu;
1078 changes_files = init();
1083 if Options["Version"]:
1084 print "jennifer %s" % (jennifer_version);
1087 # -n/--dry-run invalidates some other options which would involve things happening
1088 if Options["No-Action"]:
1089 Options["Automatic"] = "";
1091 # Ensure all the arguments we were given are .changes files
1092 for file in changes_files:
1093 if file[-8:] != ".changes":
1094 utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
1095 changes_files.remove(file);
1097 if changes_files == []:
1098 utils.fubar("Need at least one .changes file as an argument.");
1100 # Check that we aren't going to clash with the daily cron job
1102 if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::RootDir"])) and not Options["No-Lock"]:
1103 utils.fubar("Archive maintenance in progress. Try again later.");
1105 # Obtain lock if not in no-action mode and initialize the log
1107 if not Options["No-Action"]:
1108 lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1109 fcntl.lockf(lock_fd, FCNTL.F_TLOCK);
1110 Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1112 # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1113 bcc = "X-Katie: %s" % (jennifer_version);
1114 if Cnf.has_key("Dinstall::Bcc"):
1115 Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1117 Katie.Subst["__BCC__"] = bcc;
1120 # Sort the .changes files so that we process sourceful ones first
1121 changes_files.sort(utils.changes_compare);
1123 # Process the changes files
1124 for changes_file in changes_files:
1125 print "\n" + changes_file;
1127 process_it (changes_file);
1129 if not Options["No-Action"]:
1132 accept_count = Katie.accept_count;
1133 accept_bytes = Katie.accept_bytes;
1136 if accept_count > 1:
1138 print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)));
1139 Logger.log(["total",accept_count,accept_bytes]);
1141 if not Options["No-Action"]:
1144 ################################################################################
1146 if __name__ == '__main__':