1 /*
2  * Copyright (C) 2009 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 // See imgdiff.cpp in this directory for a description of the patch file
18 // format.
19 
20 #include <applypatch/imgpatch.h>
21 
22 #include <errno.h>
23 #include <stdio.h>
24 #include <string.h>
25 #include <sys/cdefs.h>
26 #include <sys/stat.h>
27 #include <unistd.h>
28 
29 #include <memory>
30 #include <string>
31 #include <vector>
32 
33 #include <android-base/logging.h>
34 #include <android-base/memory.h>
35 #include <applypatch/applypatch.h>
36 #include <applypatch/imgdiff.h>
37 #include <openssl/sha.h>
38 #include <zlib.h>
39 
40 #include "edify/expr.h"
41 #include "otautil/print_sha1.h"
42 
Read8(const void * address)43 static inline int64_t Read8(const void *address) {
44   return android::base::get_unaligned<int64_t>(address);
45 }
46 
Read4(const void * address)47 static inline int32_t Read4(const void *address) {
48   return android::base::get_unaligned<int32_t>(address);
49 }
50 
51 // This function is a wrapper of ApplyBSDiffPatch(). It has a custom sink function to deflate the
52 // patched data and stream the deflated data to output.
ApplyBSDiffPatchAndStreamOutput(const uint8_t * src_data,size_t src_len,const Value & patch,size_t patch_offset,const char * deflate_header,SinkFn sink)53 static bool ApplyBSDiffPatchAndStreamOutput(const uint8_t* src_data, size_t src_len,
54                                             const Value& patch, size_t patch_offset,
55                                             const char* deflate_header, SinkFn sink) {
56   size_t expected_target_length = static_cast<size_t>(Read8(deflate_header + 32));
57   CHECK_GT(expected_target_length, static_cast<size_t>(0));
58   int level = Read4(deflate_header + 40);
59   int method = Read4(deflate_header + 44);
60   int window_bits = Read4(deflate_header + 48);
61   int mem_level = Read4(deflate_header + 52);
62   int strategy = Read4(deflate_header + 56);
63 
64   z_stream strm;
65   strm.zalloc = Z_NULL;
66   strm.zfree = Z_NULL;
67   strm.opaque = Z_NULL;
68   strm.avail_in = 0;
69   strm.next_in = nullptr;
70   int ret = deflateInit2(&strm, level, method, window_bits, mem_level, strategy);
71   if (ret != Z_OK) {
72     LOG(ERROR) << "Failed to init uncompressed data deflation: " << ret;
73     return false;
74   }
75 
76   // Define a custom sink wrapper that feeds to bspatch. It deflates the available patch data on
77   // the fly and outputs the compressed data to the given sink.
78   size_t actual_target_length = 0;
79   size_t total_written = 0;
80   static constexpr size_t buffer_size = 32768;
81   auto compression_sink = [&strm, &actual_target_length, &expected_target_length, &total_written,
82                            &ret, &sink](const uint8_t* data, size_t len) -> size_t {
83     // The input patch length for an update never exceeds INT_MAX.
84     strm.avail_in = len;
85     strm.next_in = data;
86     do {
87       std::vector<uint8_t> buffer(buffer_size);
88       strm.avail_out = buffer_size;
89       strm.next_out = buffer.data();
90       if (actual_target_length + len < expected_target_length) {
91         ret = deflate(&strm, Z_NO_FLUSH);
92       } else {
93         ret = deflate(&strm, Z_FINISH);
94       }
95       if (ret != Z_OK && ret != Z_STREAM_END) {
96         LOG(ERROR) << "Failed to deflate stream: " << ret;
97         // zero length indicates an error in the sink function of bspatch().
98         return 0;
99       }
100 
101       size_t have = buffer_size - strm.avail_out;
102       total_written += have;
103       if (sink(buffer.data(), have) != have) {
104         LOG(ERROR) << "Failed to write " << have << " compressed bytes to output.";
105         return 0;
106       }
107     } while ((strm.avail_in != 0 || strm.avail_out == 0) && ret != Z_STREAM_END);
108 
109     actual_target_length += len;
110     return len;
111   };
112 
113   int bspatch_result = ApplyBSDiffPatch(src_data, src_len, patch, patch_offset, compression_sink);
114   deflateEnd(&strm);
115 
116   if (bspatch_result != 0) {
117     return false;
118   }
119 
120   if (ret != Z_STREAM_END) {
121     LOG(ERROR) << "ret is expected to be Z_STREAM_END, but it's " << ret;
122     return false;
123   }
124 
125   if (expected_target_length != actual_target_length) {
126     LOG(ERROR) << "target length is expected to be " << expected_target_length << ", but it's "
127                << actual_target_length;
128     return false;
129   }
130   LOG(DEBUG) << "bspatch wrote " << total_written << " bytes in total to streaming output.";
131 
132   return true;
133 }
134 
ApplyImagePatch(const unsigned char * old_data,size_t old_size,const unsigned char * patch_data,size_t patch_size,SinkFn sink)135 int ApplyImagePatch(const unsigned char* old_data, size_t old_size, const unsigned char* patch_data,
136                     size_t patch_size, SinkFn sink) {
137   Value patch(Value::Type::BLOB,
138               std::string(reinterpret_cast<const char*>(patch_data), patch_size));
139   return ApplyImagePatch(old_data, old_size, patch, sink, nullptr);
140 }
141 
ApplyImagePatch(const unsigned char * old_data,size_t old_size,const Value & patch,SinkFn sink,const Value * bonus_data)142 int ApplyImagePatch(const unsigned char* old_data, size_t old_size, const Value& patch, SinkFn sink,
143                     const Value* bonus_data) {
144   if (patch.data.size() < 12) {
145     printf("patch too short to contain header\n");
146     return -1;
147   }
148 
149   // IMGDIFF2 uses CHUNK_NORMAL, CHUNK_DEFLATE, and CHUNK_RAW. (IMGDIFF1, which is no longer
150   // supported, used CHUNK_NORMAL and CHUNK_GZIP.)
151   const char* const patch_header = patch.data.data();
152   if (memcmp(patch_header, "IMGDIFF2", 8) != 0) {
153     printf("corrupt patch file header (magic number)\n");
154     return -1;
155   }
156 
157   int num_chunks = Read4(patch_header + 8);
158   size_t pos = 12;
159   for (int i = 0; i < num_chunks; ++i) {
160     // each chunk's header record starts with 4 bytes.
161     if (pos + 4 > patch.data.size()) {
162       printf("failed to read chunk %d record\n", i);
163       return -1;
164     }
165     int type = Read4(patch_header + pos);
166     pos += 4;
167 
168     if (type == CHUNK_NORMAL) {
169       const char* normal_header = patch_header + pos;
170       pos += 24;
171       if (pos > patch.data.size()) {
172         printf("failed to read chunk %d normal header data\n", i);
173         return -1;
174       }
175 
176       size_t src_start = static_cast<size_t>(Read8(normal_header));
177       size_t src_len = static_cast<size_t>(Read8(normal_header + 8));
178       size_t patch_offset = static_cast<size_t>(Read8(normal_header + 16));
179 
180       if (src_start + src_len > old_size) {
181         printf("source data too short\n");
182         return -1;
183       }
184       if (ApplyBSDiffPatch(old_data + src_start, src_len, patch, patch_offset, sink) != 0) {
185         printf("Failed to apply bsdiff patch.\n");
186         return -1;
187       }
188 
189       LOG(DEBUG) << "Processed chunk type normal";
190     } else if (type == CHUNK_RAW) {
191       const char* raw_header = patch_header + pos;
192       pos += 4;
193       if (pos > patch.data.size()) {
194         printf("failed to read chunk %d raw header data\n", i);
195         return -1;
196       }
197 
198       size_t data_len = static_cast<size_t>(Read4(raw_header));
199 
200       if (pos + data_len > patch.data.size()) {
201         printf("failed to read chunk %d raw data\n", i);
202         return -1;
203       }
204       if (sink(reinterpret_cast<const unsigned char*>(patch_header + pos), data_len) != data_len) {
205         printf("failed to write chunk %d raw data\n", i);
206         return -1;
207       }
208       pos += data_len;
209 
210       LOG(DEBUG) << "Processed chunk type raw";
211     } else if (type == CHUNK_DEFLATE) {
212       // deflate chunks have an additional 60 bytes in their chunk header.
213       const char* deflate_header = patch_header + pos;
214       pos += 60;
215       if (pos > patch.data.size()) {
216         printf("failed to read chunk %d deflate header data\n", i);
217         return -1;
218       }
219 
220       size_t src_start = static_cast<size_t>(Read8(deflate_header));
221       size_t src_len = static_cast<size_t>(Read8(deflate_header + 8));
222       size_t patch_offset = static_cast<size_t>(Read8(deflate_header + 16));
223       size_t expanded_len = static_cast<size_t>(Read8(deflate_header + 24));
224 
225       if (src_start + src_len > old_size) {
226         printf("source data too short\n");
227         return -1;
228       }
229 
230       // Decompress the source data; the chunk header tells us exactly
231       // how big we expect it to be when decompressed.
232 
233       // Note: expanded_len will include the bonus data size if the patch was constructed with
234       // bonus data. The deflation will come up 'bonus_size' bytes short; these must be appended
235       // from the bonus_data value.
236       size_t bonus_size = (i == 1 && bonus_data != nullptr) ? bonus_data->data.size() : 0;
237 
238       std::vector<unsigned char> expanded_source(expanded_len);
239 
240       // inflate() doesn't like strm.next_out being a nullptr even with
241       // avail_out being zero (Z_STREAM_ERROR).
242       if (expanded_len != 0) {
243         z_stream strm;
244         strm.zalloc = Z_NULL;
245         strm.zfree = Z_NULL;
246         strm.opaque = Z_NULL;
247         strm.avail_in = src_len;
248         strm.next_in = old_data + src_start;
249         strm.avail_out = expanded_len;
250         strm.next_out = expanded_source.data();
251 
252         int ret = inflateInit2(&strm, -15);
253         if (ret != Z_OK) {
254           printf("failed to init source inflation: %d\n", ret);
255           return -1;
256         }
257 
258         // Because we've provided enough room to accommodate the output
259         // data, we expect one call to inflate() to suffice.
260         ret = inflate(&strm, Z_SYNC_FLUSH);
261         if (ret != Z_STREAM_END) {
262           printf("source inflation returned %d\n", ret);
263           return -1;
264         }
265         // We should have filled the output buffer exactly, except
266         // for the bonus_size.
267         if (strm.avail_out != bonus_size) {
268           printf("source inflation short by %zu bytes\n", strm.avail_out - bonus_size);
269           return -1;
270         }
271         inflateEnd(&strm);
272 
273         if (bonus_size) {
274           memcpy(expanded_source.data() + (expanded_len - bonus_size), bonus_data->data.data(),
275                  bonus_size);
276         }
277       }
278 
279       if (!ApplyBSDiffPatchAndStreamOutput(expanded_source.data(), expanded_len, patch,
280                                            patch_offset, deflate_header, sink)) {
281         LOG(ERROR) << "Fail to apply streaming bspatch.";
282         return -1;
283       }
284 
285       LOG(DEBUG) << "Processed chunk type deflate";
286     } else {
287       printf("patch chunk %d is unknown type %d\n", i, type);
288       return -1;
289     }
290   }
291 
292   return 0;
293 }
294