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