]> git.decadent.org.uk Git - dak.git/blob - jennifer
New.
[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.1 2002-02-12 23:08:07 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.1 $";
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     # Ensure the changes filename matches it's contents.
463
464     base_filename = os.path.basename(filename);
465     m = re_is_changes.match(base_filename);
466     # source package name
467     if m:
468         file_source = m.group(1);
469         if changes["source"] != file_source:
470             reject("package name part of changes filename (%s) does not match source field (%s) in the changes file." % (file_source, changes["source"]));
471         # source version
472         file_version = m.group(2);
473         if changes["chopversion"] != file_version:
474             reject("version part of changes filename (%s) does not match version field (%s) in the changes file." % (file_version, changes["chopversion"]));
475     else:
476         reject("invalid changes filename '%s'." % (filename));
477
478     # But ... we can't check architecture because there's no
479     # established policy or practice on how to handle
480     # multi-architecture uploads.  Instead we check what we can and
481     # reject if there's a changes file of the same name already in one
482     # of the queue directories.
483     for dir in [ "Accepted", "Byhand", "Done", "New" ]:
484         if os.path.exists(Cnf["Dir::Queue%sDir" % (dir) ]+'/'+base_filename):
485             reject("a changes file with the same name exists in the %s directory." % (dir));
486
487     return 1;
488
489 ################################################################################
490
491 def check_files():
492     global reprocess
493
494     archive = utils.where_am_i();
495     file_keys = files.keys();
496
497     # if reprocess is 2 we've already done this and we're checking
498     # things again for the new .orig.tar.gz.
499     # [Yes, I'm fully aware of how disgusting this is]
500     if not Options["No-Action"] and reprocess < 2:
501         cwd = os.getcwd();
502         os.chdir(pkg.directory);
503         for file in file_keys:
504             copy_to_holding(file);
505         os.chdir(cwd);
506
507     reprocess = 0;
508
509     for file in file_keys:
510         # Ensure the file does not already exist in one of the accepted directories
511         for dir in [ "Accepted", "Byhand", "New" ]:
512             if os.path.exists(Cnf["Dir::Queue%sDir" % (dir) ]+'/'+file):
513                 reject("%s file already exists in the %s directory." % (file, dir));
514         if not utils.re_taint_free.match(file):
515             reject("!!WARNING!! tainted filename: '%s'." % (file));
516         # Check the file is readable
517         if os.access(file,os.R_OK) == 0:
518             # When running in -n, copy_to_holding() won't have
519             # generated the reject_message, so we need to.
520             if Options["No-Action"]:
521                 if os.path.exists(file):
522                     reject("Can't read `%s'. [permission denied]" % (file));
523                 else:
524                     reject("Can't read `%s'. [file not found]" % (file));
525             files[file]["type"] = "unreadable";
526             continue;
527         # If it's byhand skip remaining checks
528         if files[file]["section"] == "byhand":
529             files[file]["byhand"] = 1;
530             files[file]["type"] = "byhand";
531         # Checks for a binary package...
532         elif utils.re_isadeb.match(file) != None:
533             files[file]["type"] = "deb";
534
535             # Extract package control information
536             try:
537                 control = apt_pkg.ParseSection(apt_inst.debExtractControl(utils.open_file(file)));
538             except:
539                 reject("%s: debExtractControl() raised %s." % (file, sys.exc_type));
540                 # Can't continue, none of the checks on control would work.
541                 continue;
542
543             # Check for mandatory fields
544             for field in [ "Package", "Architecture", "Version" ]:
545                 if control.Find(field) == None:
546                     reject("%s: No %s field in control." % (file, field));
547
548             # Ensure the package name matches the one give in the .changes
549             if not changes["binary"].has_key(control.Find("Package", "")):
550                 reject("%s: control file lists name as `%s', which isn't in changes file." % (file, control.Find("Package", "")));
551
552             # Ensure the architecture of the .deb is one we know about.
553             if not Cnf.has_key("Suite::Unstable::Architectures::%s" % (control.Find("Architecture", ""))):
554                 reject("Unknown architecture '%s'." % (control.Find("Architecture", "")));
555
556             # Ensure the architecture of the .deb is one of the ones
557             # listed in the .changes.
558             if not changes["architecture"].has_key(control.Find("Architecture", "")):
559                 reject("%s: control file lists arch as `%s', which isn't in changes file." % (file, control.Find("Architecture", "")));
560
561             # Check the section & priority match those given in the .changes (non-fatal)
562             if control.Find("Section") != None and files[file]["section"] != "" and files[file]["section"] != control.Find("Section"):
563                 reject("%s control file lists section as `%s', but changes file has `%s'." % (file, control.Find("Section", ""), files[file]["section"]), "Warning: ");
564             if control.Find("Priority") != None and files[file]["priority"] != "" and files[file]["priority"] != control.Find("Priority"):
565                 reject("%s control file lists priority as `%s', but changes file has `%s'." % (file, control.Find("Priority", ""), files[file]["priority"]),"Warning: ");
566
567             files[file]["package"] = control.Find("Package");
568             files[file]["architecture"] = control.Find("Architecture");
569             files[file]["version"] = control.Find("Version");
570             files[file]["maintainer"] = control.Find("Maintainer", "");
571             if file[-5:] == ".udeb":
572                 files[file]["dbtype"] = "udeb";
573             elif file[-4:] == ".deb":
574                 files[file]["dbtype"] = "deb";
575             else:
576                 reject("%s is neither a .deb or a .udeb." % (file));
577             files[file]["source"] = control.Find("Source", "");
578             if files[file]["source"] == "":
579                 files[file]["source"] = files[file]["package"];
580             # Get the source version
581             source = files[file]["source"];
582             source_version = ""
583             if string.find(source, "(") != -1:
584                 m = utils.re_extract_src_version.match(source)
585                 source = m.group(1)
586                 source_version = m.group(2)
587             if not source_version:
588                 source_version = files[file]["version"];
589             files[file]["source package"] = source;
590             files[file]["source version"] = source_version;
591
592             # Ensure the filename matches the contents of the .deb
593             m = utils.re_isadeb.match(file);
594             #  package name
595             file_package = m.group(1);
596             if files[file]["package"] != file_package:
597                 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"]));
598             epochless_version = utils.re_no_epoch.sub('', control.Find("Version", ""))
599             #  version
600             file_version = m.group(2);
601             if epochless_version != file_version:
602                 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (file, file_version, files[file]["dbtype"], epochless_version));
603             #  architecture
604             file_architecture = m.group(3);
605             if files[file]["architecture"] != file_architecture:
606                 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"]));
607
608             # Check for existent source
609             source_version = files[file]["source version"];
610             source_package = files[file]["source package"];
611             if changes["architecture"].has_key("source"):
612                 if source_version != changes["version"]:
613                     reject("source version (%s) for %s doesn't match changes version %s." % (source_version, file, changes["version"]));
614             else:
615                 # Check in the SQL database
616                 if not Katie.source_exists(source_package, source_version):
617                     # Check in one of the other directories
618                     source_epochless_version = utils.re_no_epoch.sub('', source_version);
619                     dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version);
620                     if os.path.exists(Cnf["Dir::QueueByhandDir"] + '/' + dsc_filename):
621                         files[file]["byhand"] = 1;
622                     elif os.path.exists(Cnf["Dir::QueueNewDir"] + '/' + dsc_filename):
623                         files[file]["new"] = 1;
624                     elif not os.path.exists(Cnf["Dir::QueueAcceptedDir"] + '/' + dsc_filename):
625                         reject("no source found for %s %s (%s)." % (source_package, source_version, file));
626
627         # Checks for a source package...
628         else:
629             m = utils.re_issource.match(file);
630             if m != None:
631                 files[file]["package"] = m.group(1);
632                 files[file]["version"] = m.group(2);
633                 files[file]["type"] = m.group(3);
634
635                 # Ensure the source package name matches the Source filed in the .changes
636                 if changes["source"] != files[file]["package"]:
637                     reject("%s: changes file doesn't say %s for Source" % (file, files[file]["package"]));
638
639                 # Ensure the source version matches the version in the .changes file
640                 if files[file]["type"] == "orig.tar.gz":
641                     changes_version = changes["chopversion2"];
642                 else:
643                     changes_version = changes["chopversion"];
644                 if changes_version != files[file]["version"]:
645                     reject("%s: should be %s according to changes file." % (file, changes_version));
646
647                 # Ensure the .changes lists source in the Architecture field
648                 if not changes["architecture"].has_key("source"):
649                     reject("%s: changes file doesn't list `source' in Architecture field." % (file));
650
651                 # Check the signature of a .dsc file
652                 if files[file]["type"] == "dsc":
653                     dsc["fingerprint"] = check_signature(file);
654
655                 files[file]["architecture"] = "source";
656
657             # Not a binary or source package?  Assume byhand...
658             else:
659                 files[file]["byhand"] = 1;
660                 files[file]["type"] = "byhand";
661
662         # Per-suite file checks
663         files[file]["oldfiles"] = {};
664         for suite in changes["distribution"].keys():
665             # Skip byhand
666             if files[file].has_key("byhand"):
667                 continue
668
669             # Ensure the component is valid for the target suite
670             if Cnf.has_key("Suite:%s::Components" % (suite)) and not Cnf.has_key("Suite::%s::Components::%s" % (suite, files[file]["component"])):
671                 reject("unknown component `%s' for suite `%s'." % (files[file]["component"], suite));
672                 continue
673
674             # See if the package is NEW
675             if not Katie.in_override_p(files[file]["package"], files[file]["component"], suite, files[file].get("dbtype",""), file):
676                 files[file]["new"] = 1;
677
678             if files[file]["type"] == "deb":
679                 reject(Katie.check_binaries_against_db(file, suite));
680
681             # Validate the component
682             component = files[file]["component"];
683             component_id = db_access.get_component_id(component);
684             if component_id == -1:
685                 reject("file '%s' has unknown component '%s'." % (file, component));
686                 continue;
687
688             # Validate the priority
689             if string.find(files[file]["priority"],'/') != -1:
690                 reject("file '%s' has invalid priority '%s' [contains '/']." % (file, files[file]["priority"]));
691
692             # Check the md5sum & size against existing files (if any)
693             location = Cnf["Dir::PoolDir"];
694             files[file]["location id"] = db_access.get_location_id (location, component, archive);
695
696             files[file]["pool name"] = utils.poolify (changes["source"], files[file]["component"]);
697             files_id = db_access.get_files_id(files[file]["pool name"] + file, files[file]["size"], files[file]["md5sum"], files[file]["location id"]);
698             if files_id == -1:
699                 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (file));
700             elif files_id == -2:
701                 reject("md5sum and/or size mismatch on existing copy of %s." % (file));
702             files[file]["files id"] = files_id
703
704             # Check for packages that have moved from one component to another
705             if files[file]["oldfiles"].has_key(suite) and files[file]["oldfiles"][suite]["name"] != files[file]["component"]:
706                 files[file]["othercomponents"] = files[file]["oldfiles"][suite]["name"];
707
708 ###############################################################################
709
710 def check_dsc ():
711     global reprocess;
712
713     for file in files.keys():
714         if files[file]["type"] == "dsc":
715             # Parse the .dsc file
716             try:
717                 dsc.update(utils.parse_changes(file, 1));
718             except utils.cant_open_exc:
719                 # if not -n copy_to_holding() will have done this for us...
720                 if Options["No-Action"]:
721                     reject("can't read .dsc file '%s'." % (file));
722             except utils.changes_parse_error_exc, line:
723                 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
724             except utils.invalid_dsc_format_exc, line:
725                 reject("syntax error in .dsc file '%s', line %s." % (file, line));
726             # Build up the file list of files mentioned by the .dsc
727             try:
728                 dsc_files.update(utils.build_file_list(dsc, 1));
729             except utils.no_files_exc:
730                 reject("no Files: field in .dsc file.");
731                 continue;
732             except utils.changes_parse_error_exc, line:
733                 reject("error parsing .dsc file '%s', can't grok: %s." % (file, line));
734                 continue;
735
736             # Enforce mandatory fields
737             for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
738                 if not dsc.has_key(i):
739                     reject("Missing field `%s' in dsc file." % (i));
740
741             # The dpkg maintainer from hell strikes again! Bumping the
742             # version number of the .dsc breaks extraction by stable's
743             # dpkg-source.
744             if dsc["format"] != "1.0":
745                 reject("""[dpkg-sucks] source package was produced by a broken version
746           of dpkg-dev 1.9.1{3,4}; please rebuild with >= 1.9.15 version
747           installed.""");
748
749             # Ensure the version number in the .dsc matches the version number in the .changes
750             epochless_dsc_version = utils.re_no_epoch.sub('', dsc.get("version"));
751             changes_version = files[file]["version"];
752             if epochless_dsc_version != files[file]["version"]:
753                 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version));
754
755             # Ensure source is newer than existing source in target suites
756             reject(Katie.check_source_against_db(file));
757
758             (reject_msg, is_in_incoming) = Katie.check_dsc_against_db(file);
759             reject(reject_msg);
760             if is_in_incoming:
761                 if not Options["No-Action"]:
762                     copy_to_holding(is_in_incoming);
763                 orig_tar_gz = os.path.basename(is_in_incoming);
764                 files[orig_tar_gz] = {};
765                 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE];
766                 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"];
767                 files[orig_tar_gz]["section"] = files[file]["section"];
768                 files[orig_tar_gz]["priority"] = files[file]["priority"];
769                 files[orig_tar_gz]["component"] = files[file]["component"];
770                 files[orig_tar_gz]["type"] = "orig.tar.gz";
771                 reprocess = 2;
772
773 ################################################################################
774
775 # Some cunning stunt broke dpkg-source in dpkg 1.8{,.1}; detect the
776 # resulting bad source packages and reject them.
777
778 # Even more amusingly the fix in 1.8.1.1 didn't actually fix the
779 # problem just changed the symptoms.
780
781 def check_diff ():
782     for filename in files.keys():
783         if files[filename]["type"] == "diff.gz":
784             file = gzip.GzipFile(filename, 'r');
785             for line in file.readlines():
786                 if re_bad_diff.search(line):
787                     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.");
788                     break;
789
790 ################################################################################
791
792 # FIXME: should be a debian specific check called from a hook
793
794 def check_urgency ():
795     if changes["architecture"].has_key("source"):
796         if not changes.has_key("urgency"):
797             changes["urgency"] = Cnf["Urgency::Default"];
798         if not Cnf.has_key("Urgency::Valid::%s" % changes["urgency"]):
799             reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ");
800             changes["urgency"] = Cnf["Urgency::Default"];
801         changes["urgency"] = lower(changes["urgency"]);
802
803 ################################################################################
804
805 def check_md5sums ():
806     for file in files.keys():
807         try:
808             file_handle = utils.open_file(file);
809         except utils.cant_open_exc:
810             pass;
811         else:
812             if apt_pkg.md5sum(file_handle) != files[file]["md5sum"]:
813                 reject("md5sum check failed for %s." % (file));
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                 #
851                 future_files = tar.future_files.keys();
852                 if future_files:
853                     num_future_files = len(future_files);
854                     future_file = future_files[0];
855                     future_date = tar.future_files[future_file];
856                     reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
857                            % (filename, num_future_files, future_file,
858                               time.ctime(future_date)));
859                 #
860                 ancient_files = tar.ancient_files.keys();
861                 if ancient_files:
862                     num_ancient_files = len(ancient_files);
863                     ancient_file = ancient_files[0];
864                     ancient_date = tar.ancient_files[ancient_file];
865                     reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
866                            % (filename, num_ancient_files, ancient_file,
867                               time.ctime(ancient_date)));
868             except:
869                 reject("%s: timestamp check failed; caught %s" % (filename, sys.exc_type));
870                 raise;
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     file_list = pkg.files.keys();
880     file_list.extend(pkg.dsc_files.keys());
881     file_list.append(pkg.changes_file);
882     for file in file_list:
883         try:
884             last_modified = time.time()-os.path.getmtime(pkg.changes_file);
885             if last_modified < int(Cnf["Dinstall::SkipTime"]):
886                 return 1;
887         except:
888             pass;
889     return 0;
890
891 def action ():
892     # changes["distribution"] may not exist in corner cases
893     # (e.g. unreadable changes files)
894     if not changes.has_key("distribution") or not isinstance(changes["distribution"], DictType):
895         changes["distribution"] = {};
896
897     (summary, short_summary) = Katie.build_summaries();
898
899     byhand = new = "";
900     for file in files.keys():
901         if files[file].has_key("byhand"):
902             byhand = 1
903         elif files[file].has_key("new"):
904             new = 1
905
906     (prompt, answer) = ("", "XXX")
907     if Options["No-Action"] or Options["Automatic"]:
908         answer = 'S'
909
910     if string.find(reject_message, "Rejected") != -1:
911         if upload_too_new():
912             print "SKIP (too new)\n" + reject_message,;
913             prompt = "[S]kip, Quit ?";
914         else:
915             print "REJECT\n" + reject_message,;
916             prompt = "[R]eject, Skip, Quit ?";
917             if Options["Automatic"]:
918                 answer = 'R';
919     elif new:
920         print "NEW to %s\n%s%s" % (string.join(changes["distribution"].keys(), ", "), reject_message, summary),;
921         prompt = "[N]ew, Skip, Quit ?";
922         if Options["Automatic"]:
923             answer = 'N';
924     elif byhand:
925         print "BYHAND\n" + reject_message + summary,;
926         prompt = "[B]yhand, Skip, Quit ?";
927         if Options["Automatic"]:
928             answer = 'B';
929     else:
930         print "ACCEPT\n" + reject_message + summary,;
931         prompt = "[A]ccept, Skip, Quit ?";
932         if Options["Automatic"]:
933             answer = 'A';
934
935     while string.find(prompt, answer) == -1:
936         print prompt,;
937         answer = utils.our_raw_input()
938         m = katie.re_default_answer.match(prompt)
939         if answer == "":
940             answer = m.group(1)
941         answer = string.upper(answer[:1])
942
943     if answer == 'R':
944         os.chdir (pkg.directory);
945         Katie.do_reject(0, reject_message);
946     elif answer == 'A':
947         accept(summary, short_summary);
948     elif answer == 'B':
949         do_byhand(summary);
950     elif answer == 'N':
951         acknowledge_new (summary);
952     elif answer == 'Q':
953         sys.exit(0)
954
955 ################################################################################
956
957 def accept (summary, short_summary):
958     Katie.accept(summary, short_summary);
959
960     # Check for override disparities
961     if not Cnf["Dinstall::Options::No-Mail"]:
962         Katie.check_override();
963
964     # Finally, remove the originals from the unchecked directory
965     os.chdir (pkg.directory);
966     for file in files.keys():
967         os.unlink(file);
968     os.unlink(pkg.changes_file);
969
970 ################################################################################
971
972 def do_byhand (summary):
973     print "Moving to BYHAND holding area."
974
975     Katie.dump_vars(Cnf["Dir::QueueByhandDir"]);
976
977     file_keys = files.keys();
978
979     # Move all the files into the accepted directory
980     utils.move (pkg.changes_file, Cnf["Dir::QueueByhandDir"]);
981     for file in file_keys:
982         utils.move (file, Cnf["Dir::QueueByhandDir"]);
983
984     # Check for override disparities
985     if not Cnf["Dinstall::Options::No-Mail"]:
986         Katie.Subst["__SUMMARY__"] = summary;
987         Katie.check_override();
988
989     # Finally remove the originals.
990     os.chdir (pkg.directory);
991     for file in file_keys:
992         os.unlink(file);
993     os.unlink(pkg.changes_file);
994
995 ################################################################################
996
997 def acknowledge_new (summary):
998     Subst = Katie.Subst;
999
1000     print "Moving to NEW holding area."
1001
1002     Katie.dump_vars(Cnf["Dir::QueueNewDir"]);
1003
1004     file_keys = files.keys();
1005
1006     # Move all the files into the accepted directory
1007     utils.move (pkg.changes_file, Cnf["Dir::QueueNewDir"]);
1008     for file in file_keys:
1009         utils.move (file, Cnf["Dir::QueueNewDir"]);
1010
1011     if not Options["No-Mail"]:
1012         print "Sending new ack.";
1013         Subst["__SUMMARY__"] = summary;
1014         new_ack_message = utils.TemplateSubst(Subst,open(Cnf["Dir::TemplatesDir"]+"/jennifer.new","r").read());
1015         utils.send_mail(new_ack_message,"");
1016
1017     # Finally remove the originals.
1018     os.chdir (pkg.directory);
1019     for file in file_keys:
1020         os.unlink(file);
1021     os.unlink(pkg.changes_file);
1022
1023 ################################################################################
1024
1025 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1026 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1027 # dsccheckdistrib() can find the .orig.tar.gz but it will not have
1028 # processed it during it's checks of -2.  If -1 has been deleted or
1029 # otherwise not checked by jennifer, the .orig.tar.gz will not have been
1030 # checked at all.  To get round this, we force the .orig.tar.gz into
1031 # the .changes structure and reprocess the .changes file.
1032
1033 def process_it (changes_file):
1034     global reprocess, reject_message;
1035
1036     # Reset some globals
1037     reprocess = 1;
1038     Katie.init_vars();
1039     reject_message = "";
1040
1041     # Absolutize the filename to avoid the requirement of being in the
1042     # same directory as the .changes file.
1043     pkg.changes_file = os.path.abspath(changes_file);
1044
1045     # Remember where we are so we can come back after cd-ing into the
1046     # holding directory.
1047     pkg.directory = os.getcwd();
1048
1049     try:
1050         # If this is the Real Thing(tm), copy things into a private
1051         # holding directory first to avoid replacable file races.
1052         if not Options["No-Action"]:
1053             os.chdir(Cnf["Dir::QueueHoldingDir"]);
1054             copy_to_holding(pkg.changes_file);
1055             # Relativize the filename so we use the copy in holding
1056             # rather than the original...
1057             pkg.changes_file = os.path.basename(pkg.changes_file);
1058         changes["fingerprint"] = check_signature(pkg.changes_file);
1059         changes_valid = check_changes();
1060         if changes_valid:
1061             while reprocess:
1062                 check_files();
1063                 check_md5sums();
1064                 check_dsc();
1065                 check_diff();
1066                 check_urgency();
1067                 check_timestamps();
1068         Katie.update_subst(reject_message);
1069         action();
1070     except SystemExit:
1071         raise;
1072     except:
1073         print "ERROR";
1074         traceback.print_exc(file=sys.stdout);
1075         pass;
1076
1077     # Restore previous WD
1078     os.chdir(pkg.directory);
1079
1080 ###############################################################################
1081
1082 def main():
1083     global Cnf, Options, Logger, nmu;
1084
1085     changes_files = init();
1086
1087     if Options["Help"]:
1088         usage();
1089
1090     if Options["Version"]:
1091         print "jennifer %s" % (jennifer_version);
1092         sys.exit(0);
1093
1094     # -n/--dry-run invalidates some other options which would involve things happening
1095     if Options["No-Action"]:
1096         Options["Automatic"] = "";
1097
1098     # Ensure all the arguments we were given are .changes files
1099     for file in changes_files:
1100         if file[-8:] != ".changes":
1101             utils.warn("Ignoring '%s' because it's not a .changes file." % (file));
1102             changes_files.remove(file);
1103
1104     if changes_files == []:
1105         utils.fubar("Need at least one .changes file as an argument.");
1106
1107     # Check that we aren't going to clash with the daily cron job
1108
1109     if not Options["No-Action"] and os.path.exists("%s/Archive_Maintenance_In_Progress" % (Cnf["Dir::RootDir"])) and not Options["No-Lock"]:
1110         utils.fubar("Archive maintenance in progress.  Try again later.");
1111
1112     # Obtain lock if not in no-action mode and initialize the log
1113
1114     if not Options["No-Action"]:
1115         lock_fd = os.open(Cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT);
1116         fcntl.lockf(lock_fd, FCNTL.F_TLOCK);
1117         Logger = Katie.Logger = logging.Logger(Cnf, "jennifer");
1118
1119     # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1120     bcc = "X-Katie: %s" % (jennifer_version);
1121     if Cnf.has_key("Dinstall::Bcc"):
1122         Katie.Subst["__BCC__"] = bcc + "\nBcc: %s" % (Cnf["Dinstall::Bcc"]);
1123     else:
1124         Katie.Subst["__BCC__"] = bcc;
1125
1126
1127     # Sort the .changes files so that we process sourceful ones first
1128     changes_files.sort(utils.changes_compare);
1129
1130     # Process the changes files
1131     for changes_file in changes_files:
1132         print "\n" + changes_file;
1133         try:
1134             process_it (changes_file);
1135         finally:
1136             if not Options["No-Action"]:
1137                 clean_holding();
1138
1139     accept_count = Katie.accept_count;
1140     accept_bytes = Katie.accept_bytes;
1141     if accept_count:
1142         sets = "set"
1143         if accept_count > 1:
1144             sets = "sets"
1145         sys.stderr.write("Accepted %d package %s, %s.\n" % (accept_count, sets, utils.size_type(int(accept_bytes))));
1146         Logger.log(["total",accept_count,accept_bytes]);
1147
1148     if not Options["No-Action"]:
1149         Logger.close();
1150
1151 ################################################################################
1152
1153 if __name__ == '__main__':
1154     main()
1155