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