blob: f4d80cfeef0cc3c1cfd455dc3b950051b45aa842 [file] [log] [blame]
maruelea586f32016-04-05 11:11:33 -07001# Copyright 2014 The LUCI Authors. All rights reserved.
maruelf1f5e2a2016-05-25 17:10:39 -07002# Use of this source code is governed under the Apache License, Version 2.0
3# that can be found in the LICENSE file.
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -04004
5"""Understands .isolated files and can do local operations on them."""
6
7import hashlib
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -04008import json
Marc-Antoine Ruel92257792014-08-28 20:51:08 -04009import logging
10import os
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040011import re
Marc-Antoine Ruel92257792014-08-28 20:51:08 -040012import stat
13import sys
14
15from utils import file_path
maruel12e30012015-10-09 11:55:35 -070016from utils import fs
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -040017from utils import tools
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040018
19
20# Version stored and expected in .isolated files.
tansell26de79e2016-11-13 18:41:11 -080021ISOLATED_FILE_VERSION = '1.6'
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040022
23
24# Chunk size to use when doing disk I/O.
25DISK_FILE_CHUNK = 1024 * 1024
26
27
Adrian Ludwinb4ebc092017-09-13 07:46:24 -040028# Sadly, hashlib uses 'shaX' instead of the standard 'sha-X' so explicitly
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040029# specify the names here.
30SUPPORTED_ALGOS = {
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040031 'sha-1': hashlib.sha1,
Adrian Ludwinb4ebc092017-09-13 07:46:24 -040032 'sha-256': hashlib.sha256,
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040033 'sha-512': hashlib.sha512,
34}
35
36
37# Used for serialization.
38SUPPORTED_ALGOS_REVERSE = dict((v, k) for k, v in SUPPORTED_ALGOS.iteritems())
39
Marc-Antoine Ruel7dafa772017-09-12 19:25:59 -040040
41SUPPORTED_FILE_TYPES = ['basic', 'tar']
tanselle4288c32016-07-28 09:45:40 -070042
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040043
Marc-Antoine Ruel1e7658c2014-08-28 19:46:39 -040044class IsolatedError(ValueError):
45 """Generic failure to load a .isolated file."""
46 pass
47
48
49class MappingError(OSError):
50 """Failed to recreate the tree."""
51 pass
52
53
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040054def is_valid_hash(value, algo):
55 """Returns if the value is a valid hash for the corresponding algorithm."""
56 size = 2 * algo().digest_size
57 return bool(re.match(r'^[a-fA-F0-9]{%d}$' % size, value))
58
59
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040060def hash_file(filepath, algo):
61 """Calculates the hash of a file without reading it all in memory at once.
62
63 |algo| should be one of hashlib hashing algorithm.
64 """
65 digest = algo()
maruel12e30012015-10-09 11:55:35 -070066 with fs.open(filepath, 'rb') as f:
Marc-Antoine Ruel8bee66d2014-08-28 19:02:07 -040067 while True:
68 chunk = f.read(DISK_FILE_CHUNK)
69 if not chunk:
70 break
71 digest.update(chunk)
72 return digest.hexdigest()
Marc-Antoine Ruel92257792014-08-28 20:51:08 -040073
74
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -040075class IsolatedFile(object):
76 """Represents a single parsed .isolated file."""
Vadim Shtayura7f7459c2014-09-04 13:25:10 -070077
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -040078 def __init__(self, obj_hash, algo):
Adrian Ludwinb4ebc092017-09-13 07:46:24 -040079 """|obj_hash| is really the hash of the file."""
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -040080 self.obj_hash = obj_hash
81 self.algo = algo
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -040082
83 # Raw data.
84 self.data = {}
85 # A IsolatedFile instance, one per object in self.includes.
86 self.children = []
87
88 # Set once the .isolated file is loaded.
Vadim Shtayura7f7459c2014-09-04 13:25:10 -070089 self._is_loaded = False
90
91 def __repr__(self):
92 return 'IsolatedFile(%s, loaded: %s)' % (self.obj_hash, self._is_loaded)
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -040093
94 def load(self, content):
95 """Verifies the .isolated file is valid and loads this object with the json
96 data.
97 """
98 logging.debug('IsolatedFile.load(%s)' % self.obj_hash)
Vadim Shtayura7f7459c2014-09-04 13:25:10 -070099 assert not self._is_loaded
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400100 self.data = load_isolated(content, self.algo)
101 self.children = [
102 IsolatedFile(i, self.algo) for i in self.data.get('includes', [])
103 ]
Vadim Shtayura7f7459c2014-09-04 13:25:10 -0700104 self._is_loaded = True
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400105
Vadim Shtayura7f7459c2014-09-04 13:25:10 -0700106 @property
107 def is_loaded(self):
108 """Returns True if 'load' was already called."""
109 return self._is_loaded
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400110
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400111
Vadim Shtayura7f7459c2014-09-04 13:25:10 -0700112def walk_includes(isolated):
113 """Walks IsolatedFile include graph and yields IsolatedFile objects.
114
115 Visits root node first, then recursively all children, left to right.
116 Not yet loaded nodes are considered childless.
117 """
118 yield isolated
119 for child in isolated.children:
120 for x in walk_includes(child):
121 yield x
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400122
123
Vadim Shtayurac28b74f2014-10-06 20:00:08 -0700124@tools.profile
Marc-Antoine Rueldcff6462018-12-04 16:35:18 +0000125def _expand_symlinks(indir, relfile):
126 """Finds symlinks in relfile.
127
128 Follows symlinks in |relfile|, but treating symlinks that point outside the
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400129 build tree as if they were ordinary directories/files. Returns the final
130 symlink-free target and a list of paths to symlinks encountered in the
131 process.
132
133 The rule about symlinks outside the build tree is for the benefit of the
134 Chromium OS ebuild, which symlinks the output directory to an unrelated path
135 in the chroot.
136
137 Fails when a directory loop is detected, although in theory we could support
138 that case.
Marc-Antoine Rueldcff6462018-12-04 16:35:18 +0000139
140 Arguments:
141 - indir: base directory; symlinks in indir are not processed; this is
142 the base directory that is considered 'outside of the tree'.
143 - relfile: part of the path to expand symlink.
144
145 Returns:
146 tuple(relfile, list(symlinks)): relfile is real path of relfile where all
147 symlinks were evaluated. symlinks if the chain of symlinks found along the
148 way, if any.
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400149 """
150 is_directory = relfile.endswith(os.path.sep)
151 done = indir
152 todo = relfile.strip(os.path.sep)
153 symlinks = []
154
155 while todo:
Vadim Shtayura56c17562014-10-07 17:13:34 -0700156 pre_symlink, symlink, post_symlink = file_path.split_at_symlink(done, todo)
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400157 if not symlink:
158 todo = file_path.fix_native_path_case(done, todo)
159 done = os.path.join(done, todo)
160 break
161 symlink_path = os.path.join(done, pre_symlink, symlink)
162 post_symlink = post_symlink.lstrip(os.path.sep)
163 # readlink doesn't exist on Windows.
164 # pylint: disable=E1101
165 target = os.path.normpath(os.path.join(done, pre_symlink))
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500166 symlink_target = fs.readlink(symlink_path)
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400167 if os.path.isabs(symlink_target):
168 # Absolute path are considered a normal directories. The use case is
169 # generally someone who puts the output directory on a separate drive.
170 target = symlink_target
171 else:
172 # The symlink itself could be using the wrong path case.
173 target = file_path.fix_native_path_case(target, symlink_target)
174
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500175 if not fs.exists(target):
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400176 raise MappingError(
177 'Symlink target doesn\'t exist: %s -> %s' % (symlink_path, target))
178 target = file_path.get_native_path_case(target)
179 if not file_path.path_starts_with(indir, target):
180 done = symlink_path
181 todo = post_symlink
182 continue
183 if file_path.path_starts_with(target, symlink_path):
184 raise MappingError(
185 'Can\'t map recursive symlink reference %s -> %s' %
186 (symlink_path, target))
187 logging.info('Found symlink: %s -> %s', symlink_path, target)
188 symlinks.append(os.path.relpath(symlink_path, indir))
189 # Treat the common prefix of the old and new paths as done, and start
190 # scanning again.
191 target = target.split(os.path.sep)
192 symlink_path = symlink_path.split(os.path.sep)
193 prefix_length = 0
194 for target_piece, symlink_path_piece in zip(target, symlink_path):
Marc-Antoine Rueldcff6462018-12-04 16:35:18 +0000195 if target_piece != symlink_path_piece:
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400196 break
Marc-Antoine Rueldcff6462018-12-04 16:35:18 +0000197 prefix_length += 1
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400198 done = os.path.sep.join(target[:prefix_length])
199 todo = os.path.join(
200 os.path.sep.join(target[prefix_length:]), post_symlink)
201
202 relfile = os.path.relpath(done, indir)
203 relfile = relfile.rstrip(os.path.sep) + is_directory * os.path.sep
204 return relfile, symlinks
205
206
Vadim Shtayurac28b74f2014-10-06 20:00:08 -0700207@tools.profile
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400208def expand_directory_and_symlink(indir, relfile, blacklist, follow_symlinks):
209 """Expands a single input. It can result in multiple outputs.
210
211 This function is recursive when relfile is a directory.
212
213 Note: this code doesn't properly handle recursive symlink like one created
214 with:
215 ln -s .. foo
Marc-Antoine Ruelcc802b02018-11-28 21:05:01 +0000216
217 Yields:
218 Relative file paths inside the directory.
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400219 """
220 if os.path.isabs(relfile):
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500221 raise MappingError(u'Can\'t map absolute path %s' % relfile)
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400222
223 infile = file_path.normpath(os.path.join(indir, relfile))
224 if not infile.startswith(indir):
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500225 raise MappingError(u'Can\'t map file %s outside %s' % (infile, indir))
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400226
227 filepath = os.path.join(indir, relfile)
228 native_filepath = file_path.get_native_path_case(filepath)
229 if filepath != native_filepath:
230 # Special case './'.
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500231 if filepath != native_filepath + u'.' + os.path.sep:
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400232 # While it'd be nice to enforce path casing on Windows, it's impractical.
233 # Also give up enforcing strict path case on OSX. Really, it's that sad.
234 # The case where it happens is very specific and hard to reproduce:
235 # get_native_path_case(
236 # u'Foo.framework/Versions/A/Resources/Something.nib') will return
237 # u'Foo.framework/Versions/A/resources/Something.nib', e.g. lowercase 'r'.
238 #
239 # Note that this is really something deep in OSX because running
240 # ls Foo.framework/Versions/A
241 # will print out 'Resources', while file_path.get_native_path_case()
242 # returns a lower case 'r'.
243 #
244 # So *something* is happening under the hood resulting in the command 'ls'
245 # and Carbon.File.FSPathMakeRef('path').FSRefMakePath() to disagree. We
246 # have no idea why.
247 if sys.platform not in ('darwin', 'win32'):
248 raise MappingError(
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500249 u'File path doesn\'t equal native file path\n%s != %s' %
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400250 (filepath, native_filepath))
251
252 symlinks = []
253 if follow_symlinks:
Marc-Antoine Ruela275b292014-11-25 15:17:21 -0500254 try:
Marc-Antoine Rueldcff6462018-12-04 16:35:18 +0000255 relfile, symlinks = _expand_symlinks(indir, relfile)
Marc-Antoine Ruela275b292014-11-25 15:17:21 -0500256 except OSError:
257 # The file doesn't exist, it will throw below.
258 pass
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400259
Marc-Antoine Ruelcc802b02018-11-28 21:05:01 +0000260 for s in symlinks:
261 yield s
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400262 if relfile.endswith(os.path.sep):
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500263 if not fs.isdir(infile):
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400264 raise MappingError(
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500265 u'%s is not a directory but ends with "%s"' % (infile, os.path.sep))
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400266
267 # Special case './'.
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500268 if relfile.startswith(u'.' + os.path.sep):
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400269 relfile = relfile[2:]
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400270 try:
maruel12e30012015-10-09 11:55:35 -0700271 for filename in fs.listdir(infile):
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400272 inner_relfile = os.path.join(relfile, filename)
273 if blacklist and blacklist(inner_relfile):
274 continue
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500275 if fs.isdir(os.path.join(indir, inner_relfile)):
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400276 inner_relfile += os.path.sep
Marc-Antoine Ruelcc802b02018-11-28 21:05:01 +0000277 # Apply recursively.
278 for i in expand_directory_and_symlink(
279 indir, inner_relfile, blacklist, follow_symlinks):
280 yield i
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400281 except OSError as e:
282 raise MappingError(
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500283 u'Unable to iterate over directory %s.\n%s' % (infile, e))
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400284 else:
285 # Always add individual files even if they were blacklisted.
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500286 if fs.isdir(infile):
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400287 raise MappingError(
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500288 u'Input directory %s must have a trailing slash' % infile)
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400289
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500290 if not fs.isfile(infile):
291 raise MappingError(u'Input file %s doesn\'t exist' % infile)
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400292
Marc-Antoine Ruelcc802b02018-11-28 21:05:01 +0000293 yield relfile
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400294
295
Vadim Shtayurac28b74f2014-10-06 20:00:08 -0700296@tools.profile
Marc-Antoine Ruel13554fd2018-12-04 18:01:05 +0000297def file_to_metadata(filepath, read_only, algo, collapse_symlinks):
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400298 """Processes an input file, a dependency, and return meta data about it.
299
300 Behaviors:
301 - Retrieves the file mode, file size, file timestamp, file link
302 destination if it is a file link and calcultate the SHA-1 of the file's
303 content if the path points to a file and not a symlink.
304
305 Arguments:
306 filepath: File to act on.
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400307 read_only: If 1 or 2, the file mode is manipulated. In practice, only save
308 one of 4 modes: 0755 (rwx), 0644 (rw), 0555 (rx), 0444 (r). On
309 windows, mode is not set since all files are 'executable' by
310 default.
311 algo: Hashing algorithm used.
kjlubick80596f02017-04-28 08:13:19 -0700312 collapse_symlinks: True if symlinked files should be treated like they were
313 the normal underlying file.
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400314
315 Returns:
316 The necessary dict to create a entry in the 'files' section of an .isolated
317 file.
318 """
Marc-Antoine Ruelf1d827c2014-11-24 15:22:25 -0500319 # TODO(maruel): None is not a valid value.
320 assert read_only in (None, 0, 1, 2), read_only
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400321 out = {}
Marc-Antoine Ruel13554fd2018-12-04 18:01:05 +0000322 # Always check the file stat and check if it is a link.
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400323 try:
kjlubick80596f02017-04-28 08:13:19 -0700324 if collapse_symlinks:
325 # os.stat follows symbolic links
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500326 filestats = fs.stat(filepath)
kjlubick80596f02017-04-28 08:13:19 -0700327 else:
328 # os.lstat does not follow symbolic links, and thus preserves them.
Marc-Antoine Ruel7a68f712017-12-01 18:45:18 -0500329 filestats = fs.lstat(filepath)
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400330 except OSError:
331 # The file is not present.
332 raise MappingError('%s is missing' % filepath)
333 is_link = stat.S_ISLNK(filestats.st_mode)
334
335 if sys.platform != 'win32':
336 # Ignore file mode on Windows since it's not really useful there.
337 filemode = stat.S_IMODE(filestats.st_mode)
338 # Remove write access for group and all access to 'others'.
339 filemode &= ~(stat.S_IWGRP | stat.S_IRWXO)
340 if read_only:
341 filemode &= ~stat.S_IWUSR
Marc-Antoine Ruela275b292014-11-25 15:17:21 -0500342 if filemode & (stat.S_IXUSR|stat.S_IRGRP) == (stat.S_IXUSR|stat.S_IRGRP):
343 # Only keep x group bit if both x user bit and group read bit are set.
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400344 filemode |= stat.S_IXGRP
345 else:
346 filemode &= ~stat.S_IXGRP
347 if not is_link:
348 out['m'] = filemode
349
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400350 if not is_link:
351 out['s'] = filestats.st_size
Marc-Antoine Ruel13554fd2018-12-04 18:01:05 +0000352 out['h'] = hash_file(filepath, algo)
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400353 else:
Marc-Antoine Ruel13554fd2018-12-04 18:01:05 +0000354 # The link could be in an incorrect path case. In practice, this only
355 # happens on macOS on case insensitive HFS.
356 # TODO(maruel): It'd be better if it was only done once, in
357 # expand_directory_and_symlink(), so it would not be necessary to do again
358 # here.
359 symlink_value = fs.readlink(filepath) # pylint: disable=no-member
360 filedir = file_path.get_native_path_case(os.path.dirname(filepath))
361 native_dest = file_path.fix_native_path_case(filedir, symlink_value)
362 out['l'] = os.path.relpath(native_dest, filedir)
Marc-Antoine Ruel92257792014-08-28 20:51:08 -0400363 return out
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400364
365
366def save_isolated(isolated, data):
367 """Writes one or multiple .isolated files.
368
369 Note: this reference implementation does not create child .isolated file so it
370 always returns an empty list.
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400371 """
372 # Make sure the data is valid .isolated data by 'reloading' it.
373 algo = SUPPORTED_ALGOS[data['algo']]
374 load_isolated(json.dumps(data), algo)
375 tools.write_json(isolated, data, True)
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400376
377
marueldf6e95e2016-02-26 19:05:38 -0800378def split_path(path):
379 """Splits a path and return a list with each element."""
380 out = []
381 while path:
382 path, rest = os.path.split(path)
383 if rest:
384 out.append(rest)
385 return out
386
387
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400388def load_isolated(content, algo):
389 """Verifies the .isolated file is valid and loads this object with the json
390 data.
391
392 Arguments:
393 - content: raw serialized content to load.
394 - algo: hashlib algorithm class. Used to confirm the algorithm matches the
395 algorithm used on the Isolate Server.
396 """
Marc-Antoine Ruel5da404c2017-10-31 10:46:37 -0400397 if not algo:
398 raise IsolatedError('\'algo\' is required')
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400399 try:
400 data = json.loads(content)
aludwin6b54a6b2017-08-03 18:20:06 -0700401 except ValueError as v:
Adrian Ludwin7dc29dd2017-08-17 23:01:47 -0400402 logging.error('Failed to parse .isolated file:\n%s', content)
aludwin6b54a6b2017-08-03 18:20:06 -0700403 raise IsolatedError('Failed to parse (%s): %s...' % (v, content[:100]))
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400404
405 if not isinstance(data, dict):
406 raise IsolatedError('Expected dict, got %r' % data)
407
408 # Check 'version' first, since it could modify the parsing after.
409 value = data.get('version', '1.0')
410 if not isinstance(value, basestring):
411 raise IsolatedError('Expected string, got %r' % value)
412 try:
413 version = tuple(map(int, value.split('.')))
414 except ValueError:
415 raise IsolatedError('Expected valid version, got %r' % value)
416
417 expected_version = tuple(map(int, ISOLATED_FILE_VERSION.split('.')))
418 # Major version must match.
419 if version[0] != expected_version[0]:
420 raise IsolatedError(
421 'Expected compatible \'%s\' version, got %r' %
422 (ISOLATED_FILE_VERSION, value))
423
Adrian Ludwinb4ebc092017-09-13 07:46:24 -0400424 algo_name = SUPPORTED_ALGOS_REVERSE[algo]
425
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400426 for key, value in data.iteritems():
427 if key == 'algo':
428 if not isinstance(value, basestring):
429 raise IsolatedError('Expected string, got %r' % value)
430 if value not in SUPPORTED_ALGOS:
431 raise IsolatedError(
432 'Expected one of \'%s\', got %r' %
433 (', '.join(sorted(SUPPORTED_ALGOS)), value))
434 if value != SUPPORTED_ALGOS_REVERSE[algo]:
435 raise IsolatedError(
436 'Expected \'%s\', got %r' % (SUPPORTED_ALGOS_REVERSE[algo], value))
437
438 elif key == 'command':
439 if not isinstance(value, list):
440 raise IsolatedError('Expected list, got %r' % value)
441 if not value:
442 raise IsolatedError('Expected non-empty command')
443 for subvalue in value:
444 if not isinstance(subvalue, basestring):
445 raise IsolatedError('Expected string, got %r' % subvalue)
446
447 elif key == 'files':
448 if not isinstance(value, dict):
449 raise IsolatedError('Expected dict, got %r' % value)
450 for subkey, subvalue in value.iteritems():
451 if not isinstance(subkey, basestring):
452 raise IsolatedError('Expected string, got %r' % subkey)
marueldf6e95e2016-02-26 19:05:38 -0800453 if os.path.isabs(subkey) or subkey.startswith('\\\\'):
454 # Disallow '\\\\', it could UNC on Windows but disallow this
455 # everywhere.
456 raise IsolatedError('File path can\'t be absolute: %r' % subkey)
457 if subkey.endswith(('/', '\\')):
458 raise IsolatedError(
459 'File path can\'t end with \'%s\': %r' % (subkey[-1], subkey))
460 if '..' in split_path(subkey):
461 raise IsolatedError('File path can\'t reference parent: %r' % subkey)
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400462 if not isinstance(subvalue, dict):
463 raise IsolatedError('Expected dict, got %r' % subvalue)
464 for subsubkey, subsubvalue in subvalue.iteritems():
465 if subsubkey == 'l':
466 if not isinstance(subsubvalue, basestring):
467 raise IsolatedError('Expected string, got %r' % subsubvalue)
468 elif subsubkey == 'm':
469 if not isinstance(subsubvalue, int):
470 raise IsolatedError('Expected int, got %r' % subsubvalue)
471 elif subsubkey == 'h':
472 if not is_valid_hash(subsubvalue, algo):
Adrian Ludwinb4ebc092017-09-13 07:46:24 -0400473 raise IsolatedError('Expected %s, got %r' %
474 (algo_name, subsubvalue))
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400475 elif subsubkey == 's':
476 if not isinstance(subsubvalue, (int, long)):
477 raise IsolatedError('Expected int or long, got %r' % subsubvalue)
tanselle4288c32016-07-28 09:45:40 -0700478 elif subsubkey == 't':
479 if subsubvalue not in SUPPORTED_FILE_TYPES:
480 raise IsolatedError('Expected one of \'%s\', got %r' % (
481 ', '.join(sorted(SUPPORTED_FILE_TYPES)), subsubvalue))
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400482 else:
483 raise IsolatedError('Unknown subsubkey %s' % subsubkey)
484 if bool('h' in subvalue) == bool('l' in subvalue):
485 raise IsolatedError(
Adrian Ludwinb4ebc092017-09-13 07:46:24 -0400486 'Need only one of \'h\' (%s) or \'l\' (link), got: %r' %
487 (algo_name, subvalue))
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400488 if bool('h' in subvalue) != bool('s' in subvalue):
489 raise IsolatedError(
Adrian Ludwinb4ebc092017-09-13 07:46:24 -0400490 'Both \'h\' (%s) and \'s\' (size) should be set, got: %r' %
491 (algo_name, subvalue))
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400492 if bool('s' in subvalue) == bool('l' in subvalue):
493 raise IsolatedError(
494 'Need only one of \'s\' (size) or \'l\' (link), got: %r' %
495 subvalue)
496 if bool('l' in subvalue) and bool('m' in subvalue):
497 raise IsolatedError(
498 'Cannot use \'m\' (mode) and \'l\' (link), got: %r' %
499 subvalue)
500
501 elif key == 'includes':
502 if not isinstance(value, list):
503 raise IsolatedError('Expected list, got %r' % value)
504 if not value:
505 raise IsolatedError('Expected non-empty includes list')
506 for subvalue in value:
507 if not is_valid_hash(subvalue, algo):
Adrian Ludwinb4ebc092017-09-13 07:46:24 -0400508 raise IsolatedError('Expected %s, got %r' % (algo_name, subvalue))
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400509
510 elif key == 'os':
511 if version >= (1, 4):
512 raise IsolatedError('Key \'os\' is not allowed starting version 1.4')
513
514 elif key == 'read_only':
515 if not value in (0, 1, 2):
516 raise IsolatedError('Expected 0, 1 or 2, got %r' % value)
517
518 elif key == 'relative_cwd':
519 if not isinstance(value, basestring):
520 raise IsolatedError('Expected string, got %r' % value)
521
522 elif key == 'version':
523 # Already checked above.
524 pass
525
526 else:
527 raise IsolatedError('Unknown key %r' % key)
528
529 # Automatically fix os.path.sep if necessary. While .isolated files are always
Marc-Antoine Ruelf674a582018-01-12 10:56:01 -0500530 # in the native path format, someone could want to download an .isolated tree
531 # from another OS.
Marc-Antoine Ruel52436aa2014-08-28 21:57:57 -0400532 wrong_path_sep = '/' if os.path.sep == '\\' else '\\'
533 if 'files' in data:
534 data['files'] = dict(
535 (k.replace(wrong_path_sep, os.path.sep), v)
536 for k, v in data['files'].iteritems())
537 for v in data['files'].itervalues():
538 if 'l' in v:
539 v['l'] = v['l'].replace(wrong_path_sep, os.path.sep)
540 if 'relative_cwd' in data:
541 data['relative_cwd'] = data['relative_cwd'].replace(
542 wrong_path_sep, os.path.sep)
543 return data