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