/
webhandlers.go
372 lines (346 loc) · 9.73 KB
/
webhandlers.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
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
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
// Copyright © 2013, 2014 Hraban Luyat <hraban@0brg.net>
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to
// deal in the Software without restriction, including without limitation the
// rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
// sell copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
// IN THE SOFTWARE.
package main
import (
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/url"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/hraban/lush/liblush"
"github.com/hraban/web"
)
var masterAddr string
var addrRegexp = regexp.MustCompile(":\\d+$")
// "1.2.3.4:60102" -> "1.2.3.4"
// "[::1]:123" -> "[::1]"
// anything else -> undefined
func fullAddrToBare(addrPlusIp string) (onlyAddr string) {
return addrRegexp.ReplaceAllString(addrPlusIp, "")
}
func remoteAddr(ctx *web.Context) string {
return fullAddrToBare(ctx.Request.RemoteAddr)
}
// claim that I am master. returns false if someone else already did
func claimMaster(ctx *web.Context) bool {
if ctx.User.(*server).everybodyMaster {
return true
}
remote := remoteAddr(ctx)
if remote != masterAddr {
if masterAddr == "" {
masterAddr = remote
} else {
return false
}
}
return true
}
// would prefer this as a wrapper but yeah MACROS PLZ
func errorIfNotMaster(ctx *web.Context) error {
if !claimMaster(ctx) {
return web.WebError{403, "go away you not master"}
}
return nil
}
func redirect(ctx *web.Context, loc *url.URL) {
if _, ok := ctx.Params["noredirect"]; ok {
return
}
loc = ctx.Request.URL.ResolveReference(loc)
ctx.Header().Set("Location", loc.String())
ctx.WriteHeader(303)
fmt.Fprintf(ctx, "redirecting to %s", loc)
}
func cmdloc(c liblush.Cmd) *url.URL {
return &url.URL{Path: fmt.Sprintf("/%d/", c.Id())}
}
func getCmdWeb(s liblush.Session, idstr string) (liblush.Cmd, error) {
id, _ := liblush.ParseCmdId(idstr)
c := s.GetCommand(id)
if c == nil {
return nil, web.WebError{404, "no such command: " + idstr}
}
return c, nil
}
func handleGetRoot(ctx *web.Context) error {
s := ctx.User.(*server)
ch := make(chan metacmd)
go func() {
for _, id := range s.session.GetCommandIds() {
ch <- metacmd{s.session.GetCommand(id)}
}
close(ch)
}()
err := s.tmplts.ExecuteTemplate(ctx, "/", ch)
return err
}
func handleGetCmd(ctx *web.Context, idstr string) error {
type cmdctx struct {
Cmd liblush.Cmd
Stdout string
Stderr string
Connectables chan liblush.Cmd
}
id, _ := liblush.ParseCmdId(idstr)
s := ctx.User.(*server)
c := s.session.GetCommand(id)
if c == nil {
return web.WebError{404, "no such command: " + idstr}
}
stdout := make([]byte, 1000)
stderr := make([]byte, 1000)
n := c.Stdout().Scrollback().Last(stdout)
stdout = stdout[:n]
n = c.Stderr().Scrollback().Last(stderr)
stderr = stderr[:n]
ch := make(chan liblush.Cmd)
go func() {
for _, id := range s.session.GetCommandIds() {
other := s.session.GetCommand(id)
if c.Id() != other.Id() && other.Status().Started() == nil {
ch <- other
}
}
close(ch)
}()
tmplCtx := cmdctx{
Cmd: c,
Stdout: string(stdout),
Stderr: string(stderr),
Connectables: ch,
}
err := s.tmplts.ExecuteTemplate(ctx, "cmd", tmplCtx)
return err
}
func handleGetCmdInfo(ctx *web.Context, idstr string) error {
id, _ := liblush.ParseCmdId(idstr)
s := ctx.User.(*server)
c := s.session.GetCommand(id)
if c == nil {
return web.WebError{404, "no such command: " + idstr}
}
ctx.Header().Set("content-type", "application/json")
enc := json.NewEncoder(ctx)
var info = struct {
Started, Exited *time.Time
Error string `json:",omitempty"`
}{
Started: c.Status().Started(),
Exited: c.Status().Exited(),
}
if cerr := c.Status().Err(); cerr != nil {
info.Error = cerr.Error()
}
return enc.Encode(info)
}
func handlePostSend(ctx *web.Context, idstr string) error {
if err := errorIfNotMaster(ctx); err != nil {
return err
}
id, _ := liblush.ParseCmdId(idstr)
s := ctx.User.(*server)
c := s.session.GetCommand(id)
if c == nil {
return web.WebError{404, "no such command: " + idstr}
}
if ctx.Params["stream"] != "stdin" {
return web.WebError{400, "must send to stdin"}
}
_, err := c.Stdin().Write([]byte(ctx.Params["data"]))
if err != nil {
return err
}
redirect(ctx, cmdloc(c))
return nil
}
func handlePostClose(ctx *web.Context, idstr string) error {
if err := errorIfNotMaster(ctx); err != nil {
return err
}
id, _ := liblush.ParseCmdId(idstr)
s := ctx.User.(*server)
c := s.session.GetCommand(id)
if c == nil {
return web.WebError{404, "no such command: " + idstr}
}
if ctx.Params["stream"] != "stdin" {
return web.WebError{400, "must send to stdin"}
}
err := c.Stdin().Close()
if err != nil {
return err
}
redirect(ctx, cmdloc(c))
return nil
}
func handleGetNewNames(ctx *web.Context) error {
if err := errorIfNotMaster(ctx); err != nil {
return err
}
var bins []string
term := ctx.Params["term"]
for _, d := range strings.Split(os.Getenv("PATH"), string(os.PathListSeparator)) {
fis, err := ioutil.ReadDir(d)
if err != nil {
// ignore unreadable dirs
continue
}
for _, fi := range fis {
name := fi.Name()
if strings.HasPrefix(name, term) {
bins = append(bins, fi.Name())
}
}
}
enc := json.NewEncoder(ctx)
err := enc.Encode(bins)
return err
}
func handleWsStream(ctx *web.Context, idstr, streamname string) error {
id, _ := liblush.ParseCmdId(idstr)
s := ctx.User.(*server)
c := s.session.GetCommand(id)
if c == nil {
return web.WebError{404, "no such command: " + idstr}
}
var stream liblush.OutStream
switch streamname {
case "stdout":
stream = c.Stdout()
case "stderr":
stream = c.Stderr()
default:
return web.WebError{400, "No such stream: " + streamname}
}
stream.Peeker().AddWriter(ctx.WebsockConn)
buf := make([]byte, 1)
ctx.WebsockConn.Read(buf)
return nil
}
func handlePostChdir(ctx *web.Context) error {
s := ctx.User.(*server)
return s.session.Chdir(ctx.Params["dir"])
}
// List of files nice for tab completion
func handleGetFiles(ctx *web.Context) error {
if err := errorIfNotMaster(ctx); err != nil {
return err
}
ctx.ContentType("json")
paths, err := filepath.Glob(ctx.Params["pattern"])
if err != nil {
return err
}
if paths == nil {
paths = []string{}
}
return json.NewEncoder(ctx).Encode(paths)
}
// websocket control connection (all are considered equal)
func handleWsCtrl(ctx *web.Context) error {
s := ctx.User.(*server)
ws := newWsClient(ctx.WebsockConn)
// tell the client about its Id
_, err := fmt.Fprint(ws, "clientid;", ws.Id)
if err != nil {
return fmt.Errorf("Websocket write error: %v", err)
}
// Subscribe this ws client to all future control events. Will be removed
// automatically when the first Write fails (FlexibleMultiWriter).
// Therefore, no need to worry about removing: client disconnects -> next
// Write fails -> removed.
s.ctrlclients.AddWriter(ws)
// notify all other clients that a new client has connected
wseventAllclients(s, "") // pretend somebody generated this event
// TODO: keep clients updated about disconnects, too
ws.isMaster = claimMaster(ctx)
for {
buf := make([]byte, 5000)
n, err := ws.Read(buf)
if err != nil {
return fmt.Errorf("Websocket read error: %v", err)
}
if n == cap(buf) {
// TODO: Obviously ridiculous, flexible size plz!
return fmt.Errorf("Websocket event too big (max: %d bytes)", n)
}
if n == 0 {
// TODO: tbh Im not sure why I wrote this if... why do I want to
// ignore empty messages? shouldn't that be an error? yay for not
// commenting weird code -.-
return nil
}
msg := buf[:n]
err = parseAndHandleWsEvent(s, ws, msg)
if err != nil {
return fmt.Errorf("error handling WS event: %v", err)
}
}
return errors.New("unreachable")
}
func handleGetEnviron(ctx *web.Context) (map[string]string, error) {
if err := errorIfNotMaster(ctx); err != nil {
return nil, err
}
ctx.ContentType("json")
s := ctx.User.(*server)
return s.session.Environ(), nil
}
func handlePostSetenv(ctx *web.Context) error {
if err := errorIfNotMaster(ctx); err != nil {
return err
}
s := ctx.User.(*server)
s.session.Setenv(ctx.Params["key"], ctx.Params["value"])
return nil
}
func handlePostUnsetenv(ctx *web.Context) error {
if err := errorIfNotMaster(ctx); err != nil {
return err
}
s := ctx.User.(*server)
s.session.Unsetenv(ctx.Params["key"])
return nil
}
func init() {
serverinitializers = append(serverinitializers, func(s *server) {
s.userdata = map[string]string{}
// public handlers
s.web.Get(`/`, handleGetRoot)
s.web.Get(`/(\d+)/`, handleGetCmd)
s.web.Get(`/(\d+)/info.json`, handleGetCmdInfo)
s.web.Websocket(`/ctrl`, handleWsCtrl)
s.web.Websocket(`/(\d+)/stream/(\w+).bin`, handleWsStream)
// only master
s.web.Post(`/(\d+)/send`, handlePostSend)
s.web.Post(`/(\d+)/close`, handlePostClose)
s.web.Get(`/new/names.json`, handleGetNewNames)
s.web.Get(`/files.json`, handleGetFiles)
s.web.Get(`/environ.json`, handleGetEnviron)
s.web.Post(`/setenv`, handlePostSetenv)
s.web.Post(`/unsetenv`, handlePostUnsetenv)
})
}