| 1 | // |
| 2 | // Copyright (c) SAS Institute Inc. |
| 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 | // A means of conveying a series of edits to binary files. Each item in a |
| 18 | // patchset consists of an offset into the old file, the number of bytes to |
| 19 | // remove, and the octet string to replace it with. |
| 20 | package binpatch |
| 21 | |
| 22 | import ( |
| 23 | "bytes" |
| 24 | "encoding/binary" |
| 25 | "errors" |
| 26 | "fmt" |
| 27 | "io" |
| 28 | "os" |
| 29 | "sort" |
| 30 | |
| 31 | "github.com/sassoftware/relic/v7/lib/atomicfile" |
| 32 | ) |
| 33 | |
| 34 | const ( |
| 35 | MimeType = "application/x-binary-patch" |
| 36 | |
| 37 | uint32Max = 0xffffffff |
| 38 | ) |
| 39 | |
| 40 | type PatchSet struct { |
| 41 | Patches []PatchHeader |
| 42 | Blobs [][]byte |
| 43 | } |
| 44 | |
| 45 | type PatchSetHeader struct { |
| 46 | Version, NumPatches uint32 |
| 47 | } |
| 48 | |
| 49 | type PatchHeader struct { |
| 50 | Offset int64 |
| 51 | OldSize, NewSize uint32 |
| 52 | } |
| 53 | |
| 54 | // Create a new, empty PatchSet |
| 55 | func New() *PatchSet { |
| 56 | return new(PatchSet) |
| 57 | } |
| 58 | |
| 59 | // Add a new patch region to a PatchSet. The bytes beginning at "offset" and |
| 60 | // running for "oldSize" are removed and replaced with "blob". oldSize may be 0. |
| 61 | func (p *PatchSet) Add(offset, oldSize int64, blob []byte) { |
| 62 | if len(p.Patches) > 0 { |
| 63 | i := len(p.Patches) - 1 |
| 64 | last := p.Patches[i] |
| 65 | lastEnd := last.Offset + int64(last.OldSize) |
| 66 | lastBlob := p.Blobs[i] |
| 67 | oldCombo := int64(last.OldSize) + oldSize |
| 68 | newCombo := int64(len(lastBlob)) + int64(len(blob)) |
| 69 | if offset == lastEnd && oldCombo <= uint32Max && newCombo <= uint32Max { |
| 70 | // coalesce this patch into the previous one |
| 71 | p.Patches[i].OldSize = uint32(oldCombo) |
| 72 | p.Patches[i].NewSize = uint32(newCombo) |
| 73 | if len(blob) > 0 { |
| 74 | newBlob := make([]byte, newCombo) |
| 75 | copy(newBlob, lastBlob) |
| 76 | copy(newBlob[len(lastBlob):], blob) |
| 77 | p.Blobs[i] = newBlob |
| 78 | } |
| 79 | return |
| 80 | } |
| 81 | } |
| 82 | for oldSize > uint32Max { |
| 83 | p.Patches = append(p.Patches, PatchHeader{offset, uint32Max, 0}) |
| 84 | p.Blobs = append(p.Blobs, nil) |
| 85 | offset += uint32Max |
| 86 | oldSize -= uint32Max |
| 87 | } |
| 88 | p.Patches = append(p.Patches, PatchHeader{offset, uint32(oldSize), uint32(len(blob))}) |
| 89 | p.Blobs = append(p.Blobs, blob) |
| 90 | } |
| 91 | |
| 92 | // Unmarshal a PatchSet from bytes |
| 93 | func Load(blob []byte) (*PatchSet, error) { |
| 94 | r := bytes.NewReader(blob) |
| 95 | var h PatchSetHeader |
| 96 | if err := binary.Read(r, binary.BigEndian, &h); err != nil { |
| 97 | return nil, err |
| 98 | } else if h.Version != 1 { |
| 99 | return nil, fmt.Errorf("unsupported binpatch version %d", h.Version) |
| 100 | } |
| 101 | num := int(h.NumPatches) |
| 102 | p := &PatchSet{ |
| 103 | Patches: make([]PatchHeader, num), |
| 104 | Blobs: make([][]byte, num), |
| 105 | } |
| 106 | if err := binary.Read(r, binary.BigEndian, p.Patches); err != nil { |
| 107 | return nil, err |
| 108 | } |
| 109 | for i, hdr := range p.Patches { |
| 110 | p.Blobs[i] = make([]byte, int(hdr.NewSize)) |
| 111 | if _, err := io.ReadFull(r, p.Blobs[i]); err != nil { |
| 112 | return nil, err |
| 113 | } |
| 114 | } |
| 115 | return p, nil |
| 116 | } |
| 117 | |
| 118 | // Marshal a PatchSet to bytes |
| 119 | func (p *PatchSet) Dump() []byte { |
| 120 | sort.Sort(sorter{p}) |
| 121 | header := PatchSetHeader{1, uint32(len(p.Patches))} |
| 122 | size := 8 + 16*len(p.Patches) |
| 123 | for _, hdr := range p.Patches { |
| 124 | size += int(hdr.NewSize) |
| 125 | } |
| 126 | buf := bytes.NewBuffer(make([]byte, 0, size)) |
| 127 | _ = binary.Write(buf, binary.BigEndian, header) |
| 128 | _ = binary.Write(buf, binary.BigEndian, p.Patches) |
| 129 | for _, blob := range p.Blobs { |
| 130 | _, _ = buf.Write(blob) |
| 131 | } |
| 132 | return buf.Bytes() |
| 133 | } |
| 134 | |
| 135 | // Apply a PatchSet by taking the input file, transforming it, and writing the |
| 136 | // result to outpath. If outpath is the same name as infile then the file will |
| 137 | // be updated in-place if a direct overwrite is possible. If they are not the |
| 138 | // same file, or the patch requires moving parts of the old file, then the |
| 139 | // output will be written to a temporary file then renamed over the destination |
| 140 | // path. |
| 141 | func (p *PatchSet) Apply(infile *os.File, outpath string) error { |
| 142 | if outpath == "" { |
| 143 | outpath = infile.Name() |
| 144 | } |
| 145 | // Determine if an in-place overwrite is possible. If any test fails then |
| 146 | // fall back to doing a full copy (write-rename). |
| 147 | ininfo, err := infile.Stat() |
| 148 | if err != nil { |
| 149 | return p.applyRewrite(infile, outpath) |
| 150 | } |
| 151 | outinfo, err := os.Lstat(outpath) |
| 152 | if err != nil || !canOverwrite(ininfo, outinfo) { |
| 153 | return p.applyRewrite(infile, outpath) |
| 154 | } |
| 155 | size := ininfo.Size() |
| 156 | for i, patch := range p.Patches { |
| 157 | // All patches except the last must have oldsize == newsize |
| 158 | if patch.OldSize == patch.NewSize { |
| 159 | continue |
| 160 | } else if i != len(p.Patches)-1 { |
| 161 | return p.applyRewrite(infile, outpath) |
| 162 | } |
| 163 | // For the last patch, either oldsize == newsize or the patch must extend |
| 164 | // or truncate the file, i.e. the end of the old chunk must coincide |
| 165 | // with the end of the file. |
| 166 | oldEnd := patch.Offset + int64(patch.OldSize) |
| 167 | if oldEnd != ininfo.Size() { |
| 168 | return p.applyRewrite(infile, outpath) |
| 169 | } |
| 170 | size = patch.Offset + int64(patch.NewSize) |
| 171 | } |
| 172 | // Do in-place rewrite |
| 173 | for i, patch := range p.Patches { |
| 174 | if _, err := infile.WriteAt(p.Blobs[i], patch.Offset); err != nil { |
| 175 | return err |
| 176 | } |
| 177 | } |
| 178 | return infile.Truncate(size) |
| 179 | } |
| 180 | |
| 181 | // Apply a patch by writing the patched result to a new file. This is the |
| 182 | // fallback case whenever an in-place write isn't possible. |
| 183 | func (p *PatchSet) applyRewrite(infile *os.File, outpath string) error { |
| 184 | if _, err := infile.Seek(0, 0); err != nil { |
| 185 | return err |
| 186 | } |
| 187 | outfile, err := atomicfile.New(outpath) |
| 188 | if err != nil { |
| 189 | return err |
| 190 | } |
| 191 | defer outfile.Close() |
| 192 | var pos int64 |
| 193 | for i, patch := range p.Patches { |
| 194 | blob := p.Blobs[i] |
| 195 | delta := patch.Offset - pos |
| 196 | if delta < 0 { |
| 197 | return errors.New("patches out of order") |
| 198 | } |
| 199 | // Copy data before the patch |
| 200 | if delta > 0 { |
| 201 | if _, err := io.CopyN(outfile, infile, delta); err != nil { |
| 202 | return err |
| 203 | } |
| 204 | pos += delta |
| 205 | } |
| 206 | // Skip the old data on the input file |
| 207 | delta = int64(patch.OldSize) |
| 208 | if _, err := infile.Seek(delta, io.SeekCurrent); err != nil { |
| 209 | return err |
| 210 | } |
| 211 | pos += delta |
| 212 | // Write the new data to the output file |
| 213 | if _, err := outfile.Write(blob); err != nil { |
| 214 | return err |
| 215 | } |
| 216 | } |
| 217 | // Copy everything after the last patch |
| 218 | if _, err := io.Copy(outfile, infile); err != nil { |
| 219 | return err |
| 220 | } |
| 221 | infile.Close() |
| 222 | return outfile.Commit() |
| 223 | } |
| 224 | |
| 225 | func canOverwrite(ininfo, outinfo os.FileInfo) bool { |
| 226 | if !outinfo.Mode().IsRegular() { |
| 227 | return false |
| 228 | } |
| 229 | if !os.SameFile(ininfo, outinfo) { |
| 230 | return false |
| 231 | } |
| 232 | if hasLinks(outinfo) { |
| 233 | return false |
| 234 | } |
| 235 | return true |
| 236 | } |