blob: 1796f511de7acc58fea3b4ed3663e9f3b1355d88 [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):
158
159 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
169 if (image_info.build_channel != image_info.channel):
170 _DisplayIndentedValue('Build channel', image_info.build_channel)
171
172 if (image_info.build_version != image_info.version):
173 _DisplayIndentedValue('Build version', image_info.build_version)
174
175 if self.manifest.HasField('old_image_info'):
176 _DescribeImageInfo('Old Image', self.manifest.old_image_info)
177
178 if self.manifest.HasField('new_image_info'):
179 _DescribeImageInfo('New Image', self.manifest.new_image_info)
180
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800181 def _AssertInit(self):
182 """Raises an exception if the object was not initialized."""
183 if not self.is_init:
184 raise PayloadError('payload object not initialized')
185
186 def ResetFile(self):
187 """Resets the offset of the payload file to right past the manifest."""
188 self.payload_file.seek(self.data_offset)
189
190 def IsDelta(self):
191 """Returns True iff the payload appears to be a delta."""
192 self._AssertInit()
193 return (self.manifest.HasField('old_kernel_info') or
194 self.manifest.HasField('old_rootfs_info'))
195
196 def IsFull(self):
197 """Returns True iff the payload appears to be a full."""
198 return not self.IsDelta()
199
200 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
201 report_out_file=None, assert_type=None, block_size=0,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700202 rootfs_part_size=0, kernel_part_size=0, allow_unhashed=False,
203 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800204 """Checks the payload integrity.
205
206 Args:
207 pubkey_file_name: public key used for signature verification
208 metadata_sig_file: metadata signature, if verification is desired
209 report_out_file: file object to dump the report to
210 assert_type: assert that payload is either 'full' or 'delta'
211 block_size: expected filesystem / payload block size
Gilad Arnold382df5c2013-05-03 12:49:28 -0700212 rootfs_part_size: the size of (physical) rootfs partitions in bytes
213 kernel_part_size: the size of (physical) kernel partitions in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800214 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700215 disabled_tests: list of tests to disable
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800216 Raises:
217 PayloadError if payload verification failed.
218
219 """
220 self._AssertInit()
221
222 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700223 helper = checker.PayloadChecker(
224 self, assert_type=assert_type, block_size=block_size,
225 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800226 helper.Run(pubkey_file_name=pubkey_file_name,
227 metadata_sig_file=metadata_sig_file,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700228 rootfs_part_size=rootfs_part_size,
229 kernel_part_size=kernel_part_size,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700230 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800231
Gilad Arnold16416602013-05-04 21:40:39 -0700232 def Apply(self, new_kernel_part, new_rootfs_part, old_kernel_part=None,
Gilad Arnold272a4992013-05-08 13:12:53 -0700233 old_rootfs_part=None, bsdiff_in_place=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800234 """Applies the update payload.
235
236 Args:
Gilad Arnold16416602013-05-04 21:40:39 -0700237 new_kernel_part: name of dest kernel partition file
238 new_rootfs_part: name of dest rootfs partition file
239 old_kernel_part: name of source kernel partition file (optional)
240 old_rootfs_part: name of source rootfs partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700241 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800242 Raises:
243 PayloadError if payload application failed.
244
245 """
246 self._AssertInit()
247
248 # Create a short-lived payload applier object and run it.
Gilad Arnold272a4992013-05-08 13:12:53 -0700249 helper = applier.PayloadApplier(self, bsdiff_in_place=bsdiff_in_place)
Gilad Arnold16416602013-05-04 21:40:39 -0700250 helper.Run(new_kernel_part, new_rootfs_part,
251 old_kernel_part=old_kernel_part,
252 old_rootfs_part=old_rootfs_part)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800253
254 def TraceBlock(self, block, skip, trace_out_file, is_kernel):
255 """Traces the origin(s) of a given dest partition block.
256
257 The tracing tries to find origins transitively, when possible (it currently
258 only works for move operations, where the mapping of src/dst is
259 one-to-one). It will dump a list of operations and source blocks
260 responsible for the data in the given dest block.
261
262 Args:
263 block: the block number whose origin to trace
264 skip: the number of first origin mappings to skip
265 trace_out_file: file object to dump the trace to
266 is_kernel: trace through kernel (True) or rootfs (False) operations
267
268 """
269 self._AssertInit()
270
271 # Create a short-lived payload block tracer object and run it.
272 helper = block_tracer.PayloadBlockTracer(self)
273 helper.Run(block, skip, trace_out_file, is_kernel)