| 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 | package vsix |
| 18 | |
| 19 | import ( |
| 20 | "crypto" |
| 21 | "io" |
| 22 | "path" |
| 23 | "strings" |
| 24 | |
| 25 | "github.com/sassoftware/relic/v7/lib/signappx" |
| 26 | "github.com/sassoftware/relic/v7/lib/zipslicer" |
| 27 | ) |
| 28 | |
| 29 | type mangler struct { |
| 30 | m *zipslicer.Mangler |
| 31 | digests map[string][]byte |
| 32 | ctypes *signappx.ContentTypes |
| 33 | hash crypto.Hash |
| 34 | } |
| 35 | |
| 36 | func mangleZip(r io.Reader, hash crypto.Hash) (*mangler, error) { |
| 37 | inz, err := zipslicer.ReadZipTar(r) |
| 38 | if err != nil { |
| 39 | return nil, err |
| 40 | } |
| 41 | m := &mangler{ |
| 42 | digests: make(map[string][]byte), |
| 43 | ctypes: signappx.NewContentTypes(), |
| 44 | hash: hash, |
| 45 | } |
| 46 | zm, err := inz.Mangle(func(f *zipslicer.MangleFile) error { |
| 47 | if keepFile(f.Name) { |
| 48 | sum, err := f.Digest(hash) |
| 49 | if err != nil { |
| 50 | return err |
| 51 | } |
| 52 | m.digests[f.Name] = sum |
| 53 | return nil |
| 54 | } else { |
| 55 | if f.Name == contentTypesPath { |
| 56 | if err := m.parseTypes(f); err != nil { |
| 57 | return err |
| 58 | } |
| 59 | } |
| 60 | f.Delete() |
| 61 | } |
| 62 | return nil |
| 63 | }) |
| 64 | if err != nil { |
| 65 | return nil, err |
| 66 | } |
| 67 | m.m = zm |
| 68 | return m, nil |
| 69 | } |
| 70 | |
| 71 | func keepFile(fp string) bool { |
| 72 | switch fp { |
| 73 | case rootRelsPath + "/", contentTypesPath: |
| 74 | return false |
| 75 | } |
| 76 | switch path.Ext(fp) { |
| 77 | case ".rels", ".psdsxs", ".psdor": |
| 78 | return false |
| 79 | } |
| 80 | switch { |
| 81 | case strings.HasPrefix(fp, digSigPath+"/"): |
| 82 | return false |
| 83 | } |
| 84 | return true |
| 85 | } |