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