-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathfile_system.go
3418 lines (2955 loc) · 101 KB
/
file_system.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
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"crypto/sha256"
"encoding/hex"
"encoding/json"
"errors"
"io"
"io/fs"
"log"
"math"
"mime"
"net/http"
"net/url"
"os"
"sync"
"path/filepath"
"runtime"
"sort"
"strconv"
"strings"
"time"
"github.com/gorilla/websocket"
uuid "github.com/satori/go.uuid"
"imuslab.com/arozos/mod/compatibility"
"imuslab.com/arozos/mod/filesystem"
fsp "imuslab.com/arozos/mod/filesystem/fspermission"
"imuslab.com/arozos/mod/filesystem/fssort"
"imuslab.com/arozos/mod/filesystem/fuzzy"
hidden "imuslab.com/arozos/mod/filesystem/hidden"
"imuslab.com/arozos/mod/filesystem/localversion"
metadata "imuslab.com/arozos/mod/filesystem/metadata"
"imuslab.com/arozos/mod/filesystem/shortcut"
module "imuslab.com/arozos/mod/modules"
prout "imuslab.com/arozos/mod/prouter"
"imuslab.com/arozos/mod/share"
"imuslab.com/arozos/mod/share/shareEntry"
storage "imuslab.com/arozos/mod/storage"
"imuslab.com/arozos/mod/utils"
)
var (
thumbRenderHandler *metadata.RenderHandler
shareEntryTable *shareEntry.ShareEntryTable
shareManager *share.Manager
wsConnectionStore sync.Map
)
type trashedFile struct {
Filename string
Filepath string
FileExt string
IsDir bool
Filesize int64
RemoveTimestamp int64
RemoveDate string
OriginalPath string
OriginalFilename string
}
type fileOperationTask struct {
ID string //Unique id for the task operation
Owner string //Owner of the file opr
Src string //Source folder for opr
Dest string //Destination folder for opr
Progress float64 //Progress for the operation
LatestFile string //Latest file that is current transfering
FileOperationSignal int //Current control signal of the file opr
}
func FileSystemInit() {
router := prout.NewModuleRouter(prout.RouterOption{
ModuleName: "File Manager",
AdminOnly: false,
UserHandler: userHandler,
DeniedHandler: func(w http.ResponseWriter, r *http.Request) {
utils.SendErrorResponse(w, "Permission Denied")
},
})
//Upload related functions
router.HandleFunc("/system/file_system/upload", system_fs_handleUpload)
router.HandleFunc("/system/file_system/lowmemUpload", system_fs_handleLowMemoryUpload)
//Other file operations
router.HandleFunc("/system/file_system/validateFileOpr", system_fs_validateFileOpr)
router.HandleFunc("/system/file_system/fileOpr", system_fs_handleOpr)
router.HandleFunc("/system/file_system/ws/fileOpr", system_fs_handleWebSocketOpr)
router.HandleFunc("/system/file_system/listDir", system_fs_handleList)
router.HandleFunc("/system/file_system/listDirHash", system_fs_handleDirHash)
router.HandleFunc("/system/file_system/listRoots", system_fs_listRoot)
router.HandleFunc("/system/file_system/listDrives", system_fs_listDrives)
router.HandleFunc("/system/file_system/newItem", system_fs_handleNewObjects)
router.HandleFunc("/system/file_system/preference", system_fs_handleUserPreference)
router.HandleFunc("/system/file_system/listTrash", system_fs_scanTrashBin)
router.HandleFunc("/system/file_system/ws/listTrash", system_fs_WebSocketScanTrashBin)
router.HandleFunc("/system/file_system/clearTrash", system_fs_clearTrashBin)
router.HandleFunc("/system/file_system/restoreTrash", system_fs_restoreFile)
router.HandleFunc("/system/file_system/zipHandler", system_fs_zipHandler)
router.HandleFunc("/system/file_system/getProperties", system_fs_getFileProperties)
router.HandleFunc("/system/file_system/versionHistory", system_fs_FileVersionHistory)
router.HandleFunc("/system/file_system/handleFilePermission", system_fs_handleFilePermission)
router.HandleFunc("/system/file_system/search", system_fs_handleFileSearch)
//Thumbnail caching functions
router.HandleFunc("/system/file_system/handleFolderCache", system_fs_handleFolderCache)
router.HandleFunc("/system/file_system/handleCacheRender", system_fs_handleCacheRender)
router.HandleFunc("/system/file_system/loadThumbnail", system_fs_handleThumbnailLoad)
//Directory specific config
router.HandleFunc("/system/file_system/sortMode", system_fs_handleFolderSortModePreference)
//Register the module
moduleHandler.RegisterModule(module.ModuleInfo{
Name: "File Manager",
Group: "System Tools",
IconPath: "SystemAO/file_system/img/small_icon.png",
Version: "1.0",
StartDir: "SystemAO/file_system/file_explorer.html",
SupportFW: true,
InitFWSize: []int{1075, 610},
LaunchFWDir: "SystemAO/file_system/file_explorer.html",
SupportEmb: false,
})
//Register the Trashbin module
moduleHandler.RegisterModule(module.ModuleInfo{
Name: "Trash Bin",
Group: "System Tools",
IconPath: "SystemAO/file_system/trashbin_img/small_icon.png",
Version: "1.0",
StartDir: "SystemAO/file_system/trashbin.html",
SupportFW: true,
InitFWSize: []int{400, 200},
LaunchFWDir: "SystemAO/file_system/trashbin.html",
SupportEmb: false,
SupportedExt: []string{"*"},
})
//Register the Zip Extractor module
moduleHandler.RegisterModule(module.ModuleInfo{
Name: "Zip Extractor",
Group: "System Tools",
IconPath: "SystemAO/file_system/img/zip_extractor.png",
Version: "1.0",
SupportFW: false,
LaunchEmb: "SystemAO/file_system/zip_extractor.html",
SupportEmb: true,
InitEmbSize: []int{260, 120},
SupportedExt: []string{".zip"},
})
//Create user root if not exists
err := os.MkdirAll(filepath.Join(*root_directory, "users/"), 0755)
if err != nil {
systemWideLogger.PrintAndLog("File System", "Failed to create system storage root", err)
panic(err)
}
//Create database table if not exists
err = sysdb.NewTable("fs")
if err != nil {
systemWideLogger.PrintAndLog("File System", "Failed to create table for file system", err)
panic(err)
}
//Create new table for sort preference
err = sysdb.NewTable("fs-sortpref")
if err != nil {
systemWideLogger.PrintAndLog("File System", "Failed to create table for file system", err)
panic(err)
}
//Create a RenderHandler for caching thumbnails
thumbRenderHandler = metadata.NewRenderHandler()
/*
Share Related Registering
This section of functions create and register the file share service
for the wdos
*/
//Create a share manager to handle user file sharae
shareEntryTable = shareEntry.NewShareEntryTable(sysdb)
shareManager = share.NewShareManager(share.Options{
AuthAgent: authAgent,
ShareEntryTable: shareEntryTable,
UserHandler: userHandler,
HostName: *host_name,
TmpFolder: *tmp_directory,
})
//Share related functions
router.HandleFunc("/system/file_system/share/new", shareManager.HandleCreateNewShare)
router.HandleFunc("/system/file_system/share/delete", shareManager.HandleDeleteShare)
router.HandleFunc("/system/file_system/share/edit", shareManager.HandleEditShare)
router.HandleFunc("/system/file_system/share/checkShared", shareManager.HandleShareCheck)
router.HandleFunc("/system/file_system/share/list", shareManager.HandleListAllShares)
//Handle the main share function
//Share function is now routed by the main router
//http.HandleFunc("/share", shareManager.HandleShareAccess)
/*
File Operation Resume Functions
*/
//Create a sync map for file operation opened connections
wsConnectionStore = sync.Map{}
router.HandleFunc("/system/file_system/ongoing", system_fs_HandleOnGoingTasks)
/*
Nighly Tasks
These functions allow file system to clear and maintain
the wdos file system when no one is using the system
*/
//Clear tmp folder if files is placed here too long
nightlyManager.RegisterNightlyTask(system_fs_clearOldTmpFiles)
//Clear shares that its parent file no longer exists in the system
shareManager.ValidateAndClearShares()
nightlyManager.RegisterNightlyTask(shareManager.ValidateAndClearShares)
//Clear file version history that is more than 30 days
go func() {
//Start version history cleaning in background
system_fs_clearVersionHistories()
systemWideLogger.PrintAndLog("File System", "Startup File Version History Cleaning Completed", nil)
}()
systemWideLogger.PrintAndLog("File System", "Started File Version History Cleaning in background", nil)
nightlyManager.RegisterNightlyTask(system_fs_clearVersionHistories)
}
/*
File Search
Handle file search in wildcard and recursive search
*/
func system_fs_handleFileSearch(w http.ResponseWriter, r *http.Request) {
//Get the user information
userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
utils.SendErrorResponse(w, "User not logged in")
return
}
//Get the search target root path
vpath, err := utils.PostPara(r, "path")
if err != nil {
utils.SendErrorResponse(w, "Invalid vpath given")
return
}
keyword, err := utils.PostPara(r, "keyword")
if err != nil {
utils.SendErrorResponse(w, "Invalid keyword given")
return
}
//Check if case sensitive is enabled
casesensitve, _ := utils.PostPara(r, "casesensitive")
vrootID, _, err := filesystem.GetIDFromVirtualPath(vpath)
var targetFSH *filesystem.FileSystemHandler = nil
if err != nil {
utils.SendErrorResponse(w, "Invalid path given")
return
}
targetFSH, err = GetFsHandlerByUUID(vrootID)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Translate the vpath to realpath if this is an actual path on disk
resolvedPath, err := targetFSH.FileSystemAbstraction.VirtualPathToRealPath(vpath, userinfo.Username)
if err != nil {
utils.SendErrorResponse(w, "Invalid path given")
return
}
rpath := resolvedPath
//Check if the search mode is recursive keyword or wildcard
if len(keyword) > 1 && keyword[:1] == "/" {
//Wildcard
//Updates 31-12-2021: Do not allow wildcard search on virtual type's FSH
if targetFSH == nil {
utils.SendErrorResponse(w, "Invalid path given")
return
}
targetFshAbs := targetFSH.FileSystemAbstraction
wildcard := keyword[1:]
matchingFiles, err := targetFshAbs.Glob(filepath.Join(rpath, wildcard))
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//Prepare result struct
results := []filesystem.FileData{}
escaped := false
for _, matchedFile := range matchingFiles {
thisVpath, _ := targetFSH.FileSystemAbstraction.RealPathToVirtualPath(matchedFile, userinfo.Username)
isHidden, _ := hidden.IsHidden(thisVpath, true)
if !isHidden {
results = append(results, filesystem.GetFileDataFromPath(targetFSH, thisVpath, matchedFile, 2))
}
}
if escaped {
utils.SendErrorResponse(w, "Search keywords contain escape character!")
return
}
//OK. Tidy up the results
js, _ := json.Marshal(results)
utils.SendJSONResponse(w, string(js))
} else {
//Updates 2022-02-16: Build the fuzzy matcher if it is not a wildcard search
matcher := fuzzy.NewFuzzyMatcher(keyword, casesensitve == "true")
//Recursive keyword
results := []filesystem.FileData{}
var err error = nil
fshAbs := targetFSH.FileSystemAbstraction
err = fshAbs.Walk(rpath, func(path string, info os.FileInfo, err error) error {
thisFilename := filepath.Base(path)
if casesensitve != "true" {
thisFilename = strings.ToLower(thisFilename)
}
if !filesystem.IsInsideHiddenFolder(path) {
if matcher.Match(thisFilename) {
//This is a matching file
thisVpath, _ := fshAbs.RealPathToVirtualPath(path, userinfo.Username)
results = append(results, filesystem.GetFileDataFromPath(targetFSH, thisVpath, path, 2))
}
}
return nil
})
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
//OK. Tidy up the results
js, _ := json.Marshal(results)
utils.SendJSONResponse(w, string(js))
}
}
/*
Handle low-memory upload operations
This function is specailly designed to work with low memory devices
(e.g. ZeroPi / Orange Pi Zero with 512MB RAM)
Two cases
1. Not Buffer FS + Huge File
=> Write chunks to fsa + merge to fsa
2. Else
=> write chunks to tmp (via os package) + merge to fsa
*/
func system_fs_handleLowMemoryUpload(w http.ResponseWriter, r *http.Request) {
//Get user info
userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
w.WriteHeader(http.StatusUnauthorized)
w.Write([]byte("401 - Unauthorized"))
return
}
//Get filename and upload path
filename, err := utils.GetPara(r, "filename")
if filename == "" || err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Invalid filename given"))
return
}
//Get upload target directory
uploadTarget, err := utils.GetPara(r, "path")
if uploadTarget == "" || err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Invalid path given"))
return
}
//Unescape the upload target path
unescapedPath, err := url.PathUnescape(uploadTarget)
if err != nil {
unescapedPath = uploadTarget
}
//Check if the user can write to this folder
if !userinfo.CanWrite(unescapedPath) {
//No permission
w.WriteHeader(http.StatusForbidden)
w.Write([]byte("403 - Access Denied"))
return
}
fsh, subpath, err := GetFSHandlerSubpathFromVpath(unescapedPath)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Path translation failed"))
return
}
fshAbs := fsh.FileSystemAbstraction
//Translate the upload target directory
realUploadPath, err := fshAbs.VirtualPathToRealPath(subpath, userinfo.Username)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - Path translation failed"))
return
}
//Check if it is huge file upload mode
isHugeFile := false
hugefile, _ := utils.GetPara(r, "hugefile")
if hugefile == "true" && !fsh.RequireBuffer {
//Huge file mode is only compatible with local file systems
//For remote file system, use buffer to tmp then upload method
isHugeFile = true
}
//Create destination folder if not exists
targetUploadLocation := wdfs.ToSlash(filepath.Join(realUploadPath, filename))
if !fshAbs.FileExists(realUploadPath) {
fshAbs.MkdirAll(realUploadPath, 0755)
}
//Generate an UUID for this upload
uploadUUID := uuid.NewV4().String()
uploadFolder := filepath.Join(*tmp_directory, "uploads", uploadUUID)
if isHugeFile {
//Change to upload directly to target disk
uploadFolder = filepath.Join(realUploadPath, ".metadata/.upload", uploadUUID)
fshAbs.MkdirAll(uploadFolder, 0700)
} else {
os.MkdirAll(uploadFolder, 0700)
}
//Start websocket connection
var upgrader = websocket.Upgrader{}
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
systemWideLogger.PrintAndLog("File System", "Failed to upgrade websocket connection: ", err)
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 WebSocket upgrade failed"))
return
}
defer c.Close()
//Handle WebSocket upload
blockCounter := 0
chunkName := []string{}
lastChunkArrivalTime := time.Now().Unix()
//Setup a timeout listener, check if connection still active every 1 minute
ticker := time.NewTicker(60 * time.Second)
done := make(chan bool)
go func() {
for {
select {
case <-done:
return
case <-ticker.C:
if time.Now().Unix()-lastChunkArrivalTime > 300 {
//Already 5 minutes without new data arraival. Stop connection
systemWideLogger.PrintAndLog("File System", "Upload WebSocket connection timeout. Disconnecting.", errors.New("websocket connection timeout"))
c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
time.Sleep(1 * time.Second)
c.Close()
return
}
}
}
}()
totalFileSize := int64(0)
for {
mt, message, err := c.ReadMessage()
if err != nil {
//Connection closed by client. Clear the tmp folder and exit
systemWideLogger.PrintAndLog("File System", "Upload terminated by client. Cleaning tmp folder", err)
//Clear the tmp folder
time.Sleep(1 * time.Second)
if isHugeFile {
fshAbs.RemoveAll(uploadFolder)
} else {
os.RemoveAll(uploadFolder)
}
return
}
//The mt should be 2 = binary for file upload and 1 for control syntax
if mt == 1 {
msg := strings.TrimSpace(string(message))
if msg == "done" {
//Start the merging process
break
}
} else if mt == 2 {
//File block. Save it to tmp folder
chunkFilepath := filepath.Join(uploadFolder, "upld_"+strconv.Itoa(blockCounter))
chunkName = append(chunkName, chunkFilepath)
var writeErr error
if isHugeFile {
writeErr = fshAbs.WriteFile(chunkFilepath, message, 0700)
} else {
writeErr = os.WriteFile(chunkFilepath, message, 0700)
}
if writeErr != nil {
//Unable to write block. Is the tmp folder fulled?
systemWideLogger.PrintAndLog("File System", "Upload chunk write failed: "+err.Error(), err)
c.WriteMessage(1, []byte(`{\"error\":\"Write file chunk to disk failed\"}`))
//Close the connection
c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
time.Sleep(1 * time.Second)
c.Close()
//Clear the tmp files
if isHugeFile {
fshAbs.RemoveAll(uploadFolder)
} else {
os.RemoveAll(uploadFolder)
}
return
}
//Update the last upload chunk time
lastChunkArrivalTime = time.Now().Unix()
//Check if the file size is too big
totalFileSize += int64(len(message))
if totalFileSize > max_upload_size {
//File too big
c.WriteMessage(1, []byte(`{\"error\":\"File size too large\"}`))
//Close the connection
c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
time.Sleep(1 * time.Second)
c.Close()
//Clear the tmp files
if isHugeFile {
fshAbs.RemoveAll(uploadFolder)
} else {
os.RemoveAll(uploadFolder)
}
return
} else if !userinfo.StorageQuota.HaveSpace(totalFileSize) {
//Quota exceeded
c.WriteMessage(1, []byte(`{\"error\":\"User Storage Quota Exceeded\"}`))
//Close the connection
c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
time.Sleep(1 * time.Second)
c.Close()
//Clear the tmp files
if isHugeFile {
fshAbs.RemoveAll(uploadFolder)
} else {
os.RemoveAll(uploadFolder)
}
}
blockCounter++
//Request client to send the next chunk
c.WriteMessage(1, []byte("next"))
}
//systemWideLogger.PrintAndLog("File System", ("recv:", len(message), "type", mt)
}
//Try to decode the location if possible
decodedUploadLocation, err := url.PathUnescape(targetUploadLocation)
if err != nil {
decodedUploadLocation = targetUploadLocation
}
//Do not allow % sign in filename. Replace all with underscore
decodedUploadLocation = strings.ReplaceAll(decodedUploadLocation, "%", "_")
//Merge the file. Merge file location must be on local machine
mergeFileLocation := decodedUploadLocation
var out wdfs.File
if fsh.RequireBuffer {
//The merge file location must be local buffer
mergeFileLocation = getFsBufferFilepath(decodedUploadLocation, false)
out, err = os.OpenFile(mergeFileLocation, os.O_CREATE|os.O_WRONLY, 0755)
} else {
//The merge file location can be local or remote that support OpenFile.
out, err = fshAbs.OpenFile(mergeFileLocation, os.O_CREATE|os.O_WRONLY, 0755)
}
defer out.Close()
if err != nil {
systemWideLogger.PrintAndLog("File System", "Failed to open file:"+err.Error(), err)
c.WriteMessage(1, []byte(`{\"error\":\"Failed to open destination file\"}`))
c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
time.Sleep(1 * time.Second)
c.Close()
return
}
for counter, filesrc := range chunkName {
var srcChunkReader wdfs.File
if isHugeFile {
srcChunkReader, err = fshAbs.Open(filesrc)
} else {
srcChunkReader, err = os.Open(filesrc)
}
if err != nil {
systemWideLogger.PrintAndLog("File System", "Failed to open Source Chunk"+filesrc+" with error "+err.Error(), err)
c.WriteMessage(1, []byte(`{\"error\":\"Failed to open Source Chunk\"}`))
return
}
io.Copy(out, srcChunkReader)
srcChunkReader.Close()
//Delete file immediately to save space
if isHugeFile {
fshAbs.Remove(filesrc)
} else {
os.Remove(filesrc)
}
//Write to websocket for the percentage of upload is written fro tmp to dest
moveProg := strconv.Itoa(int(math.Round(float64(counter)/float64(len(chunkName))*100))) + "%"
c.WriteMessage(1, []byte(`{\"move\":\"`+moveProg+`"}`))
}
out.Close()
//Check if the size fit in user quota
var fi fs.FileInfo
if fsh.RequireBuffer {
fi, err = os.Stat(mergeFileLocation)
} else {
fi, err = fshAbs.Stat(mergeFileLocation)
}
if err != nil {
// Could not obtain stat, handle error
systemWideLogger.PrintAndLog("File System", "Failed to validate uploaded file: "+mergeFileLocation+". Error Message: "+err.Error(), err)
c.WriteMessage(1, []byte(`{\"error\":\"Failed to validate uploaded file\"}`))
return
}
if !userinfo.StorageQuota.HaveSpace(fi.Size()) {
c.WriteMessage(1, []byte(`{\"error\":\"User Storage Quota Exceeded\"}`))
if fsh.RequireBuffer {
os.RemoveAll(mergeFileLocation)
} else {
fshAbs.RemoveAll(mergeFileLocation)
}
return
}
//Upload it to remote side if it fits the user quota && is buffer file
if fsh.RequireBuffer {
//This is local buffer file. Upload to dest fsh
f, err := os.Open(mergeFileLocation)
if err != nil {
systemWideLogger.PrintAndLog("File System", "Failed to open buffered file at "+mergeFileLocation+" with error "+err.Error(), err)
c.WriteMessage(1, []byte(`{\"error\":\"Failed to open buffered object\"}`))
f.Close()
return
}
err = fsh.FileSystemAbstraction.WriteStream(decodedUploadLocation, f, 0775)
if err != nil {
systemWideLogger.PrintAndLog("File System", "Failed to write to file system: "+fsh.UUID+" with error "+err.Error(), err)
c.WriteMessage(1, []byte(`{\"error\":\"Failed to upload to remote file system\"}`))
f.Close()
return
}
//Remove the buffered file
f.Close()
os.Remove(mergeFileLocation)
}
//Log the upload filename
systemWideLogger.PrintAndLog("File System", userinfo.Username+" uploaded a file: "+filepath.Base(decodedUploadLocation), nil)
//Set owner of the new uploaded file
userinfo.SetOwnerOfFile(fsh, unescapedPath)
//Return complete signal
c.WriteMessage(1, []byte("OK"))
//Stop the timeout listner
done <- true
//Clear the tmp folder
time.Sleep(300 * time.Millisecond)
if isHugeFile {
fshAbs.RemoveAll(uploadFolder)
} else {
os.RemoveAll(uploadFolder)
}
//Close WebSocket connection after finished
c.WriteControl(8, []byte{}, time.Now().Add(time.Second))
time.Sleep(300 * time.Second)
c.Close()
}
/*
Handle FORM POST based upload
This function is design for general SBCs or computers with more than 2GB of RAM
(e.g. Raspberry Pi 4 / Linux Server)
*/
func system_fs_handleUpload(w http.ResponseWriter, r *http.Request) {
userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
utils.SendErrorResponse(w, "User not logged in")
return
}
//Limit the max upload size to the user defined size
if max_upload_size != 0 {
r.Body = http.MaxBytesReader(w, r.Body, max_upload_size)
}
//Check if this is running under demo mode. If yes, reject upload
if *demo_mode {
utils.SendErrorResponse(w, "You cannot upload in demo mode")
return
}
err = r.ParseMultipartForm(int64(*upload_buf) << 20)
if err != nil {
//Filesize too big
systemWideLogger.PrintAndLog("File System", "Upload file size too big", err)
utils.SendErrorResponse(w, "File too large")
return
}
file, handler, err := r.FormFile("file")
if err != nil {
systemWideLogger.PrintAndLog("File System", "Error Retrieving File from upload by user: "+userinfo.Username, err)
utils.SendErrorResponse(w, "Unable to parse file from upload")
return
}
//Get upload target directory
uploadTarget, _ := utils.PostPara(r, "path")
if uploadTarget == "" {
utils.SendErrorResponse(w, "Upload target cannot be empty.")
return
}
fsh, subpath, err := GetFSHandlerSubpathFromVpath(uploadTarget)
if err != nil {
utils.SendErrorResponse(w, "Invalid upload target")
return
}
targetFs := fsh.FileSystemAbstraction
//Translate the upload target directory
realUploadPath, err := targetFs.VirtualPathToRealPath(subpath, userinfo.Username)
if err != nil {
utils.SendErrorResponse(w, "Upload target is invalid or permission denied.")
return
}
storeFilename := handler.Filename //Filename of the uploaded file
//Get request time
uploadStartTime := time.Now().UnixNano() / int64(time.Millisecond)
//Update for Firefox 94.0.2 (x64) -> Now firefox put its relative path inside Content-Disposition -> filename
//Skip this handler logic if Firefox version is in between 84.0.2 to 94.0.2
bypassMetaCheck := compatibility.FirefoxBrowserVersionForBypassUploadMetaHeaderCheck(r.UserAgent())
if !bypassMetaCheck && strings.Contains(handler.Header["Content-Disposition"][0], "filename=") && strings.Contains(handler.Header["Content-Disposition"][0], "/") {
//This is a firefox MIME Header for file inside folder. Look for the actual filename
headerFields := strings.Split(handler.Header["Content-Disposition"][0], "; ")
possibleRelativePathname := ""
for _, hf := range headerFields {
if strings.Contains(hf, "filename=") && len(hf) > 11 {
//Found. Overwrite original filename with the latest one
possibleRelativePathname = hf[10 : len(hf)-1]
storeFilename = possibleRelativePathname
break
}
}
}
destFilepath := wdfs.ToSlash(filepath.Join(realUploadPath, storeFilename))
//fmt.Println(destFilepath, realUploadPath, storeFilename)
if !targetFs.FileExists(filepath.Dir(destFilepath)) {
targetFs.MkdirAll(filepath.Dir(destFilepath), 0775)
}
//Check if the upload target is read only.
accmode := userinfo.GetPathAccessPermission(uploadTarget)
if accmode == wdfs.FsReadOnly {
utils.SendErrorResponse(w, "The upload target is Read Only.")
return
} else if accmode == wdfs.FsDenied {
utils.SendErrorResponse(w, "Access Denied")
return
}
//Check for storage quota
uploadFileSize := handler.Size
if !userinfo.StorageQuota.HaveSpace(uploadFileSize) {
utils.SendErrorResponse(w, "User Storage Quota Exceeded")
return
}
//Do not allow % sign in filename. Replace all with underscore
destFilepath = strings.ReplaceAll(destFilepath, "%", "_")
//Move the file to destination file location
if *enable_asyncFileUpload {
//Use Async upload method
systemWideLogger.PrintAndLog("File System", "AsyncFileUpload flag has been deprecated. Falling back to blocking upload.", errors.New("call to deprecated flag: asyncFileUpload"))
}
err = targetFs.WriteStream(destFilepath, file, 0775)
if err != nil {
systemWideLogger.PrintAndLog("File System", "Write stream to destination file system abstraction from upload failed", err)
utils.SendErrorResponse(w, "Write upload to destination disk failed")
return
}
file.Close()
//Clear up buffered files
r.MultipartForm.RemoveAll()
//Set the ownership of file
userinfo.SetOwnerOfFile(fsh, uploadTarget)
//Finish up the upload
/*
fmt.Printf("Uploaded File: %+v\n", handler.Filename)
fmt.Printf("File Size: %+v\n", handler.Size)
fmt.Printf("MIME Header: %+v\n", handler.Header)
fmt.Println("Upload target: " + realUploadPath)
*/
//Fnish upload. Fix the tmp filename
systemWideLogger.PrintAndLog("File System", userinfo.Username+" uploaded a file: "+handler.Filename, nil)
//Do upload finishing stuff
//Add a delay to the complete message to make sure browser catch the return value
currentTimeMilli := time.Now().UnixNano() / int64(time.Millisecond)
if currentTimeMilli-uploadStartTime < 100 {
//Sleep until at least 300 ms
time.Sleep(time.Duration(100 - (currentTimeMilli - uploadStartTime)))
}
//Completed
utils.SendOK(w)
}
// Validate if the copy and target process will involve file overwriting problem.
func system_fs_validateFileOpr(w http.ResponseWriter, r *http.Request) {
userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
utils.SendErrorResponse(w, err.Error())
return
}
vsrcFiles, _ := utils.PostPara(r, "src")
vdestFile, _ := utils.PostPara(r, "dest")
var duplicateFiles []string = []string{}
//Loop through all files are see if there are duplication during copy and paste
sourceFiles := []string{}
decodedSourceFiles, _ := url.QueryUnescape(vsrcFiles)
err = json.Unmarshal([]byte(decodedSourceFiles), &sourceFiles)
if err != nil {
utils.SendErrorResponse(w, "Source file JSON parse error.")
return
}
destFsh, destSubpath, err := GetFSHandlerSubpathFromVpath(vdestFile)
if err != nil {
utils.SendErrorResponse(w, "Operation Valid Failed: "+err.Error())
return
}
rdestFile, _ := destFsh.FileSystemAbstraction.VirtualPathToRealPath(destSubpath, userinfo.Username)
for _, file := range sourceFiles {
srcFsh, srcSubpath, _ := GetFSHandlerSubpathFromVpath(string(file))
rsrcFile, _ := srcFsh.FileSystemAbstraction.VirtualPathToRealPath(srcSubpath, userinfo.Username)
if destFsh.FileSystemAbstraction.FileExists(filepath.Join(rdestFile, filepath.Base(rsrcFile))) {
//File exists already.
vpath, _ := srcFsh.FileSystemAbstraction.RealPathToVirtualPath(rsrcFile, userinfo.Username)
duplicateFiles = append(duplicateFiles, vpath)
}
}
jsonString, _ := json.Marshal(duplicateFiles)
utils.SendJSONResponse(w, string(jsonString))
}
// Scan all directory and get trash file and send back results with WebSocket
func system_fs_WebSocketScanTrashBin(w http.ResponseWriter, r *http.Request) {
//Get and check user permission
userinfo, err := userHandler.GetUserInfoFromRequest(w, r)
if err != nil {
utils.SendErrorResponse(w, "User not logged in")
return
}
//Upgrade to websocket
var upgrader = websocket.Upgrader{}
upgrader.CheckOrigin = func(r *http.Request) bool { return true }
c, err := upgrader.Upgrade(w, r, nil)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
w.Write([]byte("500 - " + err.Error()))
log.Print("Websocket Upgrade Error:", err.Error())
return
}
//Start Scanning
scanningRoots := []*filesystem.FileSystemHandler{}
//Get all roots to scan
for _, storage := range userinfo.GetAllFileSystemHandler() {
if storage.Hierarchy == "backup" {
//Skip this fsh
continue
}
scanningRoots = append(scanningRoots, storage)
}
for _, fsh := range scanningRoots {
thisFshAbs := fsh.FileSystemAbstraction
rootPath, err := thisFshAbs.VirtualPathToRealPath("", userinfo.Username)
if err != nil {
continue
}
err = thisFshAbs.Walk(rootPath, func(path string, info os.FileInfo, err error) error {
oneLevelUpper := filepath.Base(filepath.Dir(path))
if oneLevelUpper == ".trash" {
//This is a trashbin dir.
file := path
//Parse the trashFile struct
timestamp := filepath.Ext(file)[1:]
originalName := strings.TrimSuffix(filepath.Base(file), filepath.Ext(filepath.Base(file)))
originalExt := filepath.Ext(filepath.Base(originalName))
virtualFilepath, _ := thisFshAbs.RealPathToVirtualPath(file, userinfo.Username)
virtualOrgPath, _ := thisFshAbs.RealPathToVirtualPath(filepath.Dir(filepath.Dir(filepath.Dir(file))), userinfo.Username)
rawsize := thisFshAbs.GetFileSize(file)
timestampInt64, _ := utils.StringToInt64(timestamp)
removeTimeDate := time.Unix(timestampInt64, 0)
if thisFshAbs.IsDir(file) {
originalExt = ""
}
thisTrashFileObject := trashedFile{
Filename: filepath.Base(file),
Filepath: virtualFilepath,
FileExt: originalExt,
IsDir: thisFshAbs.IsDir(file),
Filesize: int64(rawsize),
RemoveTimestamp: timestampInt64,
RemoveDate: removeTimeDate.Format("2006-01-02 15:04:05"),
OriginalPath: virtualOrgPath,
OriginalFilename: originalName,
}
//Send out the result as JSON string