1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4# Copyright (c) 2022 Huawei Device Co., Ltd.
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"""
17Description : Unpack updater package
18"""
19import os
20import struct
21import time
22from create_update_package import UPGRADE_FILE_HEADER_LEN
23from create_update_package import UPGRADE_COMPINFO_SIZE
24from create_update_package import UPGRADE_COMPINFO_SIZE_L2
25from create_update_package import COMPONENT_ADDR_SIZE
26from create_update_package import COMPONENT_ADDR_SIZE_L2
27from create_update_package import UPGRADE_RESERVE_LEN
28
29from create_hashdata import HASH_TYPE_SIZE
30from create_hashdata import HASH_LENGTH_SIZE
31from create_hashdata import HASH_TLV_SIZE
32from create_hashdata import UPGRADE_HASHINFO_SIZE
33from create_hashdata import CreateHash
34from create_hashdata import HashType
35
36from log_exception import UPDATE_LOGGER
37from utils import OPTIONS_MANAGER
38
39COMPINFO_LEN_OFFSET = 178
40COMPINFO_LEN_SIZE = 2
41COMPONENT_ADDR_OFFSET = UPGRADE_FILE_HEADER_LEN
42COMPONENT_TYPE_OFFSET = COMPONENT_ADDR_OFFSET + COMPONENT_ADDR_SIZE + 4
43COMPONENT_TYPE_OFFSET_L2 = COMPONENT_ADDR_OFFSET + COMPONENT_ADDR_SIZE_L2 + 4
44COMPONENT_TYPE_SIZE = 1
45COMPONENT_SIZE_OFFSET = 11
46COMPONENT_SIZE_SIZE = 4
47
48"""
49Format
50H: unsigned short
51I: unsigned int
52B: unsigned char
53s: char[]
54"""
55COMPINFO_LEN_FMT = "H"
56COMPONENT_TYPE_FMT = "B"
57COMPONENT_SIZE_FMT = "I"
58
59
60class UnpackPackage(object):
61    """
62    Unpack the update.bin file
63    """
64
65    def __init__(self):
66        self.count = 0
67        self.component_offset = 0
68        self.save_path = None
69
70        if OPTIONS_MANAGER.not_l2:
71            self.compinfo_size = UPGRADE_COMPINFO_SIZE
72            self.type_offset = COMPONENT_TYPE_OFFSET
73            self.addr_size = COMPONENT_ADDR_SIZE
74        else:
75            self.compinfo_size = UPGRADE_COMPINFO_SIZE_L2
76            self.type_offset = COMPONENT_TYPE_OFFSET_L2
77            self.addr_size = COMPONENT_ADDR_SIZE_L2
78
79        self.addr_offset = COMPONENT_ADDR_OFFSET
80        self.size_offset = self.type_offset + COMPONENT_SIZE_OFFSET
81
82    def check_args(self):
83        if not os.access(OPTIONS_MANAGER.unpack_package_path, os.R_OK) and \
84            not os.path.exists(self.save_path):
85                UPDATE_LOGGER.print_log(
86                    "Access unpack_package_path fail! path: %s" % \
87                    OPTIONS_MANAGER.unpack_package_path, UPDATE_LOGGER.ERROR_LOG)
88                return False
89        return True
90
91    def parse_package_file(self, package_file):
92        try:
93            package_file.seek(COMPINFO_LEN_OFFSET)
94            compinfo_len_buffer = package_file.read(COMPINFO_LEN_SIZE)
95            compinfo_len = struct.unpack(COMPINFO_LEN_FMT, compinfo_len_buffer)
96        except (struct.error, IOError):
97            return False
98
99        self.count = compinfo_len[0] // self.compinfo_size
100        self.component_offset = UPGRADE_FILE_HEADER_LEN + compinfo_len[0] + UPGRADE_RESERVE_LEN
101
102        try:
103            package_file.seek(self.component_offset)
104            next_tlv_type_buffer = package_file.read(HASH_TYPE_SIZE)
105            next_tlv_type = struct.unpack(COMPINFO_LEN_FMT, next_tlv_type_buffer)
106            if next_tlv_type[0] == 0x06:
107                UPDATE_LOGGER.print_log("parse update.bin in SDcard package")
108                self.component_offset += HASH_TLV_SIZE + UPGRADE_HASHINFO_SIZE + HASH_TYPE_SIZE
109                package_file.seek(self.component_offset)
110                hashdata_len_buffer = package_file.read(HASH_LENGTH_SIZE)
111                hashdata_len = struct.unpack(COMPONENT_SIZE_FMT, hashdata_len_buffer)
112                self.component_offset += HASH_LENGTH_SIZE + hashdata_len[0] + HASH_TYPE_SIZE
113            elif next_tlv_type[0] == 0x08:
114                self.component_offset += HASH_TYPE_SIZE
115
116            package_file.seek(self.component_offset)
117            sign_len_buffer = package_file.read(HASH_LENGTH_SIZE)
118            sign_len = struct.unpack(COMPONENT_SIZE_FMT, sign_len_buffer)
119            UPDATE_LOGGER.print_log(
120                "signdata offset:%d length:%d" % (self.component_offset + HASH_LENGTH_SIZE, sign_len[0]))
121            self.component_offset += HASH_LENGTH_SIZE + sign_len[0]
122        except (struct.error, IOError):
123            return False
124
125        UPDATE_LOGGER.print_log("parse package file success! components: %d" % self.count)
126        return True
127
128    def parse_component(self, package_file):
129        try:
130            package_file.seek(self.addr_offset)
131            component_addr = package_file.read(self.addr_size)
132            component_addr = component_addr.split(b"\x00")[0].decode('utf-8')
133
134            package_file.seek(self.type_offset)
135            component_type_buffer = package_file.read(COMPONENT_TYPE_SIZE)
136            component_type = struct.unpack(COMPONENT_TYPE_FMT, component_type_buffer)
137
138            package_file.seek(self.size_offset)
139            component_size_buffer = package_file.read(COMPONENT_SIZE_SIZE)
140            component_size = struct.unpack(COMPONENT_SIZE_FMT, component_size_buffer)
141        except (struct.error, IOError):
142            UPDATE_LOGGER.print_log(
143                "parse component failed!", UPDATE_LOGGER.ERROR_LOG)
144            return False, False, False
145
146        return component_addr, component_type[0], component_size[0]
147
148    def create_image_file(self, package_file):
149        component_name, component_type, component_size = \
150            self.parse_component(package_file)
151        if component_name is None or component_type is None or component_size is None:
152            UPDATE_LOGGER.print_log("get component_info failed!", UPDATE_LOGGER.ERROR_LOG)
153            return False
154        component_name = component_name.strip('/')
155        if component_name == "version_list":
156            component_name = "VERSION.mbn"
157        elif component_name == "board_list":
158            component_name = "BOARD.list"
159        elif component_type == 0:
160            component_name = ''.join([component_name, '.img'])
161        elif component_type == 1:
162            component_name = ''.join([component_name, '.zip'])
163
164        image_file_path = os.path.join(self.save_path, component_name)
165
166        package_file.seek(self.component_offset)
167
168        UPDATE_LOGGER.print_log("component name: %s" % component_name)
169        UPDATE_LOGGER.print_log("component offset: %s" % self.component_offset)
170        UPDATE_LOGGER.print_log("component size: %s" % component_size)
171
172        image_fd = os.open(image_file_path, os.O_RDWR | os.O_CREAT | os.O_TRUNC, 0o755)
173        with os.fdopen(image_fd, "wb") as image_file:
174            image_buffer = package_file.read(component_size)
175            image_file.write(image_buffer)
176
177        self.addr_offset += self.compinfo_size
178        self.type_offset += self.compinfo_size
179        self.size_offset += self.compinfo_size
180        self.component_offset += component_size
181        UPDATE_LOGGER.print_log("Create file: %s" % image_file_path)
182        return True
183
184    def unpack_package(self):
185        """
186        Unpack the update.bin file
187        return: result
188        """
189        UPDATE_LOGGER.print_log(
190            "Start unpack updater package: %s" % OPTIONS_MANAGER.unpack_package_path)
191        filename = ''.join(['unpack_result_', time.strftime("%H%M%S", time.localtime())])
192        self.save_path = os.path.join(OPTIONS_MANAGER.target_package, filename)
193        os.makedirs(self.save_path)
194
195        if not self.check_args():
196            UPDATE_LOGGER.print_log(
197                "check args failed!", UPDATE_LOGGER.ERROR_LOG)
198            return False
199
200        with open(OPTIONS_MANAGER.unpack_package_path, "rb") as package_file:
201            if not self.parse_package_file(package_file):
202                UPDATE_LOGGER.print_log(
203                    "parse package file failed!", UPDATE_LOGGER.ERROR_LOG)
204                return False
205
206            for image_id in range(0, self.count):
207                UPDATE_LOGGER.print_log("Start to parse component_%d" % image_id)
208                if not self.create_image_file(package_file):
209                    UPDATE_LOGGER.print_log(
210                        "create image file failed!", UPDATE_LOGGER.ERROR_LOG)
211                    return False
212        return True
213
214