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