blob: fefc7e4f9a45d5a2b774e48590953fad3e963a3a [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
157 def _AssertInit(self):
158 """Raises an exception if the object was not initialized."""
159 if not self.is_init:
160 raise PayloadError('payload object not initialized')
161
162 def ResetFile(self):
163 """Resets the offset of the payload file to right past the manifest."""
164 self.payload_file.seek(self.data_offset)
165
166 def IsDelta(self):
167 """Returns True iff the payload appears to be a delta."""
168 self._AssertInit()
169 return (self.manifest.HasField('old_kernel_info') or
170 self.manifest.HasField('old_rootfs_info'))
171
172 def IsFull(self):
173 """Returns True iff the payload appears to be a full."""
174 return not self.IsDelta()
175
176 def Check(self, pubkey_file_name=None, metadata_sig_file=None,
177 report_out_file=None, assert_type=None, block_size=0,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700178 rootfs_part_size=0, kernel_part_size=0, allow_unhashed=False,
179 disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800180 """Checks the payload integrity.
181
182 Args:
183 pubkey_file_name: public key used for signature verification
184 metadata_sig_file: metadata signature, if verification is desired
185 report_out_file: file object to dump the report to
186 assert_type: assert that payload is either 'full' or 'delta'
187 block_size: expected filesystem / payload block size
Gilad Arnold382df5c2013-05-03 12:49:28 -0700188 rootfs_part_size: the size of (physical) rootfs partitions in bytes
189 kernel_part_size: the size of (physical) kernel partitions in bytes
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800190 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700191 disabled_tests: list of tests to disable
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800192 Raises:
193 PayloadError if payload verification failed.
194
195 """
196 self._AssertInit()
197
198 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700199 helper = checker.PayloadChecker(
200 self, assert_type=assert_type, block_size=block_size,
201 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800202 helper.Run(pubkey_file_name=pubkey_file_name,
203 metadata_sig_file=metadata_sig_file,
Gilad Arnold382df5c2013-05-03 12:49:28 -0700204 rootfs_part_size=rootfs_part_size,
205 kernel_part_size=kernel_part_size,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700206 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800207
Gilad Arnold16416602013-05-04 21:40:39 -0700208 def Apply(self, new_kernel_part, new_rootfs_part, old_kernel_part=None,
Gilad Arnold272a4992013-05-08 13:12:53 -0700209 old_rootfs_part=None, bsdiff_in_place=True):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800210 """Applies the update payload.
211
212 Args:
Gilad Arnold16416602013-05-04 21:40:39 -0700213 new_kernel_part: name of dest kernel partition file
214 new_rootfs_part: name of dest rootfs partition file
215 old_kernel_part: name of source kernel partition file (optional)
216 old_rootfs_part: name of source rootfs partition file (optional)
Gilad Arnold272a4992013-05-08 13:12:53 -0700217 bsdiff_in_place: whether to perform BSDIFF operations in-place (optional)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800218 Raises:
219 PayloadError if payload application failed.
220
221 """
222 self._AssertInit()
223
224 # Create a short-lived payload applier object and run it.
Gilad Arnold272a4992013-05-08 13:12:53 -0700225 helper = applier.PayloadApplier(self, bsdiff_in_place=bsdiff_in_place)
Gilad Arnold16416602013-05-04 21:40:39 -0700226 helper.Run(new_kernel_part, new_rootfs_part,
227 old_kernel_part=old_kernel_part,
228 old_rootfs_part=old_rootfs_part)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800229
230 def TraceBlock(self, block, skip, trace_out_file, is_kernel):
231 """Traces the origin(s) of a given dest partition block.
232
233 The tracing tries to find origins transitively, when possible (it currently
234 only works for move operations, where the mapping of src/dst is
235 one-to-one). It will dump a list of operations and source blocks
236 responsible for the data in the given dest block.
237
238 Args:
239 block: the block number whose origin to trace
240 skip: the number of first origin mappings to skip
241 trace_out_file: file object to dump the trace to
242 is_kernel: trace through kernel (True) or rootfs (False) operations
243
244 """
245 self._AssertInit()
246
247 # Create a short-lived payload block tracer object and run it.
248 helper = block_tracer.PayloadBlockTracer(self)
249 helper.Run(block, skip, trace_out_file, is_kernel)