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