-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathendpoints_files.go
872 lines (837 loc) · 29.6 KB
/
endpoints_files.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
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
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
package main
import (
"archive/tar"
"archive/zip"
"bytes"
"compress/gzip"
"crypto/rand"
"encoding/hex"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"path"
"path/filepath"
"strconv"
"strings"
"time"
"github.com/puzpuzpuz/xsync/v3"
"github.com/retrixe/octyne/system"
)
// joinPath joins any number of path elements into a single path, adding a separating slash if necessary.
func joinPath(elem ...string) string {
return filepath.FromSlash(path.Join(elem...))
}
// clean combines path.Clean with filepath.FromSlash.
func clean(pathToClean string) string {
return filepath.FromSlash(path.Clean(pathToClean))
}
// GET /server/{id}/files?path=path
type serverFilesResponse struct {
Name string `json:"name"`
Size int64 `json:"size"`
MimeType string `json:"mimeType"`
Folder bool `json:"folder"`
LastModified int64 `json:"lastModified"`
}
func filesEndpoint(connector *Connector, w http.ResponseWriter, r *http.Request) {
// Check with authenticator.
user := connector.ValidateAndReject(w, r)
if user == "" {
return
}
// Get the process being accessed.
id := r.PathValue("id")
process, err := connector.Processes.Load(id)
// In case the process doesn't exist.
if !err {
httpError(w, "This server does not exist!", http.StatusNotFound)
return
}
if r.Method == "GET" {
filesEndpointGet(w, r, process)
} else if r.Method == "PATCH" {
filesEndpointPatch(connector, w, r, process, id, user)
} else {
httpError(w, "Only GET and PATCH are allowed!", http.StatusMethodNotAllowed)
}
}
func filesEndpointGet(w http.ResponseWriter, r *http.Request, process *ExposedProcess) {
// Check if folder is in the process directory or not.
process.ServerConfigMutex.RLock()
defer process.ServerConfigMutex.RUnlock()
folderPath := joinPath(process.Directory, r.URL.Query().Get("path"))
if !strings.HasPrefix(folderPath, clean(process.Directory)) {
httpError(w, "The folder requested is outside the server!", http.StatusForbidden)
return
}
// Get list of files and folders in the directory.
folder, err1 := os.Open(folderPath)
if err1 != nil {
httpError(w, "This folder does not exist!", http.StatusNotFound)
return
}
defer folder.Close()
contents, err2 := folder.Readdir(-1)
if err2 != nil {
httpError(w, "This is not a folder!", http.StatusBadRequest)
return
}
// Send the response.
toSend := make(map[string]([]serverFilesResponse))
toSend["contents"] = make([]serverFilesResponse, 0, len(contents))
for _, value := range contents {
// Determine the MIME-Type of the file.
mimeType := ""
if value.Mode()&os.ModeSymlink != 0 {
mimeType = "inode/symlink"
} else if !value.IsDir() {
var length int64 = 512
if value.Size() < 512 {
length = value.Size()
}
buffer := make([]byte, length)
path := joinPath(process.Directory, r.URL.Query().Get("path"), value.Name())
file, err := os.Open(path)
if err == nil {
file.Read(buffer) // skipcq GSC-G104
mimeType = http.DetectContentType(buffer)
file.Close() // skipcq GSC-G104
}
}
toSend["contents"] = append(toSend["contents"], serverFilesResponse{
Folder: value.IsDir() || mimeType == "inode/symlink",
Name: value.Name(),
Size: value.Size(),
LastModified: value.ModTime().Unix(),
MimeType: mimeType,
})
}
writeJsonStructRes(w, toSend) // skipcq GSC-G104
}
type fileOperation struct {
Operation string `json:"operation"` // mv, cp, rm
Src string `json:"src"`
Dest string `json:"dest"`
Path string `json:"path"`
}
type fileOperationError struct {
Index int `json:"index"`
Message string `json:"message"`
}
type filesEndpointPatchResponse struct {
Success bool `json:"success"`
Errors []fileOperationError `json:"errors,omitempty"`
}
func validateFileOperation(operation *fileOperation, process *ExposedProcess) string {
if operation.Operation != "mv" && operation.Operation != "cp" && operation.Operation != "rm" {
return "Invalid operation! Operations available: mv,cp,rm"
}
// Check if src/path exists within bounds of the server directory.
source := operation.Src
if operation.Operation == "rm" {
source = operation.Path
}
source = joinPath(process.Directory, source)
if !strings.HasPrefix(source, clean(process.Directory)) || source == clean(process.Directory) {
return "The file(s) specified in src/path is outside the server!"
}
if operation.Operation == "rm" {
operation.Path = source
} else {
operation.Src = source
}
if operation.Operation == "mv" || operation.Operation == "cp" {
// Resolve dest and check if dest exists within bounds of the server directory.
operation.Dest = joinPath(process.Directory, operation.Dest)
if !strings.HasPrefix(operation.Dest, clean(process.Directory)) ||
operation.Dest == clean(process.Directory) {
return "The path(s) specified in dest is outside the server!"
}
}
return ""
}
func performMoveCopyOperation(operation *fileOperation) (int, string) {
// Validate source
srcStat, err := os.Stat(operation.Src)
if err != nil && os.IsNotExist(err) {
return 400, "The file specified in src does not exist!"
} else if err != nil {
return 500, "Internal Server Error! " + err.Error()
}
// Validate destination
destStat, err := os.Stat(operation.Dest)
if err == nil && (destStat.IsDir() || srcStat.IsDir()) {
return 400, "The destination already exists, and either src or dest are folders!"
} else if err != nil && !os.IsNotExist(err) {
return 500, "Internal Server Error! " + err.Error()
}
// Perform move/copy operation
if operation.Operation == "mv" {
err = os.Rename(operation.Src, operation.Dest)
} else {
err = system.Copy(srcStat.Mode(), operation.Src, operation.Dest)
}
if err != nil && system.IsFileLocked(err) {
return 409, err.(*os.LinkError).Err.Error()
} else if err != nil {
return 500, "Internal Server Error! " + err.Error()
}
return 0, ""
}
func performRemoveOperation(operation *fileOperation) (int, string) {
// Check permissions in all subfolders
errStatus, errMsg := system.CanDeleteFolder(operation.Path)
if errStatus != 0 {
return errStatus, errMsg
}
// Move file/folder to temporary deletion folder
err := os.Rename(operation.Path, operation.Dest)
if err != nil && system.IsFileLocked(err) {
return 409, err.(*os.LinkError).Err.Error()
} else if err != nil && os.IsNotExist(err) {
return 400, "The file specified in path does not exist!"
} else if err != nil {
return 500, "Internal Server Error! " + err.Error()
}
return 0, ""
}
func filesEndpointPatch(
connector *Connector, w http.ResponseWriter, r *http.Request,
process *ExposedProcess, id string, user string,
) {
// Parse all transactions
var req struct {
Operations []fileOperation `json:"operations"`
}
err := json.NewDecoder(r.Body).Decode(&req)
if err != nil {
httpError(w, "Invalid JSON body!", http.StatusBadRequest)
return
}
// Validate all operations in the transaction.
response := filesEndpointPatchResponse{Errors: make([]fileOperationError, 0)}
for index := range req.Operations {
errMsg := validateFileOperation(&req.Operations[index], process)
if errMsg != "" {
w.WriteHeader(http.StatusBadRequest)
response.Errors = append(response.Errors, fileOperationError{
Index: index,
Message: errMsg,
})
break
}
}
if len(response.Errors) != 0 {
writeJsonStructRes(w, response)
return
}
// TODO: Perhaps we should lock all files on the Windows platform?
responseStatus := 200
var index int
var operation fileOperation
var removeTmpFolder string
// Begin executing all operations sequentially
for index, operation = range req.Operations {
if operation.Operation == "cp" || operation.Operation == "mv" {
errStatus, errMsg := performMoveCopyOperation(&operation)
if errStatus != 0 {
responseStatus = errStatus
response.Errors = append(response.Errors, fileOperationError{
Index: index,
Message: errMsg,
})
break
}
} else if operation.Operation == "rm" {
// Create temporary folder for deletions
if removeTmpFolder == "" {
removeTmpFolder, err = os.MkdirTemp(process.Directory, ".octyne-transaction-")
if err != nil {
responseStatus = 500
response.Errors = append(response.Errors, fileOperationError{
Index: index,
Message: "Internal Server Error! " + err.Error(),
})
break
}
}
operation.Dest = joinPath(removeTmpFolder, strconv.Itoa(index))
errStatus, errMsg := performRemoveOperation(&operation)
if errStatus != 0 {
responseStatus = errStatus
response.Errors = append(response.Errors, fileOperationError{
Index: index,
Message: errMsg,
})
break
}
}
}
// Begin a revert upon failure
if responseStatus != 200 {
for revertIndex := index - 1; revertIndex >= 0; revertIndex-- {
source := req.Operations[revertIndex].Src
if req.Operations[revertIndex].Operation == "rm" {
source = req.Operations[revertIndex].Path
}
err = os.Rename(req.Operations[revertIndex].Dest, source)
if err != nil {
responseStatus = 500
response.Errors = append(response.Errors, fileOperationError{
Index: revertIndex,
Message: "Internal Server Error! " + err.Error(),
})
}
}
}
// Delete the folder containing deletions
if removeTmpFolder != "" && len(response.Errors) < 2 { // Reverts completed/Success
err = os.RemoveAll(removeTmpFolder)
if err != nil {
responseStatus = 500
response.Errors = append(response.Errors, fileOperationError{
Index: -1,
Message: "Internal Server Error! " + err.Error(),
})
}
}
if len(response.Errors) == 0 {
connector.Info("server.files.bulk", "ip", GetIP(r), "user", user, "server", id,
"operations", req.Operations)
} else if len(response.Errors) > 1 {
connector.Info("server.files.bulk", "ip", GetIP(r), "user", user, "server", id,
"operations", req.Operations, "errors", response.Errors)
}
w.WriteHeader(responseStatus)
writeJsonStructRes(w, response)
}
// GET /server/{id}/file?path=path&ticket=ticket
// POST /server/{id}/file?path=path
// DELETE /server/{id}/file?path=path
// PATCH /server/{id}/file?path=path
func fileEndpoint(connector *Connector, w http.ResponseWriter, r *http.Request) {
ticket, ticketExists := connector.Tickets.LoadAndDelete(r.URL.Query().Get("ticket"))
user := ""
if ticketExists && ticket.IPAddr == GetIP(r) && r.Method == "GET" {
user = ticket.User
} else if user = connector.ValidateAndReject(w, r); user == "" {
return
}
// Get the process being accessed.
id := r.PathValue("id")
process, err := connector.Processes.Load(id)
// In case the process doesn't exist.
if !err {
httpError(w, "This server does not exist!", http.StatusNotFound)
return
}
// Check if path is in the process directory or not.
process.ServerConfigMutex.RLock()
defer process.ServerConfigMutex.RUnlock()
filePath := joinPath(process.Directory, r.URL.Query().Get("path"))
if (r.Method == "GET" || r.Method == "POST" || r.Method == "DELETE") &&
!strings.HasPrefix(filePath, clean(process.Directory)) {
httpError(w, "The file requested is outside the server!", http.StatusForbidden)
return
}
if r.Method == "GET" {
fileEndpointGet(connector, w, r, id, filePath, user)
} else if r.Method == "DELETE" {
fileEndpointDelete(connector, w, r, id, filePath, user)
} else if r.Method == "POST" {
fileEndpointPost(connector, w, r, id, filePath, user)
} else if r.Method == "PATCH" {
fileEndpointPatch(connector, w, r, process, id, user)
} else {
httpError(w, "Only GET, POST, PATCH and DELETE are allowed!", http.StatusMethodNotAllowed)
}
}
func fileEndpointGet(connector *Connector, w http.ResponseWriter, r *http.Request,
id string, filePath string, user string) {
// Get list of files and folders in the directory.
file, err := os.Open(filePath)
stat, err1 := file.Stat()
if err != nil || err1 != nil {
httpError(w, "This file does not exist!", http.StatusNotFound)
return
} else if !stat.Mode().IsRegular() {
httpError(w, "This is not a file!", http.StatusBadRequest)
return
}
// Send the response.
buffer := make([]byte, 512)
file.Read(buffer) // skipcq GSC-G104
file.Close() // skipcq GSC-G104
w.Header().Set("Content-Disposition", "attachment; filename="+stat.Name())
w.Header().Set("Content-Type", http.DetectContentType(buffer))
w.Header().Set("Content-Length", fmt.Sprint(stat.Size()))
file, _ = os.Open(filePath)
defer file.Close()
connector.Info("server.files.download", "ip", GetIP(r), "user", user, "server", id,
"path", clean(r.URL.Query().Get("path")))
io.Copy(w, file)
}
func fileEndpointPost(connector *Connector, w http.ResponseWriter, r *http.Request,
id string, filePath string, user string) {
// Parse our multipart form, 5120 << 20 specifies a maximum upload of a 5 GB file.
err := r.ParseMultipartForm(5120 << 20)
if err != nil {
httpError(w, "Invalid form sent!", http.StatusBadRequest)
return
}
// FormFile returns the first file for the given key `upload`
file, meta, err := r.FormFile("upload")
if err != nil {
httpError(w, "Invalid form sent!", http.StatusBadRequest)
return
}
defer file.Close()
// read the file.
filePath = joinPath(filePath, meta.Filename)
toWrite, err := os.Create(filePath)
stat, statErr := os.Stat(filePath)
if statErr == nil && stat.IsDir() {
httpError(w, "This is a folder!", http.StatusBadRequest)
return
} else if err != nil {
log.Println("An error occurred when writing to "+filePath, "("+id+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
defer toWrite.Close()
// write this byte array to our file
connector.Info("server.files.upload", "ip", GetIP(r), "user", user, "server", id,
"path", clean(r.URL.Query().Get("path")), "filename", meta.Filename)
io.Copy(toWrite, file)
writeJsonStringRes(w, "{\"success\":true}")
}
func fileEndpointPatch(connector *Connector, w http.ResponseWriter, r *http.Request,
process *ExposedProcess, id string, user string) {
// Get the request body to check the operation.
var body bytes.Buffer
_, err := body.ReadFrom(r.Body)
if err != nil {
httpError(w, "Failed to read body!", http.StatusBadRequest)
return
}
// If the body doesn't start with {, parse as a legacy request. Remove this in Octyne 2.0.
// Legacy requests will not support anything further than mv/cp operations.
var req fileOperation
if strings.TrimSpace(body.String())[0] != '{' {
split := strings.Split(body.String(), "\n")
if len(split) != 3 {
if split[0] == "mv" || split[0] == "cp" {
httpError(w, split[0]+" operation requires two arguments!", http.StatusMethodNotAllowed)
} else {
httpError(w, "Invalid operation! Operations available: mv,cp", http.StatusMethodNotAllowed)
}
return
}
req.Operation = split[0]
req.Src = split[1]
req.Dest = split[2]
} else if err = json.Unmarshal(body.Bytes(), &req); err != nil {
httpError(w, "Invalid JSON body!", http.StatusBadRequest)
return
}
// Validate operation
errMsg := validateFileOperation(&req, process)
if errMsg != "" {
httpError(w, errMsg, http.StatusBadRequest)
return
}
// Possible operations: mv, cp
if req.Operation == "mv" || req.Operation == "cp" {
oldpath := req.Src
newpath := req.Dest
// Check if original file exists.
stat, err := os.Stat(oldpath)
if os.IsNotExist(err) {
httpError(w, "This file does not exist!", http.StatusNotFound)
return
} else if err != nil {
log.Println("An error occurred in mv/cp API when checking for "+oldpath, "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
// Check if destination file exists.
if stat, err := os.Stat(newpath); err == nil && stat.IsDir() {
newpath = joinPath(newpath, path.Base(oldpath))
} else if err == nil {
httpError(w, "This file already exists!", http.StatusMethodNotAllowed)
return
} else if !os.IsNotExist(err) {
log.Println("An error occurred in mv/cp API when checking for "+newpath, "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
// Move file if operation is mv.
if req.Operation == "mv" {
err := os.Rename(oldpath, newpath)
if err != nil && system.IsFileLocked(err) {
httpError(w, err.(*os.LinkError).Err.Error(), http.StatusConflict)
return
} else if err != nil {
log.Println("An error occurred when moving "+oldpath+" to "+newpath, "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
connector.Info("server.files.move", "ip", GetIP(r), "user", user, "server", id,
"src", clean(req.Src), "dest", clean(req.Dest))
writeJsonStringRes(w, "{\"success\":true}")
} else {
err := system.Copy(stat.Mode(), oldpath, newpath)
if err != nil {
log.Println("An error occurred when copying "+oldpath+" to "+newpath, "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
connector.Info("server.files.copy", "ip", GetIP(r), "user", user, "server", id,
"src", clean(req.Src), "dest", clean(req.Dest))
writeJsonStringRes(w, "{\"success\":true}")
}
} else {
httpError(w, "Invalid operation! Operations available: mv,cp", http.StatusMethodNotAllowed)
}
}
func fileEndpointDelete(connector *Connector, w http.ResponseWriter, r *http.Request,
id string, filePath string, user string) {
// Check if the file exists.
if filePath == "/" {
httpError(w, "This operation is dangerous and has been forbidden!", http.StatusForbidden)
return
}
_, err := os.Stat(filePath)
if err != nil && os.IsNotExist(err) {
httpError(w, "This file does not exist!", http.StatusNotFound)
return
}
err = os.RemoveAll(filePath)
if err != nil && system.IsFileLocked(err) {
httpError(w, err.(*os.PathError).Err.Error(), http.StatusConflict)
return
} else if err != nil {
log.Println("An error occurred when removing "+filePath, "("+id+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
connector.Info("server.files.delete", "ip", GetIP(r), "user", user, "server", id,
"path", clean(r.URL.Query().Get("path")))
writeJsonStringRes(w, "{\"success\":true}")
}
// POST /server/{id}/folder?path=path
func folderEndpoint(connector *Connector, w http.ResponseWriter, r *http.Request) {
// Check with authenticator.
user := connector.ValidateAndReject(w, r)
if user == "" {
return
}
// Get the process being accessed.
id := r.PathValue("id")
process, err := connector.Processes.Load(id)
// In case the process doesn't exist.
if !err {
httpError(w, "This server does not exist!", http.StatusNotFound)
return
}
if r.Method == "POST" {
// Check if the folder already exists.
process.ServerConfigMutex.RLock()
defer process.ServerConfigMutex.RUnlock()
file := joinPath(process.Directory, r.URL.Query().Get("path"))
// Check if folder is in the process directory or not.
if !strings.HasPrefix(file, clean(process.Directory)) {
httpError(w, "The folder requested is outside the server!", http.StatusForbidden)
return
}
_, err := os.Stat(file)
if !os.IsNotExist(err) {
httpError(w, "This folder already exists!", http.StatusBadRequest)
return
}
// Create the folder.
err = os.Mkdir(file, os.ModePerm)
if err != nil {
log.Println("An error occurred when creating folder "+file, "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
connector.Info("server.files.createFolder", "ip", GetIP(r), "user", user, "server", id,
"path", clean(r.URL.Query().Get("path")))
writeJsonStringRes(w, "{\"success\":true}")
} else {
httpError(w, "Only POST is allowed!", http.StatusMethodNotAllowed)
}
}
// GET /server/{id}/compress?token=token
// POST /server/{id}/compress?path=path&compress=true/false/zstd/xz/gzip&archiveType=zip/tar&basePath=path&async=boolean
// POST /server/{id}/compress/v2?path=path&compress=true/false/zstd/xz/gzip&archiveType=zip/tar&basePath=path&async=boolean
var compressionProgressMap = xsync.NewMapOf[string, string]()
func compressionEndpoint(connector *Connector, w http.ResponseWriter, r *http.Request) {
// Check with authenticator.
user := connector.ValidateAndReject(w, r)
if user == "" {
return
}
// Get the process being accessed.
id := r.PathValue("id")
process, exists := connector.Processes.Load(id)
// In case the process doesn't exist.
if !exists {
httpError(w, "This server does not exist!", http.StatusNotFound)
return
} else if r.Method == "GET" {
if r.URL.Query().Get("token") == "" {
httpError(w, "No token provided!", http.StatusBadRequest)
return
}
progress, valid := compressionProgressMap.Load(r.URL.Query().Get("token"))
if !valid {
httpError(w, "Invalid token!", http.StatusBadRequest)
} else if progress == "finished" {
writeJsonStringRes(w, "{\"finished\":true}")
} else if progress == "" {
writeJsonStringRes(w, "{\"finished\":false}")
} else {
httpError(w, progress, http.StatusInternalServerError)
}
return
} else if r.Method != "POST" {
httpError(w, "Only GET and POST are allowed!", http.StatusMethodNotAllowed)
return
}
// Decode parameters.
async := r.URL.Query().Get("async") == "true"
basePath := r.URL.Query().Get("basePath")
archiveType := "zip"
compression := "true"
if r.URL.Query().Get("archiveType") != "" {
archiveType = r.URL.Query().Get("archiveType")
}
if r.URL.Query().Get("compress") != "" {
compression = r.URL.Query().Get("compress")
}
if archiveType != "zip" && archiveType != "tar" {
httpError(w, "Invalid archive type!", http.StatusBadRequest)
return
} else if compression != "true" && compression != "false" &&
compression != "zstd" && compression != "xz" && compression != "gzip" {
httpError(w, "Invalid compression type!", http.StatusBadRequest)
return
}
// Get the body.
var buffer bytes.Buffer
_, err := buffer.ReadFrom(r.Body)
if err != nil {
httpError(w, "Failed to read body!", http.StatusBadRequest)
return
}
// Decode the array body and send it to files.
var files []string
err = json.Unmarshal(buffer.Bytes(), &files)
if err != nil {
httpError(w, "Invalid JSON body!", http.StatusBadRequest)
return
}
// Validate every path.
process.ServerConfigMutex.RLock()
defer process.ServerConfigMutex.RUnlock()
if !strings.HasPrefix(joinPath(process.Directory, basePath), clean(process.Directory)) {
httpError(w, "The base path is outside the server directory!", http.StatusForbidden)
return
}
for _, file := range files {
filepath := joinPath(process.Directory, basePath, file)
if !strings.HasPrefix(filepath, clean(process.Directory)) {
httpError(w, "One of the paths provided is outside the server directory!", http.StatusForbidden)
return
} else if _, err := os.Stat(filepath); err != nil {
if os.IsNotExist(err) {
httpError(w, "The file "+file+" does not exist!", http.StatusBadRequest)
} else {
log.Println("An error occurred when checking "+filepath+" exists for compression", "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
}
return
}
}
// Check if a file exists at the location of the archive.
archivePath := joinPath(process.Directory, r.URL.Query().Get("path"))
if !strings.HasPrefix(archivePath, clean(process.Directory)) {
httpError(w, "The requested archive is outside the server directory!", http.StatusForbidden)
return
}
_, err = os.Stat(archivePath)
if !os.IsNotExist(err) {
httpError(w, "A file/folder already exists at the path of requested archive!", http.StatusBadRequest)
return
}
// Begin compressing the archive.
archiveFile, err := os.Create(archivePath)
if err != nil {
log.Println("An error occurred when creating "+archivePath+" for compression", "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
tokenBytes := make([]byte, 16)
rand.Read(tokenBytes) // Tolerate errors here, an error here is incredibly unlikely: skipcq GSC-G104
token := hex.EncodeToString(tokenBytes)
completionFunc := func() {
defer archiveFile.Close()
if archiveType == "zip" {
archive := zip.NewWriter(archiveFile)
defer archive.Close()
// Archive stuff inside.
for _, file := range files {
err := system.AddFileToZip(archive, joinPath(process.Directory, basePath), file, compression != "false")
if err != nil {
log.Println("An error occurred when adding "+file+" to "+archivePath, "("+process.Name+")", err)
if !async {
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
} else {
compressionProgressMap.Store(token, "Internal Server Error!")
}
return
}
}
} else {
var archive *tar.Writer
if compression == "true" || compression == "gzip" || compression == "" {
compressionWriter := gzip.NewWriter(archiveFile)
defer compressionWriter.Close()
archive = tar.NewWriter(compressionWriter)
} else if compression == "xz" || compression == "zstd" {
compressionWriter := system.NativeCompressionWriter(archiveFile, compression)
defer compressionWriter.Close()
archive = tar.NewWriter(compressionWriter)
} else {
archive = tar.NewWriter(archiveFile)
}
defer archive.Close()
for _, file := range files {
err := system.AddFileToTar(archive, joinPath(process.Directory, basePath), file)
if err != nil {
log.Println("An error occurred when adding "+file+" to "+archivePath, "("+process.Name+")", err)
if !async {
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
} else {
compressionProgressMap.Store(token, "Internal Server Error!")
}
return
}
}
}
connector.Info("server.files.compress", "ip", GetIP(r), "user", user, "server", id,
"archive", clean(r.URL.Query().Get("path")), "archiveType", archiveType,
"compression", compression, "basePath", basePath, "files", files)
if async {
compressionProgressMap.Store(token, "finished")
go func() { // We want our previous Close() defers to call *now*, so we do this in goroutine
<-time.After(10 * time.Second)
compressionProgressMap.Delete(token)
}()
} else {
writeJsonStringRes(w, "{\"success\":true}")
}
}
if async {
compressionProgressMap.Store(token, "")
writeJsonStringRes(w, "{\"token\":\""+token+"\"}")
go completionFunc()
} else {
completionFunc()
}
}
// POST /server/{id}/decompress?path=path
func decompressionEndpoint(connector *Connector, w http.ResponseWriter, r *http.Request) {
// Check with authenticator.
user := connector.ValidateAndReject(w, r)
if user == "" {
return
}
// Get the process being accessed.
id := r.PathValue("id")
process, err := connector.Processes.Load(id)
// In case the process doesn't exist.
if !err {
httpError(w, "This server does not exist!", http.StatusNotFound)
return
}
process.ServerConfigMutex.RLock()
defer process.ServerConfigMutex.RUnlock()
directory := clean(process.Directory)
if r.Method == "POST" {
// Check if the archive exists.
archivePath := joinPath(directory, r.URL.Query().Get("path"))
if !strings.HasPrefix(archivePath, directory) {
httpError(w, "The archive is outside the server directory!", http.StatusForbidden)
return
}
archiveStat, exists := os.Stat(archivePath)
if os.IsNotExist(exists) {
httpError(w, "The requested archive does not exist!", http.StatusBadRequest)
return
} else if exists != nil {
log.Println("An error occurred when checking "+archivePath+" archive file exists", "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
} else if archiveStat.IsDir() {
httpError(w, "The requested archive is a folder!", http.StatusBadRequest)
return
}
// Check if there is a file/folder at the destination.
var body bytes.Buffer
_, err := body.ReadFrom(r.Body)
if err != nil {
httpError(w, "Failed to read body!", http.StatusBadRequest)
return
}
unpackPath := joinPath(directory, body.String())
if !strings.HasPrefix(unpackPath, directory) {
httpError(w, "The archive file is outside the server directory!", http.StatusForbidden)
return
}
stat, err := os.Stat(unpackPath)
if os.IsNotExist(err) {
err = os.Mkdir(unpackPath, os.ModePerm)
if err != nil {
log.Println("An error occurred when creating "+unpackPath+" to unpack archive", "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
}
} else if err != nil {
log.Println("An error occurred when checking "+unpackPath+" exists to unpack archive to", "("+process.Name+")", err)
httpError(w, "Internal Server Error!", http.StatusInternalServerError)
return
} else if !stat.IsDir() {
httpError(w, "There is a file at the requested unpack destination!", http.StatusBadRequest)
return
}
// Decompress the archive.
if strings.HasSuffix(archivePath, ".zip") {
err = system.UnzipFile(archivePath, unpackPath)
} else if strings.HasSuffix(archivePath, ".tar") ||
strings.HasSuffix(archivePath, ".tar.gz") || strings.HasSuffix(archivePath, ".tgz") ||
strings.HasSuffix(archivePath, ".tar.bz") || strings.HasSuffix(archivePath, ".tbz") ||
strings.HasSuffix(archivePath, ".tar.bz2") || strings.HasSuffix(archivePath, ".tbz2") ||
strings.HasSuffix(archivePath, ".tar.xz") || strings.HasSuffix(archivePath, ".txz") ||
strings.HasSuffix(archivePath, ".tar.zst") || strings.HasSuffix(archivePath, ".tzst") {
err = system.ExtractTarFile(archivePath, unpackPath)
} else {
httpError(w, "Unsupported archive file!", http.StatusBadRequest)
return
}
if err != nil {
httpError(w, "An error occurred while decompressing archive!", http.StatusInternalServerError)
return
}
connector.Info("server.files.decompress", "ip", GetIP(r), "user", user, "server", id,
"archive", clean(r.URL.Query().Get("path")), "destPath", body.String())
writeJsonStringRes(w, "{\"success\":true}")
} else {
httpError(w, "Only POST is allowed!", http.StatusMethodNotAllowed)
}
}