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