]> git.decadent.org.uk Git - dak.git/blob - jennifer
* katie.py (source_exists): expand the list of distributionsthe source may exist...
[dak.git] / jennifer
1 #!/usr/bin/env python
2
3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001, 2002, 2003  James Troup <james@nocrew.org>
5 # $Id: jennifer,v 1.35 2003-07-29 14:00:39 ajt Exp $
6
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.
11
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.
16
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
20
21 # Originally based on dinstall by Guy Maor <maor@debian.org>
22
23 ################################################################################
24
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
27 # repetitive music.
28 #         -- Unknown
29
30 ################################################################################
31
32 import errno, fcntl, gzip, os, re, shutil, stat, sys, time, traceback;
33 import apt_inst, apt_pkg;
34 import db_access, katie, logging, utils;
35
36 from types import *;
37
38 ################################################################################
39
40 re_bad_diff = re.compile("^[\-\+][\-\+][\-\+] /dev/null");
41 re_is_changes = re.compile(r"(.+?)_(.+?)_(.+?)\.changes$");
42 re_valid_version = re.compile(r"^([0-9]+:)?[0-9A-Za-z\.\-\+:]+$");
43 re_valid_pkg_name = re.compile(r"^[\dA-Za-z][\dA-Za-z\+\-\.]+$");
44
45 ################################################################################
46
47 # Globals
48 jennifer_version = "$Revision: 1.35 $";
49
50 Cnf = None;
51 Options = None;
52 Logger = None;
53 Katie = None;
54
55 reprocess = 0;
56 in_holding = {};
57
58 # Aliases to the real vars in the Katie class; hysterical raisins.
59 reject_message = "";
60 changes = {};
61 dsc = {};
62 dsc_files = {};
63 files = {};
64 pkg = {};
65
66 ###############################################################################
67
68 def init():
69     global Cnf, Options, Katie, changes, dsc, dsc_files, files, pkg;
70
71     apt_pkg.init();
72
73     Cnf = apt_pkg.newConfiguration();
74     apt_pkg.ReadConfigFileISC(Cnf,utils.which_conf_file());
75
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")];
82
83     for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
84               "override-distribution", "version"]:
85         Cnf["Dinstall::Options::%s" % (i)] = "";
86
87     changes_files = apt_pkg.ParseCommandLine(Cnf,Arguments,sys.argv);
88     Options = Cnf.SubTree("Dinstall::Options")
89
90     if Options["Help"]:
91         usage();
92     elif Options["Version"]:
93         print "jennifer %s" % (jennifer_version);
94         sys.exit(0);
95
96     Katie = katie.Katie(Cnf);
97
98     changes = Katie.pkg.changes;
99     dsc = Katie.pkg.dsc;
100     dsc_files = Katie.pkg.dsc_files;
101     files = Katie.pkg.files;
102     pkg = Katie.pkg;
103
104     return changes_files;
105
106 ################################################################################
107
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"""
116     sys.exit(exit_code)
117
118 ################################################################################
119
120 def reject (str, prefix="Rejected: "):
121     global reject_message;
122     if str:
123         reject_message += prefix + str + "\n";
124
125 ################################################################################
126
127 def copy_to_holding(filename):
128     global in_holding;
129
130     base_filename = os.path.basename(filename);
131
132     dest = Cnf["Dir::Queue::Holding"] + '/' + base_filename;
133     try:
134         fd = os.open(dest, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0640);
135         os.close(fd);
136     except OSError, e:
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));
141             return;
142         raise;
143
144     try:
145         shutil.copy(filename, dest);
146     except IOError, e:
147         # In either case (ENOENT or EACCES) we want to remove the
148         # O_CREAT | O_EXCLed ghost file, so add the file to the list
149         # of 'in holding' even if it's not the real file.
150         if errno.errorcode[e.errno] == 'ENOENT':
151             reject("can not copy %s to holding area: file not found." % (base_filename));
152             os.unlink(dest);
153             return;
154         elif errno.errorcode[e.errno] == 'EACCES':
155             reject("can not copy %s to holding area: read permission denied." % (base_filename));
156             os.unlink(dest);
157             return;
158         raise;
159
160     in_holding[base_filename] = "";
161
162 ################################################################################
163
164 def clean_holding():
165     global in_holding;
166
167     cwd = os.getcwd();
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));
173             else:
174                 os.unlink(file);
175     in_holding = {};
176     os.chdir(cwd);
177
178 ################################################################################
179
180 def check_changes():
181     filename = pkg.changes_file;
182
183     # Default in case we bail out
184     changes["maintainer822"] = Cnf["Dinstall::MyEmailAddress"];
185     changes["changedby822"] = Cnf["Dinstall::MyEmailAddress"];
186     changes["architecture"] = {};
187
188     # Parse the .changes field into a dictionary
189     try:
190         changes.update(utils.parse_changes(filename));
191     except utils.cant_open_exc:
192         reject("can't read changes file '%s'." % (filename));
193         return 0;
194     except utils.changes_parse_error_exc, line:
195         reject("error parsing changes file '%s', can't grok: %s." % (filename, line));
196         return 0;
197
198     # Parse the Files field from the .changes into another dictionary
199     try:
200         files.update(utils.build_file_list(changes));
201     except utils.changes_parse_error_exc, line:
202         reject("error parsing changes file '%s', can't grok: %s." % (filename, line));
203     except utils.nk_format_exc, format:
204         reject("unknown format '%s' of changes file '%s'." % (format, filename));
205         return 0;
206
207     # Check for mandatory fields
208     for i in ("source", "binary", "architecture", "version", "distribution", "maintainer", "files"):
209         if not changes.has_key(i):
210             reject("Missing field `%s' in changes file." % (i));
211             return 0    # Avoid <undef> errors during later tests
212
213     # Split multi-value fields into a lower-level dictionary
214     for i in ("architecture", "distribution", "binary", "closes"):
215         o = changes.get(i, "")
216         if o != "":
217             del changes[i]
218         changes[i] = {}
219         for j in o.split():
220             changes[i][j] = 1
221
222     # Fix the Maintainer: field to be RFC822 compatible
223     (changes["maintainer822"], changes["maintainername"], changes["maintaineremail"]) = utils.fix_maintainer (changes["maintainer"])
224
225     # Fix the Changed-By: field to be RFC822 compatible; if it exists.
226     (changes["changedby822"], changes["changedbyname"], changes["changedbyemail"]) = utils.fix_maintainer(changes.get("changed-by",""));
227
228     # Ensure all the values in Closes: are numbers
229     if changes.has_key("closes"):
230         for i in changes["closes"].keys():
231             if katie.re_isanum.match (i) == None:
232                 reject("`%s' from Closes field isn't a number." % (i));
233
234
235     # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
236     changes["chopversion"] = utils.re_no_epoch.sub('', changes["version"])
237     changes["chopversion2"] = utils.re_no_revision.sub('', changes["chopversion"])
238
239     # Check there isn't already a changes file of the same name in one
240     # of the queue directories.
241     base_filename = os.path.basename(filename);
242     for dir in [ "Accepted", "Byhand", "Done", "New" ]:
243         if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+base_filename):
244             reject("a changes file with the same name already exists in the %s directory." % (dir));
245
246     return 1;
247
248 ################################################################################
249
250 def check_distributions():
251     "Check and map the Distribution field of a .changes file."
252
253     # Handle suite mappings
254     for map in Cnf.ValueList("SuiteMappings"):
255         args = map.split();
256         type = args[0];
257         if type == "map" or type == "silent-map":
258             (source, dest) = args[1:3];
259             if changes["distribution"].has_key(source):
260                 del changes["distribution"][source]
261                 changes["distribution"][dest] = 1;
262                 if type != "silent-map":
263                     reject("Mapping %s to %s." % (source, dest),"");
264         elif type == "map-unreleased":
265             (source, dest) = args[1:3];
266             if changes["distribution"].has_key(source):
267                 for arch in changes["architecture"].keys():
268                     if arch not in Cnf.ValueList("Suite::%s::Architectures" % (source)):
269                         reject("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch),"");
270                         del changes["distribution"][source];
271                         changes["distribution"][dest] = 1;
272                         break;
273         elif type == "ignore":
274             suite = args[1];
275             if changes["distribution"].has_key(suite):
276                 del changes["distribution"][suite];
277                 reject("Ignoring %s as a target suite." % (suite), "Warning: ");
278
279     # Ensure there is (still) a target distribution
280     if changes["distribution"].keys() == []:
281         reject("no valid distribution.");
282
283     # Ensure target distributions exist
284     for suite in changes["distribution"].keys():
285         if not Cnf.has_key("Suite::%s" % (suite)):
286             reject("Unknown distribution `%s'." % (suite));
287
288 ################################################################################
289
290 def check_files():
291     global reprocess
292
293     archive = utils.where_am_i();
294     file_keys = files.keys();
295
296     # if reprocess is 2 we've already done this and we're checking
297     # things again for the new .orig.tar.gz.
298     # [Yes, I'm fully aware of how disgusting this is]
299     if not Options["No-Action"] and reprocess < 2:
300         cwd = os.getcwd();
301         os.chdir(pkg.directory);
302         for file in file_keys:
303             copy_to_holding(file);
304         os.chdir(cwd);
305
306     reprocess = 0;
307
308     for file in file_keys:
309         # Ensure the file does not already exist in one of the accepted directories
310         for dir in [ "Accepted", "Byhand", "New" ]:
311             if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+file):
312                 reject("%s file already exists in the %s directory." % (file, dir));
313         if not utils.re_taint_free.match(file):
314             reject("!!WARNING!! tainted filename: '%s'." % (file));
315         # Check the file is readable
316         if os.access(file,os.R_OK) == 0:
317             # When running in -n, copy_to_holding() won't have
318             # generated the reject_message, so we need to.
319             if Options["No-Action"]:
320                 if os.path.exists(file):
321                     reject("Can't read `%s'. [permission denied]" % (file));
322                 else:
323                     reject("Can't read `%s'. [file not found]" % (file));
324             files[file]["type"] = "unreadable";
325             continue;
326         # If it's byhand skip remaining checks
327         if files[file]["section"] == "byhand":
328             files[file]["byhand"] = 1;
329             files[file]["type"] = "byhand";
330         # Checks for a binary package...
331         elif utils.re_isadeb.match(file) != None:
332             files[file]["type"] = "deb";
333
334             # Extract package control information
335             deb_file = utils.open_file(file);
336             try:
337                 control = apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file));
338             except:
339                 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
340                 deb_file.close();
341                 # Can't continue, none of the checks on control would work.
342                 continue;
343             deb_file.close();
344
345             # Check for mandatory fields
346             for field in [ "Package", "Architecture", "Version" ]:
347                 if control.Find(field) == None:
348                     reject("%s: No %s field in control." % (file, field));
349                     # Can't continue
350                     continue;
351
352             # Ensure the package name matches the one give in the .changes
353             if not changes["binary"].has_key(control.Find("Package", "")):
354                 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
355
356             # Validate the package field
357             package = control.Find("Package");
358             if not re_valid_pkg_name.match(package):
359                 reject("%s: invalid package name '%s'." % (file, package));
360
361             # Validate the version field
362             version = control.Find("Version");
363             if not re_valid_version.match(version):
364                 reject("%s: invalid version number '%s'." % (file, version));
365
366             # Ensure the architecture of the .deb is one we know about.
367             default_suite = Cnf.get("Dinstall::DefaultSuite", "Unstable")
368             architecture = control.Find("Architecture");
369             if architecture not in Cnf.ValueList("Suite::%s::Architectures" % (default_suite)):
370                 reject("Unknown architecture '%s'." % (architecture));
371
372             # Ensure the architecture of the .deb is one of the ones
373             # listed in the .changes.
374             if not changes["architecture"].has_key(architecture):
375                 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, architecture));
376
377             # Sanity-check the Depends field
378             depends = control.Find("Depends");
379             if depends == '':
380                 reject("%s: Depends field is empty." % (file));
381
382             # Check the section & priority match those given in the .changes (non-fatal)
383             if control.Find("Section") != None and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
384                 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
385             if control.Find("Priority") != None and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
386                 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
387
388             files[file]["package"] = package;
389             files[file]["architecture"] = architecture;
390             files[file]["version"] = version;
391             files[file]["maintainer"] = control.Find("Maintainer", "");
392             if file.endswith(".udeb"):
393                 files[file]["dbtype"] = "udeb";
394             elif file.endswith(".deb"):
395                 files[file]["dbtype"] = "deb";
396             else:
397                 reject("%s is neither a .deb or a .udeb." % (file));
398             files[file]["source"] = control.Find("Source", files[file]["package"]);
399             # Get the source version
400             source = files[file]["source"];
401             source_version = ""
402             if source.find("(") != -1:
403                 m = utils.re_extract_src_version.match(source)
404                 source = m.group(1)
405                 source_version = m.group(2)
406             if not source_version:
407                 source_version = files[file]["version"];
408             files[file]["source package"] = source;
409             files[file]["source version"] = source_version;
410
411             # Ensure the filename matches the contents of the .deb
412             m = utils.re_isadeb.match(file);
413             #  package name
414             file_package = m.group(1);
415             if files[file]["package"] != file_package:
416                 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"]));
417             epochless_version = utils.re_no_epoch.sub('', control.Find("Version"));
418             #  version
419             file_version = m.group(2);
420             if epochless_version != file_version:
421                 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
422             #  architecture
423             file_architecture = m.group(3);
424             if files[file]["architecture"] != file_architecture:
425                 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"]));
426
427             # Check for existent source
428             source_version = files[file]["source version"];
429             source_package = files[file]["source package"];
430             if changes["architecture"].has_key("source"):
431                 if source_version != changes["version"]:
432                     reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
433             else:
434                 # Check in the SQL database
435                 if not Katie.source_exists(source_package, source_version, changes["distribution"].keys()):
436                     # Check in one of the other directories
437                     source_epochless_version = utils.re_no_epoch.sub('', source_version);
438                     dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
439                     if os.path.exists(Cnf["Dir::Queue::Byhand"] + '/' + dsc_filename):
440                         files[file]["byhand"] = 1;
441                     elif os.path.exists(Cnf["Dir::Queue::New"] + '/' + dsc_filename):
442                         files[file]["new"] = 1;
443                     elif not os.path.exists(Cnf["Dir::Queue::Accepted"] + '/' + dsc_filename):
444                         reject("no source found for %s %s (%s)." % (source_package, source_version, file));
445             # Check the version and for file overwrites
446             reject(Katie.check_binary_against_db(file),"");
447
448         # Checks for a source package...
449         else:
450             m = utils.re_issource.match(file);
451             if m != None:
452                 files[file]["package"] = m.group(1);
453                 files[file]["version"] = m.group(2);
454                 files[file]["type"] = m.group(3);
455
456                 # Ensure the source package name matches the Source filed in the .changes
457                 if changes["source"] != files[file]["package"]:
458                     reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
459
460                 # Ensure the source version matches the version in the .changes file
461                 if files[file]["type"] == "orig.tar.gz":
462                     changes_version = changes["chopversion2"];
463                 else:
464                     changes_version = changes["chopversion"];
465                 if changes_version != files[file]["version"]:
466                     reject("%s: should be %s according to changes file." % (file, changes_version));
467
468                 # Ensure the .changes lists source in the Architecture field
469                 if not changes["architecture"].has_key("source"):
470                     reject("%s: changes file doesn't list `source' in Architecture field." % (file));
471
472                 # Check the signature of a .dsc file
473                 if files[file]["type"] == "dsc":
474                     dsc["fingerprint"] = utils.check_signature(file, reject);
475
476                 files[file]["architecture"] = "source";
477
478             # Not a binary or source package?  Assume byhand...
479             else:
480                 files[file]["byhand"] = 1;
481                 files[file]["type"] = "byhand";
482
483         # Per-suite file checks
484         files[file]["oldfiles"] = {};
485         for suite in changes["distribution"].keys():
486             # Skip byhand
487             if files[file].has_key("byhand"):
488                 continue;
489
490             # Handle component mappings
491             for map in Cnf.ValueList("ComponentMappings"):
492                 (source, dest) = map.split();
493                 if files[file]["component"] == source:
494                     files[file]["original component"] = source;
495                     files[file]["component"] = dest;
496             # Ensure the component is valid for the target suite
497             if Cnf.has_key("Suite:%s::Components" % (suite)) and \
498                files[file]["component"] not in Cnf.ValueList("Suite::%s::Components" % (suite)):
499                 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
500                 continue
501
502             # See if the package is NEW
503             if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
504                 files[file]["new"] = 1;
505
506             # Validate the component
507             component = files[file]["component"];
508             component_id = db_access.get_component_id(component);
509             if component_id == -1:
510                 reject("file '%s' has unknown component '%s'." % (file, component));
511                 continue;
512
513             # Validate the priority
514             if files[file]["priority"].find('/') != -1:
515                 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
516
517             # Determine the location
518             location = Cnf["Dir::Pool"];
519             location_id = db_access.get_location_id (location, component, archive);
520             if location_id == -1:
521                 reject("[INTERNAL ERROR] couldn't determine location (Component: %s, Archive: %s)" % (component, archive));
522             files[file]["location id"] = location_id;
523
524             # Check the md5sum & size against existing files (if any)
525             files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
526             files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
527             if files_id == -1:
528                 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
529             elif files_id == -2:
530                 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
531             files[file]["files id"] = files_id
532
533             # Check for packages that have moved from one component to another
534             q = Katie.projectB.query("""
535 SELECT c.name FROM binaries b, bin_associations ba, suite s, location l,
536                    component c, architecture a, files f
537  WHERE b.package = '%s' AND s.suite_name = '%s'
538    AND (a.arch_string = '%s' OR a.arch_string = 'all')
539    AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
540    AND f.location = l.id AND l.component = c.id AND b.file = f.id"""
541                                % (files[file]["package"], suite,
542                                   files[file]["architecture"]));
543             ql = q.getresult();
544             if ql:
545                 files[file]["othercomponents"] = ql[0][0];
546
547     # If the .changes file says it has source, it must have source.
548     if changes["architecture"].has_key("source"):
549         has_source = 0;
550         for file in file_keys:
551             if files[file]["type"] == "dsc":
552                 has_source = 1;
553         if not has_source:
554             reject("no source found and Architecture line in changes mention source.");
555
556 ###############################################################################
557
558 def check_dsc ():
559     global reprocess;
560
561     for file in files.keys():
562         # The .orig.tar.gz can disappear out from under us is it's a
563         # duplicate of one in the archive.
564         if not files.has_key(file):
565             continue;
566         if files[file]["type"] == "dsc":
567             # Parse the .dsc file
568             try:
569                 dsc.update(utils.parse_changes(file, dsc_whitespace_rules=1));
570             except utils.cant_open_exc:
571                 # if not -n copy_to_holding() will have done this for us...
572                 if Options["No-Action"]:
573                     reject("can't read .dsc file '%s'." % (file));
574             except utils.changes_parse_error_exc, line:
575                 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
576             except utils.invalid_dsc_format_exc, line:
577                 reject("syntax error in .dsc file '%s', line %s." % (file, line));
578             # Build up the file list of files mentioned by the .dsc
579             try:
580                 dsc_files.update(utils.build_file_list(dsc, is_a_dsc=1));
581             except utils.no_files_exc:
582                 reject("no Files: field in .dsc file.");
583                 continue;
584             except utils.changes_parse_error_exc, line:
585                 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
586                 continue;
587
588             # Enforce mandatory fields
589             for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
590                 if not dsc.has_key(i):
591                     reject("Missing field `%s' in dsc file." % (i));
592
593             # Validate the source and version fields
594             if dsc.has_key("source") and not re_valid_pkg_name.match(dsc["source"]):
595                 reject("%s: invalid source name '%s'." % (file, dsc["source"]));
596             if dsc.has_key("version") and not re_valid_version.match(dsc["version"]):
597                 reject("%s: invalid version number '%s'." % (file, dsc["version"]));
598
599             # The dpkg maintainer from hell strikes again! Bumping the
600             # version number of the .dsc breaks extraction by stable's
601             # dpkg-source.
602             if dsc["format"] != "1.0":
603                 reject("""[dpkg-sucks] source package was produced by a broken version
604           of dpkg-dev 1.9.1{3,4}; please rebuild with >= 1.9.15 version
605           installed.""");
606
607             # Ensure the version number in the .dsc matches the version number in the .changes
608             epochless_dsc_version = utils.re_no_epoch.sub('', dsc.get("version"));
609             changes_version = files[file]["version"];
610             if epochless_dsc_version != files[file]["version"]:
611                 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
612
613             # Ensure there is a .tar.gz in the .dsc file
614             has_tar = 0;
615             for f in dsc_files.keys():
616                 m = utils.re_issource.match(f);
617                 if not m:
618                     reject("%s mentioned in the Files field of %s not recognised as source." % (f, file));
619                 type = m.group(3);
620                 if type == "orig.tar.gz" or type == "tar.gz":
621                     has_tar = 1;
622             if not has_tar:
623                 reject("no .tar.gz or .orig.tar.gz listed in the Files field of %s." % (file));
624
625             # Ensure source is newer than existing source in target suites
626             reject(Katie.check_source_against_db(file),"");
627
628             (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
629             reject(reject_msg, "");
630             if is_in_incoming:
631                 if not Options["No-Action"]:
632                     copy_to_holding(is_in_incoming);
633                 orig_tar_gz = os.path.basename(is_in_incoming);
634                 files[orig_tar_gz] = {};
635                 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
636                 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
637                 files[orig_tar_gz]["section"] = files[file]["section"];
638                 files[orig_tar_gz]["priority"] = files[file]["priority"];
639                 files[orig_tar_gz]["component"] = files[file]["component"];
640                 files[orig_tar_gz]["type"] = "orig.tar.gz";
641                 reprocess = 2;
642
643 ################################################################################
644
645 # Some cunning stunt broke dpkg-source in dpkg 1.8{,.1}; detect the
646 # resulting bad source packages and reject them.
647
648 # Even more amusingly the fix in 1.8.1.1 didn't actually fix the
649 # problem just changed the symptoms.
650
651 def check_diff ():
652     for filename in files.keys():
653         if files[filename]["type"] == "diff.gz":
654             file = gzip.GzipFile(filename, 'r');
655             for line in file.readlines():
656                 if re_bad_diff.search(line):
657                     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.");
658                     break;
659
660 ################################################################################
661
662 # FIXME: should be a debian specific check called from a hook
663
664 def check_urgency ():
665     if changes["architecture"].has_key("source"):
666         if not changes.has_key("urgency"):
667             changes["urgency"] = Cnf["Urgency::Default"];
668         if changes["urgency"] not in Cnf.ValueList("Urgency::Valid"):
669             reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
670             changes["urgency"] = Cnf["Urgency::Default"];
671         changes["urgency"] = changes["urgency"].lower();
672
673 ################################################################################
674
675 def check_md5sums ():
676     for file in files.keys():
677         try:
678             file_handle = utils.open_file(file);
679         except utils.cant_open_exc:
680             continue;
681
682         # Check md5sum
683         if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
684             reject("%s: md5sum check failed." % (file));
685         file_handle.close();
686         # Check size
687         actual_size = os.stat(file)[stat.ST_SIZE];
688         size = int(files[file]["size"]);
689         if size != actual_size:
690             reject("%s: actual file size (%s) does not match size (%s) in .changes"
691                    % (file, actual_size, size));
692
693     for file in dsc_files.keys():
694         try:
695             file_handle = utils.open_file(file);
696         except utils.cant_open_exc:
697             continue;
698
699         # Check md5sum
700         if apt_pkg.md5sum(file_handle) != dsc_files[file]["md5sum"]:
701             reject("%s: md5sum check failed." % (file));
702         file_handle.close();
703         # Check size
704         actual_size = os.stat(file)[stat.ST_SIZE];
705         size = int(dsc_files[file]["size"]);
706         if size != actual_size:
707             reject("%s: actual file size (%s) does not match size (%s) in .dsc"
708                    % (file, actual_size, size));
709
710 ################################################################################
711
712 # Sanity check the time stamps of files inside debs.
713 # [Files in the near future cause ugly warnings and extreme time
714 #  travel can cause errors on extraction]
715
716 def check_timestamps():
717     class Tar:
718         def __init__(self, future_cutoff, past_cutoff):
719             self.reset();
720             self.future_cutoff = future_cutoff;
721             self.past_cutoff = past_cutoff;
722
723         def reset(self):
724             self.future_files = {};
725             self.ancient_files = {};
726
727         def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
728             if MTime > self.future_cutoff:
729                 self.future_files[Name] = MTime;
730             if MTime < self.past_cutoff:
731                 self.ancient_files[Name] = MTime;
732     ####
733
734     future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"]);
735     past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"));
736     tar = Tar(future_cutoff, past_cutoff);
737     for filename in files.keys():
738         if files[filename]["type"] == "deb":
739             tar.reset();
740             try:
741                 deb_file = utils.open_file(filename);
742                 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz");
743                 deb_file.seek(0);
744                 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz");
745                 deb_file.close();
746                 #
747                 future_files = tar.future_files.keys();
748                 if future_files:
749                     num_future_files = len(future_files);
750                     future_file = future_files[0];
751                     future_date = tar.future_files[future_file];
752                     reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
753                            % (filename, num_future_files, future_file,
754                               time.ctime(future_date)));
755                 #
756                 ancient_files = tar.ancient_files.keys();
757                 if ancient_files:
758                     num_ancient_files = len(ancient_files);
759                     ancient_file = ancient_files[0];
760                     ancient_date = tar.ancient_files[ancient_file];
761                     reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
762                            % (filename, num_ancient_files, ancient_file,
763                               time.ctime(ancient_date)));
764             except:
765                 reject("%s: deb contents timestamp check failed [%s: %s]" % (filename, sys.exc_type, sys.exc_value));
766
767 ################################################################################
768 ################################################################################
769
770 # If any file of an upload has a recent mtime then chances are good
771 # the file is still being uploaded.
772
773 def upload_too_new():
774     too_new = 0;
775     # Move back to the original directory to get accurate time stamps
776     cwd = os.getcwd();
777     os.chdir(pkg.directory);
778     file_list = pkg.files.keys();
779     file_list.extend(pkg.dsc_files.keys());
780     file_list.append(pkg.changes_file);
781     for file in file_list:
782         try:
783             last_modified = time.time()-os.path.getmtime(file);
784             if last_modified < int(Cnf["Dinstall::SkipTime"]):
785                 too_new = 1;
786                 break;
787         except:
788             pass;
789     os.chdir(cwd);
790     return too_new;
791
792 ################################################################################
793
794 def action ():
795     # changes["distribution"] may not exist in corner cases
796     # (e.g. unreadable changes files)
797     if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
798         changes["distribution"] = {};
799
800     (summary, short_summary) = Katie.build_summaries();
801
802     byhand = new = "";
803     for file in files.keys():
804         if files[file].has_key("byhand"):
805             byhand = 1
806         elif files[file].has_key("new"):
807             new = 1
808
809     (prompt, answer) = ("", "XXX")
810     if Options["No-Action"] or Options["Automatic"]:
811         answer = 'S'
812
813     if reject_message.find("Rejected") != -1:
814         if upload_too_new():
815             print "SKIP (too new)\n" + reject_message,;
816             prompt = "[S]kip, Quit ?";
817         else:
818             print "REJECT\n" + reject_message,;
819             prompt = "[R]eject, Skip, Quit ?";
820             if Options["Automatic"]:
821                 answer = 'R';
822     elif new:
823         print "NEW to %s\n%s%s" % (", ".join(changes["distribution"].keys()), reject_message, summary),;
824         prompt = "[N]ew, Skip, Quit ?";
825         if Options["Automatic"]:
826             answer = 'N';
827     elif byhand:
828         print "BYHAND\n" + reject_message + summary,;
829         prompt = "[B]yhand, Skip, Quit ?";
830         if Options["Automatic"]:
831             answer = 'B';
832     else:
833         print "ACCEPT\n" + reject_message + summary,;
834         prompt = "[A]ccept, Skip, Quit ?";
835         if Options["Automatic"]:
836             answer = 'A';
837
838     while prompt.find(answer) == -1:
839         answer = utils.our_raw_input(prompt);
840         m = katie.re_default_answer.match(prompt);
841         if answer == "":
842             answer = m.group(1);
843         answer = answer[:1].upper();
844
845     if answer == 'R':
846         os.chdir (pkg.directory);
847         Katie.do_reject(0, reject_message);
848     elif answer == 'A':
849         accept(summary, short_summary);
850     elif answer == 'B':
851         do_byhand(summary);
852     elif answer == 'N':
853         acknowledge_new (summary);
854     elif answer == 'Q':
855         sys.exit(0)
856
857 ################################################################################
858
859 def accept (summary, short_summary):
860     Katie.accept(summary, short_summary);
861     Katie.check_override();
862
863     # Finally, remove the originals from the unchecked directory
864     os.chdir (pkg.directory);
865     for file in files.keys():
866         os.unlink(file);
867     os.unlink(pkg.changes_file);
868
869 ################################################################################
870
871 def do_byhand (summary):
872     print "Moving to BYHAND holding area."
873     Logger.log(["Moving to byhand", pkg.changes_file]);
874
875     Katie.dump_vars(Cnf["Dir::Queue::Byhand"]);
876
877     file_keys = files.keys();
878
879     # Move all the files into the byhand directory
880     utils.move (pkg.changes_file, Cnf["Dir::Queue::Byhand"]);
881     for file in file_keys:
882         utils.move (file, Cnf["Dir::Queue::Byhand"], perms=0660);
883
884     # Check for override disparities
885     Katie.Subst["__SUMMARY__"] = summary;
886     Katie.check_override();
887
888     # Finally remove the originals.
889     os.chdir (pkg.directory);
890     for file in file_keys:
891         os.unlink(file);
892     os.unlink(pkg.changes_file);
893
894 ################################################################################
895
896 def acknowledge_new (summary):
897     Subst = Katie.Subst;
898
899     print "Moving to NEW holding area."
900     Logger.log(["Moving to new", pkg.changes_file]);
901
902     Katie.dump_vars(Cnf["Dir::Queue::New"]);
903
904     file_keys = files.keys();
905
906     # Move all the files into the 'new' directory
907     utils.move (pkg.changes_file, Cnf["Dir::Queue::New"]);
908     for file in file_keys:
909         utils.move (file, Cnf["Dir::Queue::New"], perms=0660);
910
911     if not Options["No-Mail"]:
912         print "Sending new ack.";
913         Subst["__SUMMARY__"] = summary;
914         new_ack_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/jennifer.new");
915         utils.send_mail(new_ack_message);
916
917     # Finally remove the originals.
918     os.chdir (pkg.directory);
919     for file in file_keys:
920         os.unlink(file);
921     os.unlink(pkg.changes_file);
922
923 ################################################################################
924
925 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
926 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
927 # Katie.check_dsc_against_db() can find the .orig.tar.gz but it will
928 # not have processed it during it's checks of -2.  If -1 has been
929 # deleted or otherwise not checked by jennifer, the .orig.tar.gz will
930 # not have been checked at all.  To get round this, we force the
931 # .orig.tar.gz into the .changes structure and reprocess the .changes
932 # file.
933
934 def process_it (changes_file):
935     global reprocess, reject_message;
936
937     # Reset some globals
938     reprocess = 1;
939     Katie.init_vars();
940     reject_message = "";
941
942     # Absolutize the filename to avoid the requirement of being in the
943     # same directory as the .changes file.
944     pkg.changes_file = os.path.abspath(changes_file);
945
946     # Remember where we are so we can come back after cd-ing into the
947     # holding directory.
948     pkg.directory = os.getcwd();
949
950     try:
951         # If this is the Real Thing(tm), copy things into a private
952         # holding directory first to avoid replacable file races.
953         if not Options["No-Action"]:
954             os.chdir(Cnf["Dir::Queue::Holding"]);
955             copy_to_holding(pkg.changes_file);
956             # Relativize the filename so we use the copy in holding
957             # rather than the original...
958             pkg.changes_file = os.path.basename(pkg.changes_file);
959         changes["fingerprint"] = utils.check_signature(pkg.changes_file, reject);
960         changes_valid = check_changes();
961         if changes_valid:
962             while reprocess:
963                 check_distributions();
964                 check_files();
965                 check_dsc();
966                 check_diff();
967                 check_md5sums();
968                 check_urgency();
969                 check_timestamps();
970         Katie.update_subst(reject_message);
971         action();
972     except SystemExit:
973         raise;
974     except:
975         print "ERROR";
976         traceback.print_exc(file=sys.stderr);
977         pass;
978
979     # Restore previous WD
980     os.chdir(pkg.directory);
981
982 ###############################################################################
983
984 def main():
985     global Cnf, Options, Logger, nmu;
986
987     changes_files = init();
988
989     # -n/--dry-run invalidates some other options which would involve things happening
990     if Options["No-Action"]:
991         Options["Automatic"] = "";
992
993     # Ensure all the arguments we were given are .changes files
994     for file in changes_files:
995         if not file.endswith(".changes"):
996             utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
997             changes_files.remove(file);
998
999     if changes_files == []:
1000         utils.fubar("Need at least one .changes file as an argument.");
1001
1002     # Check that we aren't going to clash with the daily cron job
1003
1004     if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::Root"])) and not Options["No-Lock"]:
1005         utils.fubar("Archive maintenance in progress.  Try again later.");
1006
1007     # Obtain lock if not in no-action mode and initialize the log
1008
1009     if not Options["No-Action"]:
1010         lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1011         try:
1012             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB);
1013         except IOError, e:
1014             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
1015                 utils.fubar("Couldn't obtain lock; assuming another jennifer is already running.");
1016             else:
1017                 raise;
1018         Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1019
1020     # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1021     bcc = "X-Katie: %s" % (jennifer_version);
1022     if Cnf.has_key("Dinstall::Bcc"):
1023         Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1024     else:
1025         Katie.Subst["__BCC__"] = bcc;
1026
1027
1028     # Sort the .changes files so that we process sourceful ones first
1029     changes_files.sort(utils.changes_compare);
1030
1031     # Process the changes files
1032     for changes_file in changes_files:
1033         print "\n" + changes_file;
1034         try:
1035             process_it (changes_file);
1036         finally:
1037             if not Options["No-Action"]:
1038                 clean_holding();
1039
1040     accept_count = Katie.accept_count;
1041     accept_bytes = Katie.accept_bytes;
1042     if accept_count:
1043         sets = "set"
1044         if accept_count > 1:
1045             sets = "sets"
1046         print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)));
1047         Logger.log(["total",accept_count,accept_bytes]);
1048
1049     if not Options["No-Action"]:
1050         Logger.close();
1051
1052 ################################################################################
1053
1054 if __name__ == '__main__':
1055     main()
1056