blob: b4760b26287a1932567f1e3e6acdb74de20f3dd0 [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 Arnoldeaed0d12013-04-30 15:38:22 -0700178 allow_unhashed=False, disabled_tests=()):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800179 """Checks the payload integrity.
180
181 Args:
182 pubkey_file_name: public key used for signature verification
183 metadata_sig_file: metadata signature, if verification is desired
184 report_out_file: file object to dump the report to
185 assert_type: assert that payload is either 'full' or 'delta'
186 block_size: expected filesystem / payload block size
187 allow_unhashed: allow unhashed operation blobs
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700188 disabled_tests: list of tests to disable
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800189 Raises:
190 PayloadError if payload verification failed.
191
192 """
193 self._AssertInit()
194
195 # Create a short-lived payload checker object and run it.
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700196 helper = checker.PayloadChecker(
197 self, assert_type=assert_type, block_size=block_size,
198 allow_unhashed=allow_unhashed, disabled_tests=disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800199 helper.Run(pubkey_file_name=pubkey_file_name,
200 metadata_sig_file=metadata_sig_file,
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700201 report_out_file=report_out_file)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800202
203 def Apply(self, dst_kernel_part, dst_rootfs_part, src_kernel_part=None,
204 src_rootfs_part=None):
205 """Applies the update payload.
206
207 Args:
208 dst_kernel_part: name of dest kernel partition file
209 dst_rootfs_part: name of dest rootfs partition file
210 src_kernel_part: name of source kernel partition file (optional)
211 src_rootfs_part: name of source rootfs partition file (optional)
212 Raises:
213 PayloadError if payload application failed.
214
215 """
216 self._AssertInit()
217
218 # Create a short-lived payload applier object and run it.
219 helper = applier.PayloadApplier(self)
220 helper.Run(dst_kernel_part, dst_rootfs_part,
221 src_kernel_part=src_kernel_part,
222 src_rootfs_part=src_rootfs_part)
223
224 def TraceBlock(self, block, skip, trace_out_file, is_kernel):
225 """Traces the origin(s) of a given dest partition block.
226
227 The tracing tries to find origins transitively, when possible (it currently
228 only works for move operations, where the mapping of src/dst is
229 one-to-one). It will dump a list of operations and source blocks
230 responsible for the data in the given dest block.
231
232 Args:
233 block: the block number whose origin to trace
234 skip: the number of first origin mappings to skip
235 trace_out_file: file object to dump the trace to
236 is_kernel: trace through kernel (True) or rootfs (False) operations
237
238 """
239 self._AssertInit()
240
241 # Create a short-lived payload block tracer object and run it.
242 helper = block_tracer.PayloadBlockTracer(self)
243 helper.Run(block, skip, trace_out_file, is_kernel)