3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004, 2005 James Troup <james@nocrew.org>
5 # $Id: jennifer,v 1.64 2005-12-05 05:31:48 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 commands, errno, fcntl, os, re, shutil, stat, sys, time, tempfile, traceback;
33 import apt_inst, apt_pkg;
34 import db_access, katie, logging, utils;
38 ################################################################################
40 re_valid_version = re.compile(r"^([0-9]+:)?[0-9A-Za-z\.\-\+:]+$");
41 re_valid_pkg_name = re.compile(r"^[\dA-Za-z][\dA-Za-z\+\-\.]+$");
42 re_changelog_versions = re.compile(r"^\w[-+0-9a-z.]+ \([^\(\) \t]+\)");
43 re_strip_revision = re.compile(r"-([^-]+)$");
45 ################################################################################
48 jennifer_version = "$Revision: 1.64 $";
58 # Aliases to the real vars in the Katie class; hysterical raisins.
66 ###############################################################################
69 global Cnf, Options, Katie, changes, dsc, dsc_files, files, pkg;
73 Cnf = apt_pkg.newConfiguration();
74 apt_pkg.ReadConfigFileISC(Cnf,utils.which_conf_file());
76 Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
77 ('h',"help","Dinstall::Options::Help"),
78 ('n',"no-action","Dinstall::Options::No-Action"),
79 ('p',"no-lock", "Dinstall::Options::No-Lock"),
80 ('s',"no-mail", "Dinstall::Options::No-Mail"),
81 ('V',"version","Dinstall::Options::Version")];
83 for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
84 "override-distribution", "version"]:
85 Cnf["Dinstall::Options::%s" % (i)] = "";
87 changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
88 Options = Cnf.SubTree("Dinstall::Options")
92 elif Options["Version"]:
93 print "jennifer %s" % (jennifer_version);
96 Katie = katie.Katie(Cnf);
98 changes = Katie.pkg.changes;
100 dsc_files = Katie.pkg.dsc_files;
101 files = Katie.pkg.files;
104 return changes_files;
106 ################################################################################
108 def usage (exit_code=0):
109 print """Usage: dinstall [OPTION]... [CHANGES]...
110 -a, --automatic automatic run
111 -h, --help show this help and exit.
112 -n, --no-action don't do anything
113 -p, --no-lock don't check lockfile !! for cron.daily only !!
114 -s, --no-mail don't send any mail
115 -V, --version display the version number and exit"""
118 ################################################################################
120 def reject (str, prefix="Rejected: "):
121 global reject_message;
123 reject_message += prefix + str + "\n";
125 ################################################################################
127 def copy_to_holding(filename):
130 base_filename = os.path.basename(filename);
132 dest = Cnf["Dir::Queue::Holding"] + '/' + base_filename;
134 fd = os.open(dest, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0640);
137 # Shouldn't happen, but will if, for example, someone lists a
138 # file twice in the .changes.
139 if errno.errorcode[e.errno] == 'EEXIST':
140 reject("%s: already exists in holding area; can not overwrite." % (base_filename));
145 shutil.copy(filename, dest);
147 # In either case (ENOENT or EACCES) we want to remove the
148 # O_CREAT | O_EXCLed ghost file, so add the file to the list
149 # of 'in holding' even if it's not the real file.
150 if errno.errorcode[e.errno] == 'ENOENT':
151 reject("%s: can not copy to holding area: file not found." % (base_filename));
154 elif errno.errorcode[e.errno] == 'EACCES':
155 reject("%s: can not copy to holding area: read permission denied." % (base_filename));
160 in_holding[base_filename] = "";
162 ################################################################################
168 os.chdir(Cnf["Dir::Queue::Holding"]);
169 for file in in_holding.keys():
170 if os.path.exists(file):
171 if file.find('/') != -1:
172 utils.fubar("WTF? clean_holding() got a file ('%s') with / in it!" % (file));
178 ################################################################################
181 filename = pkg.changes_file;
183 # Parse the .changes field into a dictionary
185 changes.update(utils.parse_changes(filename));
186 except utils.cant_open_exc:
187 reject("%s: can't read file." % (filename));
189 except utils.changes_parse_error_exc, line:
190 reject("%s: parse error, can't grok: %s." % (filename, line));
193 # Parse the Files field from the .changes into another dictionary
195 files.update(utils.build_file_list(changes));
196 except utils.changes_parse_error_exc, line:
197 reject("%s: parse error, can't grok: %s." % (filename, line));
198 except utils.nk_format_exc, format:
199 reject("%s: unknown format '%s'." % (filename, format));
202 # Check for mandatory fields
203 for i in ("source", "binary", "architecture", "version", "distribution",
204 "maintainer", "files", "changes", "description"):
205 if not changes.has_key(i):
206 reject("%s: Missing mandatory field `%s'." % (filename, i));
207 return 0 # Avoid <undef> errors during later tests
209 # Split multi-value fields into a lower-level dictionary
210 for i in ("architecture", "distribution", "binary", "closes"):
211 o = changes.get(i, "")
218 # Fix the Maintainer: field to be RFC822/2047 compatible
220 (changes["maintainer822"], changes["maintainer2047"],
221 changes["maintainername"], changes["maintaineremail"]) = \
222 utils.fix_maintainer (changes["maintainer"]);
223 except utils.ParseMaintError, msg:
224 reject("%s: Maintainer field ('%s') failed to parse: %s" \
225 % (filename, changes["maintainer"], msg));
227 # ...likewise for the Changed-By: field if it exists.
229 (changes["changedby822"], changes["changedby2047"],
230 changes["changedbyname"], changes["changedbyemail"]) = \
231 utils.fix_maintainer (changes.get("changed-by", ""));
232 except utils.ParseMaintError, msg:
233 (changes["changedby822"], changes["changedby2047"],
234 changes["changedbyname"], changes["changedbyemail"]) = \
236 reject("%s: Changed-By field ('%s') failed to parse: %s" \
237 % (filename, changes["changed-by"], msg));
239 # Ensure all the values in Closes: are numbers
240 if changes.has_key("closes"):
241 for i in changes["closes"].keys():
242 if katie.re_isanum.match (i) == None:
243 reject("%s: `%s' from Closes field isn't a number." % (filename, i));
246 # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
247 changes["chopversion"] = utils.re_no_epoch.sub('', changes["version"])
248 changes["chopversion2"] = utils.re_no_revision.sub('', changes["chopversion"])
250 # Check there isn't already a changes file of the same name in one
251 # of the queue directories.
252 base_filename = os.path.basename(filename);
253 for dir in [ "Accepted", "Byhand", "Done", "New" ]:
254 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+base_filename):
255 reject("%s: a file with this name already exists in the %s directory." % (base_filename, dir));
257 # Check the .changes is non-empty
259 reject("%s: nothing to do (Files field is empty)." % (base_filename))
264 ################################################################################
266 def check_distributions():
267 "Check and map the Distribution field of a .changes file."
269 # Handle suite mappings
270 for map in Cnf.ValueList("SuiteMappings"):
273 if type == "map" or type == "silent-map":
274 (source, dest) = args[1:3];
275 if changes["distribution"].has_key(source):
276 del changes["distribution"][source]
277 changes["distribution"][dest] = 1;
278 if type != "silent-map":
279 reject("Mapping %s to %s." % (source, dest),"");
280 if changes.has_key("distribution-version"):
281 if changes["distribution-version"].has_key(source):
282 changes["distribution-version"][source]=dest
283 elif type == "map-unreleased":
284 (source, dest) = args[1:3];
285 if changes["distribution"].has_key(source):
286 for arch in changes["architecture"].keys():
287 if arch not in Cnf.ValueList("Suite::%s::Architectures" % (source)):
288 reject("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch),"");
289 del changes["distribution"][source];
290 changes["distribution"][dest] = 1;
292 elif type == "ignore":
294 if changes["distribution"].has_key(suite):
295 del changes["distribution"][suite];
296 reject("Ignoring %s as a target suite." % (suite), "Warning: ");
297 elif type == "reject":
299 if changes["distribution"].has_key(suite):
300 reject("Uploads to %s are not accepted." % (suite));
301 elif type == "propup-version":
302 # give these as "uploaded-to(non-mapped) suites-to-add-when-upload-obsoletes"
304 # changes["distribution-version"] looks like: {'testing': 'testing-proposed-updates'}
305 if changes["distribution"].has_key(args[1]):
306 changes.setdefault("distribution-version", {})
307 for suite in args[2:]: changes["distribution-version"][suite]=suite
309 # Ensure there is (still) a target distribution
310 if changes["distribution"].keys() == []:
311 reject("no valid distribution.");
313 # Ensure target distributions exist
314 for suite in changes["distribution"].keys():
315 if not Cnf.has_key("Suite::%s" % (suite)):
316 reject("Unknown distribution `%s'." % (suite));
318 ################################################################################
320 def check_deb_ar(filename, control):
321 """Sanity check the ar of a .deb, i.e. that there is:
325 o data.tar.gz or data.tar.bz2
327 in that order, and nothing else. If the third member is a
328 data.tar.bz2, an additional check is performed for the required
329 Pre-Depends on dpkg (>= 1.10.24)."""
330 cmd = "ar t %s" % (filename)
331 (result, output) = commands.getstatusoutput(cmd)
333 reject("%s: 'ar t' invocation failed." % (filename))
334 reject(utils.prefix_multi_line_string(output, " [ar output:] "), "")
335 chunks = output.split('\n')
337 reject("%s: found %d chunks, expected 3." % (filename, len(chunks)))
338 if chunks[0] != "debian-binary":
339 reject("%s: first chunk is '%s', expected 'debian-binary'." % (filename, chunks[0]))
340 if chunks[1] != "control.tar.gz":
341 reject("%s: second chunk is '%s', expected 'control.tar.gz'." % (filename, chunks[1]))
342 if chunks[2] == "data.tar.bz2":
343 # Packages using bzip2 compression must have a Pre-Depends on dpkg >= 1.10.24.
344 found_needed_predep = 0
345 for parsed_dep in apt_pkg.ParseDepends(control.Find("Pre-Depends", "")):
346 for atom in parsed_dep:
347 (dep, version, constraint) = atom
348 if dep != "dpkg" or (constraint != ">=" and constraint != ">>") or \
349 len(parsed_dep) > 1: # or'ed deps don't count
351 if (constraint == ">=" and apt_pkg.VersionCompare(version, "1.10.24") < 0) or \
352 (constraint == ">>" and apt_pkg.VersionCompare(version, "1.10.23") < 0):
354 found_needed_predep = 1
355 if not found_needed_predep:
356 reject("%s: uses bzip2 compression, but doesn't Pre-Depend on dpkg (>= 1.10.24)" % (filename))
357 elif chunks[2] != "data.tar.gz":
358 reject("%s: third chunk is '%s', expected 'data.tar.gz' or 'data.tar.bz2'." % (filename, chunks[2]))
360 ################################################################################
365 archive = utils.where_am_i();
366 file_keys = files.keys();
368 # if reprocess is 2 we've already done this and we're checking
369 # things again for the new .orig.tar.gz.
370 # [Yes, I'm fully aware of how disgusting this is]
371 if not Options["No-Action"] and reprocess < 2:
373 os.chdir(pkg.directory);
374 for file in file_keys:
375 copy_to_holding(file);
378 # Check there isn't already a .changes or .katie file of the same name in
379 # the proposed-updates "CopyChanges" or "CopyKatie" storage directories.
380 # [NB: this check must be done post-suite mapping]
381 base_filename = os.path.basename(pkg.changes_file);
382 katie_filename = base_filename[:-8]+".katie"
383 for suite in changes["distribution"].keys():
384 copychanges = "Suite::%s::CopyChanges" % (suite);
385 if Cnf.has_key(copychanges) and \
386 os.path.exists(Cnf[copychanges]+"/"+base_filename):
387 reject("%s: a file with this name already exists in %s" \
388 % (base_filename, Cnf[copychanges]));
390 copykatie = "Suite::%s::CopyKatie" % (suite);
391 if Cnf.has_key(copykatie) and \
392 os.path.exists(Cnf[copykatie]+"/"+katie_filename):
393 reject("%s: a file with this name already exists in %s" \
394 % (katie_filename, Cnf[copykatie]));
400 for file in file_keys:
401 # Ensure the file does not already exist in one of the accepted directories
402 for dir in [ "Accepted", "Byhand", "New" ]:
403 if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+file):
404 reject("%s file already exists in the %s directory." % (file, dir));
405 if not utils.re_taint_free.match(file):
406 reject("!!WARNING!! tainted filename: '%s'." % (file));
407 # Check the file is readable
408 if os.access(file,os.R_OK) == 0:
409 # When running in -n, copy_to_holding() won't have
410 # generated the reject_message, so we need to.
411 if Options["No-Action"]:
412 if os.path.exists(file):
413 reject("Can't read `%s'. [permission denied]" % (file));
415 reject("Can't read `%s'. [file not found]" % (file));
416 files[file]["type"] = "unreadable";
418 # If it's byhand skip remaining checks
419 if files[file]["section"] == "byhand" or files[file]["section"] == "raw-installer":
420 files[file]["byhand"] = 1;
421 files[file]["type"] = "byhand";
422 # Checks for a binary package...
423 elif utils.re_isadeb.match(file):
425 files[file]["type"] = "deb";
427 # Extract package control information
428 deb_file = utils.open_file(file);
430 control = apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file));
432 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
434 # Can't continue, none of the checks on control would work.
438 # Check for mandatory fields
439 for field in [ "Package", "Architecture", "Version" ]:
440 if control.Find(field) == None:
441 reject("%s: No %s field in control." % (file, field));
445 # Ensure the package name matches the one give in the .changes
446 if not changes["binary"].has_key(control.Find("Package", "")):
447 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
449 # Validate the package field
450 package = control.Find("Package");
451 if not re_valid_pkg_name.match(package):
452 reject("%s: invalid package name '%s'." % (file, package));
454 # Validate the version field
455 version = control.Find("Version");
456 if not re_valid_version.match(version):
457 reject("%s: invalid version number '%s'." % (file, version));
459 # Ensure the architecture of the .deb is one we know about.
460 default_suite = Cnf.get("Dinstall::DefaultSuite", "Unstable")
461 architecture = control.Find("Architecture");
462 if architecture not in Cnf.ValueList("Suite::%s::Architectures" % (default_suite)):
463 reject("Unknown architecture '%s'." % (architecture));
465 # Ensure the architecture of the .deb is one of the ones
466 # listed in the .changes.
467 if not changes["architecture"].has_key(architecture):
468 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, architecture));
470 # Sanity-check the Depends field
471 depends = control.Find("Depends");
473 reject("%s: Depends field is empty." % (file));
475 # Check the section & priority match those given in the .changes (non-fatal)
476 if control.Find("Section") and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
477 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
478 if control.Find("Priority") and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
479 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
481 files[file]["package"] = package;
482 files[file]["architecture"] = architecture;
483 files[file]["version"] = version;
484 files[file]["maintainer"] = control.Find("Maintainer", "");
485 if file.endswith(".udeb"):
486 files[file]["dbtype"] = "udeb";
487 elif file.endswith(".deb"):
488 files[file]["dbtype"] = "deb";
490 reject("%s is neither a .deb or a .udeb." % (file));
491 files[file]["source"] = control.Find("Source", files[file]["package"]);
492 # Get the source version
493 source = files[file]["source"];
495 if source.find("(") != -1:
496 m = utils.re_extract_src_version.match(source);
498 source_version = m.group(2);
499 if not source_version:
500 source_version = files[file]["version"];
501 files[file]["source package"] = source;
502 files[file]["source version"] = source_version;
504 # Ensure the filename matches the contents of the .deb
505 m = utils.re_isadeb.match(file);
507 file_package = m.group(1);
508 if files[file]["package"] != file_package:
509 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"]));
510 epochless_version = utils.re_no_epoch.sub('', control.Find("Version"));
512 file_version = m.group(2);
513 if epochless_version != file_version:
514 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
516 file_architecture = m.group(3);
517 if files[file]["architecture"] != file_architecture:
518 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"]));
520 # Check for existent source
521 source_version = files[file]["source version"];
522 source_package = files[file]["source package"];
523 if changes["architecture"].has_key("source"):
524 if source_version != changes["version"]:
525 reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
527 # Check in the SQL database
528 if not Katie.source_exists(source_package, source_version, changes["distribution"].keys()):
529 # Check in one of the other directories
530 source_epochless_version = utils.re_no_epoch.sub('', source_version);
531 dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
532 if os.path.exists(Cnf["Dir::Queue::Byhand"] + '/' + dsc_filename):
533 files[file]["byhand"] = 1;
534 elif os.path.exists(Cnf["Dir::Queue::New"] + '/' + dsc_filename):
535 files[file]["new"] = 1;
536 elif not os.path.exists(Cnf["Dir::Queue::Accepted"] + '/' + dsc_filename):
537 reject("no source found for %s %s (%s)." % (source_package, source_version, file));
538 # Check the version and for file overwrites
539 reject(Katie.check_binary_against_db(file),"");
541 check_deb_ar(file, control)
543 # Checks for a source package...
545 m = utils.re_issource.match(file);
548 files[file]["package"] = m.group(1);
549 files[file]["version"] = m.group(2);
550 files[file]["type"] = m.group(3);
552 # Ensure the source package name matches the Source filed in the .changes
553 if changes["source"] != files[file]["package"]:
554 reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
556 # Ensure the source version matches the version in the .changes file
557 if files[file]["type"] == "orig.tar.gz":
558 changes_version = changes["chopversion2"];
560 changes_version = changes["chopversion"];
561 if changes_version != files[file]["version"]:
562 reject("%s: should be %s according to changes file." % (file, changes_version));
564 # Ensure the .changes lists source in the Architecture field
565 if not changes["architecture"].has_key("source"):
566 reject("%s: changes file doesn't list `source' in Architecture field." % (file));
568 # Check the signature of a .dsc file
569 if files[file]["type"] == "dsc":
570 dsc["fingerprint"] = utils.check_signature(file, reject);
572 files[file]["architecture"] = "source";
574 # Not a binary or source package? Assume byhand...
576 files[file]["byhand"] = 1;
577 files[file]["type"] = "byhand";
579 # Per-suite file checks
580 files[file]["oldfiles"] = {};
581 for suite in changes["distribution"].keys():
583 if files[file].has_key("byhand"):
586 # Handle component mappings
587 for map in Cnf.ValueList("ComponentMappings"):
588 (source, dest) = map.split();
589 if files[file]["component"] == source:
590 files[file]["original component"] = source;
591 files[file]["component"] = dest;
593 # Ensure the component is valid for the target suite
594 if Cnf.has_key("Suite:%s::Components" % (suite)) and \
595 files[file]["component"] not in Cnf.ValueList("Suite::%s::Components" % (suite)):
596 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
599 # Validate the component
600 component = files[file]["component"];
601 component_id = db_access.get_component_id(component);
602 if component_id == -1:
603 reject("file '%s' has unknown component '%s'." % (file, component));
606 # See if the package is NEW
607 if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
608 files[file]["new"] = 1;
610 # Validate the priority
611 if files[file]["priority"].find('/') != -1:
612 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
614 # Determine the location
615 location = Cnf["Dir::Pool"];
616 location_id = db_access.get_location_id (location, component, archive);
617 if location_id == -1:
618 reject("[INTERNAL ERROR] couldn't determine location (Component: %s, Archive: %s)" % (component, archive));
619 files[file]["location id"] = location_id;
621 # Check the md5sum & size against existing files (if any)
622 files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
623 files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
625 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
627 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
628 files[file]["files id"] = files_id
630 # Check for packages that have moved from one component to another
631 q = Katie.projectB.query("""
632 SELECT c.name FROM binaries b, bin_associations ba, suite s, location l,
633 component c, architecture a, files f
634 WHERE b.package = '%s' AND s.suite_name = '%s'
635 AND (a.arch_string = '%s' OR a.arch_string = 'all')
636 AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
637 AND f.location = l.id AND l.component = c.id AND b.file = f.id"""
638 % (files[file]["package"], suite,
639 files[file]["architecture"]));
642 files[file]["othercomponents"] = ql[0][0];
644 # If the .changes file says it has source, it must have source.
645 if changes["architecture"].has_key("source"):
647 reject("no source found and Architecture line in changes mention source.");
649 if not has_binaries and Cnf.FindB("Dinstall::Reject::NoSourceOnly"):
650 reject("source only uploads are not supported.");
652 ###############################################################################
657 # Ensure there is source to check
658 if not changes["architecture"].has_key("source"):
663 for file in files.keys():
664 if files[file]["type"] == "dsc":
666 reject("can not process a .changes file with multiple .dsc's.");
671 # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
673 reject("source uploads must contain a dsc file");
676 # Parse the .dsc file
678 dsc.update(utils.parse_changes(dsc_filename, signing_rules=1));
679 except utils.cant_open_exc:
680 # if not -n copy_to_holding() will have done this for us...
681 if Options["No-Action"]:
682 reject("%s: can't read file." % (dsc_filename));
683 except utils.changes_parse_error_exc, line:
684 reject("%s: parse error, can't grok: %s." % (dsc_filename, line));
685 except utils.invalid_dsc_format_exc, line:
686 reject("%s: syntax error on line %s." % (dsc_filename, line));
687 # Build up the file list of files mentioned by the .dsc
689 dsc_files.update(utils.build_file_list(dsc, is_a_dsc=1));
690 except utils.no_files_exc:
691 reject("%s: no Files: field." % (dsc_filename));
693 except utils.changes_parse_error_exc, line:
694 reject("%s: parse error, can't grok: %s." % (dsc_filename, line));
697 # Enforce mandatory fields
698 for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
699 if not dsc.has_key(i):
700 reject("%s: missing mandatory field `%s'." % (dsc_filename, i));
703 # Validate the source and version fields
704 if not re_valid_pkg_name.match(dsc["source"]):
705 reject("%s: invalid source name '%s'." % (dsc_filename, dsc["source"]));
706 if not re_valid_version.match(dsc["version"]):
707 reject("%s: invalid version number '%s'." % (dsc_filename, dsc["version"]));
709 # Bumping the version number of the .dsc breaks extraction by stable's
710 # dpkg-source. So let's not do that...
711 if dsc["format"] != "1.0":
712 reject("%s: incompatible 'Format' version produced by a broken version of dpkg-dev 1.9.1{3,4}." % (dsc_filename));
714 # Validate the Maintainer field
716 utils.fix_maintainer (dsc["maintainer"]);
717 except utils.ParseMaintError, msg:
718 reject("%s: Maintainer field ('%s') failed to parse: %s" \
719 % (dsc_filename, dsc["maintainer"], msg));
721 # Validate the build-depends field(s)
722 for field_name in [ "build-depends", "build-depends-indep" ]:
723 field = dsc.get(field_name);
725 # Check for broken dpkg-dev lossage...
726 if field.startswith("ARRAY"):
727 reject("%s: invalid %s field produced by a broken version of dpkg-dev (1.10.11)" % (dsc_filename, field_name.title()));
729 # Have apt try to parse them...
731 apt_pkg.ParseSrcDepends(field);
733 reject("%s: invalid %s field (can not be parsed by apt)." % (dsc_filename, field_name.title()));
736 # Ensure the version number in the .dsc matches the version number in the .changes
737 epochless_dsc_version = utils.re_no_epoch.sub('', dsc["version"]);
738 changes_version = files[dsc_filename]["version"];
739 if epochless_dsc_version != files[dsc_filename]["version"]:
740 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
742 # Ensure there is a .tar.gz in the .dsc file
744 for f in dsc_files.keys():
745 m = utils.re_issource.match(f);
747 reject("%s: %s in Files field not recognised as source." % (dsc_filename, f));
749 if type == "orig.tar.gz" or type == "tar.gz":
752 reject("%s: no .tar.gz or .orig.tar.gz in 'Files' field." % (dsc_filename));
754 # Ensure source is newer than existing source in target suites
755 reject(Katie.check_source_against_db(dsc_filename),"");
757 (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(dsc_filename);
758 reject(reject_msg, "");
760 if not Options["No-Action"]:
761 copy_to_holding(is_in_incoming);
762 orig_tar_gz = os.path.basename(is_in_incoming);
763 files[orig_tar_gz] = {};
764 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
765 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
766 files[orig_tar_gz]["section"] = files[dsc_filename]["section"];
767 files[orig_tar_gz]["priority"] = files[dsc_filename]["priority"];
768 files[orig_tar_gz]["component"] = files[dsc_filename]["component"];
769 files[orig_tar_gz]["type"] = "orig.tar.gz";
774 ################################################################################
776 def get_changelog_versions(source_dir):
777 """Extracts a the source package and (optionally) grabs the
778 version history out of debian/changelog for the BTS."""
780 # Find the .dsc (again)
782 for file in files.keys():
783 if files[file]["type"] == "dsc":
786 # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
790 # Create a symlink mirror of the source files in our temporary directory
791 for f in files.keys():
792 m = utils.re_issource.match(f);
794 src = os.path.join(source_dir, f);
795 # If a file is missing for whatever reason, give up.
796 if not os.path.exists(src):
799 if type == "orig.tar.gz" and pkg.orig_tar_gz:
801 dest = os.path.join(os.getcwd(), f);
802 os.symlink(src, dest);
804 # If the orig.tar.gz is not a part of the upload, create a symlink to the
807 dest = os.path.join(os.getcwd(), os.path.basename(pkg.orig_tar_gz));
808 os.symlink(pkg.orig_tar_gz, dest);
811 cmd = "dpkg-source -sn -x %s" % (dsc_filename);
812 (result, output) = commands.getstatusoutput(cmd);
814 reject("'dpkg-source -x' failed for %s [return code: %s]." % (dsc_filename, result));
815 reject(utils.prefix_multi_line_string(output, " [dpkg-source output:] "), "");
818 if not Cnf.Find("Dir::Queue::BTSVersionTrack"):
821 # Get the upstream version
822 upstr_version = utils.re_no_epoch.sub('', dsc["version"]);
823 if re_strip_revision.search(upstr_version):
824 upstr_version = re_strip_revision.sub('', upstr_version);
826 # Ensure the changelog file exists
827 changelog_filename = "%s-%s/debian/changelog" % (dsc["source"], upstr_version);
828 if not os.path.exists(changelog_filename):
829 reject("%s: debian/changelog not found in extracted source." % (dsc_filename));
832 # Parse the changelog
833 dsc["bts changelog"] = "";
834 changelog_file = utils.open_file(changelog_filename);
835 for line in changelog_file.readlines():
836 m = re_changelog_versions.match(line);
838 dsc["bts changelog"] += line;
839 changelog_file.close();
841 # Check we found at least one revision in the changelog
842 if not dsc["bts changelog"]:
843 reject("%s: changelog format not recognised (empty version tree)." % (dsc_filename));
845 ########################################
849 # a) there's no source
850 # or b) reprocess is 2 - we will do this check next time when orig.tar.gz is in 'files'
851 # or c) the orig.tar.gz is MIA
852 if not changes["architecture"].has_key("source") or reprocess == 2 \
853 or pkg.orig_tar_gz == -1:
856 # Create a temporary directory to extract the source into
857 if Options["No-Action"]:
858 tmpdir = tempfile.mktemp();
860 # We're in queue/holding and can create a random directory.
861 tmpdir = "%s" % (os.getpid());
864 # Move into the temporary directory
868 # Get the changelog version history
869 get_changelog_versions(cwd);
871 # Move back and cleanup the temporary tree
874 shutil.rmtree(tmpdir);
876 if errno.errorcode[e.errno] != 'EACCES':
877 utils.fubar("%s: couldn't remove tmp dir for source tree." % (dsc["source"]));
879 reject("%s: source tree could not be cleanly removed." % (dsc["source"]));
880 # We probably have u-r or u-w directories so chmod everything
882 cmd = "chmod -R u+rwx %s" % (tmpdir)
883 result = os.system(cmd)
885 utils.fubar("'%s' failed with result %s." % (cmd, result));
886 shutil.rmtree(tmpdir);
888 utils.fubar("%s: couldn't remove tmp dir for source tree." % (dsc["source"]));
890 ################################################################################
892 # FIXME: should be a debian specific check called from a hook
894 def check_urgency ():
895 if changes["architecture"].has_key("source"):
896 if not changes.has_key("urgency"):
897 changes["urgency"] = Cnf["Urgency::Default"];
898 if changes["urgency"] not in Cnf.ValueList("Urgency::Valid"):
899 reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
900 changes["urgency"] = Cnf["Urgency::Default"];
901 changes["urgency"] = changes["urgency"].lower();
903 ################################################################################
905 def check_md5sums ():
906 for file in files.keys():
908 file_handle = utils.open_file(file);
909 except utils.cant_open_exc:
913 if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
914 reject("%s: md5sum check failed." % (file));
917 actual_size = os.stat(file)[stat.ST_SIZE];
918 size = int(files[file]["size"]);
919 if size != actual_size:
920 reject("%s: actual file size (%s) does not match size (%s) in .changes"
921 % (file, actual_size, size));
923 for file in dsc_files.keys():
925 file_handle = utils.open_file(file);
926 except utils.cant_open_exc:
930 if apt_pkg.md5sum(file_handle) != dsc_files[file]["md5sum"]:
931 reject("%s: md5sum check failed." % (file));
934 actual_size = os.stat(file)[stat.ST_SIZE];
935 size = int(dsc_files[file]["size"]);
936 if size != actual_size:
937 reject("%s: actual file size (%s) does not match size (%s) in .dsc"
938 % (file, actual_size, size));
940 ################################################################################
942 # Sanity check the time stamps of files inside debs.
943 # [Files in the near future cause ugly warnings and extreme time
944 # travel can cause errors on extraction]
946 def check_timestamps():
948 def __init__(self, future_cutoff, past_cutoff):
950 self.future_cutoff = future_cutoff;
951 self.past_cutoff = past_cutoff;
954 self.future_files = {};
955 self.ancient_files = {};
957 def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
958 if MTime > self.future_cutoff:
959 self.future_files[Name] = MTime;
960 if MTime < self.past_cutoff:
961 self.ancient_files[Name] = MTime;
964 future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"]);
965 past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"));
966 tar = Tar(future_cutoff, past_cutoff);
967 for filename in files.keys():
968 if files[filename]["type"] == "deb":
971 deb_file = utils.open_file(filename);
972 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz");
975 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz")
976 except SystemError, e:
977 # If we can't find a data.tar.gz, look for data.tar.bz2 instead.
978 if not re.match(r"Cannot f[ui]nd chunk data.tar.gz$", str(e)):
981 apt_inst.debExtract(deb_file,tar.callback,"data.tar.bz2")
984 future_files = tar.future_files.keys();
986 num_future_files = len(future_files);
987 future_file = future_files[0];
988 future_date = tar.future_files[future_file];
989 reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
990 % (filename, num_future_files, future_file,
991 time.ctime(future_date)));
993 ancient_files = tar.ancient_files.keys();
995 num_ancient_files = len(ancient_files);
996 ancient_file = ancient_files[0];
997 ancient_date = tar.ancient_files[ancient_file];
998 reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
999 % (filename, num_ancient_files, ancient_file,
1000 time.ctime(ancient_date)));
1002 reject("%s: deb contents timestamp check failed [%s: %s]" % (filename, sys.exc_type, sys.exc_value));
1004 ################################################################################
1005 ################################################################################
1007 # If any file of an upload has a recent mtime then chances are good
1008 # the file is still being uploaded.
1010 def upload_too_new():
1012 # Move back to the original directory to get accurate time stamps
1014 os.chdir(pkg.directory);
1015 file_list = pkg.files.keys();
1016 file_list.extend(pkg.dsc_files.keys());
1017 file_list.append(pkg.changes_file);
1018 for file in file_list:
1020 last_modified = time.time()-os.path.getmtime(file);
1021 if last_modified < int(Cnf["Dinstall::SkipTime"]):
1029 ################################################################################
1032 # changes["distribution"] may not exist in corner cases
1033 # (e.g. unreadable changes files)
1034 if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
1035 changes["distribution"] = {};
1037 (summary, short_summary) = Katie.build_summaries();
1039 # q-unapproved hax0ring
1041 "New": { "is": is_new, "process": acknowledge_new },
1042 "Byhand" : { "is": is_byhand, "process": do_byhand },
1043 "Unembargo" : { "is": is_unembargo, "process": queue_unembargo },
1044 "Embargo" : { "is": is_embargo, "process": queue_embargo },
1046 queues = [ "New", "Byhand" ]
1047 if Cnf.FindB("Dinstall::SecurityQueueHandling"):
1048 queues += [ "Unembargo", "Embargo" ]
1050 (prompt, answer) = ("", "XXX")
1051 if Options["No-Action"] or Options["Automatic"]:
1056 if reject_message.find("Rejected") != -1:
1057 if upload_too_new():
1058 print "SKIP (too new)\n" + reject_message,;
1059 prompt = "[S]kip, Quit ?";
1061 print "REJECT\n" + reject_message,;
1062 prompt = "[R]eject, Skip, Quit ?";
1063 if Options["Automatic"]:
1068 if queue_info[q]["is"]():
1072 print "%s for %s\n%s%s" % (
1073 queue.upper(), ", ".join(changes["distribution"].keys()),
1074 reject_message, summary),
1075 queuekey = queue[0].upper()
1076 if queuekey in "RQSA":
1078 prompt = "[D]ivert, Skip, Quit ?"
1080 prompt = "[%s]%s, Skip, Quit ?" % (queuekey, queue[1:].lower())
1081 if Options["Automatic"]:
1084 print "ACCEPT\n" + reject_message + summary,;
1085 prompt = "[A]ccept, Skip, Quit ?";
1086 if Options["Automatic"]:
1089 while prompt.find(answer) == -1:
1090 answer = utils.our_raw_input(prompt);
1091 m = katie.re_default_answer.match(prompt);
1093 answer = m.group(1);
1094 answer = answer[:1].upper();
1097 os.chdir (pkg.directory);
1098 Katie.do_reject(0, reject_message);
1100 accept(summary, short_summary);
1101 remove_from_unchecked()
1102 elif answer == queuekey:
1103 queue_info[queue]["process"](summary)
1104 remove_from_unchecked()
1108 def remove_from_unchecked():
1109 os.chdir (pkg.directory);
1110 for file in files.keys():
1112 os.unlink(pkg.changes_file);
1114 ################################################################################
1116 def accept (summary, short_summary):
1117 Katie.accept(summary, short_summary);
1118 Katie.check_override();
1120 ################################################################################
1122 def move_to_dir (dest, perms=0660, changesperms=0664):
1123 utils.move (pkg.changes_file, dest, perms=changesperms);
1124 file_keys = files.keys();
1125 for file in file_keys:
1126 utils.move (file, dest, perms=perms);
1128 ################################################################################
1130 def is_unembargo ():
1131 q = Katie.projectB.query(
1132 "SELECT package FROM disembargo WHERE package = '%s' AND version = '%s'" %
1133 (changes["source"], changes["version"]))
1138 if pkg.directory == Cnf["Dir::Queue::Disembargo"]:
1139 if changes["architecture"].has_key("source"):
1140 if Options["No-Action"]: return 1
1142 Katie.projectB.query(
1143 "INSERT INTO disembargo (package, version) VALUES ('%s', '%s')" %
1144 (changes["source"], changes["version"]))
1149 def queue_unembargo (summary):
1150 print "Moving to UNEMBARGOED holding area."
1151 Logger.log(["Moving to unembargoed", pkg.changes_file]);
1153 Katie.dump_vars(Cnf["Dir::Queue::Unembargoed"]);
1154 move_to_dir(Cnf["Dir::Queue::Unembargoed"])
1155 Katie.queue_build("unembargoed", Cnf["Dir::Queue::Unembargoed"])
1157 # Check for override disparities
1158 Katie.Subst["__SUMMARY__"] = summary;
1159 Katie.check_override();
1161 ################################################################################
1166 def queue_embargo (summary):
1167 print "Moving to EMBARGOED holding area."
1168 Logger.log(["Moving to embargoed", pkg.changes_file]);
1170 Katie.dump_vars(Cnf["Dir::Queue::Embargoed"]);
1171 move_to_dir(Cnf["Dir::Queue::Embargoed"])
1172 Katie.queue_build("embargoed", Cnf["Dir::Queue::Embargoed"])
1174 # Check for override disparities
1175 Katie.Subst["__SUMMARY__"] = summary;
1176 Katie.check_override();
1178 ################################################################################
1181 for file in files.keys():
1182 if files[file].has_key("byhand"):
1186 def do_byhand (summary):
1187 print "Moving to BYHAND holding area."
1188 Logger.log(["Moving to byhand", pkg.changes_file]);
1190 Katie.dump_vars(Cnf["Dir::Queue::Byhand"]);
1191 move_to_dir(Cnf["Dir::Queue::Byhand"])
1193 # Check for override disparities
1194 Katie.Subst["__SUMMARY__"] = summary;
1195 Katie.check_override();
1197 ################################################################################
1200 for file in files.keys():
1201 if files[file].has_key("new"):
1205 def acknowledge_new (summary):
1206 Subst = Katie.Subst;
1208 print "Moving to NEW holding area."
1209 Logger.log(["Moving to new", pkg.changes_file]);
1211 Katie.dump_vars(Cnf["Dir::Queue::New"]);
1213 file_keys = files.keys();
1215 move_to_dir(Cnf["Dir::Queue::New"])
1217 if not Options["No-Mail"]:
1218 print "Sending new ack.";
1219 Subst["__SUMMARY__"] = summary;
1220 new_ack_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/jennifer.new");
1221 utils.send_mail(new_ack_message);
1223 ################################################################################
1225 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1226 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1227 # Katie.check_dsc_against_db() can find the .orig.tar.gz but it will
1228 # not have processed it during it's checks of -2. If -1 has been
1229 # deleted or otherwise not checked by jennifer, the .orig.tar.gz will
1230 # not have been checked at all. To get round this, we force the
1231 # .orig.tar.gz into the .changes structure and reprocess the .changes
1234 def process_it (changes_file):
1235 global reprocess, reject_message;
1237 # Reset some globals
1240 # Some defaults in case we can't fully process the .changes file
1241 changes["maintainer2047"] = Cnf["Dinstall::MyEmailAddress"];
1242 changes["changedby2047"] = Cnf["Dinstall::MyEmailAddress"];
1243 reject_message = "";
1245 # Absolutize the filename to avoid the requirement of being in the
1246 # same directory as the .changes file.
1247 pkg.changes_file = os.path.abspath(changes_file);
1249 # Remember where we are so we can come back after cd-ing into the
1250 # holding directory.
1251 pkg.directory = os.getcwd();
1254 # If this is the Real Thing(tm), copy things into a private
1255 # holding directory first to avoid replacable file races.
1256 if not Options["No-Action"]:
1257 os.chdir(Cnf["Dir::Queue::Holding"]);
1258 copy_to_holding(pkg.changes_file);
1259 # Relativize the filename so we use the copy in holding
1260 # rather than the original...
1261 pkg.changes_file = os.path.basename(pkg.changes_file);
1262 changes["fingerprint"] = utils.check_signature(pkg.changes_file, reject);
1263 if changes["fingerprint"]:
1264 valid_changes_p = check_changes();
1266 valid_changes_p = 0;
1269 check_distributions();
1271 valid_dsc_p = check_dsc();
1277 Katie.update_subst(reject_message);
1283 traceback.print_exc(file=sys.stderr);
1286 # Restore previous WD
1287 os.chdir(pkg.directory);
1289 ###############################################################################
1292 global Cnf, Options, Logger;
1294 changes_files = init();
1296 # -n/--dry-run invalidates some other options which would involve things happening
1297 if Options["No-Action"]:
1298 Options["Automatic"] = "";
1300 # Ensure all the arguments we were given are .changes files
1301 for file in changes_files:
1302 if not file.endswith(".changes"):
1303 utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
1304 changes_files.remove(file);
1306 if changes_files == []:
1307 utils.fubar("Need at least one .changes file as an argument.");
1309 # Check that we aren't going to clash with the daily cron job
1311 if not Options["No-Action"] and os.path.exists("%s/daily.lock" % (Cnf["Dir::Lock"])) and not Options["No-Lock"]:
1312 utils.fubar("Archive maintenance in progress. Try again later.");
1314 # Obtain lock if not in no-action mode and initialize the log
1316 if not Options["No-Action"]:
1317 lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1319 fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB);
1321 if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
1322 utils.fubar("Couldn't obtain lock; assuming another jennifer is already running.");
1325 Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1327 # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1328 bcc = "X-Katie: %s" % (jennifer_version);
1329 if Cnf.has_key("Dinstall::Bcc"):
1330 Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1332 Katie.Subst["__BCC__"] = bcc;
1335 # Sort the .changes files so that we process sourceful ones first
1336 changes_files.sort(utils.changes_compare);
1338 # Process the changes files
1339 for changes_file in changes_files:
1340 print "\n" + changes_file;
1342 process_it (changes_file);
1344 if not Options["No-Action"]:
1347 accept_count = Katie.accept_count;
1348 accept_bytes = Katie.accept_bytes;
1351 if accept_count > 1:
1353 print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)));
1354 Logger.log(["total",accept_count,accept_bytes]);
1356 if not Options["No-Action"]:
1359 ################################################################################
1361 if __name__ == '__main__':