1 // Copyright 2012 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
7 // Package socket implements an WebSocket-based playground backend.
8 // Clients connect to a websocket handler and send run/kill commands, and
9 // the server sends the output and exit status of the running processes.
10 // Multiple clients running multiple processes may be served concurrently.
11 // The wire format is JSON and is described by the Message type.
13 // This will not run on App Engine as WebSockets are not supported there.
14 package socket // import "golang.org/x/tools/playground/socket"
36 "golang.org/x/net/websocket"
37 "golang.org/x/tools/txtar"
40 // RunScripts specifies whether the socket handler should execute shell scripts
41 // (snippets that start with a shebang).
44 // Environ provides an environment when a binary, such as the go tool, is
46 var Environ func() []string = os.Environ
49 // The maximum number of messages to send per session (avoid flooding).
52 // Batch messages sent in this interval and send as a single message.
53 msgDelay = 10 * time.Millisecond
56 // Message is the wire format for the websocket connection to the browser.
57 // It is used for both sending output messages and receiving commands, as
58 // distinguished by the Kind field.
60 Id string // client-provided unique id for the process
61 Kind string // in: "run", "kill" out: "stdout", "stderr", "end"
63 Options *Options `json:",omitempty"`
66 // Options specify additional message options.
68 Race bool // use -race flag when building code (for "run" only)
71 // NewHandler returns a websocket server which checks the origin of requests.
72 func NewHandler(origin *url.URL) websocket.Server {
73 return websocket.Server{
74 Config: websocket.Config{Origin: origin},
76 Handler: websocket.Handler(socketHandler),
80 // handshake checks the origin of a request during the websocket handshake.
81 func handshake(c *websocket.Config, req *http.Request) error {
82 o, err := websocket.Origin(c, req)
84 log.Println("bad websocket origin:", err)
85 return websocket.ErrBadWebSocketOrigin
87 _, port, err := net.SplitHostPort(c.Origin.Host)
89 log.Println("bad websocket origin:", err)
90 return websocket.ErrBadWebSocketOrigin
92 ok := c.Origin.Scheme == o.Scheme && (c.Origin.Host == o.Host || c.Origin.Host == net.JoinHostPort(o.Host, port))
94 log.Println("bad websocket origin:", o)
95 return websocket.ErrBadWebSocketOrigin
97 log.Println("accepting connection from:", req.RemoteAddr)
101 // socketHandler handles the websocket connection for a given present session.
102 // It handles transcoding Messages to and from JSON format, and starting
103 // and killing processes.
104 func socketHandler(c *websocket.Conn) {
105 in, out := make(chan *Message), make(chan *Message)
106 errc := make(chan error, 1)
108 // Decode messages from client and send to the in channel.
110 dec := json.NewDecoder(c)
113 if err := dec.Decode(&m); err != nil {
121 // Receive messages from the out channel and encode to the client.
123 enc := json.NewEncoder(c)
125 if err := enc.Encode(m); err != nil {
133 // Start and kill processes and handle errors.
134 proc := make(map[string]*process)
140 log.Println("running snippet from:", c.Request().RemoteAddr)
142 proc[m.Id] = startProcess(m.Id, m.Body, out, m.Options)
148 // A encode or decode has failed; bail.
151 // Shut down any running processes.
152 for _, p := range proc {
160 // process represents a running process.
161 type process struct {
163 done chan struct{} // closed when wait completes
168 // startProcess builds and runs the given program, sending its output
169 // and end event as Messages on the provided channel.
170 func startProcess(id, body string, dest chan<- *Message, opt *Options) *process {
172 done = make(chan struct{})
173 out = make(chan *Message)
174 p = &process{out: out, done: done}
178 for m := range buffer(limiter(out, p), time.After) {
184 if path, args := shebang(body); path != "" {
186 err = p.startProcess(path, args, body)
188 err = errors.New("script execution is not allowed")
191 err = p.start(body, opt)
203 // end sends an "end" message to the client, containing the process id and the
204 // given error value. It also removes the binary, if present.
205 func (p *process) end(err error) {
207 defer os.RemoveAll(p.path)
209 m := &Message{Kind: "end"}
217 // A killer provides a mechanism to terminate a process.
218 // The Kill method returns only once the process has exited.
219 type killer interface {
223 // limiter returns a channel that wraps the given channel.
224 // It receives Messages from the given channel and sends them to the returned
225 // channel until it passes msgLimit messages, at which point it will kill the
226 // process and pass only the "end" message.
227 // When the given channel is closed, or when the "end" message is received,
228 // it closes the returned channel.
229 func limiter(in <-chan *Message, p killer) <-chan *Message {
230 out := make(chan *Message)
236 case n < msgLimit || m.Kind == "end":
242 // Kill in a goroutine as Kill will not return
243 // until the process' output has been
244 // processed, and we're doing that in this loop.
247 continue // don't increment
255 // buffer returns a channel that wraps the given channel. It receives messages
256 // from the given channel and sends them to the returned channel.
257 // Message bodies are gathered over the period msgDelay and coalesced into a
258 // single Message before they are passed on. Messages of the same kind are
259 // coalesced; when a message of a different kind is received, any buffered
260 // messages are flushed. When the given channel is closed, buffer flushes the
261 // remaining buffered messages and closes the returned channel.
262 // The timeAfter func should be time.After. It exists for testing.
263 func buffer(in <-chan *Message, timeAfter func(time.Duration) <-chan time.Time) <-chan *Message {
264 out := make(chan *Message)
275 out <- &Message{Kind: kind, Body: safeString(buf)}
276 buf = buf[:0] // recycle buffer
296 tc = timeAfter(msgDelay)
299 buf = append(buf, m.Body...)
309 // Kill stops the process if it is running and waits for it to exit.
310 func (p *process) Kill() {
311 if p == nil || p.run == nil {
315 <-p.done // block until process exits
318 // shebang looks for a shebang ('#!') at the beginning of the passed string.
319 // If found, it returns the path and args after the shebang.
320 // args includes the command as args[0].
321 func shebang(body string) (path string, args []string) {
322 body = strings.TrimSpace(body)
323 if !strings.HasPrefix(body, "#!") {
326 if i := strings.Index(body, "\n"); i >= 0 {
329 fs := strings.Fields(body[2:])
333 // startProcess starts a given program given its path and passing the given body
334 // to the command standard input.
335 func (p *process) startProcess(path string, args []string, body string) error {
339 Stdin: strings.NewReader(body),
340 Stdout: &messageWriter{kind: "stdout", out: p.out},
341 Stderr: &messageWriter{kind: "stderr", out: p.out},
343 if err := cmd.Start(); err != nil {
350 // start builds and starts the given program, sending its output to p.out,
351 // and stores the running *exec.Cmd in the run field.
352 func (p *process) start(body string, opt *Options) error {
353 // We "go build" and then exec the binary so that the
354 // resultant *exec.Cmd is a handle to the user's program
355 // (rather than the go tool process).
356 // This makes Kill work.
358 path, err := ioutil.TempDir("", "present-")
362 p.path = path // to be removed by p.end
365 if runtime.GOOS == "windows" {
368 bin := filepath.Join(path, out)
370 // write body to x.go files
371 a := txtar.Parse([]byte(body))
372 if len(a.Comment) != 0 {
373 a.Files = append(a.Files, txtar.File{Name: "prog.go", Data: a.Comment})
377 for _, f := range a.Files {
378 err = ioutil.WriteFile(filepath.Join(path, f.Name), f.Data, 0666)
382 if f.Name == "go.mod" {
387 // build x.go, creating x
388 args := []string{"go", "build", "-tags", "OMIT"}
389 if opt != nil && opt.Race {
392 Body: "Running with race detector.\n",
394 args = append(args, "-race")
396 args = append(args, "-o", bin)
397 cmd := p.cmd(path, args...)
399 cmd.Env = append(cmd.Env, "GO111MODULE=off")
401 cmd.Stdout = cmd.Stderr // send compiler output to stderr
402 if err := cmd.Run(); err != nil {
408 cmd, err = p.naclCmd(bin)
415 if opt != nil && opt.Race {
416 cmd.Env = append(cmd.Env, "GOMAXPROCS=2")
418 if err := cmd.Start(); err != nil {
419 // If we failed to exec, that might be because they built
420 // a non-main package instead of an executable.
421 // Check and report that.
422 if name, err := packageName(body); err == nil && name != "main" {
423 return errors.New(`executable programs must use "package main"`)
431 // cmd builds an *exec.Cmd that writes its standard output and error to the
432 // process' output channel.
433 func (p *process) cmd(dir string, args ...string) *exec.Cmd {
434 cmd := exec.Command(args[0], args[1:]...)
437 cmd.Stdout = &messageWriter{kind: "stdout", out: p.out}
438 cmd.Stderr = &messageWriter{kind: "stderr", out: p.out}
443 for _, v := range append(Environ(), os.Environ()...) {
444 if v == "GOOS=nacl" {
451 // naclCmd returns an *exec.Cmd that executes bin under native client.
452 func (p *process) naclCmd(bin string) (*exec.Cmd, error) {
453 pwd, err := os.Getwd()
459 "NACLENV_GOOS=" + runtime.GOOS,
460 "NACLENV_GOROOT=/go",
461 "NACLENV_NACLPWD=" + strings.Replace(pwd, runtime.GOROOT(), "/go", 1),
463 switch runtime.GOARCH {
465 env = append(env, "NACLENV_GOARCH=amd64p32")
466 args = []string{"sel_ldr_x86_64"}
468 env = append(env, "NACLENV_GOARCH=386")
469 args = []string{"sel_ldr_x86_32"}
471 env = append(env, "NACLENV_GOARCH=arm")
472 selLdr, err := exec.LookPath("sel_ldr_arm")
476 args = []string{"nacl_helper_bootstrap_arm", selLdr, "--reserved_at_zero=0xXXXXXXXXXXXXXXXX"}
478 return nil, errors.New("native client does not support GOARCH=" + runtime.GOARCH)
481 cmd := p.cmd("", append(args, "-l", "/dev/null", "-S", "-e", bin)...)
482 cmd.Env = append(cmd.Env, env...)
487 func packageName(body string) (string, error) {
488 f, err := parser.ParseFile(token.NewFileSet(), "prog.go",
489 strings.NewReader(body), parser.PackageClauseOnly)
493 return f.Name.String(), nil
496 // messageWriter is an io.Writer that converts all writes to Message sends on
497 // the out channel with the specified id and kind.
498 type messageWriter struct {
503 func (w *messageWriter) Write(b []byte) (n int, err error) {
504 w.out <- &Message{Kind: w.kind, Body: safeString(b)}
508 // safeString returns b as a valid UTF-8 string.
509 func safeString(b []byte) string {
515 r, size := utf8.DecodeRune(b)