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