1#!/usr/bin/env python3
2# -*- coding: utf-8 -*-
3
4# Copyright (c) 2021 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.
16import bisect
17import copy
18import os
19import struct
20import tempfile
21from hashlib import sha256
22
23from log_exception import UPDATE_LOGGER
24from blocks_manager import BlocksManager
25from utils import OPTIONS_MANAGER
26from utils import EXTEND_VALUE
27from utils import FILE_MAP_ZERO_KEY
28from utils import FILE_MAP_NONZERO_KEY
29from utils import FILE_MAP_COPY_KEY
30from utils import MAX_BLOCKS_PER_GROUP
31from utils import UPDATE_BIN_FILE_NAME
32from utils import FORBIDEN_UPDATE_IMAGE_SET
33
34
35class FullUpdateImage:
36    """
37    Full image processing class
38    """
39
40    def __init__(self, target_package_images_dir,
41                 full_img_list, full_img_name_list,
42                 verse_script, full_image_path_list,
43                 no_zip=False):
44        self.target_package_images_dir = target_package_images_dir
45        self.full_img_list = full_img_list
46        self.full_img_name_list = full_img_name_list
47        self.verse_script = verse_script
48        self.full_image_path_list = full_image_path_list
49        self.no_zip = no_zip
50
51    def update_full_image(self):
52        """
53        Processing of the full image
54        :return full_image_content_len_list: full image content length list
55        :return full_image_file_obj_list: full image temporary file list
56        """
57        full_image_file_obj_list = []
58        full_image_content_len_list = []
59        for idx, each_name in enumerate(self.full_img_list):
60            full_image_content = self.get_full_image_content(
61                self.full_image_path_list[idx])
62            img_name = self.full_img_name_list[idx][:-4]
63            if full_image_content is False:
64                UPDATE_LOGGER.print_log(
65                    "Get full image content failed!",
66                    log_type=UPDATE_LOGGER.ERROR_LOG)
67                return False, False
68            each_img = tempfile.NamedTemporaryFile(
69                dir=self.target_package_images_dir,
70                prefix="full_image%s" % img_name, mode='wb')
71            each_img.write(full_image_content)
72            each_img.seek(0)
73            full_image_content_len_list.append(len(full_image_content))
74            full_image_file_obj_list.append(each_img)
75            UPDATE_LOGGER.print_log(
76                "Image %s full processing completed" % img_name)
77        update_image_set = set(self.full_img_list) - FORBIDEN_UPDATE_IMAGE_SET
78        if not self.no_zip and len(update_image_set) != 0:
79            # No zip mode (no script command)
80            image_write_cmd = self.verse_script.full_image_update(UPDATE_BIN_FILE_NAME)
81            cmd = '%s_WRITE_FLAG%s' % (UPDATE_BIN_FILE_NAME, image_write_cmd)
82            if each_name not in FORBIDEN_UPDATE_IMAGE_SET:
83                self.verse_script.add_command(cmd=cmd)
84
85        UPDATE_LOGGER.print_log(
86            "All full image processing completed! image count: %d" %
87            len(self.full_img_list))
88        return full_image_content_len_list, full_image_file_obj_list
89
90    @staticmethod
91    def get_full_image_content(each_name):
92        """
93        Obtain the full image content.
94        :param each_name: image name
95        :return content: full image content if available; false otherwise
96        """
97        each_image_path = each_name
98        if not os.path.exists(each_image_path):
99            UPDATE_LOGGER.print_log(
100                "The file is missing "
101                "from the target package, "
102                "the component: %s cannot be full update processed. " %
103                each_image_path)
104            return False
105        with open(each_image_path, 'rb') as f_r:
106            content = f_r.read()
107        return content
108
109
110class IncUpdateImage:
111    """
112    Increment update image class
113    """
114
115    def __init__(self, image_path, map_path):
116        """
117        Initialize the inc image.
118        :param image_path: img file path
119        :param map_path: map file path
120        """
121        self.image_path = image_path
122        self.map_path = map_path
123        self.offset_value_list = []
124        self.care_block_range = None
125        self.extended_range = None
126        self.reserved_blocks = BlocksManager("0")
127        self.file_map = []
128        self.offset_index = []
129        self.block_size = None
130        self.total_blocks = None
131        self.parse_raw_image_file(image_path, map_path)
132
133    def parse_raw_image_file(self, image_path, map_path):
134        """
135        Parse the .img file.
136        :param image_path: img file path
137        :param map_path: map file path
138        """
139        self.block_size = block_size = 4096
140        self.total_blocks = total_blocks = \
141            os.path.getsize(self.image_path) // self.block_size
142        reference = b'\0' * self.block_size
143        with open(image_path, 'rb') as f_r:
144            care_value_list, offset_value_list = [], []
145            nonzero_blocks = []
146            for i in range(self.total_blocks):
147                blocks_data = f_r.read(self.block_size)
148                if blocks_data != reference:
149                    nonzero_blocks.append(i)
150                    nonzero_blocks.append(i + 1)
151            self.care_block_range = BlocksManager(nonzero_blocks)
152            care_value_list = list(self.care_block_range.range_data)
153            for idx, value in enumerate(care_value_list):
154                if idx != 0 and (idx + 1) % 2 == 0:
155                    be_value = int(care_value_list[idx - 1])
156                    af_value = int(care_value_list[idx])
157                    file_tell = be_value * block_size
158                    offset_value_list.append(
159                        (be_value, af_value - be_value,
160                         file_tell, None))
161
162            self.offset_index = [i[0] for i in offset_value_list]
163            self.offset_value_list = offset_value_list
164            extended_range = \
165                self.care_block_range.extend_value_to_blocks(EXTEND_VALUE)
166            all_blocks = BlocksManager(range_data=(0, total_blocks))
167            self.extended_range = \
168                extended_range.get_intersect_with_other(all_blocks). \
169                get_subtract_with_other(self.care_block_range)
170            self.parse_block_map_file(map_path, f_r)
171
172    def parse_block_map_file(self, map_path, image_file_r):
173        """
174        Parses the map file for blocks where files are contained in the image.
175        :param map_path: map file path
176        :param image_file_r: file reading object
177        :return:
178        """
179        remain_range = self.care_block_range
180        temp_file_map = {}
181
182        with open(map_path, 'r') as f_r:
183            # Read the .map file and process each line.
184            for each_line in f_r.readlines():
185                each_map_path, ranges_value = each_line.split(None, 1)
186                each_range = BlocksManager(ranges_value)
187                each_range = each_range.get_subtract_with_other(BlocksManager("0"))
188                # each_range may not contained in the remain range.
189                intersect_range = each_range.get_intersect_with_other(remain_range)
190                if each_range.size() != intersect_range.size():
191                    each_range = intersect_range
192                temp_file_map[each_map_path] = each_range
193                # After the processing is complete,
194                # remove each_range from remain_range.
195                remain_range = remain_range.get_subtract_with_other(each_range)
196        reserved_blocks = self.reserved_blocks
197        # Remove reserved blocks from all blocks.
198        remain_range = remain_range.get_subtract_with_other(reserved_blocks)
199
200        # Divide all blocks into zero_blocks
201        # (if there are many) and nonzero_blocks.
202        zero_blocks_list = []
203        nonzero_blocks_list = []
204        nonzero_groups_list = []
205        default_zero_block = ('\0' * self.block_size).encode()
206
207        nonzero_blocks_list, nonzero_groups_list, zero_blocks_list = \
208            self.apply_remain_range(
209                default_zero_block, image_file_r, nonzero_blocks_list,
210                nonzero_groups_list, remain_range, zero_blocks_list)
211
212        temp_file_map = self.get_file_map(
213            nonzero_blocks_list, nonzero_groups_list,
214            reserved_blocks, temp_file_map, zero_blocks_list)
215        self.file_map = temp_file_map
216
217    def apply_remain_range(self, *args):
218        """
219        Implement traversal processing of remain_range.
220        """
221        default_zero_block, image_file_r, \
222            nonzero_blocks_list, nonzero_groups_list, \
223            remain_range, zero_blocks_list = args
224        for start_value, end_value in remain_range:
225            for each_value in range(start_value, end_value):
226                # bisect 二分查找,b在self.offset_index中的位置
227                idx = bisect.bisect_right(self.offset_index, each_value) - 1
228                chunk_start, _, file_pos, fill_data = \
229                    self.offset_value_list[idx]
230                data = self.get_file_data(self.block_size, chunk_start,
231                                          default_zero_block, each_value,
232                                          file_pos, fill_data, image_file_r)
233
234                zero_blocks_list, nonzero_blocks_list, nonzero_groups_list = \
235                    self.get_zero_nonzero_blocks_list(
236                        data, default_zero_block, each_value,
237                        nonzero_blocks_list, nonzero_groups_list,
238                        zero_blocks_list)
239        return nonzero_blocks_list, nonzero_groups_list, zero_blocks_list
240
241    @staticmethod
242    def get_file_map(*args):
243        """
244        Obtain the file map.
245        nonzero_blocks_list nonzero blocks list,
246        nonzero_groups_list nonzero groups list,
247        reserved_blocks reserved blocks ,
248        temp_file_map temporary file map,
249        zero_blocks_list zero block list
250        :return temp_file_map file map
251        """
252        nonzero_blocks_list, nonzero_groups_list, \
253            reserved_blocks, temp_file_map, zero_blocks_list = args
254        if nonzero_blocks_list:
255            nonzero_groups_list.append(nonzero_blocks_list)
256        if zero_blocks_list:
257            temp_file_map[FILE_MAP_ZERO_KEY] = \
258                BlocksManager(range_data=zero_blocks_list)
259        if nonzero_groups_list:
260            for i, blocks in enumerate(nonzero_groups_list):
261                temp_file_map["%s-%d" % (FILE_MAP_NONZERO_KEY, i)] = \
262                    BlocksManager(range_data=blocks)
263        if reserved_blocks:
264            temp_file_map[FILE_MAP_COPY_KEY] = reserved_blocks
265        return temp_file_map
266
267    @staticmethod
268    def get_zero_nonzero_blocks_list(*args):
269        """
270        Get zero_blocks_list, nonzero_blocks_list, and nonzero_groups_list.
271        data: block data,
272        default_zero_block: default to zero block,
273        each_value: each value,
274        nonzero_blocks_list: nonzero_blocks_list,
275        nonzero_groups_list: nonzero_groups_list,
276        zero_blocks_list: zero_blocks_list,
277        :return new_zero_blocks_list: new zero blocks list,
278        :return new_nonzero_blocks_list: new nonzero blocks list,
279        :return new_nonzero_groups_list: new nonzero groups list.
280        """
281        data, default_zero_block, each_value, \
282            nonzero_blocks_list, nonzero_groups_list, \
283            zero_blocks_list = args
284        # Check whether the data block is equal to the default zero_blocks.
285        if data == default_zero_block:
286            zero_blocks_list.append(each_value)
287            zero_blocks_list.append(each_value + 1)
288        else:
289            nonzero_blocks_list.append(each_value)
290            nonzero_blocks_list.append(each_value + 1)
291            # The number of nonzero_blocks is greater than
292            # or equal to the upper limit.
293            if len(nonzero_blocks_list) >= MAX_BLOCKS_PER_GROUP:
294                nonzero_groups_list.append(nonzero_blocks_list)
295                nonzero_blocks_list = []
296        new_zero_blocks_list, new_nonzero_blocks_list, \
297            new_nonzero_groups_list = \
298            copy.copy(zero_blocks_list), \
299            copy.copy(nonzero_blocks_list),\
300            copy.copy(nonzero_groups_list)
301        return new_zero_blocks_list, new_nonzero_blocks_list, \
302            new_nonzero_groups_list
303
304    @staticmethod
305    def get_file_data(*args):
306        """
307        Get the file data.
308        block_size: blocksize,
309        chunk_start: the start position of chunk,
310        default_zero_block: default to zero blocks,
311        each_value: each_value,
312        file_pos: file position,
313        fill_data: data,
314        image_file_r: read file object,
315        :return data: Get the file data.
316        """
317        block_size, chunk_start, default_zero_block, each_value, \
318            file_pos, fill_data, image_file_r = args
319        if file_pos is not None:
320            file_pos += (each_value - chunk_start) * block_size
321            image_file_r.seek(file_pos, os.SEEK_SET)
322            data = image_file_r.read(block_size)
323        else:
324            if fill_data == default_zero_block[:4]:
325                data = default_zero_block
326            else:
327                data = None
328        return data
329
330    def range_sha256(self, ranges):
331        """
332        range sha256 hash content
333        :param ranges: ranges value
334        :return:
335        """
336        hash_obj = sha256()
337        for data in self.__get_blocks_set_data(ranges):
338            hash_obj.update(data)
339        return hash_obj.hexdigest()
340
341    def write_range_data_2_fd(self, ranges, file_obj):
342        """
343        write range data to fd
344        :param ranges: ranges obj
345        :param file_obj: file obj
346        :return:
347        """
348        for data in self.__get_blocks_set_data(ranges):
349            file_obj.write(data)
350
351    def get_ranges(self, ranges):
352        """
353        get ranges value
354        :param ranges: ranges
355        :return: ranges value
356        """
357        return [each_data for each_data in self.__get_blocks_set_data(ranges)]
358
359    def __get_blocks_set_data(self, blocks_set_data):
360        """
361        Get the range data.
362        """
363        with open(self.image_path, 'rb') as f_r:
364            for start, end in blocks_set_data:
365                diff_value = end - start
366                idx = bisect.bisect_right(self.offset_index, start) - 1
367                chunk_start, chunk_len, file_pos, fill_data = \
368                    self.offset_value_list[idx]
369
370                remain = chunk_len - (start - chunk_start)
371                this_read = min(remain, diff_value)
372                if file_pos is not None:
373                    pos = file_pos + ((start - chunk_start) * self.block_size)
374                    f_r.seek(pos, os.SEEK_SET)
375                    yield f_r.read(this_read * self.block_size)
376                else:
377                    yield fill_data * (this_read * (self.block_size >> 2))
378                diff_value -= this_read
379
380                while diff_value > 0:
381                    idx += 1
382                    chunk_start, chunk_len, file_pos, fill_data = \
383                        self.offset_value_list[idx]
384                    this_read = min(chunk_len, diff_value)
385                    if file_pos is not None:
386                        f_r.seek(file_pos, os.SEEK_SET)
387                        yield f_r.read(this_read * self.block_size)
388                    else:
389                        yield fill_data * (this_read * (self.block_size >> 2))
390                    diff_value -= this_read