/
cast.go
421 lines (357 loc) · 8.29 KB
/
cast.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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
package jumpi
// implements a asciicast to be later used with asciinema-player
// (https://github.com/asciinema/asciinema-player)
import (
"bufio"
"crypto/cipher"
"crypto/rand"
"encoding/json"
"errors"
"io"
"io/ioutil"
"log"
"os"
"strings"
"time"
"github.com/codahale/chacha20"
"github.com/drtoful/jumpi/utils"
)
var (
ErrNoSession = errors.New("unable to start cast recording: no session set")
channelJobs chan string
)
type castEntry struct {
Data string
Delay float64
}
type secFile struct {
secret []byte
nonce []byte
rounds uint8
fd *os.File
stream cipher.Stream
}
type secFileJob struct {
Secret string `json:"secret"`
Nonce string `json:"nonce"`
Rounds int `json:"rounds"`
File string `json:"filename"`
}
type Cast struct {
Session string `json:"session"`
Duration float64 `json:"duration"`
Records [][]interface{} `json:"stdout,omitempty"`
Width int `json:"width"`
Height int `json:"height"`
Version int `json:"version"`
User string `json:"user,omitempty"`
Target string `json:"target,omitempty"`
StartTime string `json:"start,omitempty"`
recorder chan *castEntry
file *secFile
}
func (f *secFile) Write(data []byte) (int, error) {
f.stream.XORKeyStream(data, data)
return f.fd.Write(data)
}
func (f *secFile) Read(buf []byte) (int, error) {
n, err := f.fd.Read(buf)
if err != nil {
return n, err
}
f.stream.XORKeyStream(buf[0:n], buf[0:n])
return n, err
}
func (f *secFile) Reset() error {
stream, err := chacha20.NewWithRounds(f.secret, f.nonce, f.rounds)
if err != nil {
return err
}
f.stream = stream
if _, err := f.fd.Seek(0, 0); err != nil {
return err
}
return nil
}
func (f *secFile) Close() {
f.fd.Close()
rand.Read(f.secret)
rand.Read(f.nonce)
}
func (f *secFile) Remove() {
os.Remove(f.fd.Name())
}
func newSecFile(store *Store, session string) (*secFile, error) {
tmpfile, err := ioutil.TempFile("", "jumpi")
if err != nil {
return nil, err
}
file := &secFile{fd: tmpfile, rounds: 20}
key := make([]byte, 32)
if _, err := rand.Read(key); err != nil {
return nil, err
}
nonce := make([]byte, 8)
if _, err := rand.Read(nonce); err != nil {
return nil, err
}
file.secret = key
file.nonce = nonce
if err := file.Reset(); err != nil {
return nil, err
}
// store job into storage
job := &secFileJob{
Secret: utils.Hexlify(file.secret),
Nonce: utils.Hexlify(file.nonce),
Rounds: int(file.rounds),
File: tmpfile.Name(),
}
jdata, err := json.Marshal(job)
if err != nil {
return nil, err
}
defer func() {
rand.Read(jdata)
}()
err = store.Set(BucketCasts, "job~"+session, jdata)
return file, err
}
func loadJob(id string, store *Store) (*secFile, error) {
jdata, err := store.Get(BucketCasts, id)
if err != nil {
return nil, err
}
defer func() {
rand.Read(jdata)
}()
var job secFileJob
if err := json.Unmarshal(jdata, &job); err != nil {
return nil, err
}
secret, err := utils.UnHexlify(job.Secret)
if err != nil {
return nil, err
}
nonce, err := utils.UnHexlify(job.Nonce)
if err != nil {
return nil, err
}
file, err := os.Open(job.File)
if err != nil {
return nil, err
}
sfile := &secFile{
fd: file,
secret: secret,
nonce: nonce,
rounds: uint8(job.Rounds),
}
return sfile, sfile.Reset()
}
// similar to io.copyBuffer method, but instead of directly writing to
// the destination, we will keep a copy and safe it to be replayed
// later
func (cast *Cast) Copy(dest io.Writer, src io.Reader) (int64, error) {
var written int64
var err error
buf := make([]byte, 32<<10) // 32KB
for {
nr, err := src.Read(buf)
if nr > 0 {
//save to cast
entry := &castEntry{
Data: utils.Hexlify(buf[0:nr]),
}
go func() {
cast.recorder <- entry
}()
nw, ew := dest.Write(buf[0:nr]) // only write what was read
if nw > 0 {
written += int64(nw)
}
if ew != nil {
err = ew
break
}
if nr != nw {
err = io.ErrShortWrite
break
}
}
if err == io.EOF {
err = nil // EOF is no real error
break
}
if err != nil {
break
}
}
return written, err
}
func (cast *Cast) Start(store *Store) error {
if len(cast.Session) == 0 {
return ErrNoSession
}
// set defaults
cast.Version = 1
cast.Width = 80
cast.Height = 24
cast.StartTime = time.Now().UTC().Format(time.RFC3339)
fd, err := newSecFile(store, cast.Session)
if err != nil {
return err
}
// store meta into database
jdata, err := json.Marshal(cast)
if err != nil {
return err
}
defer func() {
rand.Read(jdata)
}()
if err := store.Set(BucketCasts, "jobmeta~"+cast.Session, jdata); err != nil {
return err
}
cast.file = fd
cast.recorder = make(chan *castEntry)
log.Printf("ssh[%s]: storing recording into %s\n", cast.Session, cast.file.fd.Name())
go func() {
for {
start := time.Now().UTC()
e := <-cast.recorder
end := time.Now().UTC()
if e == nil {
break
}
e.Delay = float64(end.Sub(start)) / float64(time.Second)
jdata, err := json.Marshal(e)
if err == nil {
cast.file.Write(jdata)
cast.file.Write([]byte{'\n'})
}
cast.Duration += e.Delay
}
}()
return nil
}
func (cast *Cast) Stop() {
if cast.recorder == nil {
return
}
cast.recorder <- nil
go func() {
// start indexing job
channelJobs <- "job~" + cast.Session
}()
}
func (cast *Cast) Store(store *Store) error {
// move to top of file and reset chacha20 stream
cast.file.Reset()
cast.Records = make([][]interface{}, 0)
cast.Duration = 0
defer cast.file.Close()
// read json objects line by line and add them to the
// object and then store it in the database
reader := bufio.NewReader(cast.file)
for {
line, err := reader.ReadBytes('\n')
if err == io.EOF {
break
}
if err != nil {
return err
}
var entry castEntry
if err := json.Unmarshal(line, &entry); err != nil {
return err
}
data, err := utils.UnHexlify(entry.Data)
if err != nil {
return err
}
cast.Records = append(cast.Records, []interface{}{entry.Delay, string(data)})
cast.Duration += entry.Delay
}
// store into database
jdata, err := json.Marshal(cast)
if err != nil {
return err
}
defer func() {
rand.Read(jdata)
}()
store.Set(BucketCasts, "start~"+cast.StartTime+"~"+cast.Session, []byte(cast.Session))
store.Set(BucketCasts, "start~~", []byte(cast.StartTime))
return store.Set(BucketCasts, "cast~"+cast.Session, jdata)
}
func StartIndexerServer(store *Store) error {
channelJobs = make(chan string)
go func() {
// we wait for the store to unlock
for {
if !store.IsLocked() {
break
}
time.Sleep(time.Second)
}
log.Printf("indexer: starting indexing worker\n")
for {
jobid := <-channelJobs
splits := strings.SplitN(jobid, "~", 2)
if len(splits) < 2 {
continue
}
file, err := loadJob(jobid, store)
if err != nil {
log.Printf("indexer[%s]: unable to process session (1): %s\n", splits[1], err.Error())
continue
}
defer func() {
rand.Read(file.secret)
}()
jdata, err := store.Get(BucketCasts, "jobmeta~"+splits[1])
if err != nil {
log.Printf("indexer[%s]: unable to process session (2): %s\n", splits[1], err.Error())
continue
}
defer func() {
rand.Read(jdata)
}()
var cast Cast
if err := json.Unmarshal(jdata, &cast); err != nil {
log.Printf("indexer[%s]: unable to process session (3): %s\n", splits[1], err.Error())
continue
}
cast.file = file
cast.Session = splits[1]
log.Printf("indexer[%s]: starting indexing\n", splits[1])
if err := cast.Store(store); err != nil {
log.Printf("indexer[%s]: unable to process session (4): %s\n", splits[1], err.Error())
file.Close()
continue
}
file.Close()
file.Remove()
if err := store.Delete(BucketCasts, jobid); err != nil {
log.Printf("indexer[%s]: unable to remove session from jobqueue: %s\n", splits[1], err.Error())
continue
}
log.Printf("indexer[%s]: indexing concluded\n", splits[1])
store.Delete(BucketCasts, "jobmeta~"+splits[1])
store.Delete(BucketCasts, "job~"+splits[1])
}
}()
//load existing jobs
go func() {
kvs, err := store.Scan(BucketCasts, "job~", 0, 0, false, false)
if err != nil {
return
}
log.Printf("indexer: processing unindexed recordings\n")
for _, kv := range kvs {
channelJobs <- kv.Key
}
}()
return nil
}