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