console.go 3.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. package docker
  2. /*
  3. console.go
  4. Interactive container shell (`docker exec -it <container> <shell>`) bridged
  5. to xterm.js over a websocket. The PTY allocation is platform-specific and
  6. lives in build-tagged files:
  7. console_unix.go (linux || darwin || freebsd) — real PTY via github.com/creack/pty
  8. console_other.go (all other GOOS, incl. windows) — returns "not supported"
  9. Wire protocol:
  10. server -> client : binary frames = raw terminal output bytes
  11. client -> server : binary frames = raw keystroke bytes
  12. text frames = JSON control, e.g. {"type":"resize","rows":40,"cols":120}
  13. This is the highest-risk surface in the whole feature: a live root-equivalent
  14. shell into a running container. It is admin-only (enforced by the prout router
  15. in src/docker.go) and, when the websocket closes, the spawned `docker exec`
  16. process is killed so no orphaned shell session is left running.
  17. */
  18. import (
  19. "encoding/json"
  20. "io"
  21. "net/http"
  22. "regexp"
  23. "github.com/gorilla/websocket"
  24. "imuslab.com/arozos/mod/utils"
  25. )
  26. // shellRegex restricts the shell argument to a safe path/name charset.
  27. var shellRegex = regexp.MustCompile(`^[a-zA-Z0-9/._-]+$`)
  28. // ptySession abstracts a PTY-attached `docker exec` process. The concrete
  29. // implementation is provided per-platform by startDockerExecPTY.
  30. type ptySession interface {
  31. io.ReadWriteCloser
  32. Resize(rows, cols uint16) error
  33. Wait() error
  34. Kill()
  35. }
  36. // consoleControlMsg is the JSON shape of a client text control frame.
  37. type consoleControlMsg struct {
  38. Type string `json:"type"`
  39. Rows uint16 `json:"rows"`
  40. Cols uint16 `json:"cols"`
  41. }
  42. // HandleExecConsole upgrades to a websocket and bridges it to an interactive
  43. // shell inside the container given by ?id=, using ?shell= (default "sh").
  44. func (d *DockerManager) HandleExecConsole(w http.ResponseWriter, r *http.Request) {
  45. ref, err := utils.GetPara(r, "id")
  46. if err != nil {
  47. http.Error(w, "missing container id", http.StatusBadRequest)
  48. return
  49. }
  50. if err := validateContainerRef(ref); err != nil {
  51. http.Error(w, err.Error(), http.StatusBadRequest)
  52. return
  53. }
  54. shell, _ := utils.GetPara(r, "shell")
  55. if shell == "" {
  56. shell = "sh"
  57. }
  58. if !shellRegex.MatchString(shell) {
  59. http.Error(w, "invalid shell", http.StatusBadRequest)
  60. return
  61. }
  62. conn, err := dockerWsUpgrader.Upgrade(w, r, nil)
  63. if err != nil {
  64. return
  65. }
  66. defer conn.Close()
  67. session, err := startDockerExecPTY(ref, shell)
  68. if err != nil {
  69. conn.WriteMessage(websocket.TextMessage, []byte("Failed to start console: "+err.Error()))
  70. return
  71. }
  72. //Ensure the docker exec process is always killed when this handler returns.
  73. defer session.Kill()
  74. //Output pump: PTY -> websocket (binary frames). When the shell exits the
  75. //read returns an error and we close the socket to signal end-of-session.
  76. go func() {
  77. buf := make([]byte, 4096)
  78. for {
  79. n, rerr := session.Read(buf)
  80. if n > 0 {
  81. if werr := conn.WriteMessage(websocket.BinaryMessage, buf[:n]); werr != nil {
  82. return
  83. }
  84. }
  85. if rerr != nil {
  86. conn.Close()
  87. return
  88. }
  89. }
  90. }()
  91. //Input pump: websocket -> PTY. Binary frames are keystrokes; text frames are
  92. //JSON control messages (currently only "resize").
  93. for {
  94. mt, data, rerr := conn.ReadMessage()
  95. if rerr != nil {
  96. return
  97. }
  98. if mt == websocket.TextMessage {
  99. var ctrl consoleControlMsg
  100. if json.Unmarshal(data, &ctrl) == nil && ctrl.Type == "resize" {
  101. session.Resize(ctrl.Rows, ctrl.Cols)
  102. }
  103. continue
  104. }
  105. session.Write(data)
  106. }
  107. }