blob: 875b00f70ca219683c06b5dea4e0f0513db7c501 [file] [log] [blame]
Gilad Arnoldb92167f2015-07-15 16:49:00 -07001#!/usr/bin/python2
Gilad Arnold553b0ec2013-01-26 01:00:39 -08002#
Amin Hassanif94b6432018-01-26 17:39:47 -08003# Copyright (C) 2013 The Android Open Source Project
4#
5# Licensed under the Apache License, Version 2.0 (the "License");
6# you may not use this file except in compliance with the License.
7# You may obtain a copy of the License at
8#
9# http://www.apache.org/licenses/LICENSE-2.0
10#
11# Unless required by applicable law or agreed to in writing, software
12# distributed under the License is distributed on an "AS IS" BASIS,
13# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14# See the License for the specific language governing permissions and
15# limitations under the License.
16#
Gilad Arnold553b0ec2013-01-26 01:00:39 -080017
18"""Command-line tool for checking and applying Chrome OS update payloads."""
19
Gilad Arnoldb92167f2015-07-15 16:49:00 -070020from __future__ import print_function
21
Amin Hassani52b60392017-12-19 10:53:24 -080022# pylint: disable=import-error
23import argparse
Amin Hassanie20eb912018-02-21 12:39:42 -080024import filecmp
Gilad Arnold553b0ec2013-01-26 01:00:39 -080025import os
26import sys
Amin Hassanie20eb912018-02-21 12:39:42 -080027import tempfile
28
Tudor Brindus2d22c1a2018-06-15 13:07:13 -070029from update_payload import common
Amin Hassanie20eb912018-02-21 12:39:42 -080030from update_payload import error
Gilad Arnold553b0ec2013-01-26 01:00:39 -080031
Gilad Arnold553b0ec2013-01-26 01:00:39 -080032lib_dir = os.path.join(os.path.dirname(__file__), 'lib')
33if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
34 sys.path.insert(1, lib_dir)
35import update_payload
36
37
38_TYPE_FULL = 'full'
39_TYPE_DELTA = 'delta'
40
Xiaochu Liu6cf8e672019-03-14 16:15:42 -070041def CheckApplyPayload(args):
42 """Whether to check the result after applying the payload.
43
44 Args:
45 args: Parsed command arguments (the return value of
46 ArgumentParser.parse_args).
47
48 Returns:
49 Boolean value whether to check.
50 """
51 return args.dst_part_paths is not None
52
53def ApplyPayload(args):
54 """Whether to apply the payload.
55
56 Args:
57 args: Parsed command arguments (the return value of
58 ArgumentParser.parse_args).
59
60 Returns:
61 Boolean value whether to apply the payload.
62 """
63 return CheckApplyPayload(args) or args.out_dst_part_paths is not None
Gilad Arnold553b0ec2013-01-26 01:00:39 -080064
Gilad Arnold4fbe4092013-04-17 10:00:55 -070065def ParseArguments(argv):
Gilad Arnold553b0ec2013-01-26 01:00:39 -080066 """Parse and validate command-line arguments.
67
68 Args:
Gilad Arnold4fbe4092013-04-17 10:00:55 -070069 argv: command-line arguments to parse (excluding the program name)
Gilad Arnoldb92167f2015-07-15 16:49:00 -070070
Gilad Arnold553b0ec2013-01-26 01:00:39 -080071 Returns:
Amin Hassani52b60392017-12-19 10:53:24 -080072 Returns the arguments returned by the argument parser.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080073 """
Amin Hassani52b60392017-12-19 10:53:24 -080074 parser = argparse.ArgumentParser(
Xiaochu Liu6cf8e672019-03-14 16:15:42 -070075 description=('Applies a Chrome OS update PAYLOAD to src_part_paths'
76 'emitting dst_part_paths, respectively. '
77 'src_part_paths are only needed for delta payloads. '
Gilad Arnold4fbe4092013-04-17 10:00:55 -070078 'When no partitions are provided, verifies the payload '
79 'integrity.'),
80 epilog=('Note: a payload may verify correctly but fail to apply, and '
81 'vice versa; this is by design and can be thought of as static '
82 'vs dynamic correctness. A payload that both verifies and '
83 'applies correctly should be safe for use by the Chrome OS '
84 'Update Engine. Use --check to verify a payload prior to '
Amin Hassani52b60392017-12-19 10:53:24 -080085 'applying it.'),
86 formatter_class=argparse.RawDescriptionHelpFormatter
87 )
Gilad Arnold553b0ec2013-01-26 01:00:39 -080088
Amin Hassani52b60392017-12-19 10:53:24 -080089 check_args = parser.add_argument_group('Checking payload integrity')
90 check_args.add_argument('-c', '--check', action='store_true', default=False,
91 help=('force payload integrity check (e.g. before '
92 'applying)'))
93 check_args.add_argument('-D', '--describe', action='store_true',
94 default=False,
95 help='Print a friendly description of the payload.')
96 check_args.add_argument('-r', '--report', metavar='FILE',
97 help="dump payload report (`-' for stdout)")
98 check_args.add_argument('-t', '--type', dest='assert_type',
99 help='assert the payload type',
100 choices=[_TYPE_FULL, _TYPE_DELTA])
101 check_args.add_argument('-z', '--block-size', metavar='NUM', default=0,
102 type=int,
103 help='assert a non-default (4096) payload block size')
104 check_args.add_argument('-u', '--allow-unhashed', action='store_true',
105 default=False, help='allow unhashed operations')
106 check_args.add_argument('-d', '--disabled_tests', default=(), metavar='',
107 help=('space separated list of tests to disable. '
108 'allowed options include: ' +
109 ', '.join(update_payload.CHECKS_TO_DISABLE)),
110 choices=update_payload.CHECKS_TO_DISABLE)
111 check_args.add_argument('-k', '--key', metavar='FILE',
112 help=('override standard key used for signature '
113 'validation'))
114 check_args.add_argument('-m', '--meta-sig', metavar='FILE',
115 help='verify metadata against its signature')
Amin Hassania86b1082018-03-08 15:48:59 -0800116 check_args.add_argument('-s', '--metadata-size', metavar='NUM', default=0,
117 help='the metadata size to verify with the one in'
118 ' payload')
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700119 check_args.add_argument('--part_sizes', metavar='NUM', nargs='+', type=int,
120 help='override partition size auto-inference')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800121
Amin Hassani52b60392017-12-19 10:53:24 -0800122 apply_args = parser.add_argument_group('Applying payload')
123 # TODO(ahassani): Extent extract-bsdiff to puffdiff too.
124 apply_args.add_argument('-x', '--extract-bsdiff', action='store_true',
125 default=False,
126 help=('use temp input/output files with BSDIFF '
127 'operations (not in-place)'))
128 apply_args.add_argument('--bspatch-path', metavar='FILE',
129 help='use the specified bspatch binary')
130 apply_args.add_argument('--puffpatch-path', metavar='FILE',
131 help='use the specified puffpatch binary')
Gilad Arnold272a4992013-05-08 13:12:53 -0700132
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700133 apply_args.add_argument('--src_part_paths', metavar='FILE', nargs='+',
134 help='source partitition files')
135 apply_args.add_argument('--dst_part_paths', metavar='FILE', nargs='+',
136 help='destination partition files')
137 apply_args.add_argument('--out_dst_part_paths', metavar='FILE', nargs='+',
138 help='created destination partition files')
139
Amin Hassani52b60392017-12-19 10:53:24 -0800140 parser.add_argument('payload', metavar='PAYLOAD', help='the payload file')
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700141 parser.add_argument('--part_names', metavar='NAME', nargs='+',
142 help='names of partitions')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800143
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700144 # Parse command-line arguments.
Amin Hassani52b60392017-12-19 10:53:24 -0800145 args = parser.parse_args(argv)
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700146
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700147 # There are several options that imply --check.
Amin Hassani52b60392017-12-19 10:53:24 -0800148 args.check = (args.check or args.report or args.assert_type or
149 args.block_size or args.allow_unhashed or
150 args.disabled_tests or args.meta_sig or args.key or
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700151 args.part_sizes is not None or args.metadata_size)
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700152
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700153 # Makes sure the following arguments have the same length as |part_names| if
154 # set.
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700155 for arg in ['part_sizes', 'src_part_paths', 'dst_part_paths',
156 'out_dst_part_paths']:
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700157 if getattr(args, arg) is None:
158 # Parameter is not set.
159 continue
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700160 if len(args.part_names) != len(getattr(args, arg, [])):
161 parser.error('partitions in --%s do not match --part_names' % arg)
Amin Hassani52b60392017-12-19 10:53:24 -0800162
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700163 def _IsSrcPartPathsProvided(args):
164 return args.src_part_paths is not None
165
166 # Makes sure parameters are coherent with payload type.
167 if ApplyPayload(args):
168 if _IsSrcPartPathsProvided(args):
Amin Hassani52b60392017-12-19 10:53:24 -0800169 if args.assert_type == _TYPE_FULL:
170 parser.error('%s payload does not accept source partition arguments'
171 % _TYPE_FULL)
172 else:
173 args.assert_type = _TYPE_DELTA
174 else:
175 if args.assert_type == _TYPE_DELTA:
176 parser.error('%s payload requires source partitions arguments'
177 % _TYPE_DELTA)
178 else:
179 args.assert_type = _TYPE_FULL
180 else:
Amin Hassania5489022018-01-26 11:23:26 -0800181 # Not applying payload.
Amin Hassani52b60392017-12-19 10:53:24 -0800182 if args.extract_bsdiff:
Gilad Arnold272a4992013-05-08 13:12:53 -0700183 parser.error('--extract-bsdiff can only be used when applying payloads')
Amin Hassani52b60392017-12-19 10:53:24 -0800184 if args.bspatch_path:
Gilad Arnold21a02502013-08-22 16:59:48 -0700185 parser.error('--bspatch-path can only be used when applying payloads')
Amin Hassani52b60392017-12-19 10:53:24 -0800186 if args.puffpatch_path:
Amin Hassani6be71682017-12-01 10:46:45 -0800187 parser.error('--puffpatch-path can only be used when applying payloads')
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700188
Don Garrett30027fd2013-05-01 16:56:16 -0700189 # By default, look for a metadata-signature file with a name based on the name
Gilad Arnold9b90c932013-05-22 17:12:56 -0700190 # of the payload we are checking. We only do it if check was triggered.
Amin Hassani52b60392017-12-19 10:53:24 -0800191 if args.check and not args.meta_sig:
192 default_meta_sig = args.payload + '.metadata-signature'
Don Garrett30027fd2013-05-01 16:56:16 -0700193 if os.path.isfile(default_meta_sig):
Amin Hassani52b60392017-12-19 10:53:24 -0800194 args.meta_sig = default_meta_sig
195 print('Using default metadata signature', args.meta_sig, file=sys.stderr)
Don Garrett30027fd2013-05-01 16:56:16 -0700196
Amin Hassani52b60392017-12-19 10:53:24 -0800197 return args
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700198
199
200def main(argv):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800201 # Parse and validate arguments.
Amin Hassani52b60392017-12-19 10:53:24 -0800202 args = ParseArguments(argv[1:])
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800203
Amin Hassani52b60392017-12-19 10:53:24 -0800204 with open(args.payload) as payload_file:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800205 payload = update_payload.Payload(payload_file)
206 try:
207 # Initialize payload.
208 payload.Init()
209
Amin Hassani52b60392017-12-19 10:53:24 -0800210 if args.describe:
Don Garrett432d6012013-05-10 15:01:36 -0700211 payload.Describe()
212
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800213 # Perform payload integrity checks.
Amin Hassani52b60392017-12-19 10:53:24 -0800214 if args.check:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800215 report_file = None
216 do_close_report_file = False
Gilad Arnold7a7edfd2013-05-22 17:21:58 -0700217 metadata_sig_file = None
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800218 try:
Amin Hassani52b60392017-12-19 10:53:24 -0800219 if args.report:
220 if args.report == '-':
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800221 report_file = sys.stdout
222 else:
Amin Hassani52b60392017-12-19 10:53:24 -0800223 report_file = open(args.report, 'w')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800224 do_close_report_file = True
Gilad Arnold03959b72013-05-07 17:08:18 -0700225
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700226 part_sizes = (args.part_sizes and
227 dict(zip(args.part_names, args.part_sizes)))
Amin Hassani52b60392017-12-19 10:53:24 -0800228 metadata_sig_file = args.meta_sig and open(args.meta_sig)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800229 payload.Check(
Amin Hassani52b60392017-12-19 10:53:24 -0800230 pubkey_file_name=args.key,
Gilad Arnold4f8c17c2013-05-04 22:57:45 -0700231 metadata_sig_file=metadata_sig_file,
Amin Hassania86b1082018-03-08 15:48:59 -0800232 metadata_size=int(args.metadata_size),
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800233 report_out_file=report_file,
Amin Hassani52b60392017-12-19 10:53:24 -0800234 assert_type=args.assert_type,
235 block_size=int(args.block_size),
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700236 part_sizes=part_sizes,
Amin Hassani52b60392017-12-19 10:53:24 -0800237 allow_unhashed=args.allow_unhashed,
238 disabled_tests=args.disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800239 finally:
Gilad Arnold7a7edfd2013-05-22 17:21:58 -0700240 if metadata_sig_file:
241 metadata_sig_file.close()
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800242 if do_close_report_file:
243 report_file.close()
244
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800245 # Apply payload.
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700246 if ApplyPayload(args):
Amin Hassani52b60392017-12-19 10:53:24 -0800247 dargs = {'bsdiff_in_place': not args.extract_bsdiff}
248 if args.bspatch_path:
249 dargs['bspatch_path'] = args.bspatch_path
250 if args.puffpatch_path:
251 dargs['puffpatch_path'] = args.puffpatch_path
252 if args.assert_type == _TYPE_DELTA:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700253 dargs['old_parts'] = dict(zip(args.part_names, args.src_part_paths))
Gilad Arnold272a4992013-05-08 13:12:53 -0700254
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700255 out_dst_parts = {}
256 file_handles = []
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700257 if args.out_dst_part_paths is not None:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700258 for name, path in zip(args.part_names, args.out_dst_part_paths):
259 handle = open(path, 'w+')
260 file_handles.append(handle)
261 out_dst_parts[name] = handle.name
Amin Hassanie20eb912018-02-21 12:39:42 -0800262 else:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700263 for name in args.part_names:
264 handle = tempfile.NamedTemporaryFile()
265 file_handles.append(handle)
266 out_dst_parts[name] = handle.name
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800267
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700268 payload.Apply(out_dst_parts, **dargs)
Amin Hassanie20eb912018-02-21 12:39:42 -0800269
270 # If destination kernel and rootfs partitions are not given, then this
271 # just becomes an apply operation with no check.
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700272 if CheckApplyPayload(args):
Amin Hassanie20eb912018-02-21 12:39:42 -0800273 # Prior to comparing, add the unused space past the filesystem
274 # boundary in the new target partitions to become the same size as
275 # the given partitions. This will truncate to larger size.
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700276 for part_name, out_dst_part, dst_part in zip(args.part_names,
277 file_handles,
278 args.dst_part_paths):
279 out_dst_part.truncate(os.path.getsize(dst_part))
Amin Hassanie20eb912018-02-21 12:39:42 -0800280
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700281 # Compare resulting partitions with the ones from the target image.
282 if not filecmp.cmp(out_dst_part.name, dst_part):
283 raise error.PayloadError(
284 'Resulting %s partition corrupted.' % part_name)
Amin Hassanie20eb912018-02-21 12:39:42 -0800285
286 # Close the output files. If args.out_dst_* was not given, then these
287 # files are created as temp files and will be deleted upon close().
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700288 for handle in file_handles:
289 handle.close()
Amin Hassanie20eb912018-02-21 12:39:42 -0800290 except error.PayloadError, e:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800291 sys.stderr.write('Error: %s\n' % e)
292 return 1
293
294 return 0
295
296
297if __name__ == '__main__':
298 sys.exit(main(sys.argv))