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