This repository has been archived by the owner on Nov 21, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 34
/
stub.go
250 lines (231 loc) · 7.57 KB
/
stub.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
package main
import (
"archive/tar"
"bytes"
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"os/exec"
"path"
"path/filepath"
"regexp"
"strings"
"time"
)
func main() {
executableFile, err := os.Executable()
if err != nil {
log.Fatalf("caxa stub: Failed to find executable: %v", err)
}
executable, err := os.ReadFile(executableFile)
if err != nil {
log.Fatalf("caxa stub: Failed to read executable: %v", err)
}
footerSeparator := []byte("\n")
footerIndex := bytes.LastIndex(executable, footerSeparator)
if footerIndex == -1 {
log.Fatalf("caxa stub: Failed to find footer (did you append an archive and a footer to the stub?): %v", err)
}
footerString := executable[footerIndex+len(footerSeparator):]
var footer struct {
Identifier string `json:"identifier"`
Command []string `json:"command"`
}
if err := json.Unmarshal(footerString, &footer); err != nil {
log.Fatalf("caxa stub: Failed to parse JSON in footer: %v", err)
}
appDirectory := path.Join(os.TempDir(), "caxa", footer.Identifier)
appDirectoryFileInfo, err := os.Stat(appDirectory)
if err != nil && !errors.Is(err, os.ErrNotExist) {
log.Fatalf("caxa stub: Failed to find information about caxa directory: %v", err)
}
if err == nil && !appDirectoryFileInfo.IsDir() {
log.Fatalf("caxa stub: caxa path already exists and isn’t a directory: %v", err)
}
if err == nil && appDirectoryFileInfo.IsDir() {
// NOOP: Directory already exists; use it as a cached version of the application and don’t extract again.
}
if err != nil && errors.Is(err, os.ErrNotExist) {
// The use of ‘Repeat’ below is lower even further the chance that the separator will appear literally in the compiled stub.
archiveSeparator := []byte("\n" + strings.Repeat("#", 3) + " CAXA " + strings.Repeat("#", 3) + "\n")
archiveIndex := bytes.Index(executable, archiveSeparator)
if archiveIndex == -1 {
log.Fatalf("caxa stub: Failed to find archive (did you append the separator when building the stub?): %v", err)
}
archive := executable[archiveIndex+len(archiveSeparator) : footerIndex]
if err := Untar(bytes.NewReader(archive), appDirectory); err != nil {
log.Fatalf("caxa stub: Failed to uncompress archive: %v", err)
}
}
expandedCommand := make([]string, len(footer.Command))
appDirectoryPlaceholderRegexp := regexp.MustCompile(`\{\{\s*caxa\s*\}\}`)
for key, commandPart := range footer.Command {
expandedCommand[key] = appDirectoryPlaceholderRegexp.ReplaceAllLiteralString(commandPart, appDirectory)
}
command := exec.Command(expandedCommand[0], append(expandedCommand[1:], os.Args[1:]...)...)
command.Stdin = os.Stdin
command.Stdout = os.Stdout
command.Stderr = os.Stderr
err = command.Run()
var exitError *exec.ExitError
if errors.As(err, &exitError) {
os.Exit(exitError.ExitCode())
} else if err != nil {
log.Fatalf("caxa stub: Failed to run command: %v", err)
}
}
// Adapted from https://github.com/golang/build/blob/db2c93053bcd6b944723c262828c90af91b0477a/internal/untar/untar.go and https://github.com/mholt/archiver/tree/v3.5.0
// Copyright 2017 The Go Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
// Package untar untars a tarball to disk.
// package untar
// import (
// "archive/tar"
// "compress/gzip"
// "fmt"
// "io"
// "log"
// "os"
// "path"
// "path/filepath"
// "strings"
// "time"
// )
// TODO(bradfitz): this was copied from x/build/cmd/buildlet/buildlet.go
// but there were some buildlet-specific bits in there, so the code is
// forked for now. Unfork and add some opts arguments here, so the
// buildlet can use this code somehow.
// Untar reads the gzip-compressed tar file from r and writes it into dir.
func Untar(r io.Reader, dir string) error {
return untar(r, dir)
}
func untar(r io.Reader, dir string) (err error) {
t0 := time.Now()
nFiles := 0
madeDir := map[string]bool{}
// defer func() {
// td := time.Since(t0)
// if err == nil {
// log.Printf("extracted tarball into %s: %d files, %d dirs (%v)", dir, nFiles, len(madeDir), td)
// } else {
// log.Printf("error extracting tarball into %s after %d files, %d dirs, %v: %v", dir, nFiles, len(madeDir), td, err)
// }
// }()
zr, err := gzip.NewReader(r)
if err != nil {
return fmt.Errorf("requires gzip-compressed body: %v", err)
}
tr := tar.NewReader(zr)
loggedChtimesError := false
for {
f, err := tr.Next()
if err == io.EOF {
break
}
if err != nil {
// log.Printf("tar reading error: %v", err)
return fmt.Errorf("tar error: %v", err)
}
if !validRelPath(f.Name) {
return fmt.Errorf("tar contained invalid name error %q", f.Name)
}
rel := filepath.FromSlash(f.Name)
abs := filepath.Join(dir, rel)
fi := f.FileInfo()
mode := fi.Mode()
switch {
case mode.IsRegular():
// Make the directory. This is redundant because it should
// already be made by a directory entry in the tar
// beforehand. Thus, don't check for errors; the next
// write will fail with the same error.
dir := filepath.Dir(abs)
if !madeDir[dir] {
if err := os.MkdirAll(filepath.Dir(abs), 0755); err != nil {
return err
}
madeDir[dir] = true
}
wf, err := os.OpenFile(abs, os.O_RDWR|os.O_CREATE|os.O_TRUNC, mode.Perm())
if err != nil {
return err
}
n, err := io.Copy(wf, tr)
if closeErr := wf.Close(); closeErr != nil && err == nil {
err = closeErr
}
if err != nil {
return fmt.Errorf("error writing to %s: %v", abs, err)
}
if n != f.Size {
return fmt.Errorf("only wrote %d bytes to %s; expected %d", n, abs, f.Size)
}
modTime := f.ModTime
if modTime.After(t0) {
// Clamp modtimes at system time. See
// golang.org/issue/19062 when clock on
// buildlet was behind the gitmirror server
// doing the git-archive.
modTime = t0
}
if !modTime.IsZero() {
if err := os.Chtimes(abs, modTime, modTime); err != nil && !loggedChtimesError {
// benign error. Gerrit doesn't even set the
// modtime in these, and we don't end up relying
// on it anywhere (the gomote push command relies
// on digests only), so this is a little pointless
// for now.
// log.Printf("error changing modtime: %v (further Chtimes errors suppressed)", err)
loggedChtimesError = true // once is enough
}
}
nFiles++
case mode.IsDir():
if err := os.MkdirAll(abs, 0755); err != nil {
return err
}
madeDir[abs] = true
case f.Typeflag == tar.TypeSymlink:
// leafac: Added by me to support symbolic links. Adapted from https://github.com/mholt/archiver/blob/v3.5.0/tar.go#L254-L276 and https://github.com/mholt/archiver/blob/v3.5.0/archiver.go#L313-L332
err := os.MkdirAll(filepath.Dir(abs), 0755)
if err != nil {
return fmt.Errorf("%s: making directory for file: %v", abs, err)
}
_, err = os.Lstat(abs)
if err == nil {
err = os.Remove(abs)
if err != nil {
return fmt.Errorf("%s: failed to unlink: %+v", abs, err)
}
}
err = os.Symlink(f.Linkname, abs)
if err != nil {
return fmt.Errorf("%s: making symbolic link for: %v", abs, err)
}
default:
return fmt.Errorf("tar file entry %s contained unsupported file type %v", f.Name, mode)
}
}
return nil
}
func validRelativeDir(dir string) bool {
if strings.Contains(dir, `\`) || path.IsAbs(dir) {
return false
}
dir = path.Clean(dir)
if strings.HasPrefix(dir, "../") || strings.HasSuffix(dir, "/..") || dir == ".." {
return false
}
return true
}
func validRelPath(p string) bool {
if p == "" || strings.Contains(p, `\`) || strings.HasPrefix(p, "/") || strings.Contains(p, "../") {
return false
}
return true
}