summaryrefslogtreecommitdiff
path: root/termshare/internal/daemon/daemon.go
blob: 465cdff668ab72285cc1100e4f3deb76c6188143 (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
package daemon

import (
	"fmt"
    "bufio"
	"io"
	"log"
	"os"
	"os/exec"
	"syscall"
    "strconv"
	"unsafe"

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

func setWinsize(f *os.File, w, h int) {
	syscall.Syscall(syscall.SYS_IOCTL, f.Fd(), uintptr(syscall.TIOCSWINSZ),
		uintptr(unsafe.Pointer(&struct{ h, w, x, y uint16 }{uint16(h), uint16(w), 0, 0})))
}

func RunDaemon(port string) {
	ssh.Handle(func(s ssh.Session) {
		cmd := exec.Command("bash")
		ptyReq, winCh, isPty := s.Pty()
		if isPty {
			cmd.Env = append(cmd.Env, fmt.Sprintf("TERM=%s", ptyReq.Term))
			f, err := pty.Start(cmd)
			if err != nil {
				panic(err)
			}
			go func() {
				for win := range winCh {
					setWinsize(f, win.Width, win.Height)
				}
			}()
			go func() {
				io.Copy(f, s) // stdin
			}()
			io.Copy(s, f) // stdout
			cmd.Wait()
		} else {
			io.WriteString(s, "No PTY requested.\n")
            reader := bufio.NewReader(s)
            for {
                input, _, _ := reader.ReadRune()
                io.WriteString(os.Stdout, strconv.QuoteRune(input))
            }
			s.Exit(1)
		}
	})

	log.Println("starting ssh server on port " + port + " ...")
  log.Fatal(ssh.ListenAndServe(":" + port, nil))
}