summaryrefslogtreecommitdiff
path: root/shell.go
blob: d750136f57286958647264d9e698a1cc5ad7119a (plain)
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
package main

import (
	"fmt"
	"io"
	"os"
	"os/exec"

	"github.com/creack/pty"
	"github.com/gliderlabs/ssh"
)

func shell(s ssh.Session) {
	ptyReq, winCh, isPty := s.Pty()

	if !isPty {
		fmt.Fprintln(s, "Must be PTY")
		s.Exit(1)
		return
	}

	shell := os.Getenv("SHELL")
	if shell == "" {
		shell = "/bin/sh"
	}

	cmd := exec.Command(shell)
	cmd.Env = append(cmd.Env, fmt.Sprintf("TERM=%s", ptyReq.Term))

	ptmx, err := pty.Start(cmd)
	if err != nil {
		fmt.Fprintln(s, "Can not start shell")
		fmt.Println(err)
		s.Exit(1)
		return
	}
	defer func() { _ = ptmx.Close() }()

	go func() {
		for win := range winCh {
			pty.Setsize(ptmx, &pty.Winsize{
				Rows: uint16(win.Height),
				Cols: uint16(win.Width),
			})
		}
	}()

	go func() {
		io.Copy(s, ptmx)
		s.Close()
	}()

	go func() {
		io.Copy(ptmx, s)
		ptmx.Close()
	}()

	if err := cmd.Wait(); err != nil {
		s.Exit(1)
	} else {
		s.Exit(0)
	}
}