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
Read8(const void * address)40 static inline int64_t Read8(const void *address) {
41 return android::base::get_unaligned<int64_t>(address);
42 }
43
Read4(const void * address)44 static inline int32_t Read4(const void *address) {
45 return android::base::get_unaligned<int32_t>(address);
46 }
47
48 // This function is a wrapper of ApplyBSDiffPatch(). It has a custom sink function to deflate the
49 // 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,SHA_CTX * ctx)50 static bool ApplyBSDiffPatchAndStreamOutput(const uint8_t* src_data, size_t src_len,
51 const Value* patch, size_t patch_offset,
52 const char* deflate_header, SinkFn sink, SHA_CTX* ctx) {
53 size_t expected_target_length = static_cast<size_t>(Read8(deflate_header + 32));
54 int level = Read4(deflate_header + 40);
55 int method = Read4(deflate_header + 44);
56 int window_bits = Read4(deflate_header + 48);
57 int mem_level = Read4(deflate_header + 52);
58 int strategy = Read4(deflate_header + 56);
59
60 std::unique_ptr<z_stream, decltype(&deflateEnd)> strm(new z_stream(), deflateEnd);
61 strm->zalloc = Z_NULL;
62 strm->zfree = Z_NULL;
63 strm->opaque = Z_NULL;
64 strm->avail_in = 0;
65 strm->next_in = nullptr;
66 int ret = deflateInit2(strm.get(), level, method, window_bits, mem_level, strategy);
67 if (ret != Z_OK) {
68 LOG(ERROR) << "Failed to init uncompressed data deflation: " << ret;
69 return false;
70 }
71
72 // Define a custom sink wrapper that feeds to bspatch. It deflates the available patch data on
73 // the fly and outputs the compressed data to the given sink.
74 size_t actual_target_length = 0;
75 size_t total_written = 0;
76 static constexpr size_t buffer_size = 32768;
77 auto compression_sink = [&](const uint8_t* data, size_t len) -> size_t {
78 // The input patch length for an update never exceeds INT_MAX.
79 strm->avail_in = len;
80 strm->next_in = data;
81 do {
82 std::vector<uint8_t> buffer(buffer_size);
83 strm->avail_out = buffer_size;
84 strm->next_out = buffer.data();
85 if (actual_target_length + len < expected_target_length) {
86 ret = deflate(strm.get(), Z_NO_FLUSH);
87 } else {
88 ret = deflate(strm.get(), Z_FINISH);
89 }
90 if (ret != Z_OK && ret != Z_STREAM_END) {
91 LOG(ERROR) << "Failed to deflate stream: " << ret;
92 // zero length indicates an error in the sink function of bspatch().
93 return 0;
94 }
95
96 size_t have = buffer_size - strm->avail_out;
97 total_written += have;
98 if (sink(buffer.data(), have) != have) {
99 LOG(ERROR) << "Failed to write " << have << " compressed bytes to output.";
100 return 0;
101 }
102 if (ctx) SHA1_Update(ctx, buffer.data(), have);
103 } while ((strm->avail_in != 0 || strm->avail_out == 0) && ret != Z_STREAM_END);
104
105 actual_target_length += len;
106 return len;
107 };
108
109 if (ApplyBSDiffPatch(src_data, src_len, patch, patch_offset, compression_sink, nullptr) != 0) {
110 return false;
111 }
112
113 if (ret != Z_STREAM_END) {
114 LOG(ERROR) << "ret is expected to be Z_STREAM_END, but it's " << ret;
115 return false;
116 }
117
118 if (expected_target_length != actual_target_length) {
119 LOG(ERROR) << "target length is expected to be " << expected_target_length << ", but it's "
120 << actual_target_length;
121 return false;
122 }
123 LOG(DEBUG) << "bspatch writes " << total_written << " bytes in total to streaming output.";
124
125 return true;
126 }
127
ApplyImagePatch(const unsigned char * old_data,size_t old_size,const unsigned char * patch_data,size_t patch_size,SinkFn sink)128 int ApplyImagePatch(const unsigned char* old_data, size_t old_size, const unsigned char* patch_data,
129 size_t patch_size, SinkFn sink) {
130 Value patch(VAL_BLOB, std::string(reinterpret_cast<const char*>(patch_data), patch_size));
131
132 return ApplyImagePatch(old_data, old_size, &patch, sink, nullptr, nullptr);
133 }
134
135 /*
136 * Apply the patch given in 'patch_filename' to the source data given
137 * by (old_data, old_size). Write the patched output to the 'output'
138 * file, and update the SHA context with the output data as well.
139 * Return 0 on success.
140 */
ApplyImagePatch(const unsigned char * old_data,size_t old_size,const Value * patch,SinkFn sink,SHA_CTX * ctx,const Value * bonus_data)141 int ApplyImagePatch(const unsigned char* old_data, size_t old_size, const Value* patch, SinkFn sink,
142 SHA_CTX* ctx, const Value* bonus_data) {
143 if (patch->data.size() < 12) {
144 printf("patch too short to contain header\n");
145 return -1;
146 }
147
148 // IMGDIFF2 uses CHUNK_NORMAL, CHUNK_DEFLATE, and CHUNK_RAW.
149 // (IMGDIFF1, which is no longer supported, used CHUNK_NORMAL and
150 // CHUNK_GZIP.)
151 size_t pos = 12;
152 const char* header = &patch->data[0];
153 if (memcmp(header, "IMGDIFF2", 8) != 0) {
154 printf("corrupt patch file header (magic number)\n");
155 return -1;
156 }
157
158 int num_chunks = Read4(header + 8);
159
160 for (int i = 0; i < num_chunks; ++i) {
161 // each chunk's header record starts with 4 bytes.
162 if (pos + 4 > patch->data.size()) {
163 printf("failed to read chunk %d record\n", i);
164 return -1;
165 }
166 int type = Read4(&patch->data[pos]);
167 pos += 4;
168
169 if (type == CHUNK_NORMAL) {
170 const char* normal_header = &patch->data[pos];
171 pos += 24;
172 if (pos > patch->data.size()) {
173 printf("failed to read chunk %d normal header data\n", i);
174 return -1;
175 }
176
177 size_t src_start = static_cast<size_t>(Read8(normal_header));
178 size_t src_len = static_cast<size_t>(Read8(normal_header + 8));
179 size_t patch_offset = static_cast<size_t>(Read8(normal_header + 16));
180
181 if (src_start + src_len > old_size) {
182 printf("source data too short\n");
183 return -1;
184 }
185 if (ApplyBSDiffPatch(old_data + src_start, src_len, patch, patch_offset, sink, ctx) != 0) {
186 printf("Failed to apply bsdiff patch.\n");
187 return -1;
188 }
189 } else if (type == CHUNK_RAW) {
190 const char* raw_header = &patch->data[pos];
191 pos += 4;
192 if (pos > patch->data.size()) {
193 printf("failed to read chunk %d raw header data\n", i);
194 return -1;
195 }
196
197 size_t data_len = static_cast<size_t>(Read4(raw_header));
198
199 if (pos + data_len > patch->data.size()) {
200 printf("failed to read chunk %d raw data\n", i);
201 return -1;
202 }
203 if (ctx) SHA1_Update(ctx, &patch->data[pos], data_len);
204 if (sink(reinterpret_cast<const unsigned char*>(&patch->data[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 } else if (type == CHUNK_DEFLATE) {
210 // deflate chunks have an additional 60 bytes in their chunk header.
211 const char* deflate_header = &patch->data[pos];
212 pos += 60;
213 if (pos > patch->data.size()) {
214 printf("failed to read chunk %d deflate header data\n", i);
215 return -1;
216 }
217
218 size_t src_start = static_cast<size_t>(Read8(deflate_header));
219 size_t src_len = static_cast<size_t>(Read8(deflate_header + 8));
220 size_t patch_offset = static_cast<size_t>(Read8(deflate_header + 16));
221 size_t expanded_len = static_cast<size_t>(Read8(deflate_header + 24));
222
223 if (src_start + src_len > old_size) {
224 printf("source data too short\n");
225 return -1;
226 }
227
228 // Decompress the source data; the chunk header tells us exactly
229 // how big we expect it to be when decompressed.
230
231 // Note: expanded_len will include the bonus data size if
232 // the patch was constructed with bonus data. The
233 // deflation will come up 'bonus_size' bytes short; these
234 // must be appended from the bonus_data value.
235 size_t bonus_size = (i == 1 && bonus_data != NULL) ? bonus_data->data.size() : 0;
236
237 std::vector<unsigned char> expanded_source(expanded_len);
238
239 // inflate() doesn't like strm.next_out being a nullptr even with
240 // avail_out being zero (Z_STREAM_ERROR).
241 if (expanded_len != 0) {
242 z_stream strm;
243 strm.zalloc = Z_NULL;
244 strm.zfree = Z_NULL;
245 strm.opaque = Z_NULL;
246 strm.avail_in = src_len;
247 strm.next_in = old_data + src_start;
248 strm.avail_out = expanded_len;
249 strm.next_out = expanded_source.data();
250
251 int ret = inflateInit2(&strm, -15);
252 if (ret != Z_OK) {
253 printf("failed to init source inflation: %d\n", ret);
254 return -1;
255 }
256
257 // Because we've provided enough room to accommodate the output
258 // data, we expect one call to inflate() to suffice.
259 ret = inflate(&strm, Z_SYNC_FLUSH);
260 if (ret != Z_STREAM_END) {
261 printf("source inflation returned %d\n", ret);
262 return -1;
263 }
264 // We should have filled the output buffer exactly, except
265 // for the bonus_size.
266 if (strm.avail_out != bonus_size) {
267 printf("source inflation short by %zu bytes\n", strm.avail_out - bonus_size);
268 return -1;
269 }
270 inflateEnd(&strm);
271
272 if (bonus_size) {
273 memcpy(expanded_source.data() + (expanded_len - bonus_size), &bonus_data->data[0],
274 bonus_size);
275 }
276 }
277
278 if (!ApplyBSDiffPatchAndStreamOutput(expanded_source.data(), expanded_len, patch,
279 patch_offset, deflate_header, sink, ctx)) {
280 LOG(ERROR) << "Fail to apply streaming bspatch.";
281 return -1;
282 }
283
284 } else {
285 printf("patch chunk %d is unknown type %d\n", i, type);
286 return -1;
287 }
288 }
289
290 return 0;
291 }
292