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