-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathgorun.go
216 lines (195 loc) · 5.64 KB
/
gorun.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
//
// gorun - Script-like runner for Go source files.
//
// https://wiki.ubuntu.com/gorun
//
// Copyright (c) 2011 Canonical Ltd.
//
// Written by Gustavo Niemeyer <[email protected]>
//
package main
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU General Public License version 3, as published
// by the Free Software Foundation.
//
// This program is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranties of
// MERCHANTABILITY, SATISFACTORY QUALITY, or FITNESS FOR A PARTICULAR
// PURPOSE. See the GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License along
// with this program. If not, see <http://www.gnu.org/licenses/>.
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path/filepath"
"runtime"
"strconv"
"strings"
"syscall"
)
func main() {
args := os.Args[1:]
if len(args) == 0 {
fmt.Fprintln(os.Stderr, "usage: gorun <source file> [...]")
os.Exit(1)
}
err := Run(args)
if err != nil {
fmt.Fprintln(os.Stderr, "error: "+err.Error())
os.Exit(1)
}
panic("unreachable")
}
// Run compiles and links the Go source file on args[0] and
// runs it with arguments args[1:].
func Run(args []string) error {
sourcefile := args[0]
_, runfile, err := RunFile(sourcefile)
if err != nil {
return err
}
compile := false
sstat, err := os.Stat(sourcefile)
if err != nil {
return err
}
rstat, err := os.Stat(runfile)
switch {
case err != nil:
compile = true
case rstat.Mode()&(os.ModeDir|os.ModeSymlink|os.ModeDevice|os.ModeNamedPipe|os.ModeSocket) != 0:
return errors.New("not a file: " + runfile)
case rstat.ModTime().Before(sstat.ModTime()) || rstat.Mode().Perm()&0700 != 0700:
compile = true
default:
}
for retry := 3; retry > 0; retry-- {
if compile {
err := Compile(sourcefile, runfile)
if err != nil {
return err
}
// If sourcefile was changed, will be updated on next run.
os.Chtimes(runfile, sstat.ModTime(), sstat.ModTime())
}
err = syscall.Exec(runfile, args, os.Environ())
if os.IsNotExist(err) {
// Got cleaned up under our feet.
compile = true
continue
}
break
}
if err != nil {
panic("exec returned but succeeded")
}
return err
}
// Compile compiles and links sourcefile and atomically renames the
// resulting binary to runfile.
func Compile(sourcefile, runfile string) (err error) {
pid := strconv.Itoa(os.Getpid())
content, err := ioutil.ReadFile(sourcefile)
if len(content) > 2 && content[0] == '#' && content[1] == '!' {
content[0] = '/'
content[1] = '/'
sourcefile = runfile + "." + pid + ".go"
ioutil.WriteFile(sourcefile, content, 0600)
defer os.Remove(sourcefile)
}
gotool := filepath.Join(runtime.GOROOT(), "bin", "go")
if _, err := os.Stat(gotool); err != nil {
if gotool, err = exec.LookPath("go"); err != nil {
return errors.New("can't find go tool")
}
}
ldout := runfile + "." + pid
err = Exec([]string{gotool, "build", "-o", ldout, sourcefile})
if err != nil {
return err
}
return os.Rename(ldout, runfile)
}
// Exec runs args[0] with args[1:] arguments and passes through
// stdout and stderr.
func Exec(args []string) error {
cmd := exec.Command(args[0], args[1:]...)
cmd.Stdout = os.Stdout
cmd.Stderr = os.Stderr
err := cmd.Run()
base := filepath.Base(args[0])
if err != nil {
return errors.New("failed to run " + base + ": " + err.Error())
}
return nil
}
// RunFile returns the directory and file location where the binary generated
// for sourcefile should be put. In case the directory does not yet exist, it
// will be created by RunDir.
func RunFile(sourcefile string) (rundir, runfile string, err error) {
rundir, err = RunDir()
if err != nil {
return "", "", err
}
sourcefile, err = filepath.Abs(sourcefile)
if err != nil {
return "", "", err
}
sourcefile, err = filepath.EvalSymlinks(sourcefile)
if err != nil {
return "", "", err
}
runfile = strings.Replace(sourcefile, "%", "%%", -1)
runfile = strings.Replace(runfile, string(filepath.Separator), "%", -1)
runfile = filepath.Join(rundir, runfile)
return rundir, runfile, nil
}
func sysStat(stat os.FileInfo) *syscall.Stat_t {
return stat.Sys().(*syscall.Stat_t)
}
func canWrite(stat os.FileInfo, euid, egid int) bool {
perm := stat.Mode().Perm()
sstat := sysStat(stat)
return perm&02 != 0 || perm&020 != 0 && uint32(egid) == sstat.Gid || perm&0200 != 0 && uint32(euid) == sstat.Uid
}
// RunDir returns the directory where binary files generates should be put.
// In case a safe directory isn't found, one will be created.
func RunDir() (rundir string, err error) {
tempdir := os.TempDir()
euid := os.Geteuid()
stat, err := os.Stat(tempdir)
if err != nil || !stat.IsDir() || !canWrite(stat, euid, os.Getegid()) {
return "", errors.New("can't write on directory: " + tempdir)
}
hostname, err := os.Hostname()
if err != nil {
return "", errors.New("can't get hostname: " + err.Error())
}
prefix := "gorun-" + hostname + "-" + strconv.Itoa(euid)
suffix := runtime.GOOS + "_" + runtime.GOARCH
prefixi := prefix
var i uint64
for {
rundir = filepath.Join(tempdir, prefixi, suffix)
// A directory is only considered safe if the owner matches the
// user running the script and its permissions prevent someone
// else from writing on it.
stat, err := os.Stat(rundir)
if err == nil && stat.IsDir() && stat.Mode().Perm() == 0700 && sysStat(stat).Uid == uint32(euid) {
return rundir, nil
}
if os.IsNotExist(err) {
err := os.MkdirAll(rundir, 0700)
if err == nil {
return rundir, nil
}
}
i++
prefixi = prefix + "-" + strconv.FormatUint(i, 10)
}
panic("unreachable")
}