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