This repository has been archived by the owner on Apr 23, 2023. It is now read-only.
forked from golang/playground
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsandbox.go
705 lines (616 loc) · 15.7 KB
/
sandbox.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
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
// Copyright 2014 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.
// TODO(andybons): add logging
// TODO(andybons): restrict memory use
// TODO(andybons): send exit code to user
package main
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"fmt"
"go/ast"
"go/doc"
"go/parser"
"go/token"
"io"
"io/ioutil"
stdlog "log"
"net/http"
"os"
"os/exec"
"path/filepath"
"reflect"
"runtime"
"strings"
"text/template"
"time"
"github.com/bradfitz/gomemcache/memcache"
)
const (
maxRunTime = 2 * time.Second
// progName is the program name in compiler errors
progName = "prog.go"
)
// Runtime error strings that will not be cached if found in an Event message.
var nonCachingRuntimeErrors = []string{"out of memory", "cannot allocate memory"}
type request struct {
Body string
}
type response struct {
Errors string
Events []Event
}
// commandHandler returns an http.HandlerFunc.
// This handler creates a *request, assigning the "Body" field a value
// from the "body" form parameter or from the HTTP request body.
// If there is no cached *response for the combination of cachePrefix and request.Body,
// handler calls cmdFunc and in case of a nil error, stores the value of *response in the cache.
// The handler returned supports Cross-Origin Resource Sharing (CORS) from any domain.
func (s *server) commandHandler(cachePrefix string, cmdFunc func(*request) (*response, error)) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
if r.Method == "OPTIONS" {
// This is likely a pre-flight CORS request.
return
}
var req request
// Until programs that depend on golang.org/x/tools/godoc/static/playground.js
// are updated to always send JSON, this check is in place.
if b := r.FormValue("body"); b != "" {
req.Body = b
} else if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
s.log.Errorf("error decoding request: %v", err)
http.Error(w, http.StatusText(http.StatusBadRequest), http.StatusBadRequest)
return
}
resp := &response{}
key := cacheKey(cachePrefix, req.Body)
if err := s.cache.Get(key, resp); err != nil {
if err != memcache.ErrCacheMiss {
s.log.Errorf("s.cache.Get(%q, &response): %v", key, err)
}
resp, err = cmdFunc(&req)
if err != nil {
s.log.Errorf("cmdFunc error: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
for _, el := range resp.Events {
if el.Kind != "stderr" {
continue
}
for _, e := range nonCachingRuntimeErrors {
if strings.Contains(el.Message, e) {
s.log.Errorf("cmdFunc runtime error: %q", el.Message)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
}
}
if err := s.cache.Set(key, resp); err != nil {
s.log.Errorf("cache.Set(%q, resp): %v", key, err)
}
}
var buf bytes.Buffer
if err := json.NewEncoder(&buf).Encode(resp); err != nil {
s.log.Errorf("error encoding response: %v", err)
http.Error(w, http.StatusText(http.StatusInternalServerError), http.StatusInternalServerError)
return
}
if _, err := io.Copy(w, &buf); err != nil {
s.log.Errorf("io.Copy(w, &buf): %v", err)
return
}
}
}
func cacheKey(prefix, body string) string {
h := sha256.New()
io.WriteString(h, body)
return fmt.Sprintf("%s-%s-%x", prefix, runtime.Version(), h.Sum(nil))
}
// isTestFunc tells whether fn has the type of a testing function.
func isTestFunc(fn *ast.FuncDecl) bool {
if fn.Type.Results != nil && len(fn.Type.Results.List) > 0 ||
fn.Type.Params.List == nil ||
len(fn.Type.Params.List) != 1 ||
len(fn.Type.Params.List[0].Names) > 1 {
return false
}
ptr, ok := fn.Type.Params.List[0].Type.(*ast.StarExpr)
if !ok {
return false
}
// We can't easily check that the type is *testing.T
// because we don't know how testing has been imported,
// but at least check that it's *T or *something.T.
if name, ok := ptr.X.(*ast.Ident); ok && name.Name == "T" {
return true
}
if sel, ok := ptr.X.(*ast.SelectorExpr); ok && sel.Sel.Name == "T" {
return true
}
return false
}
// isTest tells whether name looks like a test (or benchmark, according to prefix).
// It is a Test (say) if there is a character after Test that is not a lower-case letter.
// We don't want TesticularCancer.
func isTest(name, prefix string) bool {
if !strings.HasPrefix(name, prefix) {
return false
}
if len(name) == len(prefix) { // "Test" is ok
return true
}
return ast.IsExported(name[len(prefix):])
}
// getTestProg returns source code that executes all valid tests and examples in src.
// If the main function is present or there are no tests or examples, it returns nil.
// getTestProg emulates the "go test" command as closely as possible.
// Benchmarks are not supported because of sandboxing.
func getTestProg(src []byte) []byte {
fset := token.NewFileSet()
// Early bail for most cases.
f, err := parser.ParseFile(fset, "main.go", src, parser.ImportsOnly)
if err != nil || f.Name.Name != "main" {
return nil
}
// importPos stores the position to inject the "testing" import declaration, if needed.
importPos := fset.Position(f.Name.End()).Offset
var testingImported bool
for _, s := range f.Imports {
if s.Path.Value == `"testing"` && s.Name == nil {
testingImported = true
break
}
}
// Parse everything and extract test names.
f, err = parser.ParseFile(fset, "main.go", src, parser.ParseComments)
if err != nil {
return nil
}
var tests []string
for _, d := range f.Decls {
n, ok := d.(*ast.FuncDecl)
if !ok {
continue
}
name := n.Name.Name
switch {
case name == "main":
// main declared as a method will not obstruct creation of our main function.
if n.Recv == nil {
return nil
}
case isTest(name, "Test") && isTestFunc(n):
tests = append(tests, name)
}
}
// Tests imply imported "testing" package in the code.
// If there is no import, bail to let the compiler produce an error.
if !testingImported && len(tests) > 0 {
return nil
}
// We emulate "go test". An example with no "Output" comment is compiled,
// but not executed. An example with no text after "Output:" is compiled,
// executed, and expected to produce no output.
var ex []*doc.Example
// exNoOutput indicates whether an example with no output is found.
// We need to compile the program containing such an example even if there are no
// other tests or examples.
exNoOutput := false
for _, e := range doc.Examples(f) {
if e.Output != "" || e.EmptyOutput {
ex = append(ex, e)
}
if e.Output == "" && !e.EmptyOutput {
exNoOutput = true
}
}
if len(tests) == 0 && len(ex) == 0 && !exNoOutput {
return nil
}
if !testingImported && (len(ex) > 0 || exNoOutput) {
// In case of the program with examples and no "testing" package imported,
// add import after "package main" without modifying line numbers.
importDecl := []byte(`;import "testing";`)
src = bytes.Join([][]byte{src[:importPos], importDecl, src[importPos:]}, nil)
}
data := struct {
Tests []string
Examples []*doc.Example
}{
tests,
ex,
}
code := new(bytes.Buffer)
if err := testTmpl.Execute(code, data); err != nil {
panic(err)
}
src = append(src, code.Bytes()...)
return src
}
var testTmpl = template.Must(template.New("main").Parse(`
func main() {
matchAll := func(t string, pat string) (bool, error) { return true, nil }
tests := []testing.InternalTest{
{{range .Tests}}
{"{{.}}", {{.}}},
{{end}}
}
examples := []testing.InternalExample{
{{range .Examples}}
{"Example{{.Name}}", Example{{.Name}}, {{printf "%q" .Output}}, {{.Unordered}}},
{{end}}
}
testing.Main(matchAll, tests, nil, examples)
}
`))
// compileAndRun tries to build and run a user program.
// The output of successfully ran program is returned in *response.Events.
// If a program cannot be built or has timed out,
// *response.Errors contains an explanation for a user.
func compileAndRun(req *request) (*response, error) {
// TODO(andybons): Add semaphore to limit number of running programs at once.
tmpDir, err := ioutil.TempDir("", "sandbox")
if err != nil {
return nil, fmt.Errorf("error creating temp directory: %v", err)
}
defer os.RemoveAll(tmpDir)
src := []byte(req.Body)
in := filepath.Join(tmpDir, "main.go")
if err := ioutil.WriteFile(in, src, 0400); err != nil {
return nil, fmt.Errorf("error creating temp file %q: %v", in, err)
}
fset := token.NewFileSet()
f, err := parser.ParseFile(fset, in, nil, parser.PackageClauseOnly)
if err == nil && f.Name.Name != "main" {
return &response{Errors: "package name must be main"}, nil
}
var testParam string
if code := getTestProg(src); code != nil {
testParam = "-test.v"
if err := ioutil.WriteFile(in, code, 0400); err != nil {
return nil, fmt.Errorf("error creating temp file %q: %v", in, err)
}
}
exe := filepath.Join(tmpDir, "a.out")
cmd := exec.Command("go", "build", "-o", exe, in)
cmd.Env = []string{"GOOS=nacl", "GOARCH=amd64p32", "GOPATH=" + os.Getenv("GOPATH")}
if out, err := cmd.CombinedOutput(); err != nil {
if _, ok := err.(*exec.ExitError); ok {
// Return compile errors to the user.
// Rewrite compiler errors to refer to progName
// instead of '/tmp/sandbox1234/main.go'.
errs := strings.Replace(string(out), in, progName, -1)
// "go build", invoked with a file name, puts this odd
// message before any compile errors; strip it.
errs = strings.Replace(errs, "# command-line-arguments\n", "", 1)
return &response{Errors: errs}, nil
}
return nil, fmt.Errorf("error building go source: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), maxRunTime)
defer cancel()
cmd = exec.CommandContext(ctx, "sel_ldr_x86_64", "-l", "/dev/null", "-S", "-e", exe, testParam)
rec := new(Recorder)
cmd.Stdout = rec.Stdout()
cmd.Stderr = rec.Stderr()
if err := cmd.Run(); err != nil {
if ctx.Err() == context.DeadlineExceeded {
return &response{Errors: "process took too long"}, nil
}
if _, ok := err.(*exec.ExitError); !ok {
return nil, fmt.Errorf("error running sandbox: %v", err)
}
}
events, err := rec.Events()
if err != nil {
return nil, fmt.Errorf("error decoding events: %v", err)
}
return &response{Events: events}, nil
}
func (s *server) healthCheck() error {
resp, err := compileAndRun(&request{Body: healthProg})
if err != nil {
return err
}
if resp.Errors != "" {
return fmt.Errorf("compile error: %v", resp.Errors)
}
if len(resp.Events) != 1 || resp.Events[0].Message != "ok" {
return fmt.Errorf("unexpected output: %v", resp.Events)
}
return nil
}
const healthProg = `
package main
import "fmt"
func main() { fmt.Print("ok") }
`
func (s *server) test() {
if err := s.healthCheck(); err != nil {
stdlog.Fatal(err)
}
for _, t := range tests {
resp, err := compileAndRun(&request{Body: t.prog})
if err != nil {
stdlog.Fatal(err)
}
if t.wantEvents != nil {
if !reflect.DeepEqual(resp.Events, t.wantEvents) {
stdlog.Fatalf("resp.Events = %q, want %q", resp.Events, t.wantEvents)
}
continue
}
if t.errors != "" {
if resp.Errors != t.errors {
stdlog.Fatalf("resp.Errors = %q, want %q", resp.Errors, t.errors)
}
continue
}
if resp.Errors != "" {
stdlog.Fatal(resp.Errors)
}
if len(resp.Events) == 0 {
stdlog.Fatalf("unexpected output: %q, want %q", "", t.want)
}
var b strings.Builder
for _, e := range resp.Events {
b.WriteString(e.Message)
}
if !strings.Contains(b.String(), t.want) {
stdlog.Fatalf("unexpected output: %q, want %q", b.String(), t.want)
}
}
fmt.Println("OK")
}
var tests = []struct {
prog, want, errors string
wantEvents []Event
}{
{prog: `
package main
import "time"
func main() {
loc, err := time.LoadLocation("America/New_York")
if err != nil {
panic(err.Error())
}
println(loc.String())
}
`, want: "America/New_York"},
{prog: `
package main
import (
"fmt"
"time"
)
func main() {
fmt.Println(time.Now())
}
`, want: "2009-11-10 23:00:00 +0000 UTC"},
{prog: `
package main
import (
"fmt"
"time"
)
func main() {
t1 := time.Tick(time.Second * 3)
t2 := time.Tick(time.Second * 7)
t3 := time.Tick(time.Second * 11)
end := time.After(time.Second * 19)
want := "112131211"
var got []byte
for {
var c byte
select {
case <-t1:
c = '1'
case <-t2:
c = '2'
case <-t3:
c = '3'
case <-end:
if g := string(got); g != want {
fmt.Printf("got %q, want %q\n", g, want)
} else {
fmt.Println("timers fired as expected")
}
return
}
got = append(got, c)
}
}
`, want: "timers fired as expected"},
{prog: `
package main
import (
"code.google.com/p/go-tour/pic"
"code.google.com/p/go-tour/reader"
"code.google.com/p/go-tour/tree"
"code.google.com/p/go-tour/wc"
)
var (
_ = pic.Show
_ = reader.Validate
_ = tree.New
_ = wc.Test
)
func main() {
println("ok")
}
`, want: "ok"},
{prog: `
package test
func main() {
println("test")
}
`, want: "", errors: "package name must be main"},
{prog: `
package main
import (
"fmt"
"os"
"path/filepath"
)
func main() {
filepath.Walk("/", func(path string, info os.FileInfo, err error) error {
fmt.Println(path)
return nil
})
}
`, want: `/
/dev
/dev/null
/dev/random
/dev/urandom
/dev/zero
/etc
/etc/group
/etc/hosts
/etc/passwd
/etc/resolv.conf
/tmp
/usr
/usr/local
/usr/local/go
/usr/local/go/lib
/usr/local/go/lib/time
/usr/local/go/lib/time/zoneinfo.zip`},
{prog: `
package main
import "testing"
func TestSanity(t *testing.T) {
if 1+1 != 2 {
t.Error("uhh...")
}
}
`, want: `=== RUN TestSanity
--- PASS: TestSanity (0.00s)
PASS`},
{prog: `
package main
func TestSanity(t *testing.T) {
t.Error("uhh...")
}
func ExampleNotExecuted() {
// Output: it should not run
}
`, want: "", errors: "prog.go:4:20: undefined: testing\n"},
{prog: `
package main
import (
"fmt"
"testing"
)
func TestSanity(t *testing.T) {
t.Error("uhh...")
}
func main() {
fmt.Println("test")
}
`, want: "test"},
{prog: `
package main//comment
import "fmt"
func ExampleOutput() {
fmt.Println("The output")
// Output: The output
}
`, want: `=== RUN ExampleOutput
--- PASS: ExampleOutput (0.00s)
PASS`},
{prog: `
package main//comment
import "fmt"
func ExampleUnorderedOutput() {
fmt.Println("2")
fmt.Println("1")
fmt.Println("3")
// Unordered output: 3
// 2
// 1
}
`, want: `=== RUN ExampleUnorderedOutput
--- PASS: ExampleUnorderedOutput (0.00s)
PASS`},
{prog: `
package main
import "fmt"
func ExampleEmptyOutput() {
// Output:
}
func ExampleEmptyOutputFail() {
fmt.Println("1")
// Output:
}
`, want: `=== RUN ExampleEmptyOutput
--- PASS: ExampleEmptyOutput (0.00s)
=== RUN ExampleEmptyOutputFail
--- FAIL: ExampleEmptyOutputFail (0.00s)
got:
1
want:
FAIL`},
// Run program without executing this example function.
{prog: `
package main
func ExampleNoOutput() {
panic(1)
}
`, want: `testing: warning: no tests to run
PASS`},
{prog: `
package main
import "fmt"
func ExampleShouldNotRun() {
fmt.Println("The output")
// Output: The output
}
func main() {
fmt.Println("Main")
}
`, want: "Main"},
{prog: `
package main
import (
"fmt"
"os"
)
func main() {
fmt.Fprintln(os.Stdout, "A")
fmt.Fprintln(os.Stderr, "B")
fmt.Fprintln(os.Stdout, "A")
fmt.Fprintln(os.Stdout, "A")
}
`, want: "A\nB\nA\nA\n"},
// Integration test for runtime.write fake timestamps.
{prog: `
package main
import (
"fmt"
"os"
"time"
)
func main() {
fmt.Fprintln(os.Stdout, "A")
fmt.Fprintln(os.Stderr, "B")
fmt.Fprintln(os.Stdout, "A")
fmt.Fprintln(os.Stdout, "A")
time.Sleep(time.Second)
fmt.Fprintln(os.Stderr, "B")
time.Sleep(time.Second)
fmt.Fprintln(os.Stdout, "A")
}
`, wantEvents: []Event{
{"A\n", "stdout", 0},
{"B\n", "stderr", time.Nanosecond},
{"A\nA\n", "stdout", time.Nanosecond},
{"B\n", "stderr", time.Second - 2*time.Nanosecond},
{"A\n", "stdout", time.Second},
}},
}