checks.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036
  1. # Copyright (C) 2012, Ansgar Burchardt <ansgar@debian.org>
  2. #
  3. # Parts based on code that is
  4. # Copyright (C) 2001-2006, James Troup <james@nocrew.org>
  5. # Copyright (C) 2009-2010, Joerg Jaspert <joerg@debian.org>
  6. #
  7. # This program is free software; you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation; either version 2 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This program is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License along
  18. # with this program; if not, write to the Free Software Foundation, Inc.,
  19. # 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
  20. """module provided pre-acceptance tests
  21. Please read the documentation for the L{Check} class for the interface.
  22. """
  23. from __future__ import print_function
  24. from daklib.config import Config
  25. import daklib.daksubprocess
  26. from daklib.dbconn import *
  27. import daklib.dbconn as dbconn
  28. from daklib.regexes import *
  29. from daklib.textutils import fix_maintainer, ParseMaintError
  30. import daklib.lintian as lintian
  31. import daklib.utils as utils
  32. import daklib.upload
  33. import apt_inst
  34. import apt_pkg
  35. from apt_pkg import version_compare
  36. import datetime
  37. import os
  38. import subprocess
  39. import textwrap
  40. import time
  41. import yaml
  42. def check_fields_for_valid_utf8(filename, control):
  43. """Check all fields of a control file for valid UTF-8"""
  44. for field in control.keys():
  45. try:
  46. field.decode('utf-8')
  47. control[field].decode('utf-8')
  48. except UnicodeDecodeError:
  49. raise Reject('{0}: The {1} field is not valid UTF-8'.format(filename, field))
  50. class Reject(Exception):
  51. """exception raised by failing checks"""
  52. pass
  53. class RejectExternalFilesMismatch(Reject):
  54. """exception raised by failing the external hashes check"""
  55. def __str__(self):
  56. return "'%s' has mismatching %s from the external files db ('%s' [current] vs '%s' [external])" % self.args[:4]
  57. class RejectACL(Reject):
  58. """exception raise by failing ACL checks"""
  59. def __init__(self, acl, reason):
  60. self.acl = acl
  61. self.reason = reason
  62. def __str__(self):
  63. return "ACL {0}: {1}".format(self.acl.name, self.reason)
  64. class Check(object):
  65. """base class for checks
  66. checks are called by L{daklib.archive.ArchiveUpload}. Failing tests should
  67. raise a L{daklib.checks.Reject} exception including a human-readable
  68. description why the upload should be rejected.
  69. """
  70. def check(self, upload):
  71. """do checks
  72. @type upload: L{daklib.archive.ArchiveUpload}
  73. @param upload: upload to check
  74. @raise daklib.checks.Reject: upload should be rejected
  75. """
  76. raise NotImplemented
  77. def per_suite_check(self, upload, suite):
  78. """do per-suite checks
  79. @type upload: L{daklib.archive.ArchiveUpload}
  80. @param upload: upload to check
  81. @type suite: L{daklib.dbconn.Suite}
  82. @param suite: suite to check
  83. @raise daklib.checks.Reject: upload should be rejected
  84. """
  85. raise NotImplemented
  86. @property
  87. def forcable(self):
  88. """allow to force ignore failing test
  89. C{True} if it is acceptable to force ignoring a failing test,
  90. C{False} otherwise
  91. """
  92. return False
  93. class SignatureAndHashesCheck(Check):
  94. def check_replay(self, upload):
  95. # Use private session as we want to remember having seen the .changes
  96. # in all cases.
  97. session = upload.session
  98. history = SignatureHistory.from_signed_file(upload.changes)
  99. r = history.query(session)
  100. if r is not None:
  101. raise Reject('Signature for changes file was already seen at {0}.\nPlease refresh the signature of the changes file if you want to upload it again.'.format(r.seen))
  102. return True
  103. """Check signature of changes and dsc file (if included in upload)
  104. Make sure the signature is valid and done by a known user.
  105. """
  106. def check(self, upload):
  107. allow_source_untrusted_sig_keys = Config().value_list('Dinstall::AllowSourceUntrustedSigKeys')
  108. changes = upload.changes
  109. if not changes.valid_signature:
  110. raise Reject("Signature for .changes not valid.")
  111. self.check_replay(upload)
  112. self._check_hashes(upload, changes.filename, changes.files.itervalues())
  113. source = None
  114. try:
  115. source = changes.source
  116. except Exception as e:
  117. raise Reject("Invalid dsc file: {0}".format(e))
  118. if source is not None:
  119. if changes.primary_fingerprint not in allow_source_untrusted_sig_keys:
  120. if not source.valid_signature:
  121. raise Reject("Signature for .dsc not valid.")
  122. if source.primary_fingerprint != changes.primary_fingerprint:
  123. raise Reject(".changes and .dsc not signed by the same key.")
  124. self._check_hashes(upload, source.filename, source.files.itervalues())
  125. if upload.fingerprint is None or upload.fingerprint.uid is None:
  126. raise Reject(".changes signed by unknown key.")
  127. """Make sure hashes match existing files
  128. @type upload: L{daklib.archive.ArchiveUpload}
  129. @param upload: upload we are processing
  130. @type filename: str
  131. @param filename: name of the file the expected hash values are taken from
  132. @type files: sequence of L{daklib.upload.HashedFile}
  133. @param files: files to check the hashes for
  134. """
  135. def _check_hashes(self, upload, filename, files):
  136. try:
  137. for f in files:
  138. f.check(upload.directory)
  139. except daklib.upload.FileDoesNotExist as e:
  140. raise Reject('{0}: {1}\n'
  141. 'Perhaps you need to include the file in your upload?'
  142. .format(filename, unicode(e)))
  143. except daklib.upload.UploadException as e:
  144. raise Reject('{0}: {1}'.format(filename, unicode(e)))
  145. class WeakSignatureCheck(Check):
  146. """Check that .changes and .dsc are not signed using a weak algorithm"""
  147. def check(self, upload):
  148. changes = upload.changes
  149. if changes.weak_signature:
  150. raise Reject("The .changes was signed using a weak algorithm (such as SHA-1)")
  151. source = changes.source
  152. if source is not None:
  153. if source.weak_signature:
  154. raise Reject("The source package was signed using a weak algorithm (such as SHA-1)")
  155. return True
  156. class SignatureTimestampCheck(Check):
  157. """Check timestamp of .changes signature"""
  158. def check(self, upload):
  159. changes = upload.changes
  160. now = datetime.datetime.utcnow()
  161. timestamp = changes.signature_timestamp
  162. age = now - timestamp
  163. age_max = datetime.timedelta(days=365)
  164. age_min = datetime.timedelta(days=-7)
  165. if age > age_max:
  166. raise Reject('{0}: Signature from {1} is too old (maximum age is {2} days)'.format(changes.filename, timestamp, age_max.days))
  167. if age < age_min:
  168. raise Reject('{0}: Signature from {1} is too far in the future (tolerance is {2} days)'.format(changes.filename, timestamp, abs(age_min.days)))
  169. return True
  170. class ChangesCheck(Check):
  171. """Check changes file for syntax errors."""
  172. def check(self, upload):
  173. changes = upload.changes
  174. control = changes.changes
  175. fn = changes.filename
  176. for field in ('Distribution', 'Source', 'Architecture', 'Version', 'Maintainer', 'Files', 'Changes'):
  177. if field not in control:
  178. raise Reject('{0}: misses mandatory field {1}'.format(fn, field))
  179. if len(changes.binaries) > 0:
  180. for field in ('Binary', 'Description'):
  181. if field not in control:
  182. raise Reject('{0}: binary upload requires {1} field'.format(fn, field))
  183. check_fields_for_valid_utf8(fn, control)
  184. source_match = re_field_source.match(control['Source'])
  185. if not source_match:
  186. raise Reject('{0}: Invalid Source field'.format(fn))
  187. version_match = re_field_version.match(control['Version'])
  188. if not version_match:
  189. raise Reject('{0}: Invalid Version field'.format(fn))
  190. version_without_epoch = version_match.group('without_epoch')
  191. match = re_file_changes.match(fn)
  192. if not match:
  193. raise Reject('{0}: Does not match re_file_changes'.format(fn))
  194. if match.group('package') != source_match.group('package'):
  195. raise Reject('{0}: Filename does not match Source field'.format(fn))
  196. if match.group('version') != version_without_epoch:
  197. raise Reject('{0}: Filename does not match Version field'.format(fn))
  198. for bn in changes.binary_names:
  199. if not re_field_package.match(bn):
  200. raise Reject('{0}: Invalid binary package name {1}'.format(fn, bn))
  201. if 'source' in changes.architectures and changes.source is None:
  202. raise Reject("Changes has architecture source, but no source found.")
  203. if changes.source is not None and 'source' not in changes.architectures:
  204. raise Reject("Upload includes source, but changes does not say so.")
  205. try:
  206. fix_maintainer(changes.changes['Maintainer'])
  207. except ParseMaintError as e:
  208. raise Reject('{0}: Failed to parse Maintainer field: {1}'.format(changes.filename, e))
  209. try:
  210. changed_by = changes.changes.get('Changed-By')
  211. if changed_by is not None:
  212. fix_maintainer(changed_by)
  213. except ParseMaintError as e:
  214. raise Reject('{0}: Failed to parse Changed-By field: {1}'.format(changes.filename, e))
  215. try:
  216. changes.byhand_files
  217. except daklib.upload.InvalidChangesException as e:
  218. raise Reject('{0}'.format(e))
  219. if len(changes.files) == 0:
  220. raise Reject("Changes includes no files.")
  221. for bugnum in changes.closed_bugs:
  222. if not re_isanum.match(bugnum):
  223. raise Reject('{0}: "{1}" in Closes field is not a number'.format(changes.filename, bugnum))
  224. return True
  225. class SuffixCheck(Check):
  226. """Checks suffix of .changes and .buildinfo files.
  227. buildd uploads will include _${arch}.changes and _${arch}.buildinfo, so such endings
  228. should be reserved for uploads including binaries for ${arch} to avoid conflicts
  229. (for example in policy queues where dak stores the .changes and .buildinfo for later
  230. processing)
  231. """
  232. def check(self, upload):
  233. session = upload.session
  234. changes = upload.changes
  235. suffixes = []
  236. changes_match = re_file_changes.match(changes.filename)
  237. assert(changes_match)
  238. suffixes.append((changes.filename, changes_match.group('suffix')))
  239. for bi in changes.buildinfo_files:
  240. bi_match = re_file_buildinfo.match(bi.filename)
  241. assert(bi_match)
  242. suffixes.append((bi.filename, bi_match.group('suffix')))
  243. for fn, suffix in suffixes:
  244. if suffix in changes.architectures:
  245. continue
  246. if session.query(Architecture).filter_by(arch_string=suffix).first():
  247. raise Reject("The upload includes '{}' whose filename includes the architecture name {}, but does not include binaries for {}. It is rejected to avoid filename conflicts with later buildd uploads.".format(fn, suffix, suffix))
  248. return True
  249. class ExternalHashesCheck(Check):
  250. """Checks hashes in .changes and .dsc against an external database."""
  251. def check_single(self, session, f):
  252. q = session.execute("SELECT size, md5sum, sha1sum, sha256sum FROM external_files WHERE filename LIKE :pattern", {'pattern': '%/{}'.format(f.filename)})
  253. (ext_size, ext_md5sum, ext_sha1sum, ext_sha256sum) = q.fetchone() or (None, None, None, None)
  254. if not ext_size:
  255. return
  256. if ext_size != f.size:
  257. raise RejectExternalFilesMismatch(f.filename, 'size', f.size, ext_size)
  258. if ext_md5sum != f.md5sum:
  259. raise RejectExternalFilesMismatch(f.filename, 'md5sum', f.md5sum, ext_md5sum)
  260. if ext_sha1sum != f.sha1sum:
  261. raise RejectExternalFilesMismatch(f.filename, 'sha1sum', f.sha1sum, ext_sha1sum)
  262. if ext_sha256sum != f.sha256sum:
  263. raise RejectExternalFilesMismatch(f.filename, 'sha256sum', f.sha256sum, ext_sha256sum)
  264. def check(self, upload):
  265. cnf = Config()
  266. if not cnf.use_extfiles:
  267. return
  268. session = upload.session
  269. changes = upload.changes
  270. for f in changes.files.itervalues():
  271. self.check_single(session, f)
  272. source = changes.source
  273. if source is not None:
  274. for f in source.files.itervalues():
  275. self.check_single(session, f)
  276. class BinaryCheck(Check):
  277. """Check binary packages for syntax errors."""
  278. def check(self, upload):
  279. debug_deb_name_postfix = "-dbgsym"
  280. # XXX: Handle dynamic debug section name here
  281. self._architectures = set()
  282. for binary in upload.changes.binaries:
  283. self.check_binary(upload, binary)
  284. for arch in upload.changes.architectures:
  285. if arch == 'source':
  286. continue
  287. if arch not in self._architectures:
  288. raise Reject('{}: Architecture field includes {}, but no binary packages for {} are included in the upload'.format(upload.changes.filename, arch, arch))
  289. binaries = {binary.control['Package']: binary
  290. for binary in upload.changes.binaries}
  291. for name, binary in binaries.items():
  292. if name in upload.changes.binary_names:
  293. # Package is listed in Binary field. Everything is good.
  294. pass
  295. elif daklib.utils.is_in_debug_section(binary.control):
  296. # If we have a binary package in the debug section, we
  297. # can allow it to not be present in the Binary field
  298. # in the .changes file, so long as its name (without
  299. # -dbgsym) is present in the Binary list.
  300. if not name.endswith(debug_deb_name_postfix):
  301. raise Reject('Package {0} is in the debug section, but '
  302. 'does not end in {1}.'.format(name, debug_deb_name_postfix))
  303. # Right, so, it's named properly, let's check that
  304. # the corresponding package is in the Binary list
  305. origin_package_name = name[:-len(debug_deb_name_postfix)]
  306. if origin_package_name not in upload.changes.binary_names:
  307. raise Reject(
  308. "Debug package {debug}'s corresponding binary package "
  309. "{origin} is not present in the Binary field.".format(
  310. debug=name, origin=origin_package_name))
  311. else:
  312. # Someone was a nasty little hacker and put a package
  313. # into the .changes that isn't in debian/control. Bad,
  314. # bad person.
  315. raise Reject('Package {0} is not mentioned in Binary field in changes'.format(name))
  316. return True
  317. def check_binary(self, upload, binary):
  318. fn = binary.hashed_file.filename
  319. control = binary.control
  320. for field in ('Package', 'Architecture', 'Version', 'Description', 'Section'):
  321. if field not in control:
  322. raise Reject('{0}: Missing mandatory field {0}.'.format(fn, field))
  323. check_fields_for_valid_utf8(fn, control)
  324. # check fields
  325. package = control['Package']
  326. if not re_field_package.match(package):
  327. raise Reject('{0}: Invalid Package field'.format(fn))
  328. version = control['Version']
  329. version_match = re_field_version.match(version)
  330. if not version_match:
  331. raise Reject('{0}: Invalid Version field'.format(fn))
  332. version_without_epoch = version_match.group('without_epoch')
  333. architecture = control['Architecture']
  334. if architecture not in upload.changes.architectures:
  335. raise Reject('{0}: Architecture not in Architecture field in changes file'.format(fn))
  336. if architecture == 'source':
  337. raise Reject('{0}: Architecture "source" invalid for binary packages'.format(fn))
  338. self._architectures.add(architecture)
  339. source = control.get('Source')
  340. if source is not None and not re_field_source.match(source):
  341. raise Reject('{0}: Invalid Source field'.format(fn))
  342. # check filename
  343. match = re_file_binary.match(fn)
  344. if package != match.group('package'):
  345. raise Reject('{0}: filename does not match Package field'.format(fn))
  346. if version_without_epoch != match.group('version'):
  347. raise Reject('{0}: filename does not match Version field'.format(fn))
  348. if architecture != match.group('architecture'):
  349. raise Reject('{0}: filename does not match Architecture field'.format(fn))
  350. # check dependency field syntax
  351. for field in ('Breaks', 'Conflicts', 'Depends', 'Enhances', 'Pre-Depends',
  352. 'Provides', 'Recommends', 'Replaces', 'Suggests'):
  353. value = control.get(field)
  354. if value is not None:
  355. if value.strip() == '':
  356. raise Reject('{0}: empty {1} field'.format(fn, field))
  357. try:
  358. apt_pkg.parse_depends(value)
  359. except:
  360. raise Reject('{0}: APT could not parse {1} field'.format(fn, field))
  361. for field in ('Built-Using',):
  362. value = control.get(field)
  363. if value is not None:
  364. if value.strip() == '':
  365. raise Reject('{0}: empty {1} field'.format(fn, field))
  366. try:
  367. apt_pkg.parse_src_depends(value)
  368. except:
  369. raise Reject('{0}: APT could not parse {1} field'.format(fn, field))
  370. class BinaryTimestampCheck(Check):
  371. """check timestamps of files in binary packages
  372. Files in the near future cause ugly warnings and extreme time travel
  373. can cause errors on extraction.
  374. """
  375. def check(self, upload):
  376. cnf = Config()
  377. future_cutoff = time.time() + cnf.find_i('Dinstall::FutureTimeTravelGrace', 24 * 3600)
  378. past_cutoff = time.mktime(time.strptime(cnf.find('Dinstall::PastCutoffYear', '1975'), '%Y'))
  379. class TarTime(object):
  380. def __init__(self):
  381. self.future_files = dict()
  382. self.past_files = dict()
  383. def callback(self, member, data):
  384. if member.mtime > future_cutoff:
  385. self.future_files[member.name] = member.mtime
  386. elif member.mtime < past_cutoff:
  387. self.past_files[member.name] = member.mtime
  388. def format_reason(filename, direction, files):
  389. reason = "{0}: has {1} file(s) with a timestamp too far in the {2}:\n".format(filename, len(files), direction)
  390. for fn, ts in files.iteritems():
  391. reason += " {0} ({1})".format(fn, time.ctime(ts))
  392. return reason
  393. for binary in upload.changes.binaries:
  394. filename = binary.hashed_file.filename
  395. path = os.path.join(upload.directory, filename)
  396. deb = apt_inst.DebFile(path)
  397. tar = TarTime()
  398. deb.control.go(tar.callback)
  399. if tar.future_files:
  400. raise Reject(format_reason(filename, 'future', tar.future_files))
  401. if tar.past_files:
  402. raise Reject(format_reason(filename, 'past', tar.past_files))
  403. class SourceCheck(Check):
  404. """Check source package for syntax errors."""
  405. def check_filename(self, control, filename, regex):
  406. # In case we have an .orig.tar.*, we have to strip the Debian revison
  407. # from the version number. So handle this special case first.
  408. is_orig = True
  409. match = re_file_orig.match(filename)
  410. if not match:
  411. is_orig = False
  412. match = regex.match(filename)
  413. if not match:
  414. raise Reject('{0}: does not match regular expression for source filenames'.format(filename))
  415. if match.group('package') != control['Source']:
  416. raise Reject('{0}: filename does not match Source field'.format(filename))
  417. version = control['Version']
  418. if is_orig:
  419. upstream_match = re_field_version_upstream.match(version)
  420. if not upstream_match:
  421. raise Reject('{0}: Source package includes upstream tarball, but {0} has no Debian revision.'.format(filename, version))
  422. version = upstream_match.group('upstream')
  423. version_match = re_field_version.match(version)
  424. version_without_epoch = version_match.group('without_epoch')
  425. if match.group('version') != version_without_epoch:
  426. raise Reject('{0}: filename does not match Version field'.format(filename))
  427. def check(self, upload):
  428. if upload.changes.source is None:
  429. if "source" in upload.changes.architectures:
  430. raise Reject("{}: Architecture field includes source, but no source package is included in the upload".format(upload.changes.filename))
  431. return True
  432. if "source" not in upload.changes.architectures:
  433. raise Reject("{}: Architecture field does not include source, but a source package is included in the upload".format(upload.changes.filename))
  434. changes = upload.changes.changes
  435. source = upload.changes.source
  436. control = source.dsc
  437. dsc_fn = source._dsc_file.filename
  438. check_fields_for_valid_utf8(dsc_fn, control)
  439. # check fields
  440. if not re_field_package.match(control['Source']):
  441. raise Reject('{0}: Invalid Source field'.format(dsc_fn))
  442. if control['Source'] != changes['Source']:
  443. raise Reject('{0}: Source field does not match Source field in changes'.format(dsc_fn))
  444. if control['Version'] != changes['Version']:
  445. raise Reject('{0}: Version field does not match Version field in changes'.format(dsc_fn))
  446. # check filenames
  447. self.check_filename(control, dsc_fn, re_file_dsc)
  448. for f in source.files.itervalues():
  449. self.check_filename(control, f.filename, re_file_source)
  450. # check dependency field syntax
  451. for field in ('Build-Conflicts', 'Build-Conflicts-Indep', 'Build-Depends', 'Build-Depends-Arch', 'Build-Depends-Indep'):
  452. value = control.get(field)
  453. if value is not None:
  454. if value.strip() == '':
  455. raise Reject('{0}: empty {1} field'.format(dsc_fn, field))
  456. try:
  457. apt_pkg.parse_src_depends(value)
  458. except Exception as e:
  459. raise Reject('{0}: APT could not parse {1} field: {2}'.format(dsc_fn, field, e))
  460. rejects = utils.check_dsc_files(dsc_fn, control, source.files.keys())
  461. if len(rejects) > 0:
  462. raise Reject("\n".join(rejects))
  463. return True
  464. class SingleDistributionCheck(Check):
  465. """Check that the .changes targets only a single distribution."""
  466. def check(self, upload):
  467. if len(upload.changes.distributions) != 1:
  468. raise Reject("Only uploads to a single distribution are allowed.")
  469. class ACLCheck(Check):
  470. """Check the uploader is allowed to upload the packages in .changes"""
  471. def _does_hijack(self, session, upload, suite):
  472. # Try to catch hijacks.
  473. # This doesn't work correctly. Uploads to experimental can still
  474. # "hijack" binaries from unstable. Also one can hijack packages
  475. # via buildds (but people who try this should not be DMs).
  476. for binary_name in upload.changes.binary_names:
  477. binaries = session.query(DBBinary).join(DBBinary.source) \
  478. .filter(DBBinary.suites.contains(suite)) \
  479. .filter(DBBinary.package == binary_name)
  480. for binary in binaries:
  481. if binary.source.source != upload.changes.changes['Source']:
  482. return True, binary.package, binary.source.source
  483. return False, None, None
  484. def _check_acl(self, session, upload, acl):
  485. source_name = upload.changes.source_name
  486. if acl.match_fingerprint and upload.fingerprint not in acl.fingerprints:
  487. return None, None
  488. if acl.match_keyring is not None and upload.fingerprint.keyring != acl.match_keyring:
  489. return None, None
  490. if not acl.allow_new:
  491. if upload.new:
  492. return False, "NEW uploads are not allowed"
  493. for f in upload.changes.files.itervalues():
  494. if f.section == 'byhand' or f.section.startswith("raw-"):
  495. return False, "BYHAND uploads are not allowed"
  496. if not acl.allow_source and upload.changes.source is not None:
  497. return False, "sourceful uploads are not allowed"
  498. binaries = upload.changes.binaries
  499. if len(binaries) != 0:
  500. if not acl.allow_binary:
  501. return False, "binary uploads are not allowed"
  502. if upload.changes.source is None and not acl.allow_binary_only:
  503. return False, "binary-only uploads are not allowed"
  504. if not acl.allow_binary_all:
  505. uploaded_arches = set(upload.changes.architectures)
  506. uploaded_arches.discard('source')
  507. allowed_arches = set(a.arch_string for a in acl.architectures)
  508. forbidden_arches = uploaded_arches - allowed_arches
  509. if len(forbidden_arches) != 0:
  510. return False, "uploads for architecture(s) {0} are not allowed".format(", ".join(forbidden_arches))
  511. if not acl.allow_hijack:
  512. for suite in upload.final_suites:
  513. does_hijack, hijacked_binary, hijacked_from = self._does_hijack(session, upload, suite)
  514. if does_hijack:
  515. return False, "hijacks are not allowed (binary={0}, other-source={1})".format(hijacked_binary, hijacked_from)
  516. acl_per_source = session.query(ACLPerSource).filter_by(acl=acl, fingerprint=upload.fingerprint, source=source_name).first()
  517. if acl.allow_per_source:
  518. if acl_per_source is None:
  519. return False, "not allowed to upload source package '{0}'".format(source_name)
  520. if acl.deny_per_source and acl_per_source is not None:
  521. return False, acl_per_source.reason or "forbidden to upload source package '{0}'".format(source_name)
  522. return True, None
  523. def check(self, upload):
  524. session = upload.session
  525. fingerprint = upload.fingerprint
  526. keyring = fingerprint.keyring
  527. if keyring is None:
  528. raise Reject('No keyring for fingerprint {0}'.format(fingerprint.fingerprint))
  529. if not keyring.active:
  530. raise Reject('Keyring {0} is not active'.format(keyring.name))
  531. acl = fingerprint.acl or keyring.acl
  532. if acl is None:
  533. raise Reject('No ACL for fingerprint {0}'.format(fingerprint.fingerprint))
  534. result, reason = self._check_acl(session, upload, acl)
  535. if not result:
  536. raise RejectACL(acl, reason)
  537. for acl in session.query(ACL).filter_by(is_global=True):
  538. result, reason = self._check_acl(session, upload, acl)
  539. if result is False:
  540. raise RejectACL(acl, reason)
  541. return True
  542. def per_suite_check(self, upload, suite):
  543. acls = suite.acls
  544. if len(acls) != 0:
  545. accept = False
  546. for acl in acls:
  547. result, reason = self._check_acl(upload.session, upload, acl)
  548. if result is False:
  549. raise Reject(reason)
  550. accept = accept or result
  551. if not accept:
  552. raise Reject('Not accepted by any per-suite acl (suite={0})'.format(suite.suite_name))
  553. return True
  554. class TransitionCheck(Check):
  555. """check for a transition"""
  556. def check(self, upload):
  557. if 'source' not in upload.changes.architectures:
  558. return True
  559. transitions = self.get_transitions()
  560. if transitions is None:
  561. return True
  562. session = upload.session
  563. control = upload.changes.changes
  564. source = re_field_source.match(control['Source']).group('package')
  565. for trans in transitions:
  566. t = transitions[trans]
  567. transition_source = t["source"]
  568. expected = t["new"]
  569. # Will be None if nothing is in testing.
  570. current = get_source_in_suite(transition_source, "testing", session)
  571. if current is not None:
  572. compare = apt_pkg.version_compare(current.version, expected)
  573. if current is None or compare < 0:
  574. # This is still valid, the current version in testing is older than
  575. # the new version we wait for, or there is none in testing yet
  576. # Check if the source we look at is affected by this.
  577. if source in t['packages']:
  578. # The source is affected, lets reject it.
  579. rejectmsg = "{0}: part of the {1} transition.\n\n".format(source, trans)
  580. if current is not None:
  581. currentlymsg = "at version {0}".format(current.version)
  582. else:
  583. currentlymsg = "not present in testing"
  584. rejectmsg += "Transition description: {0}\n\n".format(t["reason"])
  585. rejectmsg += "\n".join(textwrap.wrap("""Your package
  586. is part of a testing transition designed to get {0} migrated (it is
  587. currently {1}, we need version {2}). This transition is managed by the
  588. Release Team, and {3} is the Release-Team member responsible for it.
  589. Please mail debian-release@lists.debian.org or contact {3} directly if you
  590. need further assistance. You might want to upload to experimental until this
  591. transition is done.""".format(transition_source, currentlymsg, expected, t["rm"])))
  592. raise Reject(rejectmsg)
  593. return True
  594. def get_transitions(self):
  595. cnf = Config()
  596. path = cnf.get('Dinstall::ReleaseTransitions', '')
  597. if path == '' or not os.path.exists(path):
  598. return None
  599. contents = file(path, 'r').read()
  600. try:
  601. transitions = yaml.safe_load(contents)
  602. return transitions
  603. except yaml.YAMLError as msg:
  604. utils.warn('Not checking transitions, the transitions file is broken: {0}'.format(msg))
  605. return None
  606. class NoSourceOnlyCheck(Check):
  607. def is_source_only_upload(self, upload):
  608. changes = upload.changes
  609. if changes.source is not None and len(changes.binaries) == 0:
  610. return True
  611. return False
  612. """Check for source-only upload
  613. Source-only uploads are only allowed if Dinstall::AllowSourceOnlyUploads is
  614. set. Otherwise they are rejected.
  615. Source-only uploads are only accepted for source packages having a
  616. Package-List field that also lists architectures per package. This
  617. check can be disabled via
  618. Dinstall::AllowSourceOnlyUploadsWithoutPackageList.
  619. Source-only uploads to NEW are only allowed if
  620. Dinstall::AllowSourceOnlyNew is set.
  621. Uploads not including architecture-independent packages are only
  622. allowed if Dinstall::AllowNoArchIndepUploads is set.
  623. """
  624. def check(self, upload):
  625. if not self.is_source_only_upload(upload):
  626. return True
  627. allow_source_only_uploads = Config().find_b('Dinstall::AllowSourceOnlyUploads')
  628. allow_source_only_uploads_without_package_list = Config().find_b('Dinstall::AllowSourceOnlyUploadsWithoutPackageList')
  629. allow_source_only_new = Config().find_b('Dinstall::AllowSourceOnlyNew')
  630. allow_source_only_new_keys = Config().value_list('Dinstall::AllowSourceOnlyNewKeys')
  631. allow_no_arch_indep_uploads = Config().find_b('Dinstall::AllowNoArchIndepUploads', True)
  632. changes = upload.changes
  633. if not allow_source_only_uploads:
  634. raise Reject('Source-only uploads are not allowed.')
  635. if not allow_source_only_uploads_without_package_list \
  636. and changes.source.package_list.fallback:
  637. raise Reject('Source-only uploads are only allowed if a Package-List field that also list architectures is included in the source package. dpkg (>= 1.17.7) includes this information.')
  638. if not allow_source_only_new and changes.primary_fingerprint not in allow_source_only_new_keys and upload.new:
  639. raise Reject('Source-only uploads to NEW are not allowed.')
  640. if 'all' not in changes.architectures and changes.source.package_list.has_arch_indep_packages():
  641. if not allow_no_arch_indep_uploads:
  642. raise Reject('Uploads must include architecture-independent packages.')
  643. for suite in ('oldstable', 'oldstable-proposed-updates', 'oldstable-security',
  644. 'jessie', 'jessie-proposed-updates', 'jessie-security',
  645. 'oldstable-backports', 'oldstable-backports-sloppy',
  646. 'jessie-backports', 'jessie-backports-sloppy',
  647. 'oldoldstable', 'oldoldstable-security',
  648. 'wheezy', 'wheezy-security',
  649. 'oldoldstable-backports', 'oldoldstable-backports-sloppy',
  650. 'wheezy-backports', 'wheezy-backports-sloppy'):
  651. if suite in changes.distributions:
  652. raise Reject('Suite {} is not configured to build arch:all packages. Please include them in your upload'.format(suite))
  653. return True
  654. class NewOverrideCheck(Check):
  655. """Override NEW requirement
  656. """
  657. def check(self, upload):
  658. if not upload.new:
  659. return True
  660. new_override_keys = Config().value_list('Dinstall::NewOverrideKeys')
  661. changes = upload.changes
  662. if changes.primary_fingerprint in new_override_keys:
  663. upload.new = False
  664. return True
  665. class ArchAllBinNMUCheck(Check):
  666. """Check for arch:all binNMUs"""
  667. def check(self, upload):
  668. changes = upload.changes
  669. if 'all' in changes.architectures and changes.changes.get('Binary-Only') == 'yes':
  670. raise Reject('arch:all binNMUs are not allowed.')
  671. return True
  672. class LintianCheck(Check):
  673. """Check package using lintian"""
  674. def check(self, upload):
  675. changes = upload.changes
  676. # Only check sourceful uploads.
  677. if changes.source is None:
  678. return True
  679. # Only check uploads to unstable or experimental.
  680. if 'unstable' not in changes.distributions and 'experimental' not in changes.distributions:
  681. return True
  682. cnf = Config()
  683. if 'Dinstall::LintianTags' not in cnf:
  684. return True
  685. tagfile = cnf['Dinstall::LintianTags']
  686. with open(tagfile, 'r') as sourcefile:
  687. sourcecontent = sourcefile.read()
  688. try:
  689. lintiantags = yaml.safe_load(sourcecontent)['lintian']
  690. except yaml.YAMLError as msg:
  691. raise Exception('Could not read lintian tags file {0}, YAML error: {1}'.format(tagfile, msg))
  692. fd, temp_filename = utils.temp_filename(mode=0o644)
  693. temptagfile = os.fdopen(fd, 'w')
  694. for tags in lintiantags.itervalues():
  695. for tag in tags:
  696. print(tag, file=temptagfile)
  697. temptagfile.close()
  698. changespath = os.path.join(upload.directory, changes.filename)
  699. try:
  700. cmd = []
  701. result = 0
  702. user = cnf.get('Dinstall::UnprivUser') or None
  703. if user is not None:
  704. cmd.extend(['sudo', '-H', '-u', user])
  705. cmd.extend(['/usr/bin/lintian', '--show-overrides', '--tags-from-file', temp_filename, changespath])
  706. output = daklib.daksubprocess.check_output(cmd, stderr=subprocess.STDOUT)
  707. except subprocess.CalledProcessError as e:
  708. result = e.returncode
  709. output = e.output
  710. finally:
  711. os.unlink(temp_filename)
  712. if result == 2:
  713. utils.warn("lintian failed for %s [return code: %s]." %
  714. (changespath, result))
  715. utils.warn(utils.prefix_multi_line_string(output,
  716. " [possible output:] "))
  717. parsed_tags = lintian.parse_lintian_output(output)
  718. rejects = list(lintian.generate_reject_messages(parsed_tags, lintiantags))
  719. if len(rejects) != 0:
  720. raise Reject('\n'.join(rejects))
  721. return True
  722. class SourceFormatCheck(Check):
  723. """Check source format is allowed in the target suite"""
  724. def per_suite_check(self, upload, suite):
  725. source = upload.changes.source
  726. session = upload.session
  727. if source is None:
  728. return True
  729. source_format = source.dsc['Format']
  730. query = session.query(SrcFormat).filter_by(format_name=source_format).filter(SrcFormat.suites.contains(suite))
  731. if query.first() is None:
  732. raise Reject('source format {0} is not allowed in suite {1}'.format(source_format, suite.suite_name))
  733. class SuiteCheck(Check):
  734. def per_suite_check(self, upload, suite):
  735. if not suite.accept_source_uploads and upload.changes.source is not None:
  736. raise Reject('The suite "{0}" does not accept source uploads.'.format(suite.suite_name))
  737. if not suite.accept_binary_uploads and len(upload.changes.binaries) != 0:
  738. raise Reject('The suite "{0}" does not accept binary uploads.'.format(suite.suite_name))
  739. return True
  740. class SuiteArchitectureCheck(Check):
  741. def per_suite_check(self, upload, suite):
  742. session = upload.session
  743. for arch in upload.changes.architectures:
  744. query = session.query(Architecture).filter_by(arch_string=arch).filter(Architecture.suites.contains(suite))
  745. if query.first() is None:
  746. raise Reject('Architecture {0} is not allowed in suite {1}'.format(arch, suite.suite_name))
  747. return True
  748. class VersionCheck(Check):
  749. """Check version constraints"""
  750. def _highest_source_version(self, session, source_name, suite):
  751. db_source = session.query(DBSource).filter_by(source=source_name) \
  752. .filter(DBSource.suites.contains(suite)).order_by(DBSource.version.desc()).first()
  753. if db_source is None:
  754. return None
  755. else:
  756. return db_source.version
  757. def _highest_binary_version(self, session, binary_name, suite, architecture):
  758. db_binary = session.query(DBBinary).filter_by(package=binary_name) \
  759. .filter(DBBinary.suites.contains(suite)) \
  760. .join(DBBinary.architecture) \
  761. .filter(Architecture.arch_string.in_(['all', architecture])) \
  762. .order_by(DBBinary.version.desc()).first()
  763. if db_binary is None:
  764. return None
  765. else:
  766. return db_binary.version
  767. def _version_checks(self, upload, suite, other_suite, op, op_name):
  768. session = upload.session
  769. if upload.changes.source is not None:
  770. source_name = upload.changes.source.dsc['Source']
  771. source_version = upload.changes.source.dsc['Version']
  772. v = self._highest_source_version(session, source_name, other_suite)
  773. if v is not None and not op(version_compare(source_version, v)):
  774. raise Reject("Version check failed:\n"
  775. "Your upload included the source package {0}, version {1},\n"
  776. "however {3} already has version {2}.\n"
  777. "Uploads to {5} must have a {4} version than present in {3}."
  778. .format(source_name, source_version, v, other_suite.suite_name, op_name, suite.suite_name))
  779. for binary in upload.changes.binaries:
  780. binary_name = binary.control['Package']
  781. binary_version = binary.control['Version']
  782. architecture = binary.control['Architecture']
  783. v = self._highest_binary_version(session, binary_name, other_suite, architecture)
  784. if v is not None and not op(version_compare(binary_version, v)):
  785. raise Reject("Version check failed:\n"
  786. "Your upload included the binary package {0}, version {1}, for {2},\n"
  787. "however {4} already has version {3}.\n"
  788. "Uploads to {6} must have a {5} version than present in {4}."
  789. .format(binary_name, binary_version, architecture, v, other_suite.suite_name, op_name, suite.suite_name))
  790. def per_suite_check(self, upload, suite):
  791. session = upload.session
  792. vc_newer = session.query(dbconn.VersionCheck).filter_by(suite=suite) \
  793. .filter(dbconn.VersionCheck.check.in_(['MustBeNewerThan', 'Enhances']))
  794. must_be_newer_than = [vc.reference for vc in vc_newer]
  795. # Must be newer than old versions in `suite`
  796. must_be_newer_than.append(suite)
  797. for s in must_be_newer_than:
  798. self._version_checks(upload, suite, s, lambda result: result > 0, 'higher')
  799. vc_older = session.query(dbconn.VersionCheck).filter_by(suite=suite, check='MustBeOlderThan')
  800. must_be_older_than = [vc.reference for vc in vc_older]
  801. for s in must_be_older_than:
  802. self._version_checks(upload, suite, s, lambda result: result < 0, 'lower')
  803. return True
  804. @property
  805. def forcable(self):
  806. return True