utils.py 47 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417
  1. #!/usr/bin/env python
  2. # vim:set et ts=4 sw=4:
  3. """Utility functions
  4. @contact: Debian FTP Master <ftpmaster@debian.org>
  5. @copyright: 2000, 2001, 2002, 2003, 2004, 2005, 2006 James Troup <james@nocrew.org>
  6. @license: GNU General Public License version 2 or later
  7. """
  8. # This program is free software; you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation; either version 2 of the License, or
  11. # (at your option) any later version.
  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. # You should have received a copy of the GNU General Public License
  17. # along with this program; if not, write to the Free Software
  18. # Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
  19. from __future__ import absolute_import, print_function
  20. import codecs
  21. import datetime
  22. import os
  23. import pwd
  24. import grp
  25. import shutil
  26. import sqlalchemy.sql as sql
  27. import sys
  28. import tempfile
  29. import apt_inst
  30. import apt_pkg
  31. import re
  32. import email as modemail
  33. import subprocess
  34. import ldap
  35. import errno
  36. import functools
  37. import six
  38. import daklib.config as config
  39. import daklib.daksubprocess
  40. from .dbconn import DBConn, get_architecture, get_component, get_suite, \
  41. get_active_keyring_paths, \
  42. get_suite_architectures, get_or_set_metadatakey, \
  43. Component, Override, OverrideType
  44. from .dak_exceptions import *
  45. from .gpg import SignedFile
  46. from .textutils import fix_maintainer
  47. from .regexes import re_html_escaping, html_escaping, re_single_line_field, \
  48. re_multi_line_field, re_srchasver, \
  49. re_re_mark, re_whitespace_comment, re_issource, \
  50. re_build_dep_arch, re_parse_maintainer
  51. from .formats import parse_format, validate_changes_format
  52. from .srcformats import get_format_from_string
  53. from collections import defaultdict
  54. ################################################################################
  55. default_config = "/etc/dak/dak.conf" #: default dak config, defines host properties
  56. alias_cache = None #: Cache for email alias checks
  57. key_uid_email_cache = {} #: Cache for email addresses from gpg key uids
  58. ################################################################################
  59. def html_escape(s):
  60. """ Escape html chars """
  61. return re_html_escaping.sub(lambda x: html_escaping.get(x.group(0)), s)
  62. ################################################################################
  63. def our_raw_input(prompt=""):
  64. if prompt:
  65. print(prompt)
  66. # TODO: py3: use `print(..., flush=True)`
  67. sys.stdout.flush()
  68. try:
  69. ret = six.moves.input()
  70. return ret
  71. except EOFError:
  72. print("\nUser interrupt (^D).", file=sys.stderr)
  73. raise SystemExit
  74. ################################################################################
  75. def extract_component_from_section(section):
  76. component = ""
  77. if section.find('/') != -1:
  78. component = section.split('/')[0]
  79. # Expand default component
  80. if component == "":
  81. component = "main"
  82. return (section, component)
  83. ################################################################################
  84. def parse_deb822(armored_contents, signing_rules=0, keyrings=None):
  85. require_signature = True
  86. if keyrings is None:
  87. keyrings = []
  88. require_signature = False
  89. signed_file = SignedFile(armored_contents.encode('utf-8'), keyrings=keyrings, require_signature=require_signature)
  90. contents = signed_file.contents.decode('utf-8')
  91. error = ""
  92. changes = {}
  93. # Split the lines in the input, keeping the linebreaks.
  94. lines = contents.splitlines(True)
  95. if len(lines) == 0:
  96. raise ParseChangesError("[Empty changes file]")
  97. # Reindex by line number so we can easily verify the format of
  98. # .dsc files...
  99. index = 0
  100. indexed_lines = {}
  101. for line in lines:
  102. index += 1
  103. indexed_lines[index] = line[:-1]
  104. num_of_lines = len(indexed_lines)
  105. index = 0
  106. first = -1
  107. while index < num_of_lines:
  108. index += 1
  109. line = indexed_lines[index]
  110. if line == "" and signing_rules == 1:
  111. if index != num_of_lines:
  112. raise InvalidDscError(index)
  113. break
  114. slf = re_single_line_field.match(line)
  115. if slf:
  116. field = slf.groups()[0].lower()
  117. changes[field] = slf.groups()[1]
  118. first = 1
  119. continue
  120. if line == " .":
  121. changes[field] += '\n'
  122. continue
  123. mlf = re_multi_line_field.match(line)
  124. if mlf:
  125. if first == -1:
  126. raise ParseChangesError("'%s'\n [Multi-line field continuing on from nothing?]" % (line))
  127. if first == 1 and changes[field] != "":
  128. changes[field] += '\n'
  129. first = 0
  130. changes[field] += mlf.groups()[0] + '\n'
  131. continue
  132. error += line
  133. changes["filecontents"] = armored_contents
  134. if "source" in changes:
  135. # Strip the source version in brackets from the source field,
  136. # put it in the "source-version" field instead.
  137. srcver = re_srchasver.search(changes["source"])
  138. if srcver:
  139. changes["source"] = srcver.group(1)
  140. changes["source-version"] = srcver.group(2)
  141. if error:
  142. raise ParseChangesError(error)
  143. return changes
  144. ################################################################################
  145. def parse_changes(filename, signing_rules=0, dsc_file=0, keyrings=None):
  146. """
  147. Parses a changes file and returns a dictionary where each field is a
  148. key. The mandatory first argument is the filename of the .changes
  149. file.
  150. signing_rules is an optional argument:
  151. - If signing_rules == -1, no signature is required.
  152. - If signing_rules == 0 (the default), a signature is required.
  153. - If signing_rules == 1, it turns on the same strict format checking
  154. as dpkg-source.
  155. The rules for (signing_rules == 1)-mode are:
  156. - The PGP header consists of "-----BEGIN PGP SIGNED MESSAGE-----"
  157. followed by any PGP header data and must end with a blank line.
  158. - The data section must end with a blank line and must be followed by
  159. "-----BEGIN PGP SIGNATURE-----".
  160. """
  161. # TODO: py3: use open(..., encoding="utf-8")
  162. with open(filename, 'rb') as changes_in:
  163. content_bin = changes_in.read()
  164. content = content_bin.decode('utf-8')
  165. changes = parse_deb822(content, signing_rules, keyrings=keyrings)
  166. if not dsc_file:
  167. # Finally ensure that everything needed for .changes is there
  168. must_keywords = ('Format', 'Date', 'Source', 'Architecture', 'Version',
  169. 'Distribution', 'Maintainer', 'Changes', 'Files')
  170. missingfields = []
  171. for keyword in must_keywords:
  172. if keyword.lower() not in changes:
  173. missingfields.append(keyword)
  174. if len(missingfields):
  175. raise ParseChangesError("Missing mandatory field(s) in changes file (policy 5.5): %s" % (missingfields))
  176. return changes
  177. ################################################################################
  178. def check_dsc_files(dsc_filename, dsc, dsc_files):
  179. """
  180. Verify that the files listed in the Files field of the .dsc are
  181. those expected given the announced Format.
  182. @type dsc_filename: string
  183. @param dsc_filename: path of .dsc file
  184. @type dsc: dict
  185. @param dsc: the content of the .dsc parsed by C{parse_changes()}
  186. @type dsc_files: dict
  187. @param dsc_files: the file list returned by C{build_file_list()}
  188. @rtype: list
  189. @return: all errors detected
  190. """
  191. rejmsg = []
  192. # Ensure .dsc lists proper set of source files according to the format
  193. # announced
  194. has = defaultdict(lambda: 0)
  195. ftype_lookup = (
  196. (r'orig\.tar\.(gz|bz2|xz)\.asc', ('orig_tar_sig',)),
  197. (r'orig\.tar\.gz', ('orig_tar_gz', 'orig_tar')),
  198. (r'diff\.gz', ('debian_diff',)),
  199. (r'tar\.gz', ('native_tar_gz', 'native_tar')),
  200. (r'debian\.tar\.(gz|bz2|xz)', ('debian_tar',)),
  201. (r'orig\.tar\.(gz|bz2|xz)', ('orig_tar',)),
  202. (r'tar\.(gz|bz2|xz)', ('native_tar',)),
  203. (r'orig-.+\.tar\.(gz|bz2|xz)\.asc', ('more_orig_tar_sig',)),
  204. (r'orig-.+\.tar\.(gz|bz2|xz)', ('more_orig_tar',)),
  205. )
  206. for f in dsc_files:
  207. m = re_issource.match(f)
  208. if not m:
  209. rejmsg.append("%s: %s in Files field not recognised as source."
  210. % (dsc_filename, f))
  211. continue
  212. # Populate 'has' dictionary by resolving keys in lookup table
  213. matched = False
  214. for regex, keys in ftype_lookup:
  215. if re.match(regex, m.group(3)):
  216. matched = True
  217. for key in keys:
  218. has[key] += 1
  219. break
  220. # File does not match anything in lookup table; reject
  221. if not matched:
  222. rejmsg.append("%s: unexpected source file '%s'" % (dsc_filename, f))
  223. break
  224. # Check for multiple files
  225. for file_type in ('orig_tar', 'orig_tar_sig', 'native_tar', 'debian_tar', 'debian_diff'):
  226. if has[file_type] > 1:
  227. rejmsg.append("%s: lists multiple %s" % (dsc_filename, file_type))
  228. # Source format specific tests
  229. try:
  230. format = get_format_from_string(dsc['format'])
  231. rejmsg.extend([
  232. '%s: %s' % (dsc_filename, x) for x in format.reject_msgs(has)
  233. ])
  234. except UnknownFormatError:
  235. # Not an error here for now
  236. pass
  237. return rejmsg
  238. ################################################################################
  239. # Dropped support for 1.4 and ``buggy dchanges 3.4'' (?!) compared to di.pl
  240. def build_file_list(changes, is_a_dsc=0, field="files", hashname="md5sum"):
  241. files = {}
  242. # Make sure we have a Files: field to parse...
  243. if field not in changes:
  244. raise NoFilesFieldError
  245. # Validate .changes Format: field
  246. if not is_a_dsc:
  247. validate_changes_format(parse_format(changes['format']), field)
  248. includes_section = (not is_a_dsc) and field == "files"
  249. # Parse each entry/line:
  250. for i in changes[field].split('\n'):
  251. if not i:
  252. break
  253. s = i.split()
  254. section = priority = ""
  255. try:
  256. if includes_section:
  257. (md5, size, section, priority, name) = s
  258. else:
  259. (md5, size, name) = s
  260. except ValueError:
  261. raise ParseChangesError(i)
  262. if section == "":
  263. section = "-"
  264. if priority == "":
  265. priority = "-"
  266. (section, component) = extract_component_from_section(section)
  267. files[name] = dict(size=size, section=section,
  268. priority=priority, component=component)
  269. files[name][hashname] = md5
  270. return files
  271. ################################################################################
  272. def send_mail(message, filename="", whitelists=None):
  273. """sendmail wrapper, takes _either_ a message string or a file as arguments
  274. @type whitelists: list of (str or None)
  275. @param whitelists: path to whitelists. C{None} or an empty list whitelists
  276. everything, otherwise an address is whitelisted if it is
  277. included in any of the lists.
  278. In addition a global whitelist can be specified in
  279. Dinstall::MailWhiteList.
  280. """
  281. maildir = Cnf.get('Dir::Mail')
  282. if maildir:
  283. path = os.path.join(maildir, datetime.datetime.now().isoformat())
  284. path = find_next_free(path)
  285. with open(path, 'w') as fh:
  286. print(message, end=' ', file=fh)
  287. # Check whether we're supposed to be sending mail
  288. if "Dinstall::Options::No-Mail" in Cnf and Cnf["Dinstall::Options::No-Mail"]:
  289. return
  290. # If we've been passed a string dump it into a temporary file
  291. if message:
  292. (fd, filename) = tempfile.mkstemp()
  293. with os.fdopen(fd, 'wt') as f:
  294. f.write(message)
  295. if whitelists is None or None in whitelists:
  296. whitelists = []
  297. if Cnf.get('Dinstall::MailWhiteList', ''):
  298. whitelists.append(Cnf['Dinstall::MailWhiteList'])
  299. if len(whitelists) != 0:
  300. with open(filename) as message_in:
  301. message_raw = modemail.message_from_file(message_in)
  302. whitelist = []
  303. for path in whitelists:
  304. with open(path, 'r') as whitelist_in:
  305. for line in whitelist_in:
  306. if not re_whitespace_comment.match(line):
  307. if re_re_mark.match(line):
  308. whitelist.append(re.compile(re_re_mark.sub("", line.strip(), 1)))
  309. else:
  310. whitelist.append(re.compile(re.escape(line.strip())))
  311. # Fields to check.
  312. fields = ["To", "Bcc", "Cc"]
  313. for field in fields:
  314. # Check each field
  315. value = message_raw.get(field, None)
  316. if value is not None:
  317. match = []
  318. for item in value.split(","):
  319. (rfc822_maint, rfc2047_maint, name, email) = fix_maintainer(item.strip())
  320. mail_whitelisted = 0
  321. for wr in whitelist:
  322. if wr.match(email):
  323. mail_whitelisted = 1
  324. break
  325. if not mail_whitelisted:
  326. print("Skipping {0} since it's not whitelisted".format(item))
  327. continue
  328. match.append(item)
  329. # Doesn't have any mail in whitelist so remove the header
  330. if len(match) == 0:
  331. del message_raw[field]
  332. else:
  333. message_raw.replace_header(field, ', '.join(match))
  334. # Change message fields in order if we don't have a To header
  335. if "To" not in message_raw:
  336. fields.reverse()
  337. for field in fields:
  338. if field in message_raw:
  339. message_raw[fields[-1]] = message_raw[field]
  340. del message_raw[field]
  341. break
  342. else:
  343. # Clean up any temporary files
  344. # and return, as we removed all recipients.
  345. if message:
  346. os.unlink(filename)
  347. return
  348. fd = os.open(filename, os.O_RDWR | os.O_EXCL, 0o700)
  349. with os.fdopen(fd, 'wt') as f:
  350. f.write(message_raw.as_string(True))
  351. # Invoke sendmail
  352. try:
  353. with open(filename, 'r') as fh:
  354. subprocess.check_output(Cnf["Dinstall::SendmailCommand"].split(), stdin=fh, stderr=subprocess.STDOUT)
  355. except subprocess.CalledProcessError as e:
  356. raise SendmailFailedError(e.output.rstrip())
  357. # Clean up any temporary files
  358. if message:
  359. os.unlink(filename)
  360. ################################################################################
  361. def poolify(source):
  362. if source[:3] == "lib":
  363. return source[:4] + '/' + source + '/'
  364. else:
  365. return source[:1] + '/' + source + '/'
  366. ################################################################################
  367. def move(src, dest, overwrite=0, perms=0o664):
  368. if os.path.exists(dest) and os.path.isdir(dest):
  369. dest_dir = dest
  370. else:
  371. dest_dir = os.path.dirname(dest)
  372. if not os.path.lexists(dest_dir):
  373. umask = os.umask(00000)
  374. os.makedirs(dest_dir, 0o2775)
  375. os.umask(umask)
  376. #print "Moving %s to %s..." % (src, dest)
  377. if os.path.exists(dest) and os.path.isdir(dest):
  378. dest += '/' + os.path.basename(src)
  379. # Don't overwrite unless forced to
  380. if os.path.lexists(dest):
  381. if not overwrite:
  382. fubar("Can't move %s to %s - file already exists." % (src, dest))
  383. else:
  384. if not os.access(dest, os.W_OK):
  385. fubar("Can't move %s to %s - can't write to existing file." % (src, dest))
  386. shutil.copy2(src, dest)
  387. os.chmod(dest, perms)
  388. os.unlink(src)
  389. ################################################################################
  390. def TemplateSubst(subst_map, filename):
  391. """ Perform a substition of template """
  392. with open(filename) as templatefile:
  393. template = templatefile.read()
  394. for k, v in six.iteritems(subst_map):
  395. template = template.replace(k, str(v))
  396. return template
  397. ################################################################################
  398. def fubar(msg, exit_code=1):
  399. print("E:", msg, file=sys.stderr)
  400. sys.exit(exit_code)
  401. def warn(msg):
  402. print("W:", msg, file=sys.stderr)
  403. ################################################################################
  404. # Returns the user name with a laughable attempt at rfc822 conformancy
  405. # (read: removing stray periods).
  406. def whoami():
  407. return pwd.getpwuid(os.getuid())[4].split(',')[0].replace('.', '')
  408. def getusername():
  409. return pwd.getpwuid(os.getuid())[0]
  410. ################################################################################
  411. def size_type(c):
  412. t = " B"
  413. if c > 10240:
  414. c = c / 1024
  415. t = " KB"
  416. if c > 10240:
  417. c = c / 1024
  418. t = " MB"
  419. return ("%d%s" % (c, t))
  420. ################################################################################
  421. def find_next_free(dest, too_many=100):
  422. extra = 0
  423. orig_dest = dest
  424. while os.path.lexists(dest) and extra < too_many:
  425. dest = orig_dest + '.' + repr(extra)
  426. extra += 1
  427. if extra >= too_many:
  428. raise NoFreeFilenameError
  429. return dest
  430. ################################################################################
  431. def result_join(original, sep='\t'):
  432. return sep.join(
  433. x if x is not None else ""
  434. for x in original
  435. )
  436. ################################################################################
  437. def prefix_multi_line_string(str, prefix, include_blank_lines=0):
  438. out = ""
  439. for line in str.split('\n'):
  440. line = line.strip()
  441. if line or include_blank_lines:
  442. out += "%s%s\n" % (prefix, line)
  443. # Strip trailing new line
  444. if out:
  445. out = out[:-1]
  446. return out
  447. ################################################################################
  448. def join_with_commas_and(list):
  449. if len(list) == 0:
  450. return "nothing"
  451. if len(list) == 1:
  452. return list[0]
  453. return ", ".join(list[:-1]) + " and " + list[-1]
  454. ################################################################################
  455. def pp_deps(deps):
  456. pp_deps = []
  457. for atom in deps:
  458. (pkg, version, constraint) = atom
  459. if constraint:
  460. pp_dep = "%s (%s %s)" % (pkg, constraint, version)
  461. else:
  462. pp_dep = pkg
  463. pp_deps.append(pp_dep)
  464. return " |".join(pp_deps)
  465. ################################################################################
  466. def get_conf():
  467. return Cnf
  468. ################################################################################
  469. def parse_args(Options):
  470. """ Handle -a, -c and -s arguments; returns them as SQL constraints """
  471. # XXX: This should go away and everything which calls it be converted
  472. # to use SQLA properly. For now, we'll just fix it not to use
  473. # the old Pg interface though
  474. session = DBConn().session()
  475. # Process suite
  476. if Options["Suite"]:
  477. suite_ids_list = []
  478. for suitename in split_args(Options["Suite"]):
  479. suite = get_suite(suitename, session=session)
  480. if not suite or suite.suite_id is None:
  481. warn("suite '%s' not recognised." % (suite and suite.suite_name or suitename))
  482. else:
  483. suite_ids_list.append(suite.suite_id)
  484. if suite_ids_list:
  485. con_suites = "AND su.id IN (%s)" % ", ".join([str(i) for i in suite_ids_list])
  486. else:
  487. fubar("No valid suite given.")
  488. else:
  489. con_suites = ""
  490. # Process component
  491. if Options["Component"]:
  492. component_ids_list = []
  493. for componentname in split_args(Options["Component"]):
  494. component = get_component(componentname, session=session)
  495. if component is None:
  496. warn("component '%s' not recognised." % (componentname))
  497. else:
  498. component_ids_list.append(component.component_id)
  499. if component_ids_list:
  500. con_components = "AND c.id IN (%s)" % ", ".join([str(i) for i in component_ids_list])
  501. else:
  502. fubar("No valid component given.")
  503. else:
  504. con_components = ""
  505. # Process architecture
  506. con_architectures = ""
  507. check_source = 0
  508. if Options["Architecture"]:
  509. arch_ids_list = []
  510. for archname in split_args(Options["Architecture"]):
  511. if archname == "source":
  512. check_source = 1
  513. else:
  514. arch = get_architecture(archname, session=session)
  515. if arch is None:
  516. warn("architecture '%s' not recognised." % (archname))
  517. else:
  518. arch_ids_list.append(arch.arch_id)
  519. if arch_ids_list:
  520. con_architectures = "AND a.id IN (%s)" % ", ".join([str(i) for i in arch_ids_list])
  521. else:
  522. if not check_source:
  523. fubar("No valid architecture given.")
  524. else:
  525. check_source = 1
  526. return (con_suites, con_architectures, con_components, check_source)
  527. ################################################################################
  528. @functools.total_ordering
  529. class ArchKey(object):
  530. """
  531. Key object for use in sorting lists of architectures.
  532. Sorts normally except that 'source' dominates all others.
  533. """
  534. __slots__ = ['arch', 'issource']
  535. def __init__(self, arch, *args):
  536. self.arch = arch
  537. self.issource = arch == 'source'
  538. def __lt__(self, other):
  539. if self.issource:
  540. return not other.issource
  541. if other.issource:
  542. return False
  543. return self.arch < other.arch
  544. def __eq__(self, other):
  545. return self.arch == other.arch
  546. ################################################################################
  547. def split_args(s, dwim=True):
  548. """
  549. Split command line arguments which can be separated by either commas
  550. or whitespace. If dwim is set, it will complain about string ending
  551. in comma since this usually means someone did 'dak ls -a i386, m68k
  552. foo' or something and the inevitable confusion resulting from 'm68k'
  553. being treated as an argument is undesirable.
  554. """
  555. if s.find(",") == -1:
  556. return s.split()
  557. else:
  558. if s[-1:] == "," and dwim:
  559. fubar("split_args: found trailing comma, spurious space maybe?")
  560. return s.split(",")
  561. ################################################################################
  562. def gpg_keyring_args(keyrings=None):
  563. if not keyrings:
  564. keyrings = get_active_keyring_paths()
  565. return ["--keyring={}".format(path) for path in keyrings]
  566. ################################################################################
  567. def gpg_get_key_addresses(fingerprint):
  568. """retreive email addresses from gpg key uids for a given fingerprint"""
  569. addresses = key_uid_email_cache.get(fingerprint)
  570. if addresses is not None:
  571. return addresses
  572. addresses = list()
  573. try:
  574. with open(os.devnull, "wb") as devnull:
  575. cmd = ["gpg", "--no-default-keyring"]
  576. cmd.extend(gpg_keyring_args())
  577. cmd.extend(["--with-colons", "--list-keys", "--", fingerprint])
  578. output = daklib.daksubprocess.check_output(cmd, stderr=devnull)
  579. except subprocess.CalledProcessError:
  580. pass
  581. else:
  582. for l in six.ensure_str(output).split('\n'):
  583. parts = l.split(':')
  584. if parts[0] not in ("uid", "pub"):
  585. continue
  586. if parts[1] in ("i", "d", "r"):
  587. # Skip uid that is invalid, disabled or revoked
  588. continue
  589. try:
  590. uid = parts[9]
  591. except IndexError:
  592. continue
  593. try:
  594. uid = six.ensure_text(uid)
  595. except UnicodeDecodeError:
  596. uid = uid.decode("latin1") # does not fail
  597. m = re_parse_maintainer.match(uid)
  598. if not m:
  599. continue
  600. address = m.group(2)
  601. address = six.ensure_str(address)
  602. if address.endswith('@debian.org'):
  603. # prefer @debian.org addresses
  604. # TODO: maybe not hardcode the domain
  605. addresses.insert(0, address)
  606. else:
  607. addresses.append(address)
  608. key_uid_email_cache[fingerprint] = addresses
  609. return addresses
  610. ################################################################################
  611. def get_logins_from_ldap(fingerprint='*'):
  612. """retrieve login from LDAP linked to a given fingerprint"""
  613. LDAPDn = Cnf['Import-LDAP-Fingerprints::LDAPDn']
  614. LDAPServer = Cnf['Import-LDAP-Fingerprints::LDAPServer']
  615. l = ldap.initialize(LDAPServer)
  616. l.simple_bind_s('', '')
  617. Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
  618. '(keyfingerprint=%s)' % fingerprint,
  619. ['uid', 'keyfingerprint'])
  620. login = {}
  621. for elem in Attrs:
  622. login[elem[1]['keyFingerPrint'][0]] = elem[1]['uid'][0]
  623. return login
  624. ################################################################################
  625. def get_users_from_ldap():
  626. """retrieve login and user names from LDAP"""
  627. LDAPDn = Cnf['Import-LDAP-Fingerprints::LDAPDn']
  628. LDAPServer = Cnf['Import-LDAP-Fingerprints::LDAPServer']
  629. l = ldap.initialize(LDAPServer)
  630. l.simple_bind_s('', '')
  631. Attrs = l.search_s(LDAPDn, ldap.SCOPE_ONELEVEL,
  632. '(uid=*)', ['uid', 'cn', 'mn', 'sn'])
  633. users = {}
  634. for elem in Attrs:
  635. elem = elem[1]
  636. name = []
  637. for k in ('cn', 'mn', 'sn'):
  638. try:
  639. if elem[k][0] != '-':
  640. name.append(elem[k][0])
  641. except KeyError:
  642. pass
  643. users[' '.join(name)] = elem['uid'][0]
  644. return users
  645. ################################################################################
  646. def clean_symlink(src, dest, root):
  647. """
  648. Relativize an absolute symlink from 'src' -> 'dest' relative to 'root'.
  649. Returns fixed 'src'
  650. """
  651. src = src.replace(root, '', 1)
  652. dest = dest.replace(root, '', 1)
  653. dest = os.path.dirname(dest)
  654. new_src = '../' * len(dest.split('/'))
  655. return new_src + src
  656. ################################################################################
  657. def temp_filename(directory=None, prefix="dak", suffix="", mode=None, group=None):
  658. """
  659. Return a secure and unique filename by pre-creating it.
  660. @type directory: str
  661. @param directory: If non-null it will be the directory the file is pre-created in.
  662. @type prefix: str
  663. @param prefix: The filename will be prefixed with this string
  664. @type suffix: str
  665. @param suffix: The filename will end with this string
  666. @type mode: str
  667. @param mode: If set the file will get chmodded to those permissions
  668. @type group: str
  669. @param group: If set the file will get chgrped to the specified group.
  670. @rtype: list
  671. @return: Returns a pair (fd, name)
  672. """
  673. (tfd, tfname) = tempfile.mkstemp(suffix, prefix, directory)
  674. if mode:
  675. os.chmod(tfname, mode)
  676. if group:
  677. gid = grp.getgrnam(group).gr_gid
  678. os.chown(tfname, -1, gid)
  679. return (tfd, tfname)
  680. ################################################################################
  681. def temp_dirname(parent=None, prefix="dak", suffix="", mode=None, group=None):
  682. """
  683. Return a secure and unique directory by pre-creating it.
  684. @type parent: str
  685. @param parent: If non-null it will be the directory the directory is pre-created in.
  686. @type prefix: str
  687. @param prefix: The filename will be prefixed with this string
  688. @type suffix: str
  689. @param suffix: The filename will end with this string
  690. @type mode: str
  691. @param mode: If set the file will get chmodded to those permissions
  692. @type group: str
  693. @param group: If set the file will get chgrped to the specified group.
  694. @rtype: list
  695. @return: Returns a pair (fd, name)
  696. """
  697. tfname = tempfile.mkdtemp(suffix, prefix, parent)
  698. if mode:
  699. os.chmod(tfname, mode)
  700. if group:
  701. gid = grp.getgrnam(group).gr_gid
  702. os.chown(tfname, -1, gid)
  703. return tfname
  704. ################################################################################
  705. def get_changes_files(from_dir):
  706. """
  707. Takes a directory and lists all .changes files in it (as well as chdir'ing
  708. to the directory; this is due to broken behaviour on the part of p-u/p-a
  709. when you're not in the right place)
  710. Returns a list of filenames
  711. """
  712. try:
  713. # Much of the rest of p-u/p-a depends on being in the right place
  714. os.chdir(from_dir)
  715. changes_files = [x for x in os.listdir(from_dir) if x.endswith('.changes')]
  716. except OSError as e:
  717. fubar("Failed to read list from directory %s (%s)" % (from_dir, e))
  718. return changes_files
  719. ################################################################################
  720. Cnf = config.Config().Cnf
  721. ################################################################################
  722. def parse_wnpp_bug_file(file="/srv/ftp-master.debian.org/scripts/masterfiles/wnpp_rm"):
  723. """
  724. Parses the wnpp bug list available at https://qa.debian.org/data/bts/wnpp_rm
  725. Well, actually it parsed a local copy, but let's document the source
  726. somewhere ;)
  727. returns a dict associating source package name with a list of open wnpp
  728. bugs (Yes, there might be more than one)
  729. """
  730. line = []
  731. try:
  732. with open(file) as f:
  733. lines = f.readlines()
  734. except IOError as e:
  735. print("Warning: Couldn't open %s; don't know about WNPP bugs, so won't close any." % file)
  736. lines = []
  737. wnpp = {}
  738. for line in lines:
  739. splited_line = line.split(": ", 1)
  740. if len(splited_line) > 1:
  741. wnpp[splited_line[0]] = splited_line[1].split("|")
  742. for source in wnpp:
  743. bugs = []
  744. for wnpp_bug in wnpp[source]:
  745. bug_no = re.search(r"(\d)+", wnpp_bug).group()
  746. if bug_no:
  747. bugs.append(bug_no)
  748. wnpp[source] = bugs
  749. return wnpp
  750. ################################################################################
  751. def deb_extract_control(fh):
  752. """extract DEBIAN/control from a binary package"""
  753. return apt_inst.DebFile(fh).control.extractdata("control")
  754. ################################################################################
  755. def mail_addresses_for_upload(maintainer, changed_by, fingerprint):
  756. """mail addresses to contact for an upload
  757. @type maintainer: str
  758. @param maintainer: Maintainer field of the .changes file
  759. @type changed_by: str
  760. @param changed_by: Changed-By field of the .changes file
  761. @type fingerprint: str
  762. @param fingerprint: fingerprint of the key used to sign the upload
  763. @rtype: list of str
  764. @return: list of RFC 2047-encoded mail addresses to contact regarding
  765. this upload
  766. """
  767. recipients = Cnf.value_list('Dinstall::UploadMailRecipients')
  768. if not recipients:
  769. recipients = [
  770. 'maintainer',
  771. 'changed_by',
  772. 'signer',
  773. ]
  774. # Ensure signer is last if present
  775. try:
  776. recipients.remove('signer')
  777. recipients.append('signer')
  778. except ValueError:
  779. pass
  780. # Compute the set of addresses of the recipients
  781. addresses = set() # Name + email
  782. emails = set() # Email only, used to avoid duplicates
  783. for recipient in recipients:
  784. if recipient.startswith('mail:'): # Email hardcoded in config
  785. address = recipient[5:]
  786. elif recipient == 'maintainer':
  787. address = maintainer
  788. elif recipient == 'changed_by':
  789. address = changed_by
  790. elif recipient == 'signer':
  791. fpr_addresses = gpg_get_key_addresses(fingerprint)
  792. address = fpr_addresses[0] if fpr_addresses else None
  793. if any(x in emails for x in fpr_addresses):
  794. # The signer already gets a copy via another email
  795. address = None
  796. else:
  797. raise Exception('Unsupported entry in {0}: {1}'.format(
  798. 'Dinstall::UploadMailRecipients', recipient))
  799. if address is not None:
  800. email = fix_maintainer(address)[3]
  801. if email not in emails:
  802. addresses.add(address)
  803. emails.add(email)
  804. encoded_addresses = [fix_maintainer(e)[1] for e in addresses]
  805. return encoded_addresses
  806. ################################################################################
  807. def call_editor_for_file(path):
  808. editor = os.environ.get('VISUAL', os.environ.get('EDITOR', 'sensible-editor'))
  809. daklib.daksubprocess.check_call([editor, path])
  810. ################################################################################
  811. def call_editor(text="", suffix=".txt"):
  812. """run editor and return the result as a string
  813. @type text: str
  814. @param text: initial text
  815. @type suffix: str
  816. @param suffix: extension for temporary file
  817. @rtype: str
  818. @return: string with the edited text
  819. """
  820. with tempfile.NamedTemporaryFile(mode='w+t', suffix=suffix) as fh:
  821. print(text, end='', file=fh)
  822. fh.flush()
  823. call_editor_for_file(fh.name)
  824. fh.seek(0)
  825. return fh.read()
  826. ################################################################################
  827. def check_reverse_depends(removals, suite, arches=None, session=None, cruft=False, quiet=False, include_arch_all=True):
  828. dbsuite = get_suite(suite, session)
  829. overridesuite = dbsuite
  830. if dbsuite.overridesuite is not None:
  831. overridesuite = get_suite(dbsuite.overridesuite, session)
  832. dep_problem = 0
  833. p2c = {}
  834. all_broken = defaultdict(lambda: defaultdict(set))
  835. if arches:
  836. all_arches = set(arches)
  837. else:
  838. all_arches = set(x.arch_string for x in get_suite_architectures(suite))
  839. all_arches -= set(["source", "all"])
  840. removal_set = set(removals)
  841. metakey_d = get_or_set_metadatakey("Depends", session)
  842. metakey_p = get_or_set_metadatakey("Provides", session)
  843. params = {
  844. 'suite_id': dbsuite.suite_id,
  845. 'metakey_d_id': metakey_d.key_id,
  846. 'metakey_p_id': metakey_p.key_id,
  847. }
  848. if include_arch_all:
  849. rdep_architectures = all_arches | set(['all'])
  850. else:
  851. rdep_architectures = all_arches
  852. for architecture in rdep_architectures:
  853. deps = {}
  854. sources = {}
  855. virtual_packages = {}
  856. try:
  857. params['arch_id'] = get_architecture(architecture, session).arch_id
  858. except AttributeError:
  859. continue
  860. statement = sql.text('''
  861. SELECT b.package, s.source, c.name as component,
  862. (SELECT bmd.value FROM binaries_metadata bmd WHERE bmd.bin_id = b.id AND bmd.key_id = :metakey_d_id) AS depends,
  863. (SELECT bmp.value FROM binaries_metadata bmp WHERE bmp.bin_id = b.id AND bmp.key_id = :metakey_p_id) AS provides
  864. FROM binaries b
  865. JOIN bin_associations ba ON b.id = ba.bin AND ba.suite = :suite_id
  866. JOIN source s ON b.source = s.id
  867. JOIN files_archive_map af ON b.file = af.file_id
  868. JOIN component c ON af.component_id = c.id
  869. WHERE b.architecture = :arch_id''')
  870. query = session.query('package', 'source', 'component', 'depends', 'provides'). \
  871. from_statement(statement).params(params)
  872. for package, source, component, depends, provides in query:
  873. sources[package] = source
  874. p2c[package] = component
  875. if depends is not None:
  876. deps[package] = depends
  877. # Maintain a counter for each virtual package. If a
  878. # Provides: exists, set the counter to 0 and count all
  879. # provides by a package not in the list for removal.
  880. # If the counter stays 0 at the end, we know that only
  881. # the to-be-removed packages provided this virtual
  882. # package.
  883. if provides is not None:
  884. for virtual_pkg in provides.split(","):
  885. virtual_pkg = virtual_pkg.strip()
  886. if virtual_pkg == package:
  887. continue
  888. if virtual_pkg not in virtual_packages:
  889. virtual_packages[virtual_pkg] = 0
  890. if package not in removals:
  891. virtual_packages[virtual_pkg] += 1
  892. # If a virtual package is only provided by the to-be-removed
  893. # packages, treat the virtual package as to-be-removed too.
  894. removal_set.update(virtual_pkg for virtual_pkg in virtual_packages if not virtual_packages[virtual_pkg])
  895. # Check binary dependencies (Depends)
  896. for package in deps:
  897. if package in removals:
  898. continue
  899. try:
  900. parsed_dep = apt_pkg.parse_depends(deps[package])
  901. except ValueError as e:
  902. print("Error for package %s: %s" % (package, e))
  903. parsed_dep = []
  904. for dep in parsed_dep:
  905. # Check for partial breakage. If a package has a ORed
  906. # dependency, there is only a dependency problem if all
  907. # packages in the ORed depends will be removed.
  908. unsat = 0
  909. for dep_package, _, _ in dep:
  910. if dep_package in removals:
  911. unsat += 1
  912. if unsat == len(dep):
  913. component = p2c[package]
  914. source = sources[package]
  915. if component != "main":
  916. source = "%s/%s" % (source, component)
  917. all_broken[source][package].add(architecture)
  918. dep_problem = 1
  919. if all_broken and not quiet:
  920. if cruft:
  921. print(" - broken Depends:")
  922. else:
  923. print("# Broken Depends:")
  924. for source, bindict in sorted(all_broken.items()):
  925. lines = []
  926. for binary, arches in sorted(bindict.items()):
  927. if arches == all_arches or 'all' in arches:
  928. lines.append(binary)
  929. else:
  930. lines.append('%s [%s]' % (binary, ' '.join(sorted(arches))))
  931. if cruft:
  932. print(' %s: %s' % (source, lines[0]))
  933. else:
  934. print('%s: %s' % (source, lines[0]))
  935. for line in lines[1:]:
  936. if cruft:
  937. print(' ' + ' ' * (len(source) + 2) + line)
  938. else:
  939. print(' ' * (len(source) + 2) + line)
  940. if not cruft:
  941. print()
  942. # Check source dependencies (Build-Depends and Build-Depends-Indep)
  943. all_broken = defaultdict(set)
  944. metakey_bd = get_or_set_metadatakey("Build-Depends", session)
  945. metakey_bdi = get_or_set_metadatakey("Build-Depends-Indep", session)
  946. if include_arch_all:
  947. metakey_ids = (metakey_bd.key_id, metakey_bdi.key_id)
  948. else:
  949. metakey_ids = (metakey_bd.key_id,)
  950. params = {
  951. 'suite_id': dbsuite.suite_id,
  952. 'metakey_ids': metakey_ids,
  953. }
  954. statement = sql.text('''
  955. SELECT s.source, string_agg(sm.value, ', ') as build_dep
  956. FROM source s
  957. JOIN source_metadata sm ON s.id = sm.src_id
  958. WHERE s.id in
  959. (SELECT src FROM newest_src_association
  960. WHERE suite = :suite_id)
  961. AND sm.key_id in :metakey_ids
  962. GROUP BY s.id, s.source''')
  963. query = session.query('source', 'build_dep').from_statement(statement). \
  964. params(params)
  965. for source, build_dep in query:
  966. if source in removals:
  967. continue
  968. parsed_dep = []
  969. if build_dep is not None:
  970. # Remove [arch] information since we want to see breakage on all arches
  971. build_dep = re_build_dep_arch.sub("", build_dep)
  972. try:
  973. parsed_dep = apt_pkg.parse_src_depends(build_dep)
  974. except ValueError as e:
  975. print("Error for source %s: %s" % (source, e))
  976. for dep in parsed_dep:
  977. unsat = 0
  978. for dep_package, _, _ in dep:
  979. if dep_package in removals:
  980. unsat += 1
  981. if unsat == len(dep):
  982. component, = session.query(Component.component_name) \
  983. .join(Component.overrides) \
  984. .filter(Override.suite == overridesuite) \
  985. .filter(Override.package == re.sub('/(contrib|non-free)$', '', source)) \
  986. .join(Override.overridetype).filter(OverrideType.overridetype == 'dsc') \
  987. .first()
  988. key = source
  989. if component != "main":
  990. key = "%s/%s" % (source, component)
  991. all_broken[key].add(pp_deps(dep))
  992. dep_problem = 1
  993. if all_broken and not quiet:
  994. if cruft:
  995. print(" - broken Build-Depends:")
  996. else:
  997. print("# Broken Build-Depends:")
  998. for source, bdeps in sorted(all_broken.items()):
  999. bdeps = sorted(bdeps)
  1000. if cruft:
  1001. print(' %s: %s' % (source, bdeps[0]))
  1002. else:
  1003. print('%s: %s' % (source, bdeps[0]))
  1004. for bdep in bdeps[1:]:
  1005. if cruft:
  1006. print(' ' + ' ' * (len(source) + 2) + bdep)
  1007. else:
  1008. print(' ' * (len(source) + 2) + bdep)
  1009. if not cruft:
  1010. print()
  1011. return dep_problem
  1012. ################################################################################
  1013. def parse_built_using(control):
  1014. """source packages referenced via Built-Using
  1015. @type control: dict-like
  1016. @param control: control file to take Built-Using field from
  1017. @rtype: list of (str, str)
  1018. @return: list of (source_name, source_version) pairs
  1019. """
  1020. built_using = control.get('Built-Using', None)
  1021. if built_using is None:
  1022. return []
  1023. bu = []
  1024. for dep in apt_pkg.parse_depends(built_using):
  1025. assert len(dep) == 1, 'Alternatives are not allowed in Built-Using field'
  1026. source_name, source_version, comp = dep[0]
  1027. assert comp == '=', 'Built-Using must contain strict dependencies'
  1028. bu.append((source_name, source_version))
  1029. return bu
  1030. ################################################################################
  1031. def is_in_debug_section(control):
  1032. """binary package is a debug package
  1033. @type control: dict-like
  1034. @param control: control file of binary package
  1035. @rtype Boolean
  1036. @return: True if the binary package is a debug package
  1037. """
  1038. section = control['Section'].split('/', 1)[-1]
  1039. auto_built_package = control.get("Auto-Built-Package")
  1040. return section == "debug" and auto_built_package == "debug-symbols"
  1041. ################################################################################
  1042. def find_possibly_compressed_file(filename):
  1043. """
  1044. @type filename: string
  1045. @param filename: path to a control file (Sources, Packages, etc) to
  1046. look for
  1047. @rtype string
  1048. @return: path to the (possibly compressed) control file, or null if the
  1049. file doesn't exist
  1050. """
  1051. _compressions = ('', '.xz', '.gz', '.bz2')
  1052. for ext in _compressions:
  1053. _file = filename + ext
  1054. if os.path.exists(_file):
  1055. return _file
  1056. raise IOError(errno.ENOENT, os.strerror(errno.ENOENT), filename)
  1057. ################################################################################
  1058. def parse_boolean_from_user(value):
  1059. value = value.lower()
  1060. if value in {'yes', 'true', 'enable', 'enabled'}:
  1061. return True
  1062. if value in {'no', 'false', 'disable', 'disabled'}:
  1063. return False
  1064. raise ValueError("Not sure whether %s should be a True or a False" % value)
  1065. def suite_suffix(suite_name):
  1066. """Return suite_suffix for the given suite"""
  1067. suffix = Cnf.find('Dinstall::SuiteSuffix', '')
  1068. if suffix == '':
  1069. return ''
  1070. elif 'Dinstall::SuiteSuffixSuites' not in Cnf:
  1071. # TODO: warn (once per run) that SuiteSuffix will be deprecated in the future
  1072. return suffix
  1073. elif suite_name in Cnf.value_list('Dinstall::SuiteSuffixSuites'):
  1074. return suffix
  1075. return ''
  1076. ################################################################################
  1077. def process_buildinfos(directory, buildinfo_files, fs_transaction, logger):
  1078. """Copy buildinfo files into Dir::BuildinfoArchive
  1079. @type directory: string
  1080. @param directory: directory where .changes is stored
  1081. @type buildinfo_files: list of str
  1082. @param buildinfo_files: names of buildinfo files
  1083. @type fs_transaction: L{daklib.fstransactions.FilesystemTransaction}
  1084. @param fs_transaction: FilesystemTransaction instance
  1085. @type logger: L{daklib.daklog.Logger}
  1086. @param logger: logger instance
  1087. """
  1088. if 'Dir::BuildinfoArchive' not in Cnf:
  1089. return
  1090. target_dir = os.path.join(
  1091. Cnf['Dir::BuildinfoArchive'],
  1092. datetime.datetime.now().strftime('%Y/%m/%d'),
  1093. )
  1094. for f in buildinfo_files:
  1095. src = os.path.join(directory, f.filename)
  1096. dst = find_next_free(os.path.join(target_dir, f.filename))
  1097. logger.log(["Archiving", f.filename])
  1098. fs_transaction.copy(src, dst, mode=0o644)
  1099. ################################################################################
  1100. def move_to_morgue(morguesubdir, filenames, fs_transaction, logger):
  1101. """Move a file to the correct dir in morgue
  1102. @type morguesubdir: string
  1103. @param morguesubdir: subdirectory of morgue where this file needs to go
  1104. @type filename: list of str
  1105. @param filename: names of files
  1106. @type fs_transaction: L{daklib.fstransactions.FilesystemTransaction}
  1107. @param fs_transaction: FilesystemTransaction instance
  1108. @type logger: L{daklib.daklog.Logger}
  1109. @param logger: logger instance
  1110. """
  1111. morguedir = Cnf.get("Dir::Morgue", os.path.join(
  1112. Cnf.get("Dir::Base"), 'morgue'))
  1113. # Build directory as morguedir/morguesubdir/year/month/day
  1114. now = datetime.datetime.now()
  1115. dest = os.path.join(morguedir,
  1116. morguesubdir,
  1117. str(now.year),
  1118. '%.2d' % now.month,
  1119. '%.2d' % now.day)
  1120. for filename in filenames:
  1121. dest_filename = dest + '/' + os.path.basename(filename)
  1122. # If the destination file exists; try to find another filename to use
  1123. if os.path.lexists(dest_filename):
  1124. dest_filename = find_next_free(dest_filename)
  1125. logger.log(["move to morgue", filename, dest_filename])
  1126. fs_transaction.move(filename, dest_filename)