]> git.decadent.org.uk Git - dak.git/blob - jennifer
2004-08-04 James Troup <james@nocrew.org> * jennifer (check_files): check for unkno...
[dak.git] / jennifer
1 #!/usr/bin/env python
2
3 # Checks Debian packages from Incoming
4 # Copyright (C) 2000, 2001, 2002, 2003, 2004  James Troup <james@nocrew.org>
5 # $Id: jennifer,v 1.52 2004-11-27 13:32:16 troup 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 commands, errno, fcntl, os, re, shutil, stat, sys, time, tempfile, traceback;
33 import apt_inst, apt_pkg;
34 import db_access, katie, logging, utils;
35
36 from types import *;
37
38 ################################################################################
39
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"-([^-]+)$");
44
45 ################################################################################
46
47 # Globals
48 jennifer_version = "$Revision: 1.52 $";
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("%s: can not copy to holding area: file not found." % (base_filename));
152             os.unlink(dest);
153             return;
154         elif errno.errorcode[e.errno] == 'EACCES':
155             reject("%s: can not copy 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     # Defaults in case we bail out
184     changes["maintainer2047"] = Cnf["Dinstall::MyEmailAddress"];
185     changes["changedby2047"] = 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("%s: can't read file." % (filename));
193         return 0;
194     except utils.changes_parse_error_exc, line:
195         reject("%s: parse error, 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("%s: parse error, can't grok: %s." % (filename, line));
203     except utils.nk_format_exc, format:
204         reject("%s: unknown format '%s'." % (filename, format));
205         return 0;
206
207     # Check for mandatory fields
208     for i in ("source", "binary", "architecture", "version", "distribution",
209               "maintainer", "files", "changes"):
210         if not changes.has_key(i):
211             reject("%s: Missing mandatory field `%s'." % (filename, i));
212             return 0    # Avoid <undef> errors during later tests
213
214     # Split multi-value fields into a lower-level dictionary
215     for i in ("architecture", "distribution", "binary", "closes"):
216         o = changes.get(i, "")
217         if o != "":
218             del changes[i]
219         changes[i] = {}
220         for j in o.split():
221             changes[i][j] = 1
222
223     # Fix the Maintainer: field to be RFC822/2047 compatible
224     try:
225         (changes["maintainer822"], changes["maintainer2047"],
226          changes["maintainername"], changes["maintaineremail"]) = \
227          utils.fix_maintainer (changes["maintainer"]);
228     except utils.ParseMaintError, msg:
229         reject("%s: Maintainer field ('%s') failed to parse: %s" \
230                % (filename, changes["maintainer"], msg));
231
232     # ...likewise for the Changed-By: field if it exists.
233     try:
234         (changes["changedby822"], changes["changedby2047"],
235          changes["changedbyname"], changes["changedbyemail"]) = \
236          utils.fix_maintainer (changes.get("changed-by", ""));
237     except utils.ParseMaintError, msg:
238         reject("%s: Changed-By field ('%s') failed to parse: %s" \
239                % (filename, changes["changed-by"], msg));
240
241     # Ensure all the values in Closes: are numbers
242     if changes.has_key("closes"):
243         for i in changes["closes"].keys():
244             if katie.re_isanum.match (i) == None:
245                 reject("%s: `%s' from Closes field isn't a number." % (filename, i));
246
247
248     # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
249     changes["chopversion"] = utils.re_no_epoch.sub('', changes["version"])
250     changes["chopversion2"] = utils.re_no_revision.sub('', changes["chopversion"])
251
252     # Check there isn't already a changes file of the same name in one
253     # of the queue directories.
254     base_filename = os.path.basename(filename);
255     for dir in [ "Accepted", "Byhand", "Done", "New" ]:
256         if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+base_filename):
257             reject("%s: a file with this name already exists in the %s directory." % (base_filename, dir));
258
259     # Check the .changes is non-empty
260     if not files:
261         reject("%s: nothing to do (Files field is empty)." % (base_filename))
262         return 0;
263
264     return 1;
265
266 ################################################################################
267
268 def check_distributions():
269     "Check and map the Distribution field of a .changes file."
270
271     # Handle suite mappings
272     for map in Cnf.ValueList("SuiteMappings"):
273         args = map.split();
274         type = args[0];
275         if type == "map" or type == "silent-map":
276             (source, dest) = args[1:3];
277             if changes["distribution"].has_key(source):
278                 del changes["distribution"][source]
279                 changes["distribution"][dest] = 1;
280                 if type != "silent-map":
281                     reject("Mapping %s to %s." % (source, dest),"");
282         elif type == "map-unreleased":
283             (source, dest) = args[1:3];
284             if changes["distribution"].has_key(source):
285                 for arch in changes["architecture"].keys():
286                     if arch not in Cnf.ValueList("Suite::%s::Architectures" % (source)):
287                         reject("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch),"");
288                         del changes["distribution"][source];
289                         changes["distribution"][dest] = 1;
290                         break;
291         elif type == "ignore":
292             suite = args[1];
293             if changes["distribution"].has_key(suite):
294                 del changes["distribution"][suite];
295                 reject("Ignoring %s as a target suite." % (suite), "Warning: ");
296
297     # Ensure there is (still) a target distribution
298     if changes["distribution"].keys() == []:
299         reject("no valid distribution.");
300
301     # Ensure target distributions exist
302     for suite in changes["distribution"].keys():
303         if not Cnf.has_key("Suite::%s" % (suite)):
304             reject("Unknown distribution `%s'." % (suite));
305
306 ################################################################################
307
308 def check_files():
309     global reprocess
310
311     archive = utils.where_am_i();
312     file_keys = files.keys();
313
314     # if reprocess is 2 we've already done this and we're checking
315     # things again for the new .orig.tar.gz.
316     # [Yes, I'm fully aware of how disgusting this is]
317     if not Options["No-Action"] and reprocess < 2:
318         cwd = os.getcwd();
319         os.chdir(pkg.directory);
320         for file in file_keys:
321             copy_to_holding(file);
322         os.chdir(cwd);
323
324     # Check there isn't already a .changes or .katie file of the same name in
325     # the proposed-updates "CopyChanges" or "CopyKatie" storage directories.
326     # [NB: this check must be done post-suite mapping]
327     base_filename = os.path.basename(pkg.changes_file);
328     katie_filename = base_filename[:-8]+".katie"
329     for suite in changes["distribution"].keys():
330         copychanges = "Suite::%s::CopyChanges" % (suite);
331         if Cnf.has_key(copychanges) and \
332                os.path.exists(Cnf[copychanges]+"/"+base_filename):
333             reject("%s: a file with this name already exists in %s" \
334                    % (base_filename, Cnf[copychanges]));
335
336         copykatie = "Suite::%s::CopyKatie" % (suite);
337         if Cnf.has_key(copykatie) and \
338                os.path.exists(Cnf[copykatie]+"/"+katie_filename):
339             reject("%s: a file with this name already exists in %s" \
340                    % (katie_filename, Cnf[copykatie]));
341
342     reprocess = 0;
343     has_binaries = 0;
344     has_source = 0;
345
346     for file in file_keys:
347         # Ensure the file does not already exist in one of the accepted directories
348         for dir in [ "Accepted", "Byhand", "New" ]:
349             if os.path.exists(Cnf["Dir::Queue::%s" % (dir) ]+'/'+file):
350                 reject("%s file already exists in the %s directory." % (file, dir));
351         if not utils.re_taint_free.match(file):
352             reject("!!WARNING!! tainted filename: '%s'." % (file));
353         # Check the file is readable
354         if os.access(file,os.R_OK) == 0:
355             # When running in -n, copy_to_holding() won't have
356             # generated the reject_message, so we need to.
357             if Options["No-Action"]:
358                 if os.path.exists(file):
359                     reject("Can't read `%s'. [permission denied]" % (file));
360                 else:
361                     reject("Can't read `%s'. [file not found]" % (file));
362             files[file]["type"] = "unreadable";
363             continue;
364         # If it's byhand skip remaining checks
365         if files[file]["section"] == "byhand":
366             files[file]["byhand"] = 1;
367             files[file]["type"] = "byhand";
368         # Checks for a binary package...
369         elif utils.re_isadeb.match(file):
370             has_binaries = 1;
371             files[file]["type"] = "deb";
372
373             # Extract package control information
374             deb_file = utils.open_file(file);
375             try:
376                 control = apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file));
377             except:
378                 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
379                 deb_file.close();
380                 # Can't continue, none of the checks on control would work.
381                 continue;
382             deb_file.close();
383
384             # Check for mandatory fields
385             for field in [ "Package", "Architecture", "Version" ]:
386                 if control.Find(field) == None:
387                     reject("%s: No %s field in control." % (file, field));
388                     # Can't continue
389                     continue;
390
391             # Ensure the package name matches the one give in the .changes
392             if not changes["binary"].has_key(control.Find("Package", "")):
393                 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
394
395             # Validate the package field
396             package = control.Find("Package");
397             if not re_valid_pkg_name.match(package):
398                 reject("%s: invalid package name '%s'." % (file, package));
399
400             # Validate the version field
401             version = control.Find("Version");
402             if not re_valid_version.match(version):
403                 reject("%s: invalid version number '%s'." % (file, version));
404
405             # Ensure the architecture of the .deb is one we know about.
406             default_suite = Cnf.get("Dinstall::DefaultSuite", "Unstable")
407             architecture = control.Find("Architecture");
408             if architecture not in Cnf.ValueList("Suite::%s::Architectures" % (default_suite)):
409                 reject("Unknown architecture '%s'." % (architecture));
410
411             # Ensure the architecture of the .deb is one of the ones
412             # listed in the .changes.
413             if not changes["architecture"].has_key(architecture):
414                 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, architecture));
415
416             # Sanity-check the Depends field
417             depends = control.Find("Depends");
418             if depends == '':
419                 reject("%s: Depends field is empty." % (file));
420
421             # Check the section & priority match those given in the .changes (non-fatal)
422             if control.Find("Section") and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
423                 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
424             if control.Find("Priority") and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
425                 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
426
427             files[file]["package"] = package;
428             files[file]["architecture"] = architecture;
429             files[file]["version"] = version;
430             files[file]["maintainer"] = control.Find("Maintainer", "");
431             if file.endswith(".udeb"):
432                 files[file]["dbtype"] = "udeb";
433             elif file.endswith(".deb"):
434                 files[file]["dbtype"] = "deb";
435             else:
436                 reject("%s is neither a .deb or a .udeb." % (file));
437             files[file]["source"] = control.Find("Source", files[file]["package"]);
438             # Get the source version
439             source = files[file]["source"];
440             source_version = "";
441             if source.find("(") != -1:
442                 m = utils.re_extract_src_version.match(source);
443                 source = m.group(1);
444                 source_version = m.group(2);
445             if not source_version:
446                 source_version = files[file]["version"];
447             files[file]["source package"] = source;
448             files[file]["source version"] = source_version;
449
450             # Ensure the filename matches the contents of the .deb
451             m = utils.re_isadeb.match(file);
452             #  package name
453             file_package = m.group(1);
454             if files[file]["package"] != file_package:
455                 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"]));
456             epochless_version = utils.re_no_epoch.sub('', control.Find("Version"));
457             #  version
458             file_version = m.group(2);
459             if epochless_version != file_version:
460                 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
461             #  architecture
462             file_architecture = m.group(3);
463             if files[file]["architecture"] != file_architecture:
464                 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"]));
465
466             # Check for existent source
467             source_version = files[file]["source version"];
468             source_package = files[file]["source package"];
469             if changes["architecture"].has_key("source"):
470                 if source_version != changes["version"]:
471                     reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
472             else:
473                 # Check in the SQL database
474                 if not Katie.source_exists(source_package, source_version, changes["distribution"].keys()):
475                     # Check in one of the other directories
476                     source_epochless_version = utils.re_no_epoch.sub('', source_version);
477                     dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
478                     if os.path.exists(Cnf["Dir::Queue::Byhand"] + '/' + dsc_filename):
479                         files[file]["byhand"] = 1;
480                     elif os.path.exists(Cnf["Dir::Queue::New"] + '/' + dsc_filename):
481                         files[file]["new"] = 1;
482                     elif not os.path.exists(Cnf["Dir::Queue::Accepted"] + '/' + dsc_filename):
483                         reject("no source found for %s %s (%s)." % (source_package, source_version, file));
484             # Check the version and for file overwrites
485             reject(Katie.check_binary_against_db(file),"");
486
487         # Checks for a source package...
488         else:
489             m = utils.re_issource.match(file);
490             if m:
491                 has_source = 1;
492                 files[file]["package"] = m.group(1);
493                 files[file]["version"] = m.group(2);
494                 files[file]["type"] = m.group(3);
495
496                 # Ensure the source package name matches the Source filed in the .changes
497                 if changes["source"] != files[file]["package"]:
498                     reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
499
500                 # Ensure the source version matches the version in the .changes file
501                 if files[file]["type"] == "orig.tar.gz":
502                     changes_version = changes["chopversion2"];
503                 else:
504                     changes_version = changes["chopversion"];
505                 if changes_version != files[file]["version"]:
506                     reject("%s: should be %s according to changes file." % (file, changes_version));
507
508                 # Ensure the .changes lists source in the Architecture field
509                 if not changes["architecture"].has_key("source"):
510                     reject("%s: changes file doesn't list `source' in Architecture field." % (file));
511
512                 # Check the signature of a .dsc file
513                 if files[file]["type"] == "dsc":
514                     dsc["fingerprint"] = utils.check_signature(file, reject);
515
516                 files[file]["architecture"] = "source";
517
518             # Not a binary or source package?  Assume byhand...
519             else:
520                 files[file]["byhand"] = 1;
521                 files[file]["type"] = "byhand";
522
523         # Per-suite file checks
524         files[file]["oldfiles"] = {};
525         for suite in changes["distribution"].keys():
526             # Skip byhand
527             if files[file].has_key("byhand"):
528                 continue;
529
530             # Handle component mappings
531             for map in Cnf.ValueList("ComponentMappings"):
532                 (source, dest) = map.split();
533                 if files[file]["component"] == source:
534                     files[file]["original component"] = source;
535                     files[file]["component"] = dest;
536
537             # Ensure the component is valid for the target suite
538             if Cnf.has_key("Suite:%s::Components" % (suite)) and \
539                files[file]["component"] not in Cnf.ValueList("Suite::%s::Components" % (suite)):
540                 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
541                 continue;
542
543             # Validate the component
544             component = files[file]["component"];
545             component_id = db_access.get_component_id(component);
546             if component_id == -1:
547                 reject("file '%s' has unknown component '%s'." % (file, component));
548                 continue;
549
550             # See if the package is NEW
551             if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
552                 files[file]["new"] = 1;
553
554             # Validate the priority
555             if files[file]["priority"].find('/') != -1:
556                 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
557
558             # Determine the location
559             location = Cnf["Dir::Pool"];
560             location_id = db_access.get_location_id (location, component, archive);
561             if location_id == -1:
562                 reject("[INTERNAL ERROR] couldn't determine location (Component: %s, Archive: %s)" % (component, archive));
563             files[file]["location id"] = location_id;
564
565             # Check the md5sum & size against existing files (if any)
566             files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
567             files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
568             if files_id == -1:
569                 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
570             elif files_id == -2:
571                 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
572             files[file]["files id"] = files_id
573
574             # Check for packages that have moved from one component to another
575             q = Katie.projectB.query("""
576 SELECT c.name FROM binaries b, bin_associations ba, suite s, location l,
577                    component c, architecture a, files f
578  WHERE b.package = '%s' AND s.suite_name = '%s'
579    AND (a.arch_string = '%s' OR a.arch_string = 'all')
580    AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
581    AND f.location = l.id AND l.component = c.id AND b.file = f.id"""
582                                % (files[file]["package"], suite,
583                                   files[file]["architecture"]));
584             ql = q.getresult();
585             if ql:
586                 files[file]["othercomponents"] = ql[0][0];
587
588     # If the .changes file says it has source, it must have source.
589     if changes["architecture"].has_key("source"):
590         if not has_source:
591             reject("no source found and Architecture line in changes mention source.");
592
593         if not has_binaries and Cnf.FindB("Dinstall::Reject::NoSourceOnly"):
594             reject("source only uploads are not supported.");
595
596 ###############################################################################
597
598 def check_dsc():
599     global reprocess;
600
601     # Ensure there is source to check
602     if not changes["architecture"].has_key("source"):
603         return 1;
604
605     # Find the .dsc
606     dsc_filename = None;
607     for file in files.keys():
608         if files[file]["type"] == "dsc":
609             if dsc_filename:
610                 reject("can not process a .changes file with multiple .dsc's.");
611                 return 0;
612             else:
613                 dsc_filename = file;
614
615     # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
616     if not dsc_filename:
617         return 0;
618
619     # Parse the .dsc file
620     try:
621         dsc.update(utils.parse_changes(dsc_filename, signing_rules=1));
622     except utils.cant_open_exc:
623         # if not -n copy_to_holding() will have done this for us...
624         if Options["No-Action"]:
625             reject("%s: can't read file." % (dsc_filename));
626     except utils.changes_parse_error_exc, line:
627         reject("%s: parse error, can't grok: %s." % (dsc_filename, line));
628     except utils.invalid_dsc_format_exc, line:
629         reject("%s: syntax error on line %s." % (dsc_filename, line));
630     # Build up the file list of files mentioned by the .dsc
631     try:
632         dsc_files.update(utils.build_file_list(dsc, is_a_dsc=1));
633     except utils.no_files_exc:
634         reject("%s: no Files: field." % (dsc_filename));
635         return 0;
636     except utils.changes_parse_error_exc, line:
637         reject("%s: parse error, can't grok: %s." % (dsc_filename, line));
638         return 0;
639
640     # Enforce mandatory fields
641     for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
642         if not dsc.has_key(i):
643             reject("%s: missing mandatory field `%s'." % (dsc_filename, i));
644             return 0;
645
646     # Validate the source and version fields
647     if not re_valid_pkg_name.match(dsc["source"]):
648         reject("%s: invalid source name '%s'." % (dsc_filename, dsc["source"]));
649     if not re_valid_version.match(dsc["version"]):
650         reject("%s: invalid version number '%s'." % (dsc_filename, dsc["version"]));
651
652     # Bumping the version number of the .dsc breaks extraction by stable's
653     # dpkg-source.  So let's not do that...
654     if dsc["format"] != "1.0":
655         reject("%s: incompatible 'Format' version produced by a broken version of dpkg-dev 1.9.1{3,4}." % (dsc_filename));
656
657     # Validate the Maintainer field
658     try:
659         utils.fix_maintainer (dsc["maintainer"]);
660     except utils.ParseMaintError, msg:
661         reject("%s: Maintainer field ('%s') failed to parse: %s" \
662                % (dsc_filename, changes["changed-by"], msg));
663
664     # Validate the build-depends field(s)
665     for field_name in [ "build-depends", "build-depends-indep" ]:
666         field = dsc.get(field_name);
667         if field:
668             # Check for broken dpkg-dev lossage...
669             if field.startswith("ARRAY"):
670                 reject("%s: invalid %s field produced by a broken version of dpkg-dev (1.10.11)" % (dsc_filename, field_name.title()));
671
672             # Have apt try to parse them...
673             try:
674                 apt_pkg.ParseSrcDepends(field);
675             except:
676                 reject("%s: invalid %s field (can not be parsed by apt)." % (dsc_filename, field_name.title()));
677                 pass;
678
679     # Ensure the version number in the .dsc matches the version number in the .changes
680     epochless_dsc_version = utils.re_no_epoch.sub('', dsc["version"]);
681     changes_version = files[dsc_filename]["version"];
682     if epochless_dsc_version != files[dsc_filename]["version"]:
683         reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
684
685     # Ensure there is a .tar.gz in the .dsc file
686     has_tar = 0;
687     for f in dsc_files.keys():
688         m = utils.re_issource.match(f);
689         if not m:
690             reject("%s: %s in Files field not recognised as source." % (dsc_filename, f));
691         type = m.group(3);
692         if type == "orig.tar.gz" or type == "tar.gz":
693             has_tar = 1;
694     if not has_tar:
695         reject("%s: no .tar.gz or .orig.tar.gz in 'Files' field." % (dsc_filename));
696
697     # Ensure source is newer than existing source in target suites
698     reject(Katie.check_source_against_db(dsc_filename),"");
699
700     (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(dsc_filename);
701     reject(reject_msg, "");
702     if is_in_incoming:
703         if not Options["No-Action"]:
704             copy_to_holding(is_in_incoming);
705         orig_tar_gz = os.path.basename(is_in_incoming);
706         files[orig_tar_gz] = {};
707         files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
708         files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
709         files[orig_tar_gz]["section"] = files[dsc_filename]["section"];
710         files[orig_tar_gz]["priority"] = files[dsc_filename]["priority"];
711         files[orig_tar_gz]["component"] = files[dsc_filename]["component"];
712         files[orig_tar_gz]["type"] = "orig.tar.gz";
713         reprocess = 2;
714
715     return 1;
716
717 ################################################################################
718
719 def get_changelog_versions(source_dir):
720     """Extracts a the source package and (optionally) grabs the
721     version history out of debian/changelog for the BTS."""
722
723     # Find the .dsc (again)
724     dsc_filename = None;
725     for file in files.keys():
726         if files[file]["type"] == "dsc":
727             dsc_filename = file;
728
729     # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
730     if not dsc_filename:
731         return;
732
733     # Create a symlink mirror of the source files in our temporary directory
734     for f in files.keys():
735         m = utils.re_issource.match(f);
736         if m:
737             src = os.path.join(source_dir, f);
738             # If a file is missing for whatever reason, give up.
739             if not os.path.exists(src):
740                 return;
741             type = m.group(3);
742             if type == "orig.tar.gz" and pkg.orig_tar_gz:
743                 continue;
744             dest = os.path.join(os.getcwd(), f);
745             os.symlink(src, dest);
746
747     # If the orig.tar.gz is not a part of the upload, create a symlink to the
748     # existing copy.
749     if pkg.orig_tar_gz:
750         dest = os.path.join(os.getcwd(), os.path.basename(pkg.orig_tar_gz));
751         os.symlink(pkg.orig_tar_gz, dest);
752
753     # Extract the source
754     cmd = "dpkg-source -sn -x %s" % (dsc_filename);
755     (result, output) = commands.getstatusoutput(cmd);
756     if (result != 0):
757         reject("'dpkg-source -x' failed for %s [return code: %s]." % (dsc_filename, result));
758         reject(utils.prefix_multi_line_string(output, " [dpkg-source output:] "), "");
759         return;
760
761     if not Cnf.Find("Dir::Queue::BTSVersionTrack"):
762         return;
763
764     # Get the upstream version
765     upstr_version = utils.re_no_epoch.sub('', dsc["version"]);
766     if re_strip_revision.search(upstr_version):
767         upstr_version = re_strip_revision.sub('', upstr_version);
768
769     # Ensure the changelog file exists
770     changelog_filename = "%s-%s/debian/changelog" % (dsc["source"], upstr_version);
771     if not os.path.exists(changelog_filename):
772         reject("%s: debian/changelog not found in extracted source." % (dsc_filename));
773         return;
774
775     # Parse the changelog
776     dsc["bts changelog"] = "";
777     changelog_file = utils.open_file(changelog_filename);
778     for line in changelog_file.readlines():
779         m = re_changelog_versions.match(line);
780         if m:
781             dsc["bts changelog"] += line;
782     changelog_file.close();
783
784     # Check we found at least one revision in the changelog
785     if not dsc["bts changelog"]:
786         reject("%s: changelog format not recognised (empty version tree)." % (dsc_filename));
787
788 ########################################
789
790 def check_source():
791     # Bail out if:
792     #    a) there's no source 
793     # or b) reprocess is 2 - we will do this check next time when orig.tar.gz is in 'files'
794     # or c) the orig.tar.gz is MIA
795     if not changes["architecture"].has_key("source") or reprocess == 2 \
796        or pkg.orig_tar_gz == -1:
797         return;
798
799     # Create a temporary directory to extract the source into
800     if Options["No-Action"]:
801         tmpdir = tempfile.mktemp();
802     else:
803         # We're in queue/holding and can create a random directory.
804         tmpdir = "%s" % (os.getpid());
805     os.mkdir(tmpdir);
806
807     # Move into the temporary directory
808     cwd = os.getcwd();
809     os.chdir(tmpdir);
810
811     # Get the changelog version history
812     get_changelog_versions(cwd);
813
814     # Move back and cleanup the temporary tree
815     os.chdir(cwd);
816     try:
817         shutil.rmtree(tmpdir);
818     except OSError, e:
819         if errno.errorcode[e.errno] != 'EACCES':
820             utils.fubar("%s: couldn't remove tmp dir for source tree." % (dsc["source"]));
821
822         reject("%s: source tree could not be cleanly removed." % (dsc["source"]));
823         # We probably have u-r or u-w directories so chmod everything
824         # and try again.
825         cmd = "chmod -R u+rwx %s" % (tmpdir)
826         result = os.system(cmd)
827         if result != 0:
828             utils.fubar("'%s' failed with result %s." % (cmd, result));
829         shutil.rmtree(tmpdir);
830     except:
831         utils.fubar("%s: couldn't remove tmp dir for source tree." % (dsc["source"]));
832
833 ################################################################################
834
835 # FIXME: should be a debian specific check called from a hook
836
837 def check_urgency ():
838     if changes["architecture"].has_key("source"):
839         if not changes.has_key("urgency"):
840             changes["urgency"] = Cnf["Urgency::Default"];
841         if changes["urgency"] not in Cnf.ValueList("Urgency::Valid"):
842             reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
843             changes["urgency"] = Cnf["Urgency::Default"];
844         changes["urgency"] = changes["urgency"].lower();
845
846 ################################################################################
847
848 def check_md5sums ():
849     for file in files.keys():
850         try:
851             file_handle = utils.open_file(file);
852         except utils.cant_open_exc:
853             continue;
854
855         # Check md5sum
856         if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
857             reject("%s: md5sum check failed." % (file));
858         file_handle.close();
859         # Check size
860         actual_size = os.stat(file)[stat.ST_SIZE];
861         size = int(files[file]["size"]);
862         if size != actual_size:
863             reject("%s: actual file size (%s) does not match size (%s) in .changes"
864                    % (file, actual_size, size));
865
866     for file in dsc_files.keys():
867         try:
868             file_handle = utils.open_file(file);
869         except utils.cant_open_exc:
870             continue;
871
872         # Check md5sum
873         if apt_pkg.md5sum(file_handle) != dsc_files[file]["md5sum"]:
874             reject("%s: md5sum check failed." % (file));
875         file_handle.close();
876         # Check size
877         actual_size = os.stat(file)[stat.ST_SIZE];
878         size = int(dsc_files[file]["size"]);
879         if size != actual_size:
880             reject("%s: actual file size (%s) does not match size (%s) in .dsc"
881                    % (file, actual_size, size));
882
883 ################################################################################
884
885 # Sanity check the time stamps of files inside debs.
886 # [Files in the near future cause ugly warnings and extreme time
887 #  travel can cause errors on extraction]
888
889 def check_timestamps():
890     class Tar:
891         def __init__(self, future_cutoff, past_cutoff):
892             self.reset();
893             self.future_cutoff = future_cutoff;
894             self.past_cutoff = past_cutoff;
895
896         def reset(self):
897             self.future_files = {};
898             self.ancient_files = {};
899
900         def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
901             if MTime > self.future_cutoff:
902                 self.future_files[Name] = MTime;
903             if MTime < self.past_cutoff:
904                 self.ancient_files[Name] = MTime;
905     ####
906
907     future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"]);
908     past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"));
909     tar = Tar(future_cutoff, past_cutoff);
910     for filename in files.keys():
911         if files[filename]["type"] == "deb":
912             tar.reset();
913             try:
914                 deb_file = utils.open_file(filename);
915                 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz");
916                 deb_file.seek(0);
917                 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz");
918                 deb_file.close();
919                 #
920                 future_files = tar.future_files.keys();
921                 if future_files:
922                     num_future_files = len(future_files);
923                     future_file = future_files[0];
924                     future_date = tar.future_files[future_file];
925                     reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
926                            % (filename, num_future_files, future_file,
927                               time.ctime(future_date)));
928                 #
929                 ancient_files = tar.ancient_files.keys();
930                 if ancient_files:
931                     num_ancient_files = len(ancient_files);
932                     ancient_file = ancient_files[0];
933                     ancient_date = tar.ancient_files[ancient_file];
934                     reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
935                            % (filename, num_ancient_files, ancient_file,
936                               time.ctime(ancient_date)));
937             except:
938                 reject("%s: deb contents timestamp check failed [%s: %s]" % (filename, sys.exc_type, sys.exc_value));
939
940 ################################################################################
941 ################################################################################
942
943 # If any file of an upload has a recent mtime then chances are good
944 # the file is still being uploaded.
945
946 def upload_too_new():
947     too_new = 0;
948     # Move back to the original directory to get accurate time stamps
949     cwd = os.getcwd();
950     os.chdir(pkg.directory);
951     file_list = pkg.files.keys();
952     file_list.extend(pkg.dsc_files.keys());
953     file_list.append(pkg.changes_file);
954     for file in file_list:
955         try:
956             last_modified = time.time()-os.path.getmtime(file);
957             if last_modified < int(Cnf["Dinstall::SkipTime"]):
958                 too_new = 1;
959                 break;
960         except:
961             pass;
962     os.chdir(cwd);
963     return too_new;
964
965 ################################################################################
966
967 def action ():
968     # changes["distribution"] may not exist in corner cases
969     # (e.g. unreadable changes files)
970     if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
971         changes["distribution"] = {};
972
973     (summary, short_summary) = Katie.build_summaries();
974
975     byhand = new = "";
976     for file in files.keys():
977         if files[file].has_key("byhand"):
978             byhand = 1
979         elif files[file].has_key("new"):
980             new = 1
981
982     (prompt, answer) = ("", "XXX")
983     if Options["No-Action"] or Options["Automatic"]:
984         answer = 'S'
985
986     if reject_message.find("Rejected") != -1:
987         if upload_too_new():
988             print "SKIP (too new)\n" + reject_message,;
989             prompt = "[S]kip, Quit ?";
990         else:
991             print "REJECT\n" + reject_message,;
992             prompt = "[R]eject, Skip, Quit ?";
993             if Options["Automatic"]:
994                 answer = 'R';
995     elif new:
996         print "NEW to %s\n%s%s" % (", ".join(changes["distribution"].keys()), reject_message, summary),;
997         prompt = "[N]ew, Skip, Quit ?";
998         if Options["Automatic"]:
999             answer = 'N';
1000     elif byhand:
1001         print "BYHAND\n" + reject_message + summary,;
1002         prompt = "[B]yhand, Skip, Quit ?";
1003         if Options["Automatic"]:
1004             answer = 'B';
1005     else:
1006         print "ACCEPT\n" + reject_message + summary,;
1007         prompt = "[A]ccept, Skip, Quit ?";
1008         if Options["Automatic"]:
1009             answer = 'A';
1010
1011     while prompt.find(answer) == -1:
1012         answer = utils.our_raw_input(prompt);
1013         m = katie.re_default_answer.match(prompt);
1014         if answer == "":
1015             answer = m.group(1);
1016         answer = answer[:1].upper();
1017
1018     if answer == 'R':
1019         os.chdir (pkg.directory);
1020         Katie.do_reject(0, reject_message);
1021     elif answer == 'A':
1022         accept(summary, short_summary);
1023     elif answer == 'B':
1024         do_byhand(summary);
1025     elif answer == 'N':
1026         acknowledge_new (summary);
1027     elif answer == 'Q':
1028         sys.exit(0)
1029
1030 ################################################################################
1031
1032 def accept (summary, short_summary):
1033     Katie.accept(summary, short_summary);
1034     Katie.check_override();
1035
1036     # Finally, remove the originals from the unchecked directory
1037     os.chdir (pkg.directory);
1038     for file in files.keys():
1039         os.unlink(file);
1040     os.unlink(pkg.changes_file);
1041
1042 ################################################################################
1043
1044 def do_byhand (summary):
1045     print "Moving to BYHAND holding area."
1046     Logger.log(["Moving to byhand", pkg.changes_file]);
1047
1048     Katie.dump_vars(Cnf["Dir::Queue::Byhand"]);
1049
1050     file_keys = files.keys();
1051
1052     # Move all the files into the byhand directory
1053     utils.move (pkg.changes_file, Cnf["Dir::Queue::Byhand"]);
1054     for file in file_keys:
1055         utils.move (file, Cnf["Dir::Queue::Byhand"], perms=0660);
1056
1057     # Check for override disparities
1058     Katie.Subst["__SUMMARY__"] = summary;
1059     Katie.check_override();
1060
1061     # Finally remove the originals.
1062     os.chdir (pkg.directory);
1063     for file in file_keys:
1064         os.unlink(file);
1065     os.unlink(pkg.changes_file);
1066
1067 ################################################################################
1068
1069 def acknowledge_new (summary):
1070     Subst = Katie.Subst;
1071
1072     print "Moving to NEW holding area."
1073     Logger.log(["Moving to new", pkg.changes_file]);
1074
1075     Katie.dump_vars(Cnf["Dir::Queue::New"]);
1076
1077     file_keys = files.keys();
1078
1079     # Move all the files into the 'new' directory
1080     utils.move (pkg.changes_file, Cnf["Dir::Queue::New"]);
1081     for file in file_keys:
1082         utils.move (file, Cnf["Dir::Queue::New"], perms=0660);
1083
1084     if not Options["No-Mail"]:
1085         print "Sending new ack.";
1086         Subst["__SUMMARY__"] = summary;
1087         new_ack_message = utils.TemplateSubst(Subst,Cnf["Dir::Templates"]+"/jennifer.new");
1088         utils.send_mail(new_ack_message);
1089
1090     # Finally remove the originals.
1091     os.chdir (pkg.directory);
1092     for file in file_keys:
1093         os.unlink(file);
1094     os.unlink(pkg.changes_file);
1095
1096 ################################################################################
1097
1098 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1099 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1100 # Katie.check_dsc_against_db() can find the .orig.tar.gz but it will
1101 # not have processed it during it's checks of -2.  If -1 has been
1102 # deleted or otherwise not checked by jennifer, the .orig.tar.gz will
1103 # not have been checked at all.  To get round this, we force the
1104 # .orig.tar.gz into the .changes structure and reprocess the .changes
1105 # file.
1106
1107 def process_it (changes_file):
1108     global reprocess, reject_message;
1109
1110     # Reset some globals
1111     reprocess = 1;
1112     Katie.init_vars();
1113     reject_message = "";
1114
1115     # Absolutize the filename to avoid the requirement of being in the
1116     # same directory as the .changes file.
1117     pkg.changes_file = os.path.abspath(changes_file);
1118
1119     # Remember where we are so we can come back after cd-ing into the
1120     # holding directory.
1121     pkg.directory = os.getcwd();
1122
1123     try:
1124         # If this is the Real Thing(tm), copy things into a private
1125         # holding directory first to avoid replacable file races.
1126         if not Options["No-Action"]:
1127             os.chdir(Cnf["Dir::Queue::Holding"]);
1128             copy_to_holding(pkg.changes_file);
1129             # Relativize the filename so we use the copy in holding
1130             # rather than the original...
1131             pkg.changes_file = os.path.basename(pkg.changes_file);
1132         changes["fingerprint"] = utils.check_signature(pkg.changes_file, reject);
1133         valid_changes_p = check_changes();
1134         if valid_changes_p:
1135             while reprocess:
1136                 check_distributions();
1137                 check_files();
1138                 valid_dsc_p = check_dsc();
1139                 if valid_dsc_p:
1140                     check_source();
1141                 check_md5sums();
1142                 check_urgency();
1143                 check_timestamps();
1144         Katie.update_subst(reject_message);
1145         action();
1146     except SystemExit:
1147         raise;
1148     except:
1149         print "ERROR";
1150         traceback.print_exc(file=sys.stderr);
1151         pass;
1152
1153     # Restore previous WD
1154     os.chdir(pkg.directory);
1155
1156 ###############################################################################
1157
1158 def main():
1159     global Cnf, Options, Logger;
1160
1161     changes_files = init();
1162
1163     # -n/--dry-run invalidates some other options which would involve things happening
1164     if Options["No-Action"]:
1165         Options["Automatic"] = "";
1166
1167     # Ensure all the arguments we were given are .changes files
1168     for file in changes_files:
1169         if not file.endswith(".changes"):
1170             utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
1171             changes_files.remove(file);
1172
1173     if changes_files == []:
1174         utils.fubar("Need at least one .changes file as an argument.");
1175
1176     # Check that we aren't going to clash with the daily cron job
1177
1178     if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::Root"])) and not Options["No-Lock"]:
1179         utils.fubar("Archive maintenance in progress.  Try again later.");
1180
1181     # Obtain lock if not in no-action mode and initialize the log
1182
1183     if not Options["No-Action"]:
1184         lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1185         try:
1186             fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB);
1187         except IOError, e:
1188             if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
1189                 utils.fubar("Couldn't obtain lock; assuming another jennifer is already running.");
1190             else:
1191                 raise;
1192         Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1193
1194     # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1195     bcc = "X-Katie: %s" % (jennifer_version);
1196     if Cnf.has_key("Dinstall::Bcc"):
1197         Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1198     else:
1199         Katie.Subst["__BCC__"] = bcc;
1200
1201
1202     # Sort the .changes files so that we process sourceful ones first
1203     changes_files.sort(utils.changes_compare);
1204
1205     # Process the changes files
1206     for changes_file in changes_files:
1207         print "\n" + changes_file;
1208         try:
1209             process_it (changes_file);
1210         finally:
1211             if not Options["No-Action"]:
1212                 clean_holding();
1213
1214     accept_count = Katie.accept_count;
1215     accept_bytes = Katie.accept_bytes;
1216     if accept_count:
1217         sets = "set"
1218         if accept_count > 1:
1219             sets = "sets";
1220         print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)));
1221         Logger.log(["total",accept_count,accept_bytes]);
1222
1223     if not Options["No-Action"]:
1224         Logger.close();
1225
1226 ################################################################################
1227
1228 if __name__ == '__main__':
1229     main()
1230