blob: a8697306d82699fb7e468f891072a0b036244b95 [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"""Utilities for update payload processing."""
6
7import ctypes
Gilad Arnold553b0ec2013-01-26 01:00:39 -08008
9from error import PayloadError
10import update_metadata_pb2
11
12
13#
14# Constants.
15#
16PSEUDO_EXTENT_MARKER = ctypes.c_uint64(-1).value
17
Gilad Arnold5502b562013-03-08 13:22:31 -080018SIG_ASN1_HEADER = (
19 '\x30\x31\x30\x0d\x06\x09\x60\x86'
20 '\x48\x01\x65\x03\x04\x02\x01\x05'
21 '\x00\x04\x20'
22)
23
Gilad Arnold553b0ec2013-01-26 01:00:39 -080024
25#
26# Payload operation types.
27#
28class OpType(object):
29 """Container for operation type constants."""
30 _CLASS = update_metadata_pb2.DeltaArchiveManifest.InstallOperation
31 # pylint: disable=E1101
32 REPLACE = _CLASS.REPLACE
33 REPLACE_BZ = _CLASS.REPLACE_BZ
34 MOVE = _CLASS.MOVE
35 BSDIFF = _CLASS.BSDIFF
Gilad Arnold5502b562013-03-08 13:22:31 -080036 ALL = (REPLACE, REPLACE_BZ, MOVE, BSDIFF)
Gilad Arnold553b0ec2013-01-26 01:00:39 -080037 NAMES = {
38 REPLACE: 'REPLACE',
39 REPLACE_BZ: 'REPLACE_BZ',
40 MOVE: 'MOVE',
41 BSDIFF: 'BSDIFF',
42 }
43
44 def __init__(self):
45 pass
46
47
48#
Gilad Arnold382df5c2013-05-03 12:49:28 -070049# Checked and hashed reading of data.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080050#
Gilad Arnold5502b562013-03-08 13:22:31 -080051def IntPackingFmtStr(size, is_unsigned):
52 """Returns an integer format string for use by the struct module.
53
54 Args:
55 size: the integer size in bytes (2, 4 or 8)
56 is_unsigned: whether it is signed or not
57 Returns:
58 A format string for packing/unpacking integer values; assumes network byte
59 order (big-endian).
60 Raises:
61 PayloadError if something is wrong with the arguments.
62
63 """
64 # Determine the base conversion format.
65 if size == 2:
66 fmt = 'h'
67 elif size == 4:
68 fmt = 'i'
69 elif size == 8:
70 fmt = 'q'
71 else:
72 raise PayloadError('unsupport numeric field size (%s)' % size)
73
74 # Signed or unsigned?
75 if is_unsigned:
76 fmt = fmt.upper()
77
78 # Make it network byte order (big-endian).
79 fmt = '!' + fmt
80
81 return fmt
82
83
Gilad Arnold553b0ec2013-01-26 01:00:39 -080084def Read(file_obj, length, offset=None, hasher=None):
85 """Reads binary data from a file.
86
87 Args:
88 file_obj: an open file object
89 length: the length of the data to read
90 offset: an offset to seek to prior to reading; this is an absolute offset
91 from either the beginning (non-negative) or end (negative) of the
92 file. (optional)
93 hasher: a hashing object to pass the read data through (optional)
94 Returns:
95 A string containing the read data.
96 Raises:
97 PayloadError if a read error occurred or not enough data was read.
98
99 """
100 if offset is not None:
101 if offset >= 0:
102 file_obj.seek(offset)
103 else:
104 file_obj.seek(offset, 2)
105
106 try:
107 data = file_obj.read(length)
108 except IOError, e:
109 raise PayloadError('error reading from file (%s): %s' % (file_obj.name, e))
110
111 if len(data) != length:
112 raise PayloadError(
113 'reading from file (%s) too short (%d instead of %d bytes)' %
114 (file_obj.name, len(data), length))
115
116 if hasher:
117 hasher.update(data)
118
119 return data
120
121
122#
123# Formatting functions.
124#
125def FormatExtent(ex, block_size=0):
126 end_block = ex.start_block + ex.num_blocks
127 if block_size:
128 return '%d->%d * %d' % (ex.start_block, end_block, block_size)
129 else:
130 return '%d->%d' % (ex.start_block, end_block)
131
132
133def FormatSha256(digest):
134 """Returns a canonical string representation of a SHA256 digest."""
Chris Sosa857223b2013-03-29 14:31:43 -0700135 return digest.encode('base64')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800136
137
138#
139# Useful iterators.
140#
141def _ObjNameIter(items, base_name, reverse=False, name_format_func=None):
142 """A generic (item, name) tuple iterators.
143
144 Args:
145 items: the sequence of objects to iterate on
146 base_name: the base name for all objects
147 reverse: whether iteration should be in reverse order
148 name_format_func: a function to apply to the name string
149 Yields:
150 An iterator whose i-th invocation returns (items[i], name), where name ==
151 base_name + '[i]' (with a formatting function optionally applied to it).
152
153 """
154 idx, inc = (len(items), -1) if reverse else (1, 1)
155 for item in items:
156 item_name = '%s[%d]' % (base_name, idx)
157 if name_format_func:
158 item_name = name_format_func(item, item_name)
159 yield (item, item_name)
160 idx += inc
161
162
163def _OperationNameFormatter(op, op_name):
164 return '%s(%s)' % (op_name, OpType.NAMES.get(op.type, '?'))
165
166
167def OperationIter(operations, base_name, reverse=False):
168 """An (item, name) iterator for update operations."""
169 return _ObjNameIter(operations, base_name, reverse=reverse,
170 name_format_func=_OperationNameFormatter)
171
172
173def ExtentIter(extents, base_name, reverse=False):
174 """An (item, name) iterator for operation extents."""
175 return _ObjNameIter(extents, base_name, reverse=reverse)
176
177
178def SignatureIter(sigs, base_name, reverse=False):
179 """An (item, name) iterator for signatures."""
180 return _ObjNameIter(sigs, base_name, reverse=reverse)