-
-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathfile_unix.go
More file actions
504 lines (394 loc) · 10.5 KB
/
file_unix.go
File metadata and controls
504 lines (394 loc) · 10.5 KB
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
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
//go:build !windows
// +build !windows
/* SPDX-License-Identifier: MIT */
/*
* Author: Jianhui Zhao <zhaojh329@gmail.com>
*/
package main
import (
"encoding/binary"
"fmt"
"io"
"os"
"os/signal"
"path/filepath"
"syscall"
"time"
"github.com/zhaojh329/rtty-go/proto"
"github.com/zhaojh329/rtty-go/utils"
"github.com/rs/zerolog/log"
)
const (
MsgTypeFileCtlRequestAccept = byte(iota)
MsgTypeFileCtlProgress
MsgTypeFileCtlInfo
MsgTypeFileCtlBusy
MsgTypeFileCtlAbort
MsgTypeFileCtlNoSpace
MsgTypeFileCtlErrExist
MsgTypeFileCtlErr
)
const (
fileSizeLimit int64 = 2 * 1024 * 1024 * 1024 // 2 GB
fileCtlMsgSize = 129
)
var RttyFileMagic = [12]byte{0xb6, 0xbc, 0xbd}
func handleFileMsg(cli *RttyClient, data []byte) error {
sid := string(data[:32])
typ := data[32]
val, ok := cli.sessions.Load(sid)
if !ok {
log.Error().Msgf("terminal session %s not found", sid)
return nil
}
s := val.(*TermSession)
data = data[33:]
switch typ {
case proto.MsgTypeFileInfo:
s.fc.startDownload(data)
case proto.MsgTypeFileData:
if len(data) > 0 {
if s.fc.file != nil {
s.fc.file.Write(data)
s.fc.remainSize -= uint32(len(data))
if s.fc.notifyProgress() != nil {
s.fc.reset()
} else {
if s.fc.remainSize == 0 {
s.fc.reset()
} else {
cli.SendFileMsg(s.sid, proto.MsgTypeFileAck, nil)
}
}
}
} else {
s.fc.reset()
}
case proto.MsgTypeFileAck:
s.fc.sendData()
case proto.MsgTypeFileAbort:
s.fc.sendControlMsg(MsgTypeFileCtlAbort, nil)
s.fc.reset()
}
return nil
}
type RttyFileContext struct {
ses *TermSession
file *os.File
fifo *os.File
busy bool
uid uint32
gid uint32
totalSize uint32
remainSize uint32
savepath string
buf [1024 * 63]byte
}
func (ctx *RttyFileContext) detect(data []byte) bool {
if len(data) != len(RttyFileMagic) {
return false
}
if data[0] != RttyFileMagic[0] || data[1] != RttyFileMagic[1] || data[2] != RttyFileMagic[2] {
return false
}
pid := binary.NativeEndian.Uint32(data[4:])
uid, err := utils.GetUidByPid(pid)
if err != nil {
syscall.Kill(int(pid), syscall.SIGTERM)
log.Error().Err(err).Msgf("failed to get uid for pid %d", pid)
return true
}
gid, err := utils.GetGidByPid(pid)
if err != nil {
syscall.Kill(int(pid), syscall.SIGTERM)
log.Error().Err(err).Msgf("failed to get gid for pid %d", pid)
return true
}
fifoName := fmt.Sprintf("/tmp/rtty-fifo-%d.fifo", pid)
fifo, err := os.OpenFile(fifoName, os.O_WRONLY, 0)
if err != nil {
syscall.Kill(int(pid), syscall.SIGTERM)
log.Error().Err(err).Msgf("Could not open fifo %s", fifoName)
return true
}
ctx.fifo = fifo
if ctx.busy {
ctx.sendControlMsg(MsgTypeFileCtlBusy, nil)
fifo.Close()
return true
}
log.Debug().Msgf("detected file operation: sid=%s pid=%d, uid=%d, gid=%d", ctx.ses.sid, pid, uid, gid)
if data[3] == 'R' {
savepath, err := utils.GetCwdByPid(pid)
if err != nil {
ctx.sendControlMsg(MsgTypeFileCtlErr, nil)
fifo.Close()
log.Error().Err(err).Msgf("failed to get cwd for pid %d", pid)
return true
}
ctx.savepath = savepath
ctx.uid = uid
ctx.gid = gid
ctx.ses.cli.SendFileMsg(ctx.ses.sid, proto.MsgTypeFileRecv, nil)
ctx.sendControlMsg(MsgTypeFileCtlRequestAccept, nil)
} else {
fd := binary.NativeEndian.Uint32(data[8:])
link := fmt.Sprintf("/proc/%d/fd/%d", pid, fd)
path, err := os.Readlink(link)
if err != nil {
log.Error().Err(err).Msgf("failed to read link %s", link)
ctx.sendControlMsg(MsgTypeFileCtlErr, nil)
fifo.Close()
return true
}
ctx.sendControlMsg(MsgTypeFileCtlRequestAccept, nil)
err = ctx.startUpload(path)
if err != nil {
log.Error().Err(err).Msgf("failed to start upload file for path %s", path)
ctx.sendControlMsg(MsgTypeFileCtlErr, nil)
fifo.Close()
return true
}
}
ctx.busy = true
return true
}
func (ctx *RttyFileContext) startDownload(data []byte) {
ctx.totalSize = binary.BigEndian.Uint32(data)
ctx.remainSize = ctx.totalSize
err := utils.CheckSpaceAvailable(ctx.savepath, uint64(ctx.totalSize))
if err != nil {
log.Error().Err(err).Msgf("download file fail for %s", ctx.savepath)
ctx.sendControlMsg(MsgTypeFileCtlNoSpace, nil)
ctx.reset()
return
}
name := string(data[4:])
ctx.savepath = filepath.Join(ctx.savepath, name)
if utils.FileExists(ctx.savepath) {
log.Error().Msgf("file %s already exists", ctx.savepath)
ctx.sendControlMsg(MsgTypeFileCtlErrExist, nil)
ctx.reset()
return
}
fd, err := os.OpenFile(ctx.savepath, os.O_WRONLY|os.O_CREATE, 0644)
if err != nil {
log.Error().Err(err).Msgf("failed to open file %s for writing", ctx.savepath)
ctx.sendControlMsg(MsgTypeFileCtlErr, nil)
ctx.reset()
return
}
log.Debug().Msgf("download file: %s, size: %d bytes", ctx.savepath, ctx.totalSize)
err = fd.Chown(int(ctx.uid), int(ctx.gid))
if err != nil {
log.Warn().Err(err).Msgf("failed to change owner of file %s to uid=%d gid=%d", ctx.savepath, ctx.uid, ctx.gid)
}
if ctx.totalSize == 0 {
fd.Close()
} else {
ctx.file = fd
}
data = []byte{0, 0, 0, 0}
binary.NativeEndian.PutUint32(data, ctx.totalSize)
data = append(data, []byte(name)...)
ctx.sendControlMsg(MsgTypeFileCtlInfo, data)
}
func (ctx *RttyFileContext) startUpload(path string) error {
file, err := os.Open(path)
if err != nil {
return fmt.Errorf("failed to open file %s: %w", path, err)
}
info, _ := file.Stat()
ctx.file = file
ctx.totalSize = uint32(info.Size())
ctx.remainSize = ctx.totalSize
ctx.ses.cli.SendFileMsg(ctx.ses.sid, proto.MsgTypeFileSend, []byte(filepath.Base(path)))
log.Debug().Msgf("upload file: %s, size: %d bytes", path, ctx.totalSize)
return nil
}
func (ctx *RttyFileContext) reset() {
if ctx.file != nil {
ctx.file.Close()
ctx.file = nil
}
if ctx.fifo != nil {
ctx.fifo.Close()
ctx.fifo = nil
}
ctx.busy = false
}
func (ctx *RttyFileContext) notifyProgress() error {
buf := make([]byte, 4)
binary.NativeEndian.PutUint32(buf, ctx.remainSize)
return ctx.sendControlMsg(MsgTypeFileCtlProgress, buf)
}
func (ctx *RttyFileContext) sendData() {
if ctx.file == nil {
return
}
n, err := ctx.file.Read(ctx.buf[:])
if err != nil {
if err != io.EOF {
log.Error().Err(err).Msgf("failed to read file %s", ctx.ses.sid)
ctx.ses.cli.SendFileMsg(ctx.ses.sid, proto.MsgTypeFileAbort, nil)
ctx.sendControlMsg(MsgTypeFileCtlErr, nil)
ctx.reset()
return
}
}
ctx.remainSize -= uint32(n)
ctx.ses.cli.SendFileMsg(ctx.ses.sid, proto.MsgTypeFileData, ctx.buf[:n])
if n == 0 {
ctx.reset()
return
}
if ctx.notifyProgress() != nil {
ctx.ses.cli.SendFileMsg(ctx.ses.sid, proto.MsgTypeFileAbort, nil)
ctx.reset()
return
}
}
func (ctx *RttyFileContext) sendControlMsg(typ byte, data []byte) error {
buf := [fileCtlMsgSize]byte{typ}
copy(buf[1:], data)
if _, err := ctx.fifo.Write(buf[:]); err != nil {
return err
}
return nil
}
func requestTransferFile(typ byte, path string) {
var totalSize uint32
var sfd *os.File
var err error
pid := os.Getpid()
if typ == 'R' {
info, err := os.Stat(".")
if err != nil {
fmt.Println("Permission denied")
os.Exit(1)
}
// Check the write and execute permissions of the current directory
if info.Mode().Perm()&0200 == 0 {
fmt.Println("Permission denied")
os.Exit(1)
}
} else {
sfd, err = os.Open(path)
if err != nil {
if os.IsNotExist(err) {
fmt.Printf("open '%s' failed: No such file\n", path)
} else {
fmt.Printf("open '%s' failed: %s\n", path, err.Error())
}
os.Exit(1)
}
defer sfd.Close()
stat, err := sfd.Stat()
if err != nil {
fmt.Printf("stat '%s' failed: %s\n", path, err.Error())
os.Exit(1)
}
if !stat.Mode().IsRegular() {
fmt.Printf("'%s' is not a regular file\n", path)
os.Exit(1)
}
if stat.Size() > fileSizeLimit {
fmt.Printf("'%s' is too large(> %d Byte)\n", path, fileSizeLimit)
os.Exit(1)
}
totalSize = uint32(stat.Size())
}
fifoName := fmt.Sprintf("/tmp/rtty-fifo-%d.fifo", pid)
if err := syscall.Mkfifo(fifoName, 0644); err != nil {
fmt.Fprintf(os.Stderr, "Could not create fifo %s\n", fifoName)
os.Exit(1)
}
setupSignalHandler(fifoName)
defer os.Remove(fifoName)
time.Sleep(10 * time.Millisecond)
RttyFileMagic[3] = typ
binary.NativeEndian.PutUint32(RttyFileMagic[4:], uint32(pid))
if typ == 'S' {
fd := uint32(sfd.Fd())
binary.NativeEndian.PutUint32(RttyFileMagic[8:], fd)
}
os.Stdout.Write(RttyFileMagic[:])
os.Stdout.Sync()
ctlfd, err := os.OpenFile(fifoName, os.O_RDONLY, 0)
if err != nil {
fmt.Fprintf(os.Stderr, "Could not open fifo %s\n", fifoName)
os.Exit(1)
}
defer ctlfd.Close()
handleFileControlMsg(ctlfd, sfd, totalSize, path)
}
func handleFileControlMsg(ctlfd *os.File, sfd *os.File, totalSize uint32, path string) {
var startTime time.Time
for {
buf := make([]byte, fileCtlMsgSize)
_, err := io.ReadFull(ctlfd, buf)
if err != nil {
return
}
typ := buf[0]
buf = buf[1:]
switch typ {
case MsgTypeFileCtlRequestAccept:
if sfd != nil {
sfd.Close()
startTime = time.Now()
fmt.Printf("Transferring '%s'...Press Ctrl+C to cancel\n", filepath.Base(path))
if totalSize == 0 {
fmt.Println(" 100%% 0 B 0s")
}
} else {
fmt.Println("Waiting to receive. Press Ctrl+C to cancel")
}
case MsgTypeFileCtlInfo:
totalSize = binary.NativeEndian.Uint32(buf)
fmt.Printf("Transferring '%s'...\n", string(buf[4:]))
if totalSize == 0 {
fmt.Println(" 100%% 0 B 0s")
return
}
startTime = time.Now()
case MsgTypeFileCtlProgress:
remainSize := binary.NativeEndian.Uint32(buf)
updateProgress(startTime, totalSize, remainSize)
if remainSize == 0 {
fmt.Println()
return
}
case MsgTypeFileCtlAbort:
fmt.Println("\nTransfer aborted")
return
case MsgTypeFileCtlBusy:
fmt.Println("\033[31mRtty is busy to transfer file\033[0m")
return
case MsgTypeFileCtlNoSpace:
fmt.Println("\033[31mNo enough space\033[0m")
return
case MsgTypeFileCtlErrExist:
fmt.Println("\033[31mThe file already exists\033[0m")
return
}
}
}
func setupSignalHandler(fifoName string) {
c := make(chan os.Signal, 1)
signal.Notify(c, syscall.SIGINT)
go func() {
<-c
fmt.Println()
os.Remove(fifoName)
os.Exit(0)
}()
}
func updateProgress(startTime time.Time, totalSize uint32, remainSize uint32) {
elapsed := time.Since(startTime).Seconds()
transferred := totalSize - remainSize
percentage := uint64(transferred) * 100 / uint64(totalSize)
fmt.Printf("%100c\r", ' ')
fmt.Printf(" %d%% %s %.3fs\r", percentage, utils.FormatSize(uint64(transferred)), elapsed)
os.Stdout.Sync()
}