-
Notifications
You must be signed in to change notification settings - Fork 2
/
teleshell.go
241 lines (216 loc) · 5.9 KB
/
teleshell.go
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
package teleshell
import (
"bytes"
"fmt"
"log"
"os"
"os/exec"
"os/signal"
"regexp"
"strings"
"time"
"github.com/dmfed/teleshell/shell"
"gopkg.in/telebot.v3"
)
// 4096 is Telegram's max message size.
const maxTelegramMessageSize = 4096
var (
botCommandRegexp = regexp.MustCompile(`^/(\w+) *`)
)
var (
commStartSession = "shell"
commStopSession = "exit"
commSingleCommand = "cmd"
commHelp = "help"
)
var (
msgSessionStarted = "Shell started. You can talk to your machine now. Say 'exit' to stop the shell."
msgErrStartingSession = "Could not start shell."
msgSessionStopped = "Shell stopped. You are no longer talking to your machine."
// msgErrStoppingSession = "Could not stop shell."
msgSessionInProgress = "Your shell session is in progress. Say 'exit' to stop it."
msgSessionNotInProgress = "There are no active shell sessions."
msgNotAuthorized = "Sorry, you are not permitted to issue commands."
)
var msgHelp string = fmt.Sprintf(`Welcome to teleshell!
Use the following commands:
/%v <command> to run a single command on your machine
without launching shell.
/%v to start bash shell on your machine and redirect
input from this chat to the shell. Avoid launching
interactive programs. sudo is OK, but vim is NOT.
Also colored output of programs appears as
garbage in chat.
/%v to force-kill running shell
/%v to see this message again.`, commSingleCommand, commStartSession, commStopSession, commHelp)
type TeleShell struct {
TelegramUsername string
OnStart string
shell *shell.Shell
bot *telebot.Bot
}
// New returns instance of TeleShell with default settings.
// Call Start() method (blocking) to make the bot accept messages.
func New(token, username, onstartscript string) (*TeleShell, error) {
// init the bot.
// These are default settings from example code in
// telebot docs
settings := telebot.Settings{Token: token,
Poller: &telebot.LongPoller{Timeout: 10 * time.Second}}
bot, err := telebot.NewBot(settings)
if err != nil {
return nil, err
}
// init state
var ts TeleShell
ts.TelegramUsername = username
ts.OnStart = onstartscript
ts.bot = bot
// single handler since we only want to talk to authorized user
ts.bot.Handle(telebot.OnText, ts.authAndRoute)
return &ts, nil
}
// Start starts Teleshell and embedded bot. Calling Start is blocking.
func (ts *TeleShell) Start() {
interrupts := make(chan os.Signal, 1)
signal.Notify(interrupts, os.Interrupt)
go func() {
sig := <-interrupts
log.Printf("teleshell exiting on signal: %v", sig)
ts.Stop()
}()
ts.bot.Start()
}
// Stop stops TeleShell and embedded bot.
func (ts *TeleShell) Stop() {
if ts.shell != nil {
ts.shell.Stop()
}
ts.bot.Stop()
}
func (ts *TeleShell) authAndRoute(c telebot.Context) error {
m := c.Message()
if !ts.isAuthorized(m.Sender) {
ts.sorry(m)
return nil
}
command := ""
if botCommandRegexp.MatchString(m.Text) {
command = botCommandRegexp.FindStringSubmatch(m.Text)[1]
}
switch {
case command == commSingleCommand:
ts.execSingleCommand(m)
case command == commStartSession:
ts.startSession(m)
case command == commStopSession:
ts.stopSession(m)
case command == commHelp:
ts.help(m)
case ts.shell != nil:
ts.handleSessionMsg(m)
default:
ts.help(m)
}
return nil
}
func (ts *TeleShell) isAuthorized(u *telebot.User) bool {
return u.Username == ts.TelegramUsername && !u.IsBot
}
func (ts *TeleShell) execSingleCommand(m *telebot.Message) {
command := stripBotCommand(m.Text)
output, err := execCmd(command)
ts.send(m.Chat, output)
if err != nil {
ts.send(m.Chat, err.Error())
}
}
func (ts *TeleShell) startSession(m *telebot.Message) {
if ts.shell != nil {
ts.send(m.Chat, msgSessionInProgress)
return
}
shell, err := shell.New(ts.OnStart)
if err != nil {
ts.send(m.Chat, msgErrStartingSession)
return
}
ts.shell = shell
ts.send(m.Chat, msgSessionStarted)
go func() {
for ts.shell != nil {
select {
case <-shell.Stopped():
ts.shell = nil
case output := <-shell.Output():
ts.send(m.Chat, output)
}
}
ts.send(m.Chat, msgSessionStopped)
// log.Println("teleshell: shell listening goroutine finishing")
}()
}
func (ts *TeleShell) stopSession(m *telebot.Message) {
if ts.shell == nil {
ts.send(m.Chat, msgSessionNotInProgress)
return
}
ts.shell.Stop() // this will trigger release from select is startSession
}
func (ts *TeleShell) handleSessionMsg(m *telebot.Message) {
if err := ts.shell.Execute(m.Text); err != nil {
ts.send(m.Chat, err.Error())
}
}
func (ts *TeleShell) send(c *telebot.Chat, msg string) {
if len(msg) > maxTelegramMessageSize {
ts.paginatedSend(c, msg)
} else {
ts.bot.Send(c, msg)
}
}
func (ts *TeleShell) paginatedSend(c *telebot.Chat, msg string) {
messages := paginate(msg)
for _, message := range messages {
ts.bot.Send(c, message)
}
}
func (ts *TeleShell) help(m *telebot.Message) {
ts.send(m.Chat, msgHelp)
}
func (ts *TeleShell) sorry(m *telebot.Message) {
ts.send(m.Chat, msgNotAuthorized)
}
func (ts *TeleShell) inProgress(m *telebot.Message) {
ts.send(m.Chat, msgSessionInProgress)
}
func stripBotCommand(message string) string {
loc := botCommandRegexp.FindStringIndex(message)
return message[loc[1]:]
}
func execCmd(c string) (string, error) {
commSlice := strings.Split(c, " ")
var cmd *exec.Cmd
if len(commSlice) > 1 {
cmd = exec.Command(commSlice[0], commSlice[1:]...)
} else {
cmd = exec.Command(commSlice[0])
}
stdout, err := cmd.CombinedOutput()
return string(stdout), err
}
func paginate(input string) []string {
pages := []string{}
buf := bytes.Buffer{}
// make sure we do not split a single line of text
for _, s := range strings.Split(input, "\n") {
// assuming single line of input (s) can not exceed maxTelegramMessageSize bytes
if buf.Len()+len(s) > maxTelegramMessageSize {
pages = append(pages, buf.String())
buf.Reset()
}
buf.WriteString(s + "\n")
}
pages = append(pages, buf.String())
return pages
}