main.go 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193
  1. // Copyright 2015 The Gorilla WebSocket 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.
  4. package main
  5. import (
  6. "bufio"
  7. "flag"
  8. "io"
  9. "log"
  10. "net/http"
  11. "os"
  12. "os/exec"
  13. "time"
  14. "github.com/gorilla/websocket"
  15. )
  16. var (
  17. addr = flag.String("addr", "127.0.0.1:8080", "http service address")
  18. cmdPath string
  19. )
  20. const (
  21. // Time allowed to write a message to the peer.
  22. writeWait = 10 * time.Second
  23. // Maximum message size allowed from peer.
  24. maxMessageSize = 8192
  25. // Time allowed to read the next pong message from the peer.
  26. pongWait = 60 * time.Second
  27. // Send pings to peer with this period. Must be less than pongWait.
  28. pingPeriod = (pongWait * 9) / 10
  29. // Time to wait before force close on connection.
  30. closeGracePeriod = 10 * time.Second
  31. )
  32. func pumpStdin(ws *websocket.Conn, w io.Writer) {
  33. defer ws.Close()
  34. ws.SetReadLimit(maxMessageSize)
  35. ws.SetReadDeadline(time.Now().Add(pongWait))
  36. ws.SetPongHandler(func(string) error { ws.SetReadDeadline(time.Now().Add(pongWait)); return nil })
  37. for {
  38. _, message, err := ws.ReadMessage()
  39. if err != nil {
  40. break
  41. }
  42. message = append(message, '\n')
  43. if _, err := w.Write(message); err != nil {
  44. break
  45. }
  46. }
  47. }
  48. func pumpStdout(ws *websocket.Conn, r io.Reader, done chan struct{}) {
  49. defer func() {
  50. }()
  51. s := bufio.NewScanner(r)
  52. for s.Scan() {
  53. ws.SetWriteDeadline(time.Now().Add(writeWait))
  54. if err := ws.WriteMessage(websocket.TextMessage, s.Bytes()); err != nil {
  55. ws.Close()
  56. break
  57. }
  58. }
  59. if s.Err() != nil {
  60. log.Println("scan:", s.Err())
  61. }
  62. close(done)
  63. ws.SetWriteDeadline(time.Now().Add(writeWait))
  64. ws.WriteMessage(websocket.CloseMessage, websocket.FormatCloseMessage(websocket.CloseNormalClosure, ""))
  65. time.Sleep(closeGracePeriod)
  66. ws.Close()
  67. }
  68. func ping(ws *websocket.Conn, done chan struct{}) {
  69. ticker := time.NewTicker(pingPeriod)
  70. defer ticker.Stop()
  71. for {
  72. select {
  73. case <-ticker.C:
  74. if err := ws.WriteControl(websocket.PingMessage, []byte{}, time.Now().Add(writeWait)); err != nil {
  75. log.Println("ping:", err)
  76. }
  77. case <-done:
  78. return
  79. }
  80. }
  81. }
  82. func internalError(ws *websocket.Conn, msg string, err error) {
  83. log.Println(msg, err)
  84. ws.WriteMessage(websocket.TextMessage, []byte("Internal server error."))
  85. }
  86. var upgrader = websocket.Upgrader{}
  87. func serveWs(w http.ResponseWriter, r *http.Request) {
  88. ws, err := upgrader.Upgrade(w, r, nil)
  89. if err != nil {
  90. log.Println("upgrade:", err)
  91. return
  92. }
  93. defer ws.Close()
  94. outr, outw, err := os.Pipe()
  95. if err != nil {
  96. internalError(ws, "stdout:", err)
  97. return
  98. }
  99. defer outr.Close()
  100. defer outw.Close()
  101. inr, inw, err := os.Pipe()
  102. if err != nil {
  103. internalError(ws, "stdin:", err)
  104. return
  105. }
  106. defer inr.Close()
  107. defer inw.Close()
  108. proc, err := os.StartProcess(cmdPath, flag.Args(), &os.ProcAttr{
  109. Files: []*os.File{inr, outw, outw},
  110. })
  111. if err != nil {
  112. internalError(ws, "start:", err)
  113. return
  114. }
  115. inr.Close()
  116. outw.Close()
  117. stdoutDone := make(chan struct{})
  118. go pumpStdout(ws, outr, stdoutDone)
  119. go ping(ws, stdoutDone)
  120. pumpStdin(ws, inw)
  121. // Some commands will exit when stdin is closed.
  122. inw.Close()
  123. // Other commands need a bonk on the head.
  124. if err := proc.Signal(os.Interrupt); err != nil {
  125. log.Println("inter:", err)
  126. }
  127. select {
  128. case <-stdoutDone:
  129. case <-time.After(time.Second):
  130. // A bigger bonk on the head.
  131. if err := proc.Signal(os.Kill); err != nil {
  132. log.Println("term:", err)
  133. }
  134. <-stdoutDone
  135. }
  136. if _, err := proc.Wait(); err != nil {
  137. log.Println("wait:", err)
  138. }
  139. }
  140. func serveHome(w http.ResponseWriter, r *http.Request) {
  141. if r.URL.Path != "/" {
  142. http.Error(w, "Not found", 404)
  143. return
  144. }
  145. if r.Method != "GET" {
  146. http.Error(w, "Method not allowed", 405)
  147. return
  148. }
  149. http.ServeFile(w, r, "home.html")
  150. }
  151. func main() {
  152. flag.Parse()
  153. if len(flag.Args()) < 1 {
  154. log.Fatal("must specify at least one argument")
  155. }
  156. var err error
  157. cmdPath, err = exec.LookPath(flag.Args()[0])
  158. if err != nil {
  159. log.Fatal(err)
  160. }
  161. http.HandleFunc("/", serveHome)
  162. http.HandleFunc("/ws", serveWs)
  163. log.Fatal(http.ListenAndServe(*addr, nil))
  164. }