aboutsummaryrefslogtreecommitdiffstats
path: root/golib/eows/eows.go
blob: 9d0b52086325061d2d9bc23cd54de87d07767aa4 (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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
// Package eows is used to Execute commands Over WebSocket
package eows

import (
	"fmt"
	"os"
	"os/exec"
	"strings"
	"syscall"
	"time"
	"unsafe"

	"github.com/Sirupsen/logrus"
	"github.com/googollee/go-socket.io"
	"github.com/kr/pty"
)

// OnInputCB is the function callback used to receive data
type OnInputCB func(e *ExecOverWS, stdin []byte) ([]byte, error)

// EmitOutputCB is the function callback used to emit data
type EmitOutputCB func(e *ExecOverWS, stdout, stderr []byte)

// EmitExitCB is the function callback used to emit exit proc code
type EmitExitCB func(e *ExecOverWS, code int, err error)

// SplitType Type of spliting method to tokenize stdout/stderr
type SplitType uint8

const (
	// SplitLine Split line by line
	SplitLine SplitType = iota
	// SplitChar Split character by character
	SplitChar
	// SplitLineTime Split by line or until a timeout has passed
	SplitLineTime
	// SplitTime Split until a timeout has passed
	SplitTime
)

// Inspired by :
// https://github.com/gorilla/websocket/blob/master/examples/command/main.go

// ExecOverWS .
type ExecOverWS struct {
	Cmd      string           // command name to execute
	Args     []string         // command arguments
	SocketIO *socketio.Socket // websocket
	Sid      string           // websocket ID
	CmdID    string           // command ID

	// Optional fields
	Env            []string                // command environment variables
	CmdExecTimeout int                     // command execution time timeout
	Log            *logrus.Logger          // logger (nil if disabled)
	InputEvent     string                  // websocket input event name
	InputCB        OnInputCB               // stdin callback
	OutputCB       EmitOutputCB            // stdout/stderr callback
	ExitCB         EmitExitCB              // exit proc callback
	UserData       *map[string]interface{} // user data passed to callbacks
	OutSplit       SplitType               // split method to tokenize stdout/stderr
	LineTimeSpan   int64                   // time span (only used with SplitTime or SplitLineTime)
	PtyMode        bool                    // Allocate a pseudo-terminal (allow to execute screen-based program)
	PtyTermEcho    bool                    // Turn on/off terminal echo

	// Private fields

	proc       *os.Process
	command    *exec.Cmd
	ptmx       *os.File
	procExited bool
}

var cmdIDMap = make(map[string]*ExecOverWS)

// New creates a new instace of eows
func New(cmd string, args []string, so *socketio.Socket, soID, cmdID string) *ExecOverWS {

	e := &ExecOverWS{
		Cmd:            cmd,
		Args:           args,
		SocketIO:       so,
		Sid:            soID,
		CmdID:          cmdID,
		CmdExecTimeout: -1,            // default no timeout
		OutSplit:       SplitLineTime, // default split by line with time
		LineTimeSpan:   500 * time.Millisecond.Nanoseconds(),
		PtyMode:        false,
		PtyTermEcho:    true,
	}

	cmdIDMap[cmdID] = e

	return e
}

// GetEows gets ExecOverWS object from command ID
func GetEows(cmdID string) *ExecOverWS {
	if _, ok := cmdIDMap[cmdID]; !ok {
		return nil
	}
	return cmdIDMap[cmdID]
}

// Start executes the command and redirect stdout/stderr into a WebSocket
func (e *ExecOverWS) Start() error {
	var err error
	var outr, outw, errr, errw, inr, inw *os.File

	bashArgs := []string{"/bin/bash", "-c", e.Cmd + " " + strings.Join(e.Args, " ")}

	// no timeout == 1 year
	if e.CmdExecTimeout == -1 {
		e.CmdExecTimeout = 365 * 24 * 60 * 60
	}

	e.procExited = false

	if e.PtyMode {

		e.command = exec.Command(bashArgs[0], bashArgs[1:]...)
		e.command.Env = append(os.Environ(), e.Env...)
		e.ptmx, err = pty.Start(e.command)
		if err != nil {
			err = fmt.Errorf("Process start error: " + err.Error())
			goto exitErr
		}
		e.proc = e.command.Process

		// Turn off terminal echo
		if !e.PtyTermEcho {
			e.terminalEcho(e.ptmx, false)
		}

	} else {

		// Create pipes
		outr, outw, err = os.Pipe()
		if err != nil {
			err = fmt.Errorf("Pipe stdout error: " + err.Error())
			goto exitErr
		}

		errr, errw, err = os.Pipe()
		if err != nil {
			err = fmt.Errorf("Pipe stderr error: " + err.Error())
			goto exitErr
		}

		inr, inw, err = os.Pipe()
		if err != nil {
			err = fmt.Errorf("Pipe stdin error: " + err.Error())
			goto exitErr
		}

		e.proc, err = os.StartProcess(bashArgs[0], bashArgs, &os.ProcAttr{
			Files: []*os.File{inr, outw, errw},
			Env:   append(os.Environ(), e.Env...),
		})
		if err != nil {
			err = fmt.Errorf("Process start error: " + err.Error())
			goto exitErr
		}
	}

	go func() {
		stdoutDone := make(chan struct{})

		if e.PtyMode {
			// Make sure to close the pty at the end.
			defer e.ptmx.Close()

			// Handle both stdout mixed with stderr
			go e.ptsPumpStdout(e.ptmx, stdoutDone)

			// Blocking function that poll input or wait for end of process
			e.pumpStdin(e.ptmx)

		} else {
			// Make sure to close all pipes
			defer outr.Close()
			defer outw.Close()
			defer errr.Close()
			defer errw.Close()
			defer inr.Close()
			defer inw.Close()

			// Handle stdout + stderr
			go e.pipePumpStdout(outr, stdoutDone)
			go e.pipePumpStderr(errr)

			// Blocking function that poll input or wait for end of process
			e.pumpStdin(inw)
		}

		if status, err := e.proc.Wait(); err == nil {
			// Other commands need a bonk on the head.
			if !status.Exited() {
				if err := e.proc.Signal(os.Interrupt); err != nil {
					e.logError("Proc interrupt:", err)
				}

				select {
				case <-stdoutDone:
				case <-time.After(time.Second):
					// A bigger bonk on the head.
					if err := e.proc.Signal(os.Kill); err != nil {
						e.logError("Proc term:", err)
					}
					<-stdoutDone
				}
			}
		}

		delete(cmdIDMap, e.CmdID)
	}()

	return nil

exitErr:
	for _, pf := range []*os.File{outr, outw, errr, errw, inr, inw} {
		pf.Close()
	}
	return err
}

// TerminalSetSize Set terminal size
func (e *ExecOverWS) TerminalSetSize(rows, cols uint16) error {
	if !e.PtyMode || e.ptmx == nil {
		return fmt.Errorf("PtyMode not set")
	}
	w, err := pty.GetsizeFull(e.ptmx)
	if err != nil {
		return err
	}
	return e.TerminalSetSizePos(rows, cols, w.X, w.Y)
}

// TerminalSetSizePos Set terminal size and position
func (e *ExecOverWS) TerminalSetSizePos(rows, cols, x, y uint16) error {
	if !e.PtyMode || e.ptmx == nil {
		return fmt.Errorf("PtyMode not set")
	}
	winSz := pty.Winsize{Rows: rows, Cols: cols, X: x, Y: y}
	return pty.Setsize(e.ptmx, &winSz)
}

/**
 * Private functions
 **/

// terminalEcho Enable or disable echoing terminal input.
// This is useful specifically for when users enter passwords.
func (e *ExecOverWS) terminalEcho(ff *os.File, show bool) {
	var termios = &syscall.Termios{}

	fd := ff.Fd()

	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd,
		syscall.TCGETS, uintptr(unsafe.Pointer(termios))); err != 0 {
		return
	}

	if show {
		termios.Lflag |= syscall.ECHO
	} else {
		termios.Lflag &^= syscall.ECHO
	}

	if _, _, err := syscall.Syscall(syscall.SYS_IOCTL, fd,
		uintptr(syscall.TCSETS),
		uintptr(unsafe.Pointer(termios))); err != 0 {
		return
	}
}

func (e *ExecOverWS) logDebug(format string, a ...interface{}) {
	if e.Log != nil {
		e.Log.Debugf(format, a...)
	}
}

func (e *ExecOverWS) logError(format string, a ...interface{}) {
	if e.Log != nil {
		e.Log.Errorf(format, a...)
	}
}