blob: b13aa111949dd4fca3a29c9c94b10fdf1e1af719 [file] [log] [blame]
Gilad Arnold553b0ec2013-01-26 01:00:39 -08001# Copyright (c) 2013 The Chromium OS Authors. All rights reserved.
2# Use of this source code is governed by a BSD-style license that can be
3# found in the LICENSE file.
4
5"""Tools for reading, verifying and applying Chrome OS update payloads."""
6
7import hashlib
8import struct
9
10import applier
11import block_tracer
12import checker
13import common
14from error import PayloadError
15import update_metadata_pb2
16
17
18#
19# Helper functions.
20#
21def _ReadInt(file_obj, size, is_unsigned, hasher=None):
Gilad Arnold5502b562013-03-08 13:22:31 -080022 """Reads a binary-encoded integer from a file.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080023
24 It will do the correct conversion based on the reported size and whether or
25 not a signed number is expected. Assumes a network (big-endian) byte
26 ordering.
27
28 Args:
29 file_obj: a file object
30 size: the integer size in bytes (2, 4 or 8)
31 is_unsigned: whether it is signed or not
32 hasher: an optional hasher to pass the value through
33 Returns:
34 An "unpacked" (Python) integer value.
35 Raises:
36 PayloadError if an read error occurred.
37
38 """
Gilad Arnold5502b562013-03-08 13:22:31 -080039 return struct.unpack(common.IntPackingFmtStr(size, is_unsigned),
40 common.Read(file_obj, size, hasher=hasher))[0]
Gilad Arnold553b0ec2013-01-26 01:00:39 -080041
42
43#
44# Update payload.
45#
46class Payload(object):
47 """Chrome OS update payload processor."""
48
49 class _PayloadHeader(object):
50 """Update payload header struct."""
51
52 def __init__(self, version, manifest_len):
53 self.version = version
54 self.manifest_len = manifest_len
55
56 # Header constants; sizes are in bytes.
57 _MAGIC = 'CrAU'
58 _VERSION_SIZE = 8
59 _MANIFEST_LEN_SIZE = 8
60
61 def __init__(self, payload_file):
62 """Initialize the payload object.
63
64 Args:
65 payload_file: update payload file object open for reading
66
67 """
68 self.payload_file = payload_file
69 self.manifest_hasher = None
70 self.is_init = False
71 self.header = None
72 self.manifest = None
73 self.data_offset = 0
74
75 def _ReadHeader(self):
76 """Reads and returns the payload header.
77
78 Returns:
79 A payload header object.
80 Raises:
81 PayloadError if a read error occurred.
82
83 """
84 # Verify magic
85 magic = common.Read(self.payload_file, len(self._MAGIC),
86 hasher=self.manifest_hasher)
87 if magic != self._MAGIC:
88 raise PayloadError('invalid payload magic: %s' % magic)
89
90 return self._PayloadHeader(
91 _ReadInt(self.payload_file, self._VERSION_SIZE, True,
92 hasher=self.manifest_hasher),
93 _ReadInt(self.payload_file, self._MANIFEST_LEN_SIZE, True,
94 hasher=self.manifest_hasher))
95
96 def _ReadManifest(self):
97 """Reads and returns the payload manifest.
98
99 Returns:
100 A string containing the payload manifest in binary form.
101 Raises:
102 PayloadError if a read error occurred.
103
104 """
105 if not self.header:
106 raise PayloadError('payload header not present')
107
108 return common.Read(self.payload_file, self.header.manifest_len,
109 hasher=self.manifest_hasher)
110
111 def ReadDataBlob(self, offset, length):
112 """Reads and returns a single data blob from the update payload.
113
114 Args:
115 offset: offset to the beginning of the blob from the end of the manifest
116 length: the blob's length
117 Returns:
118 A string containing the raw blob data.
119 Raises:
120 PayloadError if a read error occurred.
121
122 """
123 return common.Read(self.payload_file, length,
124 offset=self.data_offset + offset)
125
126 def Init(self):
127 """Initializes the payload object.
128
129 This is a prerequisite for any other public API call.
130
131 Raises:
132 PayloadError if object already initialized or fails to initialize
133 correctly.
134
135 """
136 if self.is_init:
137 raise PayloadError('payload object already initialized')
138
139 # Initialize hash context.
140 # pylint: disable=E1101
141 self.manifest_hasher = hashlib.sha256()
142
143 # Read the file header.
144 self.header = self._ReadHeader()
145
146 # Read the manifest.
147 manifest_raw = self._ReadManifest()
148 self.manifest = update_metadata_pb2.DeltaArchiveManifest()
149 self.manifest.ParseFromString(manifest_raw)
150
151 # Store data offset.
152 self.data_offset = (len(self._MAGIC) + self._VERSION_SIZE +
153 self._MANIFEST_LEN_SIZE + self.header.manifest_len)
154
155 self.is_init = True
156
Don Garrett432d6012013-05-10 15:01:36 -0700157 def Describe(self):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700158 """Emits the payload embedded description data to standard output."""
Don Garrett432d6012013-05-10 15:01:36 -0700159 def _DescribeImageInfo(description, image_info):
160 def _DisplayIndentedValue(name, value):
161 print ' {:<14} {}'.format(name+':', value)
162
163 print '%s:' % description
164 _DisplayIndentedValue('Channel', image_info.channel)
165 _DisplayIndentedValue('Board', image_info.board)
166 _DisplayIndentedValue('Version', image_info.version)
167 _DisplayIndentedValue('Key', image_info.key)
168
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700169 if image_info.build_channel != image_info.channel:
Don Garrett432d6012013-05-10 15:01:36 -0700170 _DisplayIndentedValue('Build channel', image_info.build_channel)
171
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700172 if image_info.build_version != image_info.version:
Don Garrett432d6012013-05-10 15:01:36 -0700173 _DisplayIndentedValue('Build version', image_info.build_version)
174
175 if self.manifest.HasField('old_image_info'):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700176 # pylint: disable=E1101
Don Garrett432d6012013-05-10 15:01:36 -0700177 _DescribeImageInfo('Old Image', self.manifest.old_image_info)
178
179 if self.manifest.HasField('new_image_info'):
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700180 # pylint: disable=E1101
Don Garrett432d6012013-05-10 15:01:36 -0700181 _DescribeImageInfo('New Image', self.manifest.new_image_info)
182
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800183 def _AssertInit(self):
184 """Raises an exception if the object was not initialized."""
185 if not self.is_init:
186 raise PayloadError('payload object not initialized')
187
188 def ResetFile(self):
189 """Resets the offset of the payload file to right past the manifest."""
190 self.payload_file.seek(self.data_offset)
191
192 def IsDelta(self):
193 """Returns True iff the payload appears to be a delta."""
194 self._AssertInit()
195 return (self.manifest.HasField('old_kernel_info') or
196 self.manifest.HasField('old_rootfs_info'))
197
198 def IsFull(self):
199 """Returns True iff the payload appears to be a full."""
200 return not self.IsDelta()
201
202 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
203 report_out_file=None, assert_type=None, block_size=0,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700204 rootfs_part_size=0, kernel_part_size=0, allow_unhashed=False,
205 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800206 """Checks the payload integrity.
207
208 Args:
209 pubkey_file_name: public key used for signature verification
210 metadata_sig_file: metadata signature, if verification is desired
211 report_out_file: file object to dump the report to
212 assert_type: assert that payload is either 'full' or 'delta'
213 block_size: expected filesystem / payload block size
Gilad Arnold382df5c2013-05-03 12:49:28 -0700214 rootfs_part_size: the size of (physical) rootfs partitions in bytes
215 kernel_part_size: the size of (physical) kernel partitions in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800216 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700217 disabled_tests: list of tests to disable
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800218 Raises:
219 PayloadError if payload verification failed.
220
221 """
222 self._AssertInit()
223
224 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700225 helper = checker.PayloadChecker(
226 self, assert_type=assert_type, block_size=block_size,
227 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800228 helper.Run(pubkey_file_name=pubkey_file_name,
229 metadata_sig_file=metadata_sig_file,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700230 rootfs_part_size=rootfs_part_size,
231 kernel_part_size=kernel_part_size,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700232 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800233
Gilad Arnold16416602013-05-04 21:40:39 -0700234 def Apply(self, new_kernel_part, new_rootfs_part, old_kernel_part=None,
Gilad Arnold21a02502013-08-22 16:59:48 -0700235 old_rootfs_part=None, bsdiff_in_place=True, bspatch_path=None,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700236 truncate_to_expected_size=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800237 """Applies the update payload.
238
239 Args:
Gilad Arnold16416602013-05-04 21:40:39 -0700240 new_kernel_part: name of dest kernel partition file
241 new_rootfs_part: name of dest rootfs partition file
242 old_kernel_part: name of source kernel partition file (optional)
243 old_rootfs_part: name of source rootfs partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700244 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold21a02502013-08-22 16:59:48 -0700245 bspatch_path: path to the bspatch binary (optional)
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700246 truncate_to_expected_size: whether to truncate the resulting partitions
247 to their expected sizes, as specified in the
248 payload (optional)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800249 Raises:
250 PayloadError if payload application failed.
251
252 """
253 self._AssertInit()
254
255 # Create a short-lived payload applier object and run it.
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700256 helper = applier.PayloadApplier(
Gilad Arnold21a02502013-08-22 16:59:48 -0700257 self, bsdiff_in_place=bsdiff_in_place, bspatch_path=bspatch_path,
Gilad Arnolde5fdf182013-05-23 16:13:38 -0700258 truncate_to_expected_size=truncate_to_expected_size)
Gilad Arnold16416602013-05-04 21:40:39 -0700259 helper.Run(new_kernel_part, new_rootfs_part,
260 old_kernel_part=old_kernel_part,
261 old_rootfs_part=old_rootfs_part)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800262
263 def TraceBlock(self, block, skip, trace_out_file, is_kernel):
264 """Traces the origin(s) of a given dest partition block.
265
266 The tracing tries to find origins transitively, when possible (it currently
267 only works for move operations, where the mapping of src/dst is
268 one-to-one). It will dump a list of operations and source blocks
269 responsible for the data in the given dest block.
270
271 Args:
272 block: the block number whose origin to trace
273 skip: the number of first origin mappings to skip
274 trace_out_file: file object to dump the trace to
275 is_kernel: trace through kernel (True) or rootfs (False) operations
276
277 """
278 self._AssertInit()
279
280 # Create a short-lived payload block tracer object and run it.
281 helper = block_tracer.PayloadBlockTracer(self)
282 helper.Run(block, skip, trace_out_file, is_kernel)