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