blob: f4ccca2c4c7089d17df57e728f0b1786deed2f18 [file] [log] [blame]
Andrew Lassalle165843c2019-11-05 13:30:34 -08001#!/usr/bin/env python
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
Andrew Lassalle165843c2019-11-05 13:30:34 -080020from __future__ import absolute_import
Gilad Arnoldb92167f2015-07-15 16:49:00 -070021from __future__ import print_function
22
Amin Hassani52b60392017-12-19 10:53:24 -080023# pylint: disable=import-error
24import argparse
Amin Hassanie20eb912018-02-21 12:39:42 -080025import filecmp
Gilad Arnold553b0ec2013-01-26 01:00:39 -080026import os
27import sys
Amin Hassanie20eb912018-02-21 12:39:42 -080028import tempfile
29
Andrew Lassalle165843c2019-11-05 13:30:34 -080030from six.moves import zip
Amin Hassanie20eb912018-02-21 12:39:42 -080031from update_payload import error
Gilad Arnold553b0ec2013-01-26 01:00:39 -080032
Andrew Lassalle165843c2019-11-05 13:30:34 -080033
Gilad Arnold553b0ec2013-01-26 01:00:39 -080034lib_dir = os.path.join(os.path.dirname(__file__), 'lib')
35if os.path.exists(lib_dir) and os.path.isdir(lib_dir):
36 sys.path.insert(1, lib_dir)
Andrew Lassalle165843c2019-11-05 13:30:34 -080037import update_payload # pylint: disable=wrong-import-position
Gilad Arnold553b0ec2013-01-26 01:00:39 -080038
39
40_TYPE_FULL = 'full'
41_TYPE_DELTA = 'delta'
42
Xiaochu Liu6cf8e672019-03-14 16:15:42 -070043def CheckApplyPayload(args):
44 """Whether to check the result after applying the payload.
45
46 Args:
47 args: Parsed command arguments (the return value of
48 ArgumentParser.parse_args).
49
50 Returns:
51 Boolean value whether to check.
52 """
53 return args.dst_part_paths is not None
54
55def ApplyPayload(args):
56 """Whether to apply the payload.
57
58 Args:
59 args: Parsed command arguments (the return value of
60 ArgumentParser.parse_args).
61
62 Returns:
63 Boolean value whether to apply the payload.
64 """
65 return CheckApplyPayload(args) or args.out_dst_part_paths is not None
Gilad Arnold553b0ec2013-01-26 01:00:39 -080066
Gilad Arnold4fbe4092013-04-17 10:00:55 -070067def ParseArguments(argv):
Gilad Arnold553b0ec2013-01-26 01:00:39 -080068 """Parse and validate command-line arguments.
69
70 Args:
Gilad Arnold4fbe4092013-04-17 10:00:55 -070071 argv: command-line arguments to parse (excluding the program name)
Gilad Arnoldb92167f2015-07-15 16:49:00 -070072
Gilad Arnold553b0ec2013-01-26 01:00:39 -080073 Returns:
Amin Hassani52b60392017-12-19 10:53:24 -080074 Returns the arguments returned by the argument parser.
Gilad Arnold553b0ec2013-01-26 01:00:39 -080075 """
Amin Hassani52b60392017-12-19 10:53:24 -080076 parser = argparse.ArgumentParser(
Xiaochu Liu6cf8e672019-03-14 16:15:42 -070077 description=('Applies a Chrome OS update PAYLOAD to src_part_paths'
78 'emitting dst_part_paths, respectively. '
79 'src_part_paths are only needed for delta payloads. '
Gilad Arnold4fbe4092013-04-17 10:00:55 -070080 'When no partitions are provided, verifies the payload '
81 'integrity.'),
82 epilog=('Note: a payload may verify correctly but fail to apply, and '
83 'vice versa; this is by design and can be thought of as static '
84 'vs dynamic correctness. A payload that both verifies and '
85 'applies correctly should be safe for use by the Chrome OS '
86 'Update Engine. Use --check to verify a payload prior to '
Amin Hassani52b60392017-12-19 10:53:24 -080087 'applying it.'),
88 formatter_class=argparse.RawDescriptionHelpFormatter
89 )
Gilad Arnold553b0ec2013-01-26 01:00:39 -080090
Amin Hassani52b60392017-12-19 10:53:24 -080091 check_args = parser.add_argument_group('Checking payload integrity')
92 check_args.add_argument('-c', '--check', action='store_true', default=False,
93 help=('force payload integrity check (e.g. before '
94 'applying)'))
95 check_args.add_argument('-D', '--describe', action='store_true',
96 default=False,
97 help='Print a friendly description of the payload.')
98 check_args.add_argument('-r', '--report', metavar='FILE',
99 help="dump payload report (`-' for stdout)")
100 check_args.add_argument('-t', '--type', dest='assert_type',
101 help='assert the payload type',
102 choices=[_TYPE_FULL, _TYPE_DELTA])
103 check_args.add_argument('-z', '--block-size', metavar='NUM', default=0,
104 type=int,
105 help='assert a non-default (4096) payload block size')
106 check_args.add_argument('-u', '--allow-unhashed', action='store_true',
107 default=False, help='allow unhashed operations')
108 check_args.add_argument('-d', '--disabled_tests', default=(), metavar='',
109 help=('space separated list of tests to disable. '
110 'allowed options include: ' +
111 ', '.join(update_payload.CHECKS_TO_DISABLE)),
112 choices=update_payload.CHECKS_TO_DISABLE)
113 check_args.add_argument('-k', '--key', metavar='FILE',
114 help=('override standard key used for signature '
115 'validation'))
116 check_args.add_argument('-m', '--meta-sig', metavar='FILE',
117 help='verify metadata against its signature')
Amin Hassania86b1082018-03-08 15:48:59 -0800118 check_args.add_argument('-s', '--metadata-size', metavar='NUM', default=0,
119 help='the metadata size to verify with the one in'
120 ' payload')
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700121 check_args.add_argument('--part_sizes', metavar='NUM', nargs='+', type=int,
122 help='override partition size auto-inference')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800123
Amin Hassani52b60392017-12-19 10:53:24 -0800124 apply_args = parser.add_argument_group('Applying payload')
125 # TODO(ahassani): Extent extract-bsdiff to puffdiff too.
126 apply_args.add_argument('-x', '--extract-bsdiff', action='store_true',
127 default=False,
128 help=('use temp input/output files with BSDIFF '
129 'operations (not in-place)'))
130 apply_args.add_argument('--bspatch-path', metavar='FILE',
131 help='use the specified bspatch binary')
132 apply_args.add_argument('--puffpatch-path', metavar='FILE',
133 help='use the specified puffpatch binary')
Gilad Arnold272a4992013-05-08 13:12:53 -0700134
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700135 apply_args.add_argument('--src_part_paths', metavar='FILE', nargs='+',
136 help='source partitition files')
137 apply_args.add_argument('--dst_part_paths', metavar='FILE', nargs='+',
138 help='destination partition files')
139 apply_args.add_argument('--out_dst_part_paths', metavar='FILE', nargs='+',
140 help='created destination partition files')
141
Amin Hassani52b60392017-12-19 10:53:24 -0800142 parser.add_argument('payload', metavar='PAYLOAD', help='the payload file')
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700143 parser.add_argument('--part_names', metavar='NAME', nargs='+',
144 help='names of partitions')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800145
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700146 # Parse command-line arguments.
Amin Hassani52b60392017-12-19 10:53:24 -0800147 args = parser.parse_args(argv)
Gilad Arnoldeaed0d12013-04-30 15:38:22 -0700148
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700149 # There are several options that imply --check.
Amin Hassani52b60392017-12-19 10:53:24 -0800150 args.check = (args.check or args.report or args.assert_type or
151 args.block_size or args.allow_unhashed or
152 args.disabled_tests or args.meta_sig or args.key or
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700153 args.part_sizes is not None or args.metadata_size)
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700154
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700155 # Makes sure the following arguments have the same length as |part_names| if
156 # set.
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700157 for arg in ['part_sizes', 'src_part_paths', 'dst_part_paths',
158 'out_dst_part_paths']:
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700159 if getattr(args, arg) is None:
160 # Parameter is not set.
161 continue
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700162 if len(args.part_names) != len(getattr(args, arg, [])):
163 parser.error('partitions in --%s do not match --part_names' % arg)
Amin Hassani52b60392017-12-19 10:53:24 -0800164
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700165 def _IsSrcPartPathsProvided(args):
166 return args.src_part_paths is not None
167
168 # Makes sure parameters are coherent with payload type.
169 if ApplyPayload(args):
170 if _IsSrcPartPathsProvided(args):
Amin Hassani52b60392017-12-19 10:53:24 -0800171 if args.assert_type == _TYPE_FULL:
172 parser.error('%s payload does not accept source partition arguments'
173 % _TYPE_FULL)
174 else:
175 args.assert_type = _TYPE_DELTA
176 else:
177 if args.assert_type == _TYPE_DELTA:
178 parser.error('%s payload requires source partitions arguments'
179 % _TYPE_DELTA)
180 else:
181 args.assert_type = _TYPE_FULL
182 else:
Amin Hassania5489022018-01-26 11:23:26 -0800183 # Not applying payload.
Amin Hassani52b60392017-12-19 10:53:24 -0800184 if args.extract_bsdiff:
Gilad Arnold272a4992013-05-08 13:12:53 -0700185 parser.error('--extract-bsdiff can only be used when applying payloads')
Amin Hassani52b60392017-12-19 10:53:24 -0800186 if args.bspatch_path:
Gilad Arnold21a02502013-08-22 16:59:48 -0700187 parser.error('--bspatch-path can only be used when applying payloads')
Amin Hassani52b60392017-12-19 10:53:24 -0800188 if args.puffpatch_path:
Amin Hassani6be71682017-12-01 10:46:45 -0800189 parser.error('--puffpatch-path can only be used when applying payloads')
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700190
Don Garrett30027fd2013-05-01 16:56:16 -0700191 # By default, look for a metadata-signature file with a name based on the name
Gilad Arnold9b90c932013-05-22 17:12:56 -0700192 # of the payload we are checking. We only do it if check was triggered.
Amin Hassani52b60392017-12-19 10:53:24 -0800193 if args.check and not args.meta_sig:
194 default_meta_sig = args.payload + '.metadata-signature'
Don Garrett30027fd2013-05-01 16:56:16 -0700195 if os.path.isfile(default_meta_sig):
Amin Hassani52b60392017-12-19 10:53:24 -0800196 args.meta_sig = default_meta_sig
197 print('Using default metadata signature', args.meta_sig, file=sys.stderr)
Don Garrett30027fd2013-05-01 16:56:16 -0700198
Amin Hassani52b60392017-12-19 10:53:24 -0800199 return args
Gilad Arnold4fbe4092013-04-17 10:00:55 -0700200
201
202def main(argv):
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800203 # Parse and validate arguments.
Amin Hassani52b60392017-12-19 10:53:24 -0800204 args = ParseArguments(argv[1:])
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800205
Andrew1f6bcab2019-11-21 11:34:22 -0800206 with open(args.payload, 'rb') as payload_file:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800207 payload = update_payload.Payload(payload_file)
208 try:
209 # Initialize payload.
210 payload.Init()
211
Amin Hassani52b60392017-12-19 10:53:24 -0800212 if args.describe:
Don Garrett432d6012013-05-10 15:01:36 -0700213 payload.Describe()
214
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800215 # Perform payload integrity checks.
Amin Hassani52b60392017-12-19 10:53:24 -0800216 if args.check:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800217 report_file = None
218 do_close_report_file = False
Gilad Arnold7a7edfd2013-05-22 17:21:58 -0700219 metadata_sig_file = None
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800220 try:
Amin Hassani52b60392017-12-19 10:53:24 -0800221 if args.report:
222 if args.report == '-':
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800223 report_file = sys.stdout
224 else:
Amin Hassani52b60392017-12-19 10:53:24 -0800225 report_file = open(args.report, 'w')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800226 do_close_report_file = True
Gilad Arnold03959b72013-05-07 17:08:18 -0700227
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700228 part_sizes = (args.part_sizes and
229 dict(zip(args.part_names, args.part_sizes)))
Andrew1f6bcab2019-11-21 11:34:22 -0800230 metadata_sig_file = args.meta_sig and open(args.meta_sig, 'rb')
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800231 payload.Check(
Amin Hassani52b60392017-12-19 10:53:24 -0800232 pubkey_file_name=args.key,
Gilad Arnold4f8c17c2013-05-04 22:57:45 -0700233 metadata_sig_file=metadata_sig_file,
Amin Hassania86b1082018-03-08 15:48:59 -0800234 metadata_size=int(args.metadata_size),
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800235 report_out_file=report_file,
Amin Hassani52b60392017-12-19 10:53:24 -0800236 assert_type=args.assert_type,
237 block_size=int(args.block_size),
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700238 part_sizes=part_sizes,
Amin Hassani52b60392017-12-19 10:53:24 -0800239 allow_unhashed=args.allow_unhashed,
240 disabled_tests=args.disabled_tests)
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800241 finally:
Gilad Arnold7a7edfd2013-05-22 17:21:58 -0700242 if metadata_sig_file:
243 metadata_sig_file.close()
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800244 if do_close_report_file:
245 report_file.close()
246
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800247 # Apply payload.
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700248 if ApplyPayload(args):
Amin Hassani52b60392017-12-19 10:53:24 -0800249 dargs = {'bsdiff_in_place': not args.extract_bsdiff}
250 if args.bspatch_path:
251 dargs['bspatch_path'] = args.bspatch_path
252 if args.puffpatch_path:
253 dargs['puffpatch_path'] = args.puffpatch_path
254 if args.assert_type == _TYPE_DELTA:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700255 dargs['old_parts'] = dict(zip(args.part_names, args.src_part_paths))
Gilad Arnold272a4992013-05-08 13:12:53 -0700256
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700257 out_dst_parts = {}
258 file_handles = []
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700259 if args.out_dst_part_paths is not None:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700260 for name, path in zip(args.part_names, args.out_dst_part_paths):
Andrew1f6bcab2019-11-21 11:34:22 -0800261 handle = open(path, 'wb+')
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700262 file_handles.append(handle)
263 out_dst_parts[name] = handle.name
Amin Hassanie20eb912018-02-21 12:39:42 -0800264 else:
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700265 for name in args.part_names:
266 handle = tempfile.NamedTemporaryFile()
267 file_handles.append(handle)
268 out_dst_parts[name] = handle.name
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800269
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700270 payload.Apply(out_dst_parts, **dargs)
Amin Hassanie20eb912018-02-21 12:39:42 -0800271
272 # If destination kernel and rootfs partitions are not given, then this
273 # just becomes an apply operation with no check.
Xiaochu Liu6cf8e672019-03-14 16:15:42 -0700274 if CheckApplyPayload(args):
Amin Hassanie20eb912018-02-21 12:39:42 -0800275 # Prior to comparing, add the unused space past the filesystem
276 # boundary in the new target partitions to become the same size as
277 # the given partitions. This will truncate to larger size.
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700278 for part_name, out_dst_part, dst_part in zip(args.part_names,
279 file_handles,
280 args.dst_part_paths):
281 out_dst_part.truncate(os.path.getsize(dst_part))
Amin Hassanie20eb912018-02-21 12:39:42 -0800282
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700283 # Compare resulting partitions with the ones from the target image.
284 if not filecmp.cmp(out_dst_part.name, dst_part):
285 raise error.PayloadError(
286 'Resulting %s partition corrupted.' % part_name)
Amin Hassanie20eb912018-02-21 12:39:42 -0800287
288 # Close the output files. If args.out_dst_* was not given, then these
289 # files are created as temp files and will be deleted upon close().
Tudor Brindus2d22c1a2018-06-15 13:07:13 -0700290 for handle in file_handles:
291 handle.close()
Andrew Lassalle165843c2019-11-05 13:30:34 -0800292 except error.PayloadError as e:
Gilad Arnold553b0ec2013-01-26 01:00:39 -0800293 sys.stderr.write('Error: %s\n' % e)
294 return 1
295
296 return 0
297
298
299if __name__ == '__main__':
300 sys.exit(main(sys.argv))