- add sources.
[platform/framework/web/crosswalk.git] / src / courgette / third_party / bsdiff_apply.cc
1 /*-
2  * Copyright 2003,2004 Colin Percival
3  * All rights reserved
4  *
5  * Redistribution and use in source and binary forms, with or without
6  * modification, are permitted providing that the following conditions
7  * are met:
8  * 1. Redistributions of source code must retain the above copyright
9  *    notice, this list of conditions and the following disclaimer.
10  * 2. Redistributions in binary form must reproduce the above copyright
11  *    notice, this list of conditions and the following disclaimer in the
12  *    documentation and/or other materials provided with the distribution.
13  *
14  * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
15  * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
16  * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
17  * ARE DISCLAIMED.  IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY
18  * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
19  * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS
20  * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
21  * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
22  * STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING
23  * IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
24  * POSSIBILITY OF SUCH DAMAGE.
25  *
26  * Changelog:
27  * 2009-03-31 - Change to use Streams.  Move CRC code to crc.{h,cc}
28  *                --Stephen Adams <sra@chromium.org>
29  * 2013-04-10 - Add wrapper method to apply a patch to files directly.
30  *                --Joshua Pawlicki <waffles@chromium.org>
31  */
32
33 // Copyright (c) 2009 The Chromium Authors. All rights reserved.
34 // Use of this source code is governed by a BSD-style license that can be
35 // found in the LICENSE file.
36
37 #include "courgette/third_party/bsdiff.h"
38
39 #include "base/files/memory_mapped_file.h"
40 #include "courgette/crc.h"
41 #include "courgette/streams.h"
42
43 namespace courgette {
44
45 BSDiffStatus MBS_ReadHeader(SourceStream* stream, MBSPatchHeader* header) {
46   if (!stream->Read(header->tag, sizeof(header->tag))) return READ_ERROR;
47   if (!stream->ReadVarint32(&header->slen)) return READ_ERROR;
48   if (!stream->ReadVarint32(&header->scrc32)) return READ_ERROR;
49   if (!stream->ReadVarint32(&header->dlen)) return READ_ERROR;
50
51   // The string will have a NUL terminator that we don't use, hence '-1'.
52   COMPILE_ASSERT(sizeof(MBS_PATCH_HEADER_TAG) - 1 == sizeof(header->tag),
53                  MBS_PATCH_HEADER_TAG_must_match_header_field_size);
54   if (memcmp(header->tag, MBS_PATCH_HEADER_TAG, 8) != 0)
55     return UNEXPECTED_ERROR;
56
57   return OK;
58 }
59
60 BSDiffStatus MBS_ApplyPatch(const MBSPatchHeader *header,
61                             SourceStream* patch_stream,
62                             const uint8* old_start, size_t old_size,
63                             SinkStream* new_stream) {
64   const uint8* old_end = old_start + old_size;
65
66   SourceStreamSet patch_streams;
67   if (!patch_streams.Init(patch_stream))
68     return READ_ERROR;
69
70   SourceStream* control_stream_copy_counts = patch_streams.stream(0);
71   SourceStream* control_stream_extra_counts = patch_streams.stream(1);
72   SourceStream* control_stream_seeks = patch_streams.stream(2);
73   SourceStream* diff_skips = patch_streams.stream(3);
74   SourceStream* diff_bytes = patch_streams.stream(4);
75   SourceStream* extra_bytes = patch_streams.stream(5);
76
77   const uint8* extra_start = extra_bytes->Buffer();
78   const uint8* extra_end = extra_start + extra_bytes->Remaining();
79   const uint8* extra_position = extra_start;
80
81   const uint8* old_position = old_start;
82
83   if (header->dlen && !new_stream->Reserve(header->dlen))
84     return MEM_ERROR;
85
86   uint32 pending_diff_zeros = 0;
87   if (!diff_skips->ReadVarint32(&pending_diff_zeros))
88     return UNEXPECTED_ERROR;
89
90   while (!control_stream_copy_counts->Empty()) {
91     uint32 copy_count, extra_count;
92     int32 seek_adjustment;
93     if (!control_stream_copy_counts->ReadVarint32(&copy_count))
94       return UNEXPECTED_ERROR;
95     if (!control_stream_extra_counts->ReadVarint32(&extra_count))
96       return UNEXPECTED_ERROR;
97     if (!control_stream_seeks->ReadVarint32Signed(&seek_adjustment))
98       return UNEXPECTED_ERROR;
99
100 #ifdef DEBUG_bsmedberg
101     printf("Applying block:  copy: %-8u extra: %-8u seek: %+i\n",
102            copy_count, extra_count, seek_adjustment);
103 #endif
104     // Byte-wise arithmetically add bytes from old file to bytes from the diff
105     // block.
106     if (copy_count > static_cast<size_t>(old_end - old_position))
107       return UNEXPECTED_ERROR;
108
109     // Add together bytes from the 'old' file and the 'diff' stream.
110     for (size_t i = 0;  i < copy_count;  ++i) {
111       uint8 diff_byte = 0;
112       if (pending_diff_zeros) {
113         --pending_diff_zeros;
114       } else {
115         if (!diff_skips->ReadVarint32(&pending_diff_zeros))
116           return UNEXPECTED_ERROR;
117         if (!diff_bytes->Read(&diff_byte, 1))
118           return UNEXPECTED_ERROR;
119       }
120       uint8 byte = old_position[i] + diff_byte;
121       if (!new_stream->Write(&byte, 1))
122         return MEM_ERROR;
123     }
124     old_position += copy_count;
125
126     // Copy bytes from the extra block.
127     if (extra_count > static_cast<size_t>(extra_end - extra_position))
128       return UNEXPECTED_ERROR;
129
130     if (!new_stream->Write(extra_position, extra_count))
131       return MEM_ERROR;
132
133     extra_position += extra_count;
134
135     // "seek" forwards (or backwards) in oldfile.
136     if (old_position + seek_adjustment < old_start ||
137         old_position + seek_adjustment > old_end)
138       return UNEXPECTED_ERROR;
139
140     old_position += seek_adjustment;
141   }
142
143   if (!control_stream_copy_counts->Empty() ||
144       !control_stream_extra_counts->Empty() ||
145       !control_stream_seeks->Empty() ||
146       !diff_skips->Empty() ||
147       !diff_bytes->Empty() ||
148       !extra_bytes->Empty())
149     return UNEXPECTED_ERROR;
150
151   return OK;
152 }
153
154 BSDiffStatus ApplyBinaryPatch(SourceStream* old_stream,
155                               SourceStream* patch_stream,
156                               SinkStream* new_stream) {
157   MBSPatchHeader header;
158   BSDiffStatus ret = MBS_ReadHeader(patch_stream, &header);
159   if (ret != OK) return ret;
160
161   const uint8* old_start = old_stream->Buffer();
162   size_t old_size = old_stream->Remaining();
163
164   if (old_size != header.slen) return UNEXPECTED_ERROR;
165
166   if (CalculateCrc(old_start, old_size) != header.scrc32)
167     return CRC_ERROR;
168
169   MBS_ApplyPatch(&header, patch_stream, old_start, old_size, new_stream);
170
171   return OK;
172 }
173
174 BSDiffStatus ApplyBinaryPatch(const base::FilePath& old_file_path,
175                               const base::FilePath& patch_file_path,
176                               const base::FilePath& new_file_path) {
177   // Set up the old stream.
178   base::MemoryMappedFile old_file;
179   if (!old_file.Initialize(old_file_path)) {
180     return READ_ERROR;
181   }
182   SourceStream old_file_stream;
183   old_file_stream.Init(old_file.data(), old_file.length());
184
185   // Set up the patch stream.
186   base::MemoryMappedFile patch_file;
187   if (!patch_file.Initialize(patch_file_path)) {
188     return READ_ERROR;
189   }
190   SourceStream patch_file_stream;
191   patch_file_stream.Init(patch_file.data(), patch_file.length());
192
193   // Set up the new stream and apply the patch.
194   SinkStream new_sink_stream;
195   BSDiffStatus status = ApplyBinaryPatch(&old_file_stream,
196                                          &patch_file_stream,
197                                          &new_sink_stream);
198   if (status != OK) {
199     return status;
200   }
201
202   // Write the stream to disk.
203   int written = file_util::WriteFile(
204       new_file_path,
205       reinterpret_cast<const char*>(new_sink_stream.Buffer()),
206       static_cast<int>(new_sink_stream.Length()));
207   if (written != static_cast<int>(new_sink_stream.Length()))
208     return WRITE_ERROR;
209   return OK;
210 }
211
212 }  // namespace