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