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