4 Checks Debian packages from Incoming
5 @contact: Debian FTP Master <ftpmaster@debian.org>
6 @copyright: 2000, 2001, 2002, 2003, 2004, 2005, 2006 James Troup <james@nocrew.org>
7 @copyright: 2009 Joerg Jaspert <joerg@debian.org>
8 @copyright: 2009 Mark Hymers <mhy@debian.org>
9 @license: GNU General Public License version 2 or later
12 # This program is free software; you can redistribute it and/or modify
13 # it under the terms of the GNU General Public License as published by
14 # the Free Software Foundation; either version 2 of the License, or
15 # (at your option) any later version.
17 # This program is distributed in the hope that it will be useful,
18 # but WITHOUT ANY WARRANTY; without even the implied warranty of
19 # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
20 # GNU General Public License for more details.
22 # You should have received a copy of the GNU General Public License
23 # along with this program; if not, write to the Free Software
24 # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
26 # Originally based on dinstall by Guy Maor <maor@debian.org>
28 ################################################################################
30 # Computer games don't affect kids. I mean if Pacman affected our generation as
31 # kids, we'd all run around in a darkened room munching pills and listening to
35 ################################################################################
50 from debian_bundle import deb822
52 from daklib.dbconn import *
53 from daklib.binary import Binary
54 from daklib import daklog
55 from daklib.queue import *
56 from daklib import utils
57 from daklib.textutils import fix_maintainer
58 from daklib.dak_exceptions import *
59 from daklib.regexes import re_default_answer
60 from daklib.summarystats import SummaryStats
61 from daklib.holding import Holding
62 from daklib.config import Config
66 ################################################################################
69 ################################################################################
75 ###############################################################################
83 Arguments = [('a',"automatic","Dinstall::Options::Automatic"),
84 ('h',"help","Dinstall::Options::Help"),
85 ('n',"no-action","Dinstall::Options::No-Action"),
86 ('p',"no-lock", "Dinstall::Options::No-Lock"),
87 ('s',"no-mail", "Dinstall::Options::No-Mail"),
88 ('d',"directory", "Dinstall::Options::Directory", "HasArg")]
90 for i in ["automatic", "help", "no-action", "no-lock", "no-mail",
91 "override-distribution", "version", "directory"]:
92 cnf["Dinstall::Options::%s" % (i)] = ""
94 changes_files = apt_pkg.ParseCommandLine(cnf.Cnf, Arguments, sys.argv)
95 Options = cnf.SubTree("Dinstall::Options")
100 # If we have a directory flag, use it to find our files
101 if cnf["Dinstall::Options::Directory"] != "":
102 # Note that we clobber the list of files we were given in this case
103 # so warn if the user has done both
104 if len(changes_files) > 0:
105 utils.warn("Directory provided so ignoring files given on command line")
107 changes_files = utils.get_changes_files(cnf["Dinstall::Options::Directory"])
111 ################################################################################
113 def usage (exit_code=0):
114 print """Usage: dinstall [OPTION]... [CHANGES]...
115 -a, --automatic automatic run
116 -h, --help show this help and exit.
117 -n, --no-action don't do anything
118 -p, --no-lock don't check lockfile !! for cron.daily only !!
119 -s, --no-mail don't send any mail
120 -V, --version display the version number and exit"""
123 ################################################################################
125 def reject (str, prefix="Rejected: "):
126 global reject_message
128 reject_message += prefix + str + "\n"
130 ################################################################################
132 def copy_to_holding(filename):
135 base_filename = os.path.basename(filename)
137 dest = Cnf["Dir::Queue::Holding"] + '/' + base_filename
139 fd = os.open(dest, os.O_RDWR|os.O_CREAT|os.O_EXCL, 0640)
142 # Shouldn't happen, but will if, for example, someone lists a
143 # file twice in the .changes.
144 if errno.errorcode[e.errno] == 'EEXIST':
145 reject("%s: already exists in holding area; can not overwrite." % (base_filename))
150 shutil.copy(filename, dest)
152 # In either case (ENOENT or EACCES) we want to remove the
153 # O_CREAT | O_EXCLed ghost file, so add the file to the list
154 # of 'in holding' even if it's not the real file.
155 if errno.errorcode[e.errno] == 'ENOENT':
156 reject("%s: can not copy to holding area: file not found." % (base_filename))
159 elif errno.errorcode[e.errno] == 'EACCES':
160 reject("%s: can not copy to holding area: read permission denied." % (base_filename))
165 in_holding[base_filename] = ""
167 ################################################################################
173 os.chdir(Cnf["Dir::Queue::Holding"])
174 for f in in_holding.keys():
175 if os.path.exists(f):
176 if f.find('/') != -1:
177 utils.fubar("WTF? clean_holding() got a file ('%s') with / in it!" % (f))
183 ################################################################################
186 filename = pkg.changes_file
188 # Parse the .changes field into a dictionary
190 changes.update(utils.parse_changes(filename))
191 except CantOpenError:
192 reject("%s: can't read file." % (filename))
194 except ParseChangesError, line:
195 reject("%s: parse error, can't grok: %s." % (filename, line))
197 except ChangesUnicodeError:
198 reject("%s: changes file not proper utf-8" % (filename))
201 # Parse the Files field from the .changes into another dictionary
203 files.update(utils.build_file_list(changes))
204 except ParseChangesError, line:
205 reject("%s: parse error, can't grok: %s." % (filename, line))
206 except UnknownFormatError, format:
207 reject("%s: unknown format '%s'." % (filename, format))
210 # Check for mandatory fields
211 for i in ("source", "binary", "architecture", "version", "distribution",
212 "maintainer", "files", "changes", "description"):
213 if not changes.has_key(i):
214 reject("%s: Missing mandatory field `%s'." % (filename, i))
215 return 0 # Avoid <undef> errors during later tests
217 # Strip a source version in brackets from the source field
218 if re_strip_srcver.search(changes["source"]):
219 changes["source"] = re_strip_srcver.sub('', changes["source"])
221 # Ensure the source field is a valid package name.
222 if not re_valid_pkg_name.match(changes["source"]):
223 reject("%s: invalid source name '%s'." % (filename, changes["source"]))
225 # Split multi-value fields into a lower-level dictionary
226 for i in ("architecture", "distribution", "binary", "closes"):
227 o = changes.get(i, "")
234 # Fix the Maintainer: field to be RFC822/2047 compatible
236 (changes["maintainer822"], changes["maintainer2047"],
237 changes["maintainername"], changes["maintaineremail"]) = \
238 utils.fix_maintainer (changes["maintainer"])
239 except ParseMaintError, msg:
240 reject("%s: Maintainer field ('%s') failed to parse: %s" \
241 % (filename, changes["maintainer"], msg))
243 # ...likewise for the Changed-By: field if it exists.
245 (changes["changedby822"], changes["changedby2047"],
246 changes["changedbyname"], changes["changedbyemail"]) = \
247 utils.fix_maintainer (changes.get("changed-by", ""))
248 except ParseMaintError, msg:
249 (changes["changedby822"], changes["changedby2047"],
250 changes["changedbyname"], changes["changedbyemail"]) = \
252 reject("%s: Changed-By field ('%s') failed to parse: %s" \
253 % (filename, changes["changed-by"], msg))
255 # Ensure all the values in Closes: are numbers
256 if changes.has_key("closes"):
257 for i in changes["closes"].keys():
258 if re_isanum.match (i) == None:
259 reject("%s: `%s' from Closes field isn't a number." % (filename, i))
262 # chopversion = no epoch; chopversion2 = no epoch and no revision (e.g. for .orig.tar.gz comparison)
263 changes["chopversion"] = re_no_epoch.sub('', changes["version"])
264 changes["chopversion2"] = re_no_revision.sub('', changes["chopversion"])
266 # Check there isn't already a changes file of the same name in one
267 # of the queue directories.
268 base_filename = os.path.basename(filename)
269 for d in [ "Accepted", "Byhand", "Done", "New", "ProposedUpdates", "OldProposedUpdates" ]:
270 if os.path.exists(Cnf["Dir::Queue::%s" % (d) ]+'/'+base_filename):
271 reject("%s: a file with this name already exists in the %s directory." % (base_filename, d))
273 # Check the .changes is non-empty
275 reject("%s: nothing to do (Files field is empty)." % (base_filename))
280 ################################################################################
282 def check_distributions():
283 "Check and map the Distribution field of a .changes file."
285 # Handle suite mappings
286 for m in Cnf.ValueList("SuiteMappings"):
289 if mtype == "map" or mtype == "silent-map":
290 (source, dest) = args[1:3]
291 if changes["distribution"].has_key(source):
292 del changes["distribution"][source]
293 changes["distribution"][dest] = 1
294 if mtype != "silent-map":
295 reject("Mapping %s to %s." % (source, dest),"")
296 if changes.has_key("distribution-version"):
297 if changes["distribution-version"].has_key(source):
298 changes["distribution-version"][source]=dest
299 elif mtype == "map-unreleased":
300 (source, dest) = args[1:3]
301 if changes["distribution"].has_key(source):
302 for arch in changes["architecture"].keys():
303 if arch not in DBConn().get_suite_architectures(source):
304 reject("Mapping %s to %s for unreleased architecture %s." % (source, dest, arch),"")
305 del changes["distribution"][source]
306 changes["distribution"][dest] = 1
308 elif mtype == "ignore":
310 if changes["distribution"].has_key(suite):
311 del changes["distribution"][suite]
312 reject("Ignoring %s as a target suite." % (suite), "Warning: ")
313 elif mtype == "reject":
315 if changes["distribution"].has_key(suite):
316 reject("Uploads to %s are not accepted." % (suite))
317 elif mtype == "propup-version":
318 # give these as "uploaded-to(non-mapped) suites-to-add-when-upload-obsoletes"
320 # changes["distribution-version"] looks like: {'testing': 'testing-proposed-updates'}
321 if changes["distribution"].has_key(args[1]):
322 changes.setdefault("distribution-version", {})
323 for suite in args[2:]: changes["distribution-version"][suite]=suite
325 # Ensure there is (still) a target distribution
326 if changes["distribution"].keys() == []:
327 reject("no valid distribution.")
329 # Ensure target distributions exist
330 for suite in changes["distribution"].keys():
331 if not Cnf.has_key("Suite::%s" % (suite)):
332 reject("Unknown distribution `%s'." % (suite))
334 ################################################################################
339 archive = utils.where_am_i()
340 file_keys = files.keys()
342 # if reprocess is 2 we've already done this and we're checking
343 # things again for the new .orig.tar.gz.
344 # [Yes, I'm fully aware of how disgusting this is]
345 if not Options["No-Action"] and reprocess < 2:
347 os.chdir(pkg.directory)
352 # Check there isn't already a .changes or .dak file of the same name in
353 # the proposed-updates "CopyChanges" or "CopyDotDak" storage directories.
354 # [NB: this check must be done post-suite mapping]
355 base_filename = os.path.basename(pkg.changes_file)
356 dot_dak_filename = base_filename[:-8]+".dak"
357 for suite in changes["distribution"].keys():
358 copychanges = "Suite::%s::CopyChanges" % (suite)
359 if Cnf.has_key(copychanges) and \
360 os.path.exists(Cnf[copychanges]+"/"+base_filename):
361 reject("%s: a file with this name already exists in %s" \
362 % (base_filename, Cnf[copychanges]))
364 copy_dot_dak = "Suite::%s::CopyDotDak" % (suite)
365 if Cnf.has_key(copy_dot_dak) and \
366 os.path.exists(Cnf[copy_dot_dak]+"/"+dot_dak_filename):
367 reject("%s: a file with this name already exists in %s" \
368 % (dot_dak_filename, Cnf[copy_dot_dak]))
374 cursor = DBConn().cursor()
375 # Check for packages that have moved from one component to another
376 # STU: this should probably be changed to not join on architecture, suite tables but instead to used their cached name->id mappings from DBConn
377 DBConn().prepare("moved_pkg_q", """
378 PREPARE moved_pkg_q(text,text,text) AS
379 SELECT c.name FROM binaries b, bin_associations ba, suite s, location l,
380 component c, architecture a, files f
381 WHERE b.package = $1 AND s.suite_name = $2
382 AND (a.arch_string = $3 OR a.arch_string = 'all')
383 AND ba.bin = b.id AND ba.suite = s.id AND b.architecture = a.id
384 AND f.location = l.id
385 AND l.component = c.id
386 AND b.file = f.id""")
389 # Ensure the file does not already exist in one of the accepted directories
390 for d in [ "Accepted", "Byhand", "New", "ProposedUpdates", "OldProposedUpdates", "Embargoed", "Unembargoed" ]:
391 if not Cnf.has_key("Dir::Queue::%s" % (d)): continue
392 if os.path.exists(Cnf["Dir::Queue::%s" % (d) ] + '/' + f):
393 reject("%s file already exists in the %s directory." % (f, d))
394 if not re_taint_free.match(f):
395 reject("!!WARNING!! tainted filename: '%s'." % (f))
396 # Check the file is readable
397 if os.access(f, os.R_OK) == 0:
398 # When running in -n, copy_to_holding() won't have
399 # generated the reject_message, so we need to.
400 if Options["No-Action"]:
401 if os.path.exists(f):
402 reject("Can't read `%s'. [permission denied]" % (f))
404 reject("Can't read `%s'. [file not found]" % (f))
405 files[f]["type"] = "unreadable"
407 # If it's byhand skip remaining checks
408 if files[f]["section"] == "byhand" or files[f]["section"][:4] == "raw-":
409 files[f]["byhand"] = 1
410 files[f]["type"] = "byhand"
411 # Checks for a binary package...
412 elif re_isadeb.match(f):
414 files[f]["type"] = "deb"
416 # Extract package control information
417 deb_file = utils.open_file(f)
419 control = apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file))
421 reject("%s: debExtractControl() raised %s." % (f, sys.exc_type))
423 # Can't continue, none of the checks on control would work.
426 # Check for mandantory "Description:"
429 apt_pkg.ParseSection(apt_inst.debExtractControl(deb_file))["Description"] + '\n'
431 reject("%s: Missing Description in binary package" % (f))
436 # Check for mandatory fields
437 for field in [ "Package", "Architecture", "Version" ]:
438 if control.Find(field) == None:
439 reject("%s: No %s field in control." % (f, field))
443 # Ensure the package name matches the one give in the .changes
444 if not changes["binary"].has_key(control.Find("Package", "")):
445 reject("%s: control file lists name as `%s', which isn't in changes file." % (f, control.Find("Package", "")))
447 # Validate the package field
448 package = control.Find("Package")
449 if not re_valid_pkg_name.match(package):
450 reject("%s: invalid package name '%s'." % (f, package))
452 # Validate the version field
453 version = control.Find("Version")
454 if not re_valid_version.match(version):
455 reject("%s: invalid version number '%s'." % (f, version))
457 # Ensure the architecture of the .deb is one we know about.
458 default_suite = Cnf.get("Dinstall::DefaultSuite", "Unstable")
459 architecture = control.Find("Architecture")
460 upload_suite = changes["distribution"].keys()[0]
461 if architecture not in DBConn().get_suite_architectures(default_suite) and architecture not in DBConn().get_suite_architectures(upload_suite):
462 reject("Unknown architecture '%s'." % (architecture))
464 # Ensure the architecture of the .deb is one of the ones
465 # listed in the .changes.
466 if not changes["architecture"].has_key(architecture):
467 reject("%s: control file lists arch as `%s', which isn't in changes file." % (f, architecture))
469 # Sanity-check the Depends field
470 depends = control.Find("Depends")
472 reject("%s: Depends field is empty." % (f))
474 # Sanity-check the Provides field
475 provides = control.Find("Provides")
477 provide = re_spacestrip.sub('', provides)
479 reject("%s: Provides field is empty." % (f))
480 prov_list = provide.split(",")
481 for prov in prov_list:
482 if not re_valid_pkg_name.match(prov):
483 reject("%s: Invalid Provides field content %s." % (f, prov))
486 # Check the section & priority match those given in the .changes (non-fatal)
487 if control.Find("Section") and files[f]["section"] != "" and files[f]["section"] != control.Find("Section"):
488 reject("%s control file lists section as `%s', but changes file has `%s'." % (f, control.Find("Section", ""), files[f]["section"]), "Warning: ")
489 if control.Find("Priority") and files[f]["priority"] != "" and files[f]["priority"] != control.Find("Priority"):
490 reject("%s control file lists priority as `%s', but changes file has `%s'." % (f, control.Find("Priority", ""), files[f]["priority"]),"Warning: ")
492 files[f]["package"] = package
493 files[f]["architecture"] = architecture
494 files[f]["version"] = version
495 files[f]["maintainer"] = control.Find("Maintainer", "")
496 if f.endswith(".udeb"):
497 files[f]["dbtype"] = "udeb"
498 elif f.endswith(".deb"):
499 files[f]["dbtype"] = "deb"
501 reject("%s is neither a .deb or a .udeb." % (f))
502 files[f]["source"] = control.Find("Source", files[f]["package"])
503 # Get the source version
504 source = files[f]["source"]
506 if source.find("(") != -1:
507 m = re_extract_src_version.match(source)
509 source_version = m.group(2)
510 if not source_version:
511 source_version = files[f]["version"]
512 files[f]["source package"] = source
513 files[f]["source version"] = source_version
515 # Ensure the filename matches the contents of the .deb
516 m = re_isadeb.match(f)
518 file_package = m.group(1)
519 if files[f]["package"] != file_package:
520 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"]))
521 epochless_version = re_no_epoch.sub('', control.Find("Version"))
523 file_version = m.group(2)
524 if epochless_version != file_version:
525 reject("%s: version part of filename (%s) does not match package version in the %s (%s)." % (f, file_version, files[f]["dbtype"], epochless_version))
527 file_architecture = m.group(3)
528 if files[f]["architecture"] != file_architecture:
529 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"]))
531 # Check for existent source
532 source_version = files[f]["source version"]
533 source_package = files[f]["source package"]
534 if changes["architecture"].has_key("source"):
535 if source_version != changes["version"]:
536 reject("source version (%s) for %s doesn't match changes version %s." % (source_version, f, changes["version"]))
538 # Check in the SQL database
539 if not Upload.source_exists(source_package, source_version, changes["distribution"].keys()):
540 # Check in one of the other directories
541 source_epochless_version = re_no_epoch.sub('', source_version)
542 dsc_filename = "%s_%s.dsc" % (source_package, source_epochless_version)
543 if os.path.exists(Cnf["Dir::Queue::Byhand"] + '/' + dsc_filename):
544 files[f]["byhand"] = 1
545 elif os.path.exists(Cnf["Dir::Queue::New"] + '/' + dsc_filename):
549 for myq in ["Accepted", "Embargoed", "Unembargoed", "ProposedUpdates", "OldProposedUpdates"]:
550 if Cnf.has_key("Dir::Queue::%s" % (myq)):
551 if os.path.exists(Cnf["Dir::Queue::"+myq] + '/' + dsc_filename):
554 if not dsc_file_exists:
555 reject("no source found for %s %s (%s)." % (source_package, source_version, f))
556 # Check the version and for file overwrites
557 reject(Upload.check_binary_against_db(f),"")
559 Binary(f, reject).scan_package()
561 # Checks for a source package...
563 m = re_issource.match(f)
566 files[f]["package"] = m.group(1)
567 files[f]["version"] = m.group(2)
568 files[f]["type"] = m.group(3)
570 # Ensure the source package name matches the Source filed in the .changes
571 if changes["source"] != files[f]["package"]:
572 reject("%s: changes file doesn't say %s for Source" % (f, files[f]["package"]))
574 # Ensure the source version matches the version in the .changes file
575 if files[f]["type"] == "orig.tar.gz":
576 changes_version = changes["chopversion2"]
578 changes_version = changes["chopversion"]
579 if changes_version != files[f]["version"]:
580 reject("%s: should be %s according to changes file." % (f, changes_version))
582 # Ensure the .changes lists source in the Architecture field
583 if not changes["architecture"].has_key("source"):
584 reject("%s: changes file doesn't list `source' in Architecture field." % (f))
586 # Check the signature of a .dsc file
587 if files[f]["type"] == "dsc":
588 dsc["fingerprint"] = utils.check_signature(f, reject)
590 files[f]["architecture"] = "source"
592 # Not a binary or source package? Assume byhand...
594 files[f]["byhand"] = 1
595 files[f]["type"] = "byhand"
597 # Per-suite file checks
598 files[f]["oldfiles"] = {}
599 for suite in changes["distribution"].keys():
601 if files[f].has_key("byhand"):
604 # Handle component mappings
605 for m in Cnf.ValueList("ComponentMappings"):
606 (source, dest) = m.split()
607 if files[f]["component"] == source:
608 files[f]["original component"] = source
609 files[f]["component"] = dest
611 # Ensure the component is valid for the target suite
612 if Cnf.has_key("Suite:%s::Components" % (suite)) and \
613 files[f]["component"] not in Cnf.ValueList("Suite::%s::Components" % (suite)):
614 reject("unknown component `%s' for suite `%s'." % (files[f]["component"], suite))
617 # Validate the component
618 component = files[f]["component"]
619 component_id = DBConn().get_component_id(component)
620 if component_id == -1:
621 reject("file '%s' has unknown component '%s'." % (f, component))
624 # See if the package is NEW
625 if not Upload.in_override_p(files[f]["package"], files[f]["component"], suite, files[f].get("dbtype",""), f):
628 # Validate the priority
629 if files[f]["priority"].find('/') != -1:
630 reject("file '%s' has invalid priority '%s' [contains '/']." % (f, files[f]["priority"]))
632 # Determine the location
633 location = Cnf["Dir::Pool"]
634 location_id = DBConn().get_location_id(location, component, archive)
635 if location_id == -1:
636 reject("[INTERNAL ERROR] couldn't determine location (Component: %s, Archive: %s)" % (component, archive))
637 files[f]["location id"] = location_id
639 # Check the md5sum & size against existing files (if any)
640 files[f]["pool name"] = utils.poolify (changes["source"], files[f]["component"])
641 files_id = DBConn().get_files_id(files[f]["pool name"] + f, files[f]["size"], files[f]["md5sum"], files[f]["location id"])
643 reject("INTERNAL ERROR, get_files_id() returned multiple matches for %s." % (f))
645 reject("md5sum and/or size mismatch on existing copy of %s." % (f))
646 files[f]["files id"] = files_id
648 # Check for packages that have moved from one component to another
649 files[f]['suite'] = suite
650 cursor.execute("""EXECUTE moved_pkg_q( %(package)s, %(suite)s, %(architecture)s )""", ( files[f] ) )
651 ql = cursor.fetchone()
653 files[f]["othercomponents"] = ql[0][0]
655 # If the .changes file says it has source, it must have source.
656 if changes["architecture"].has_key("source"):
658 reject("no source found and Architecture line in changes mention source.")
660 if not has_binaries and Cnf.FindB("Dinstall::Reject::NoSourceOnly"):
661 reject("source only uploads are not supported.")
663 ###############################################################################
668 # Ensure there is source to check
669 if not changes["architecture"].has_key("source"):
674 for f in files.keys():
675 if files[f]["type"] == "dsc":
677 reject("can not process a .changes file with multiple .dsc's.")
682 # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
684 reject("source uploads must contain a dsc file")
687 # Parse the .dsc file
689 dsc.update(utils.parse_changes(dsc_filename, signing_rules=1))
690 except CantOpenError:
691 # if not -n copy_to_holding() will have done this for us...
692 if Options["No-Action"]:
693 reject("%s: can't read file." % (dsc_filename))
694 except ParseChangesError, line:
695 reject("%s: parse error, can't grok: %s." % (dsc_filename, line))
696 except InvalidDscError, line:
697 reject("%s: syntax error on line %s." % (dsc_filename, line))
698 except ChangesUnicodeError:
699 reject("%s: dsc file not proper utf-8." % (dsc_filename))
701 # Build up the file list of files mentioned by the .dsc
703 dsc_files.update(utils.build_file_list(dsc, is_a_dsc=1))
704 except NoFilesFieldError:
705 reject("%s: no Files: field." % (dsc_filename))
707 except UnknownFormatError, format:
708 reject("%s: unknown format '%s'." % (dsc_filename, format))
710 except ParseChangesError, line:
711 reject("%s: parse error, can't grok: %s." % (dsc_filename, line))
714 # Enforce mandatory fields
715 for i in ("format", "source", "version", "binary", "maintainer", "architecture", "files"):
716 if not dsc.has_key(i):
717 reject("%s: missing mandatory field `%s'." % (dsc_filename, i))
720 # Validate the source and version fields
721 if not re_valid_pkg_name.match(dsc["source"]):
722 reject("%s: invalid source name '%s'." % (dsc_filename, dsc["source"]))
723 if not re_valid_version.match(dsc["version"]):
724 reject("%s: invalid version number '%s'." % (dsc_filename, dsc["version"]))
726 # Bumping the version number of the .dsc breaks extraction by stable's
727 # dpkg-source. So let's not do that...
728 if dsc["format"] != "1.0":
729 reject("%s: incompatible 'Format' version produced by a broken version of dpkg-dev 1.9.1{3,4}." % (dsc_filename))
731 # Validate the Maintainer field
733 utils.fix_maintainer (dsc["maintainer"])
734 except ParseMaintError, msg:
735 reject("%s: Maintainer field ('%s') failed to parse: %s" \
736 % (dsc_filename, dsc["maintainer"], msg))
738 # Validate the build-depends field(s)
739 for field_name in [ "build-depends", "build-depends-indep" ]:
740 field = dsc.get(field_name)
742 # Check for broken dpkg-dev lossage...
743 if field.startswith("ARRAY"):
744 reject("%s: invalid %s field produced by a broken version of dpkg-dev (1.10.11)" % (dsc_filename, field_name.title()))
746 # Have apt try to parse them...
748 apt_pkg.ParseSrcDepends(field)
750 reject("%s: invalid %s field (can not be parsed by apt)." % (dsc_filename, field_name.title()))
753 # Ensure the version number in the .dsc matches the version number in the .changes
754 epochless_dsc_version = re_no_epoch.sub('', dsc["version"])
755 changes_version = files[dsc_filename]["version"]
756 if epochless_dsc_version != files[dsc_filename]["version"]:
757 reject("version ('%s') in .dsc does not match version ('%s') in .changes." % (epochless_dsc_version, changes_version))
759 # Ensure there is a .tar.gz in the .dsc file
761 for f in dsc_files.keys():
762 m = re_issource.match(f)
764 reject("%s: %s in Files field not recognised as source." % (dsc_filename, f))
767 if ftype == "orig.tar.gz" or ftype == "tar.gz":
770 reject("%s: no .tar.gz or .orig.tar.gz in 'Files' field." % (dsc_filename))
772 # Ensure source is newer than existing source in target suites
773 reject(Upload.check_source_against_db(dsc_filename),"")
775 (reject_msg, is_in_incoming) = Upload.check_dsc_against_db(dsc_filename)
776 reject(reject_msg, "")
778 if not Options["No-Action"]:
779 copy_to_holding(is_in_incoming)
780 orig_tar_gz = os.path.basename(is_in_incoming)
781 files[orig_tar_gz] = {}
782 files[orig_tar_gz]["size"] = os.stat(orig_tar_gz)[stat.ST_SIZE]
783 files[orig_tar_gz]["md5sum"] = dsc_files[orig_tar_gz]["md5sum"]
784 files[orig_tar_gz]["sha1sum"] = dsc_files[orig_tar_gz]["sha1sum"]
785 files[orig_tar_gz]["sha256sum"] = dsc_files[orig_tar_gz]["sha256sum"]
786 files[orig_tar_gz]["section"] = files[dsc_filename]["section"]
787 files[orig_tar_gz]["priority"] = files[dsc_filename]["priority"]
788 files[orig_tar_gz]["component"] = files[dsc_filename]["component"]
789 files[orig_tar_gz]["type"] = "orig.tar.gz"
794 ################################################################################
796 def get_changelog_versions(source_dir):
797 """Extracts a the source package and (optionally) grabs the
798 version history out of debian/changelog for the BTS."""
800 # Find the .dsc (again)
802 for f in files.keys():
803 if files[f]["type"] == "dsc":
806 # If there isn't one, we have nothing to do. (We have reject()ed the upload already)
810 # Create a symlink mirror of the source files in our temporary directory
811 for f in files.keys():
812 m = re_issource.match(f)
814 src = os.path.join(source_dir, f)
815 # If a file is missing for whatever reason, give up.
816 if not os.path.exists(src):
819 if ftype == "orig.tar.gz" and pkg.orig_tar_gz:
821 dest = os.path.join(os.getcwd(), f)
822 os.symlink(src, dest)
824 # If the orig.tar.gz is not a part of the upload, create a symlink to the
827 dest = os.path.join(os.getcwd(), os.path.basename(pkg.orig_tar_gz))
828 os.symlink(pkg.orig_tar_gz, dest)
831 cmd = "dpkg-source -sn -x %s" % (dsc_filename)
832 (result, output) = commands.getstatusoutput(cmd)
834 reject("'dpkg-source -x' failed for %s [return code: %s]." % (dsc_filename, result))
835 reject(utils.prefix_multi_line_string(output, " [dpkg-source output:] "), "")
838 if not Cnf.Find("Dir::Queue::BTSVersionTrack"):
841 # Get the upstream version
842 upstr_version = re_no_epoch.sub('', dsc["version"])
843 if re_strip_revision.search(upstr_version):
844 upstr_version = re_strip_revision.sub('', upstr_version)
846 # Ensure the changelog file exists
847 changelog_filename = "%s-%s/debian/changelog" % (dsc["source"], upstr_version)
848 if not os.path.exists(changelog_filename):
849 reject("%s: debian/changelog not found in extracted source." % (dsc_filename))
852 # Parse the changelog
853 dsc["bts changelog"] = ""
854 changelog_file = utils.open_file(changelog_filename)
855 for line in changelog_file.readlines():
856 m = re_changelog_versions.match(line)
858 dsc["bts changelog"] += line
859 changelog_file.close()
861 # Check we found at least one revision in the changelog
862 if not dsc["bts changelog"]:
863 reject("%s: changelog format not recognised (empty version tree)." % (dsc_filename))
865 ########################################
869 # a) there's no source
870 # or b) reprocess is 2 - we will do this check next time when orig.tar.gz is in 'files'
871 # or c) the orig.tar.gz is MIA
872 if not changes["architecture"].has_key("source") or reprocess == 2 \
873 or pkg.orig_tar_gz == -1:
876 tmpdir = utils.temp_dirname()
878 # Move into the temporary directory
882 # Get the changelog version history
883 get_changelog_versions(cwd)
885 # Move back and cleanup the temporary tree
888 shutil.rmtree(tmpdir)
890 if errno.errorcode[e.errno] != 'EACCES':
891 utils.fubar("%s: couldn't remove tmp dir for source tree." % (dsc["source"]))
893 reject("%s: source tree could not be cleanly removed." % (dsc["source"]))
894 # We probably have u-r or u-w directories so chmod everything
896 cmd = "chmod -R u+rwx %s" % (tmpdir)
897 result = os.system(cmd)
899 utils.fubar("'%s' failed with result %s." % (cmd, result))
900 shutil.rmtree(tmpdir)
902 utils.fubar("%s: couldn't remove tmp dir for source tree." % (dsc["source"]))
904 ################################################################################
906 # FIXME: should be a debian specific check called from a hook
908 def check_urgency ():
909 if changes["architecture"].has_key("source"):
910 if not changes.has_key("urgency"):
911 changes["urgency"] = Cnf["Urgency::Default"]
912 # Urgency may be followed by space & comment (policy 5.6.17)
913 changes["urgency"] = changes["urgency"].split(" ")[0].lower();
914 if changes["urgency"] not in Cnf.ValueList("Urgency::Valid"):
915 reject("%s is not a valid urgency; it will be treated as %s by testing." % (changes["urgency"], Cnf["Urgency::Default"]), "Warning: ")
916 changes["urgency"] = Cnf["Urgency::Default"]
918 ################################################################################
921 utils.check_hash(".changes", files, "md5", apt_pkg.md5sum)
922 utils.check_size(".changes", files)
923 utils.check_hash(".dsc", dsc_files, "md5", apt_pkg.md5sum)
924 utils.check_size(".dsc", dsc_files)
926 # This is stupid API, but it'll have to do for now until
927 # we actually have proper abstraction
928 for m in utils.ensure_hashes(changes, dsc, files, dsc_files):
931 ################################################################################
933 # Sanity check the time stamps of files inside debs.
934 # [Files in the near future cause ugly warnings and extreme time
935 # travel can cause errors on extraction]
937 def check_timestamps():
939 def __init__(self, future_cutoff, past_cutoff):
941 self.future_cutoff = future_cutoff
942 self.past_cutoff = past_cutoff
945 self.future_files = {}
946 self.ancient_files = {}
948 def callback(self, Kind,Name,Link,Mode,UID,GID,Size,MTime,Major,Minor):
949 if MTime > self.future_cutoff:
950 self.future_files[Name] = MTime
951 if MTime < self.past_cutoff:
952 self.ancient_files[Name] = MTime
955 future_cutoff = time.time() + int(Cnf["Dinstall::FutureTimeTravelGrace"])
956 past_cutoff = time.mktime(time.strptime(Cnf["Dinstall::PastCutoffYear"],"%Y"))
957 tar = Tar(future_cutoff, past_cutoff)
958 for filename in files.keys():
959 if files[filename]["type"] == "deb":
962 deb_file = utils.open_file(filename)
963 apt_inst.debExtract(deb_file,tar.callback,"control.tar.gz")
966 apt_inst.debExtract(deb_file,tar.callback,"data.tar.gz")
967 except SystemError, e:
968 # If we can't find a data.tar.gz, look for data.tar.bz2 instead.
969 if not re.search(r"Cannot f[ui]nd chunk data.tar.gz$", str(e)):
972 apt_inst.debExtract(deb_file,tar.callback,"data.tar.bz2")
975 future_files = tar.future_files.keys()
977 num_future_files = len(future_files)
978 future_file = future_files[0]
979 future_date = tar.future_files[future_file]
980 reject("%s: has %s file(s) with a time stamp too far into the future (e.g. %s [%s])."
981 % (filename, num_future_files, future_file,
982 time.ctime(future_date)))
984 ancient_files = tar.ancient_files.keys()
986 num_ancient_files = len(ancient_files)
987 ancient_file = ancient_files[0]
988 ancient_date = tar.ancient_files[ancient_file]
989 reject("%s: has %s file(s) with a time stamp too ancient (e.g. %s [%s])."
990 % (filename, num_ancient_files, ancient_file,
991 time.ctime(ancient_date)))
993 reject("%s: deb contents timestamp check failed [%s: %s]" % (filename, sys.exc_type, sys.exc_value))
995 ################################################################################
997 def lookup_uid_from_fingerprint(fpr):
999 Return the uid,name,isdm for a given gpg fingerprint
1002 @param fpr: a 40 byte GPG fingerprint
1004 @return: (uid, name, isdm)
1006 cursor = DBConn().cursor()
1007 cursor.execute( "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))
1008 qs = cursor.fetchone()
1012 return (None, None, False)
1014 def check_signed_by_key():
1015 """Ensure the .changes is signed by an authorized uploader."""
1017 (uid, uid_name, is_dm) = lookup_uid_from_fingerprint(changes["fingerprint"])
1018 if uid_name == None:
1021 # match claimed name with actual name:
1023 # This is fundamentally broken but need us to refactor how we get
1024 # the UIDs/Fingerprints in order for us to fix it properly
1025 uid, uid_email = changes["fingerprint"], uid
1026 may_nmu, may_sponsor = 1, 1
1027 # XXX by default new dds don't have a fingerprint/uid in the db atm,
1028 # and can't get one in there if we don't allow nmu/sponsorship
1029 elif is_dm is False:
1030 # If is_dm is False, we allow full upload rights
1031 uid_email = "%s@debian.org" % (uid)
1032 may_nmu, may_sponsor = 1, 1
1034 # Assume limited upload rights unless we've discovered otherwise
1036 may_nmu, may_sponsor = 0, 0
1039 if uid_email in [changes["maintaineremail"], changes["changedbyemail"]]:
1041 elif uid_name in [changes["maintainername"], changes["changedbyname"]]:
1043 if uid_name == "": sponsored = 1
1046 if ("source" in changes["architecture"] and
1047 uid_email and utils.is_email_alias(uid_email)):
1048 sponsor_addresses = utils.gpg_get_key_addresses(changes["fingerprint"])
1049 if (changes["maintaineremail"] not in sponsor_addresses and
1050 changes["changedbyemail"] not in sponsor_addresses):
1051 changes["sponsoremail"] = uid_email
1053 if sponsored and not may_sponsor:
1054 reject("%s is not authorised to sponsor uploads" % (uid))
1056 cursor = DBConn().cursor()
1057 if not sponsored and not may_nmu:
1059 cursor.execute( "SELECT s.id, s.version FROM source s JOIN src_associations sa ON (s.id = sa.source) WHERE s.source = %(source)s AND s.dm_upload_allowed = 'yes'", changes )
1061 highest_sid, highest_version = None, None
1063 should_reject = True
1065 si = cursor.fetchone()
1069 if highest_version == None or apt_pkg.VersionCompare(si[1], highest_version) == 1:
1071 highest_version = si[1]
1073 if highest_sid == None:
1074 reject("Source package %s does not have 'DM-Upload-Allowed: yes' in its most recent version" % changes["source"])
1077 cursor.execute("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))
1080 m = cursor.fetchone()
1084 (rfc822, rfc2047, name, email) = utils.fix_maintainer(m[0])
1085 if email == uid_email or name == uid_name:
1089 if should_reject == True:
1090 reject("%s is not in Maintainer or Uploaders of source package %s" % (uid, changes["source"]))
1092 for b in changes["binary"].keys():
1093 for suite in changes["distribution"].keys():
1094 suite_id = DBConn().get_suite_id(suite)
1096 cursor.execute("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 = %(package)s AND ba.suite = %(suite)s" , {'package':b, 'suite':suite_id} )
1098 s = cursor.fetchone()
1102 if s[0] != changes["source"]:
1103 reject("%s may not hijack %s from source package %s in suite %s" % (uid, b, s, suite))
1105 for f in files.keys():
1106 if files[f].has_key("byhand"):
1107 reject("%s may not upload BYHAND file %s" % (uid, f))
1108 if files[f].has_key("new"):
1109 reject("%s may not upload NEW file %s" % (uid, f))
1112 ################################################################################
1113 ################################################################################
1115 # If any file of an upload has a recent mtime then chances are good
1116 # the file is still being uploaded.
1118 def upload_too_new():
1120 # Move back to the original directory to get accurate time stamps
1122 os.chdir(pkg.directory)
1123 file_list = pkg.files.keys()
1124 file_list.extend(pkg.dsc_files.keys())
1125 file_list.append(pkg.changes_file)
1128 last_modified = time.time()-os.path.getmtime(f)
1129 if last_modified < int(Cnf["Dinstall::SkipTime"]):
1137 ################################################################################
1140 # changes["distribution"] may not exist in corner cases
1141 # (e.g. unreadable changes files)
1142 if not u.pkg.changes.has_key("distribution") or not isinstance(u.pkg.changes["distribution"], DictType):
1143 u.pkg.changes["distribution"] = {}
1145 (summary, short_summary) = u.build_summaries()
1147 # q-unapproved hax0ring
1149 "New": { "is": is_new, "process": acknowledge_new },
1150 "Autobyhand" : { "is" : is_autobyhand, "process": do_autobyhand },
1151 "Byhand" : { "is": is_byhand, "process": do_byhand },
1152 "OldStableUpdate" : { "is": is_oldstableupdate,
1153 "process": do_oldstableupdate },
1154 "StableUpdate" : { "is": is_stableupdate, "process": do_stableupdate },
1155 "Unembargo" : { "is": is_unembargo, "process": queue_unembargo },
1156 "Embargo" : { "is": is_embargo, "process": queue_embargo },
1159 queues = [ "New", "Autobyhand", "Byhand" ]
1160 if cnf.FindB("Dinstall::SecurityQueueHandling"):
1161 queues += [ "Unembargo", "Embargo" ]
1163 queues += [ "OldStableUpdate", "StableUpdate" ]
1165 (prompt, answer) = ("", "XXX")
1166 if Options["No-Action"] or Options["Automatic"]:
1171 pi = u.package_info()
1173 if len(u.rejects) > 0:
1174 if u.upload_too_new():
1175 print "SKIP (too new)\n" + pi,
1176 prompt = "[S]kip, Quit ?"
1178 print "REJECT\n" + pi
1179 prompt = "[R]eject, Skip, Quit ?"
1180 if Options["Automatic"]:
1185 if queue_info[q]["is"](u):
1189 print "%s for %s\n%s%s" % ( qu.upper(), ", ".join(u.pkg.changes["distribution"].keys()), pi, summary)
1190 queuekey = qu[0].upper()
1191 if queuekey in "RQSA":
1193 prompt = "[D]ivert, Skip, Quit ?"
1195 prompt = "[%s]%s, Skip, Quit ?" % (queuekey, qu[1:].lower())
1196 if Options["Automatic"]:
1199 print "ACCEPT\n" + pi + summary,
1200 prompt = "[A]ccept, Skip, Quit ?"
1201 if Options["Automatic"]:
1204 while prompt.find(answer) == -1:
1205 answer = utils.our_raw_input(prompt)
1206 m = re_default_answer.match(prompt)
1209 answer = answer[:1].upper()
1212 os.chdir(u.pkg.directory)
1215 u.accept(summary, short_summary)
1218 elif answer == queuekey:
1219 queue_info[qu]["process"](u, summary, short_summary)
1224 ################################################################################
1226 def package_to_suite(u, suite):
1227 if not u.pkg.changes["distribution"].has_key(suite):
1232 if not u.pkg.changes["architecture"].has_key("source"):
1233 s = DBConn().session()
1234 q = s.query(SrcAssociation.sa_id)
1235 q = q.join(Suite).filter_by(suite_name=suite)
1236 q = q.join(DBSource).filter_by(source=u.pkg.changes['source'])
1237 q = q.filter_by(version=u.pkg.changes['version']).limit(1)
1246 def package_to_queue(u, summary, short_summary, queue, perms=0660, build=True, announce=None):
1248 dir = cnf["Dir::Queue::%s" % queue]
1250 print "Moving to %s holding area" % queue.upper()
1251 Logger.log(["Moving to %s" % queue, u.pkg.changes_file])
1253 u.pkg.write_dot_dak(dir)
1254 u.move_to_dir(dir, perms=perms)
1256 get_queue(queue.lower()).autobuild_upload(u.pkg, dir)
1258 # Check for override disparities
1261 # Send accept mail, announce to lists and close bugs
1262 if announce and not cnf["Dinstall::Options::No-Mail"]:
1263 template = os.path.join(cnf["Dir::Templates"], announce)
1265 u.Subst["__SUITE__"] = ""
1266 mail_message = utils.TemplateSubst(u.Subst, template)
1267 utils.send_mail(mail_message)
1268 u.announce(short_summary, True)
1270 ################################################################################
1272 def is_unembargo(u):
1273 session = DBConn().session()
1276 q = session.execute("SELECT package FROM disembargo WHERE package = :source AND version = :version", u.pkg.changes)
1281 oldcwd = os.getcwd()
1282 os.chdir(cnf["Dir::Queue::Disembargo"])
1283 disdir = os.getcwd()
1288 if u.pkg.directory == disdir:
1289 if u.pkg.changes["architecture"].has_key("source"):
1290 if not Options["No-Action"]:
1291 session.execute("INSERT INTO disembargo (package, version) VALUES (:package, :version)", u.pkg.changes)
1300 def queue_unembargo(u, summary, short_summary):
1301 return package_to_queue(u, summary, short_summary, "Unembargoed",
1302 perms=0660, build=True, announce='process-unchecked.accepted')
1304 ################################################################################
1307 # if embargoed queues are enabled always embargo
1310 def queue_embargo(u, summary, short_summary):
1311 return package_to_queue(u, summary, short_summary, "Unembargoed",
1312 perms=0660, build=True, announce='process-unchecked.accepted')
1314 ################################################################################
1316 def is_stableupdate(u):
1317 return package_to_suite(u, 'proposed-updates')
1319 def do_stableupdate(u, summary, short_summary):
1320 return package_to_queue(u, summary, short_summary, "ProposedUpdates",
1321 perms=0664, build=False, announce=None)
1323 ################################################################################
1325 def is_oldstableupdate(u):
1326 return package_to_suite(u, 'oldstable-proposed-updates')
1328 def do_oldstableupdate(u, summary, short_summary):
1329 return package_to_queue(u, summary, short_summary, "OldProposedUpdates",
1330 perms=0664, build=False, announce=None)
1332 ################################################################################
1334 def is_autobyhand(u):
1339 for f in u.pkg.files.keys():
1340 if u.pkg.files[f].has_key("byhand"):
1343 # filename is of form "PKG_VER_ARCH.EXT" where PKG, VER and ARCH
1344 # don't contain underscores, and ARCH doesn't contain dots.
1345 # further VER matches the .changes Version:, and ARCH should be in
1346 # the .changes Architecture: list.
1347 if f.count("_") < 2:
1351 (pckg, ver, archext) = f.split("_", 2)
1352 if archext.count(".") < 1 or u.pkg.changes["version"] != ver:
1356 ABH = cnf.SubTree("AutomaticByHandPackages")
1357 if not ABH.has_key(pckg) or \
1358 ABH["%s::Source" % (pckg)] != u.pkg.changes["source"]:
1359 print "not match %s %s" % (pckg, u.pkg.changes["source"])
1363 (arch, ext) = archext.split(".", 1)
1364 if arch not in u.pkg.changes["architecture"]:
1368 u.pkg.files[f]["byhand-arch"] = arch
1369 u.pkg.files[f]["byhand-script"] = ABH["%s::Script" % (pckg)]
1371 return any_auto and all_auto
1373 def do_autobyhand(u, summary, short_summary):
1374 print "Attempting AUTOBYHAND."
1376 for f, entry in u.pkg.files.items():
1379 if not entry.has_key("byhand"):
1382 if not entry.has_key("byhand-script"):
1386 os.system("ls -l %s" % byhandfile)
1388 result = os.system("%s %s %s %s %s" % (
1389 entry["byhand-script"],
1391 u.pkg.changes["version"],
1392 entry["byhand-arch"],
1393 os.path.abspath(u.pkg.changes_file)))
1396 os.unlink(byhandfile)
1399 print "Error processing %s, left as byhand." % (f)
1403 do_byhand(u, summary, short_summary)
1405 u.accept(summary, short_summary)
1407 # XXX: We seem to be missing a u.remove() here
1408 # This might explain why we get byhand leftovers in unchecked - mhy
1410 ################################################################################
1413 for f in u.pkg.files.keys():
1414 if u.pkg.files[f].has_key("byhand"):
1418 def do_byhand(u, summary, short_summary):
1419 return package_to_queue(u, summary, short_summary, "Byhand",
1420 perms=0660, build=False, announce=None)
1422 ################################################################################
1425 for f in u.pkg.files.keys():
1426 if u.pkg.files[f].has_key("new"):
1430 def acknowledge_new(u, summary, short_summary):
1433 print "Moving to NEW holding area."
1434 Logger.log(["Moving to new", u.pkg.changes_file])
1436 u.pkg.write_dot_dak(cnf["Dir::Queue::New"])
1437 u.move_to_dir(cnf["Dir::Queue::New"], perms=0640, changesperms=0644)
1439 if not Options["No-Mail"]:
1440 print "Sending new ack."
1441 template = os.path.join(cnf["Dir::Templates"], 'process-unchecked.new')
1442 u.Subst["__SUMMARY__"] = summary
1443 new_ack_message = utils.TemplateSubst(u.Subst, template)
1444 utils.send_mail(new_ack_message)
1446 ################################################################################
1448 # reprocess is necessary for the case of foo_1.2-1 and foo_1.2-2 in
1449 # Incoming. -1 will reference the .orig.tar.gz, but -2 will not.
1450 # Upload.check_dsc_against_db() can find the .orig.tar.gz but it will
1451 # not have processed it during it's checks of -2. If -1 has been
1452 # deleted or otherwise not checked by 'dak process-unchecked', the
1453 # .orig.tar.gz will not have been checked at all. To get round this,
1454 # we force the .orig.tar.gz into the .changes structure and reprocess
1455 # the .changes file.
1457 def process_it(changes_file):
1465 u.pkg.changes_file = changes_file
1466 u.pkg.directory = os.getcwd()
1468 origchanges = os.path.join(u.pkg.directory, u.pkg.changes_file)
1470 # Some defaults in case we can't fully process the .changes file
1471 u.pkg.changes["maintainer2047"] = cnf["Dinstall::MyEmailAddress"]
1472 u.pkg.changes["changedby2047"] = cnf["Dinstall::MyEmailAddress"]
1474 # debian-{devel-,}-changes@lists.debian.org toggles writes access based on this header
1475 bcc = "X-DAK: dak process-unchecked\nX-Katie: $Revision: 1.65 $"
1476 if cnf.has_key("Dinstall::Bcc"):
1477 u.Subst["__BCC__"] = bcc + "\nBcc: %s" % (cnf["Dinstall::Bcc"])
1479 u.Subst["__BCC__"] = bcc
1481 # Remember where we are so we can come back after cd-ing into the
1482 # holding directory. TODO: Fix this stupid hack
1483 u.prevdir = os.getcwd()
1485 # TODO: Figure out something better for this (or whether it's even
1486 # necessary - it seems to have been for use when we were
1487 # still doing the is_unchecked check; reprocess = 2)
1491 # If this is the Real Thing(tm), copy things into a private
1492 # holding directory first to avoid replacable file races.
1493 if not Options["No-Action"]:
1494 os.chdir(cnf["Dir::Queue::Holding"])
1496 # Absolutize the filename to avoid the requirement of being in the
1497 # same directory as the .changes file.
1498 holding.copy_to_holding(origchanges)
1500 # Relativize the filename so we use the copy in holding
1501 # rather than the original...
1502 changespath = os.path.basename(u.pkg.changes_file)
1504 (u.pkg.changes["fingerprint"], rejects) = utils.check_signature(changespath)
1506 if u.pkg.changes["fingerprint"]:
1507 valid_changes_p = u.load_changes(changespath)
1509 valid_changes_p = False
1510 u.rejects.extend(rejects)
1514 u.check_distributions()
1515 u.check_files(not Options["No-Action"])
1516 valid_dsc_p = u.check_dsc(not Options["No-Action"])
1521 u.check_timestamps()
1522 u.check_signed_by_key()
1531 traceback.print_exc(file=sys.stderr)
1533 # Restore previous WD
1536 ###############################################################################
1539 global Options, Logger
1542 changes_files = init()
1544 # -n/--dry-run invalidates some other options which would involve things happening
1545 if Options["No-Action"]:
1546 Options["Automatic"] = ""
1548 # Initialize our Holding singleton
1551 # Ensure all the arguments we were given are .changes files
1552 for f in changes_files:
1553 if not f.endswith(".changes"):
1554 utils.warn("Ignoring '%s' because it's not a .changes file." % (f))
1555 changes_files.remove(f)
1557 if changes_files == []:
1558 if cnf["Dinstall::Options::Directory"] == "":
1559 utils.fubar("Need at least one .changes file as an argument.")
1563 # Check that we aren't going to clash with the daily cron job
1564 if not Options["No-Action"] and os.path.exists("%s/daily.lock" % (cnf["Dir::Lock"])) and not Options["No-Lock"]:
1565 utils.fubar("Archive maintenance in progress. Try again later.")
1567 # Obtain lock if not in no-action mode and initialize the log
1568 if not Options["No-Action"]:
1569 lock_fd = os.open(cnf["Dinstall::LockFile"], os.O_RDWR | os.O_CREAT)
1571 fcntl.lockf(lock_fd, fcntl.LOCK_EX | fcntl.LOCK_NB)
1573 if errno.errorcode[e.errno] == 'EACCES' or errno.errorcode[e.errno] == 'EAGAIN':
1574 utils.fubar("Couldn't obtain lock; assuming another 'dak process-unchecked' is already running.")
1577 Logger = daklog.Logger(cnf, "process-unchecked")
1579 # Sort the .changes files so that we process sourceful ones first
1580 changes_files.sort(utils.changes_compare)
1582 # Process the changes files
1583 for changes_file in changes_files:
1584 print "\n" + changes_file
1586 process_it (changes_file)
1588 if not Options["No-Action"]:
1591 accept_count = SummaryStats().accept_count
1592 accept_bytes = SummaryStats().accept_bytes
1596 if accept_count > 1:
1598 print "Accepted %d package %s, %s." % (accept_count, sets, utils.size_type(int(accept_bytes)))
1599 Logger.log(["total",accept_count,accept_bytes])
1601 if not Options["No-Action"]:
1604 ################################################################################
1606 if __name__ == '__main__':