share.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  1. package share
  2. /*
  3. Arozos File Share Manager
  4. author: tobychui
  5. This module handle file share request and other stuffs
  6. */
  7. import (
  8. "encoding/json"
  9. "errors"
  10. "io/ioutil"
  11. "log"
  12. "net/http"
  13. "net/url"
  14. "os"
  15. "path/filepath"
  16. "strconv"
  17. "strings"
  18. "sync"
  19. "time"
  20. "github.com/valyala/fasttemplate"
  21. uuid "github.com/satori/go.uuid"
  22. "imuslab.com/arozos/mod/auth"
  23. "imuslab.com/arozos/mod/common"
  24. "imuslab.com/arozos/mod/database"
  25. filesystem "imuslab.com/arozos/mod/filesystem"
  26. "imuslab.com/arozos/mod/user"
  27. )
  28. type Options struct {
  29. AuthAgent *auth.AuthAgent
  30. Database *database.Database
  31. UserHandler *user.UserHandler
  32. HostName string
  33. TmpFolder string
  34. }
  35. type ShareOption struct {
  36. UUID string
  37. FileRealPath string
  38. Owner string
  39. Accessibles []string //Use to store username or group names if permission is groups or users
  40. Permission string //Access permission, allow {anyone / signedin / samegroup / groups / users}
  41. AllowLivePreview bool
  42. }
  43. type Manager struct {
  44. fileToUrlMap *sync.Map
  45. urlToFileMap *sync.Map
  46. options Options
  47. }
  48. //Create a new Share Manager
  49. func NewShareManager(options Options) *Manager {
  50. //Create the share table if not exists
  51. db := options.Database
  52. db.NewTable("share")
  53. fileToUrlMap := sync.Map{}
  54. urlToFileMap := sync.Map{}
  55. //Load the old share links
  56. entries, _ := db.ListTable("share")
  57. for _, keypairs := range entries {
  58. shareObject := new(ShareOption)
  59. json.Unmarshal(keypairs[1], &shareObject)
  60. if shareObject != nil {
  61. //Append this to the maps
  62. fileToUrlMap.Store(shareObject.FileRealPath, shareObject)
  63. urlToFileMap.Store(shareObject.UUID, shareObject)
  64. }
  65. }
  66. //Return a new manager object
  67. return &Manager{
  68. options: options,
  69. fileToUrlMap: &fileToUrlMap,
  70. urlToFileMap: &urlToFileMap,
  71. }
  72. }
  73. //Main function for handle share. Must be called with http.HandleFunc (No auth)
  74. func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
  75. //New download method variables
  76. subpathElements := []string{}
  77. directDownload := false
  78. directServe := false
  79. relpath := ""
  80. id, err := mv(r, "id", false)
  81. if err != nil {
  82. //ID is not defined in the URL paramter. New ID defination is based on the subpath content
  83. requestURI := filepath.ToSlash(filepath.Clean(r.URL.Path))
  84. subpathElements = strings.Split(requestURI[1:], "/")
  85. if len(subpathElements) == 2 {
  86. //E.g. /share/{id} => Show the download page
  87. id = subpathElements[1]
  88. //Check if there is missing / at the end. Redirect if true
  89. if r.URL.Path[len(r.URL.Path)-1:] != "/" {
  90. http.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
  91. return
  92. }
  93. } else if len(subpathElements) >= 3 {
  94. //E.g. /share/{id}/myfile.txt => Enter download mode
  95. id = subpathElements[2]
  96. if subpathElements[1] == "download" {
  97. directDownload = true
  98. //Check if this contain a subpath
  99. if len(subpathElements) > 3 {
  100. relpath = strings.Join(subpathElements[3:], "/")
  101. }
  102. } else if subpathElements[1] == "preview" {
  103. directServe = true
  104. }
  105. log.Println(len(subpathElements[3:]), subpathElements[3:], relpath)
  106. } else {
  107. http.NotFound(w, r)
  108. return
  109. }
  110. } else {
  111. //Parse and redirect to new share path
  112. download, _ := mv(r, "download", false)
  113. if download == "true" {
  114. directDownload = true
  115. }
  116. serve, _ := mv(r, "serve", false)
  117. if serve == "true" {
  118. directServe = true
  119. }
  120. relpath, _ = mv(r, "rel", false)
  121. redirectURL := "./" + id + "/"
  122. if directDownload == true {
  123. redirectURL = "./download/" + id + "/"
  124. }
  125. http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
  126. }
  127. //Check if id exists
  128. val, ok := s.urlToFileMap.Load(id)
  129. if ok {
  130. //Parse the option structure
  131. shareOption := val.(*ShareOption)
  132. //Check for permission
  133. if shareOption.Permission == "anyone" {
  134. //OK to proceed
  135. } else if shareOption.Permission == "signedin" {
  136. if s.options.AuthAgent.CheckAuth(r) == false {
  137. //Redirect to login page
  138. if directDownload || directServe {
  139. w.WriteHeader(http.StatusUnauthorized)
  140. w.Write([]byte("401 - Unauthorized"))
  141. } else {
  142. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/preview/?id="+id, 307)
  143. }
  144. return
  145. } else {
  146. //Ok to proccedd
  147. }
  148. } else if shareOption.Permission == "samegroup" {
  149. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  150. if err != nil {
  151. if directDownload || directServe {
  152. w.WriteHeader(http.StatusUnauthorized)
  153. w.Write([]byte("401 - Unauthorized"))
  154. } else {
  155. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/preview/?id="+id, 307)
  156. }
  157. return
  158. }
  159. //Check if all the user groups are inside the share owner groups
  160. valid := true
  161. thisUsersGroupByName := []string{}
  162. for _, pg := range thisuserinfo.PermissionGroup {
  163. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  164. }
  165. for _, allowedpg := range shareOption.Accessibles {
  166. if inArray(thisUsersGroupByName, allowedpg) {
  167. //This required group is inside this user's group. OK
  168. } else {
  169. //This required group is not inside user's group. Reject
  170. valid = false
  171. }
  172. }
  173. if !valid {
  174. //Serve permission denied page
  175. if directDownload || directServe {
  176. w.WriteHeader(http.StatusForbidden)
  177. w.Write([]byte("401 - Forbidden"))
  178. } else {
  179. ServePermissionDeniedPage(w)
  180. }
  181. return
  182. }
  183. } else if shareOption.Permission == "users" {
  184. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  185. if err != nil {
  186. //User not logged in. Redirect to login page
  187. if directDownload || directServe {
  188. w.WriteHeader(http.StatusUnauthorized)
  189. w.Write([]byte("401 - Unauthorized"))
  190. } else {
  191. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  192. }
  193. return
  194. }
  195. //Check if username in the allowed user list
  196. if !inArray(shareOption.Accessibles, thisuserinfo.Username) {
  197. //Serve permission denied page
  198. //Serve permission denied page
  199. if directDownload || directServe {
  200. w.WriteHeader(http.StatusForbidden)
  201. w.Write([]byte("401 - Forbidden"))
  202. } else {
  203. ServePermissionDeniedPage(w)
  204. }
  205. return
  206. }
  207. } else if shareOption.Permission == "groups" {
  208. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  209. if err != nil {
  210. //User not logged in. Redirect to login page
  211. if directDownload || directServe {
  212. w.WriteHeader(http.StatusUnauthorized)
  213. w.Write([]byte("401 - Unauthorized"))
  214. } else {
  215. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  216. }
  217. return
  218. }
  219. allowAccess := false
  220. thisUsersGroupByName := []string{}
  221. for _, pg := range thisuserinfo.PermissionGroup {
  222. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  223. }
  224. for _, thisUserPg := range thisUsersGroupByName {
  225. if inArray(shareOption.Accessibles, thisUserPg) {
  226. allowAccess = true
  227. }
  228. }
  229. if !allowAccess {
  230. //Serve permission denied page
  231. if directDownload || directServe {
  232. w.WriteHeader(http.StatusForbidden)
  233. w.Write([]byte("401 - Forbidden"))
  234. } else {
  235. ServePermissionDeniedPage(w)
  236. }
  237. return
  238. }
  239. } else {
  240. //Unsupported mode. Show notfound
  241. http.NotFound(w, r)
  242. return
  243. }
  244. //Serve the download page
  245. if isDir(shareOption.FileRealPath) {
  246. type File struct {
  247. Filename string
  248. RelPath string
  249. Filesize string
  250. IsDir bool
  251. }
  252. if directDownload == true {
  253. if relpath != "" {
  254. //User specified a specific file within the directory. Escape the relpath
  255. targetFilepath := filepath.Join(shareOption.FileRealPath, relpath)
  256. //Check if file exists
  257. if !fileExists(targetFilepath) {
  258. http.NotFound(w, r)
  259. return
  260. }
  261. //Validate the absolute path to prevent path escape
  262. absroot, _ := filepath.Abs(shareOption.FileRealPath)
  263. abstarget, _ := filepath.Abs(targetFilepath)
  264. if len(abstarget) <= len(absroot) || abstarget[:len(absroot)] != absroot {
  265. //Directory escape detected
  266. w.WriteHeader(http.StatusBadRequest)
  267. w.Write([]byte("400 - Bad Request: Invalid relative path"))
  268. return
  269. }
  270. //Serve the target file
  271. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(targetFilepath)), "+", "%20"))
  272. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  273. http.ServeFile(w, r, targetFilepath)
  274. sendOK(w)
  275. } else {
  276. //Download this folder as zip
  277. //Build the filelist to download
  278. //Create a zip using ArOZ Zipper, tmp zip files are located under tmp/share-cache/*.zip
  279. tmpFolder := s.options.TmpFolder
  280. tmpFolder = filepath.Join(tmpFolder, "share-cache")
  281. os.MkdirAll(tmpFolder, 0755)
  282. targetZipFilename := filepath.Join(tmpFolder, filepath.Base(shareOption.FileRealPath)) + ".zip"
  283. //Build a filelist
  284. err := filesystem.ArozZipFile([]string{shareOption.FileRealPath}, targetZipFilename, false)
  285. if err != nil {
  286. //Failed to create zip file
  287. w.WriteHeader(http.StatusInternalServerError)
  288. w.Write([]byte("500 - Internal Server Error: Zip file creation failed"))
  289. log.Println("Failed to create zip file for share download: " + err.Error())
  290. return
  291. }
  292. //Serve thje zip file
  293. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20")+".zip")
  294. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  295. http.ServeFile(w, r, targetZipFilename)
  296. }
  297. } else {
  298. //Show download page. Do not allow serving
  299. content, err := ioutil.ReadFile("./system/share/downloadPageFolder.html")
  300. if err != nil {
  301. http.NotFound(w, r)
  302. return
  303. }
  304. //Get file size
  305. fsize, fcount := filesystem.GetDirctorySize(shareOption.FileRealPath, false)
  306. //Build the tree list of the folder
  307. treeList := map[string][]File{}
  308. err = filepath.Walk(filepath.Clean(shareOption.FileRealPath), func(file string, info os.FileInfo, err error) error {
  309. if err != nil {
  310. //If error skip this
  311. return nil
  312. }
  313. if filepath.Base(file)[:1] != "." {
  314. fileSize := filesystem.GetFileSize(file)
  315. if filesystem.IsDir(file) {
  316. fileSize, _ = filesystem.GetDirctorySize(file, false)
  317. }
  318. relPath, err := filepath.Rel(shareOption.FileRealPath, file)
  319. if err != nil {
  320. relPath = ""
  321. }
  322. relPath = filepath.ToSlash(filepath.Clean(relPath))
  323. relDir := filepath.ToSlash(filepath.Dir(relPath))
  324. if relPath == "." {
  325. //The root file object. Skip this
  326. return nil
  327. }
  328. treeList[relDir] = append(treeList[relDir], File{
  329. Filename: filepath.Base(file),
  330. RelPath: filepath.ToSlash(relPath),
  331. Filesize: filesystem.GetFileDisplaySize(fileSize, 2),
  332. IsDir: filesystem.IsDir(file),
  333. })
  334. }
  335. return nil
  336. })
  337. tl, _ := json.Marshal(treeList)
  338. //Get modification time
  339. fmodtime, _ := filesystem.GetModTime(shareOption.FileRealPath)
  340. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  341. t := fasttemplate.New(string(content), "{{", "}}")
  342. s := t.ExecuteString(map[string]interface{}{
  343. "hostname": s.options.HostName,
  344. "reqid": id,
  345. "mime": "application/x-directory",
  346. "size": filesystem.GetFileDisplaySize(fsize, 2),
  347. "filecount": strconv.Itoa(fcount),
  348. "modtime": timeString,
  349. "downloadurl": "../../share/download/" + id,
  350. "filename": filepath.Base(shareOption.FileRealPath),
  351. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  352. "treelist": tl,
  353. "downloaduuid": id,
  354. })
  355. w.Write([]byte(s))
  356. return
  357. }
  358. } else {
  359. if directDownload {
  360. //Serve the file directly
  361. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20"))
  362. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  363. http.ServeFile(w, r, shareOption.FileRealPath)
  364. } else if directServe {
  365. w.Header().Set("Access-Control-Allow-Origin", "*")
  366. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  367. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  368. http.ServeFile(w, r, shareOption.FileRealPath)
  369. } else {
  370. //Serve the download page
  371. content, err := ioutil.ReadFile("./system/share/downloadPage.html")
  372. if err != nil {
  373. http.NotFound(w, r)
  374. return
  375. }
  376. //Get file mime type
  377. mime, ext, err := filesystem.GetMime(shareOption.FileRealPath)
  378. if err != nil {
  379. mime = "Unknown"
  380. }
  381. //Load the preview template
  382. templateRoot := "./system/share/"
  383. previewTemplate := filepath.Join(templateRoot, "defaultTemplate.html")
  384. if ext == ".mp4" || ext == ".webm" {
  385. previewTemplate = filepath.Join(templateRoot, "video.html")
  386. } else if ext == ".mp3" || ext == ".wav" || ext == ".flac" || ext == ".ogg" {
  387. previewTemplate = filepath.Join(templateRoot, "audio.html")
  388. } else if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".webp" {
  389. previewTemplate = filepath.Join(templateRoot, "image.html")
  390. } else if ext == ".pdf" {
  391. previewTemplate = filepath.Join(templateRoot, "iframe.html")
  392. } else {
  393. //Format do not support preview. Use the default.html
  394. previewTemplate = filepath.Join(templateRoot, "default.html")
  395. }
  396. tp, err := ioutil.ReadFile(previewTemplate)
  397. if err != nil {
  398. tp = []byte("")
  399. }
  400. //Merge two templates
  401. content = []byte(strings.ReplaceAll(string(content), "{{previewer}}", string(tp)))
  402. //Get file size
  403. fsize := filesystem.GetFileSize(shareOption.FileRealPath)
  404. //Get modification time
  405. fmodtime, _ := filesystem.GetModTime(shareOption.FileRealPath)
  406. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  407. downloadURI := "../../share/download/" + id + "/" + filepath.Base(shareOption.FileRealPath)
  408. //Check if ext match with filepath ext
  409. displayExt := ext
  410. if ext != filepath.Ext(shareOption.FileRealPath) {
  411. displayExt = filepath.Ext(shareOption.FileRealPath) + " (" + ext + ")"
  412. }
  413. t := fasttemplate.New(string(content), "{{", "}}")
  414. s := t.ExecuteString(map[string]interface{}{
  415. "hostname": s.options.HostName,
  416. "reqid": id,
  417. "mime": mime,
  418. "ext": displayExt,
  419. "size": filesystem.GetFileDisplaySize(fsize, 2),
  420. "modtime": timeString,
  421. "downloadurl": downloadURI,
  422. "preview_url": "/share/preview/?id=" + id + "&serve=true",
  423. "filename": filepath.Base(shareOption.FileRealPath),
  424. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  425. })
  426. w.Write([]byte(s))
  427. return
  428. }
  429. }
  430. } else {
  431. //This share not exists
  432. if err != nil {
  433. //Template not found. Just send a 404 Not Found
  434. http.NotFound(w, r)
  435. return
  436. }
  437. if directDownload == true {
  438. //Send 404 header
  439. http.NotFound(w, r)
  440. return
  441. } else {
  442. //Send not found page
  443. content, err := ioutil.ReadFile("./system/share/notfound.html")
  444. if err != nil {
  445. http.NotFound(w, r)
  446. return
  447. }
  448. t := fasttemplate.New(string(content), "{{", "}}")
  449. s := t.ExecuteString(map[string]interface{}{
  450. "hostname": s.options.HostName,
  451. "reqid": id,
  452. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  453. })
  454. w.Write([]byte(s))
  455. return
  456. }
  457. }
  458. }
  459. //Check if a file is shared
  460. func (s *Manager) HandleShareCheck(w http.ResponseWriter, r *http.Request) {
  461. //Get the vpath from paramters
  462. vpath, err := mv(r, "path", true)
  463. if err != nil {
  464. sendErrorResponse(w, "Invalid path given")
  465. return
  466. }
  467. //Get userinfo
  468. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  469. if err != nil {
  470. sendErrorResponse(w, "User not logged in")
  471. return
  472. }
  473. //Get realpath from userinfo
  474. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  475. if err != nil {
  476. sendErrorResponse(w, "Unable to resolve realpath")
  477. return
  478. }
  479. type Result struct {
  480. IsShared bool
  481. ShareUUID *ShareOption
  482. }
  483. //Check if share exists
  484. shareExists := s.FileIsShared(rpath)
  485. if !shareExists {
  486. //Share not exists
  487. js, _ := json.Marshal(Result{
  488. IsShared: false,
  489. ShareUUID: &ShareOption{},
  490. })
  491. sendJSONResponse(w, string(js))
  492. } else {
  493. //Share exists
  494. thisSharedInfo := s.GetShareObjectFromRealPath(rpath)
  495. js, _ := json.Marshal(Result{
  496. IsShared: true,
  497. ShareUUID: thisSharedInfo,
  498. })
  499. sendJSONResponse(w, string(js))
  500. }
  501. }
  502. //Create new share from the given path
  503. func (s *Manager) HandleCreateNewShare(w http.ResponseWriter, r *http.Request) {
  504. //Get the vpath from paramters
  505. vpath, err := mv(r, "path", true)
  506. if err != nil {
  507. sendErrorResponse(w, "Invalid path given")
  508. return
  509. }
  510. //Get userinfo
  511. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  512. if err != nil {
  513. sendErrorResponse(w, "User not logged in")
  514. return
  515. }
  516. share, err := s.CreateNewShare(userinfo, vpath)
  517. if err != nil {
  518. sendErrorResponse(w, err.Error())
  519. return
  520. }
  521. js, _ := json.Marshal(share)
  522. sendJSONResponse(w, string(js))
  523. }
  524. // Handle Share Edit.
  525. // For allowing groups / users, use the following syntax
  526. // groups:group1,group2,group3
  527. // users:user1,user2,user3
  528. // For basic modes, use the following keywords
  529. // anyone / signedin / samegroup
  530. // anyone: Anyone who has the link
  531. // signedin: Anyone logged in to this system
  532. // samegroup: The requesting user has the same (or more) user group as the share owner
  533. func (s *Manager) HandleEditShare(w http.ResponseWriter, r *http.Request) {
  534. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  535. if err != nil {
  536. sendErrorResponse(w, "User not logged in")
  537. return
  538. }
  539. uuid, err := mv(r, "uuid", true)
  540. if err != nil {
  541. sendErrorResponse(w, "Invalid path given")
  542. return
  543. }
  544. shareMode, _ := mv(r, "mode", true)
  545. if shareMode == "" {
  546. shareMode = "signedin"
  547. }
  548. //Check if share exists
  549. so := s.GetShareObjectFromUUID(uuid)
  550. if so == nil {
  551. //This share url not exists
  552. sendErrorResponse(w, "Share UUID not exists")
  553. return
  554. }
  555. //Check if the user has permission to edit this share
  556. if so.Owner != userinfo.Username && userinfo.IsAdmin() == false {
  557. //This file is not shared by this user and this user is not admin. Block this request
  558. sendErrorResponse(w, "Permission denied")
  559. return
  560. }
  561. //Validate and extract the storage mode
  562. ok, sharetype, settings := validateShareModes(shareMode)
  563. if !ok {
  564. sendErrorResponse(w, "Invalid share setting")
  565. return
  566. }
  567. //Analysis the sharetype
  568. if sharetype == "anyone" || sharetype == "signedin" || sharetype == "samegroup" {
  569. //Basic types.
  570. so.Permission = sharetype
  571. if sharetype == "samegroup" {
  572. //Write user groups into accessible (Must be all match inorder to allow access)
  573. userpg := []string{}
  574. for _, pg := range userinfo.PermissionGroup {
  575. userpg = append(userpg, pg.Name)
  576. }
  577. so.Accessibles = userpg
  578. }
  579. //Write changes to database
  580. s.options.Database.Write("share", uuid, so)
  581. } else if sharetype == "groups" || sharetype == "users" {
  582. //Username or group is listed = ok
  583. so.Permission = sharetype
  584. so.Accessibles = settings
  585. //Write changes to database
  586. s.options.Database.Write("share", uuid, so)
  587. }
  588. sendOK(w)
  589. }
  590. func (s *Manager) HandleDeleteShare(w http.ResponseWriter, r *http.Request) {
  591. //Get the vpath from paramters
  592. vpath, err := mv(r, "path", true)
  593. if err != nil {
  594. sendErrorResponse(w, "Invalid path given")
  595. return
  596. }
  597. //Get userinfo
  598. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  599. if err != nil {
  600. sendErrorResponse(w, "User not logged in")
  601. return
  602. }
  603. //Delete the share setting
  604. err = s.DeleteShare(userinfo, vpath)
  605. if err != nil {
  606. sendErrorResponse(w, err.Error())
  607. } else {
  608. sendOK(w)
  609. }
  610. }
  611. //Craete a new file or folder share
  612. func (s *Manager) CreateNewShare(userinfo *user.User, vpath string) (*ShareOption, error) {
  613. //Translate the vpath to realpath
  614. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  615. if err != nil {
  616. return nil, errors.New("Unable to find the file on disk")
  617. }
  618. rpath = filepath.ToSlash(filepath.Clean(rpath))
  619. //Check if source file exists
  620. if !fileExists(rpath) {
  621. return nil, errors.New("Unable to find the file on disk")
  622. }
  623. //Check if the share already exists. If yes, use the previous link
  624. val, ok := s.fileToUrlMap.Load(rpath)
  625. if ok {
  626. //Exists. Send back the old share url
  627. ShareOption := val.(*ShareOption)
  628. return ShareOption, nil
  629. } else {
  630. //Create new link for this file
  631. shareUUID := uuid.NewV4().String()
  632. //user groups when share
  633. groups := []string{}
  634. for _, pg := range userinfo.GetUserPermissionGroup() {
  635. groups = append(groups, pg.Name)
  636. }
  637. //Create a share object
  638. shareOption := ShareOption{
  639. UUID: shareUUID,
  640. FileRealPath: rpath,
  641. Owner: userinfo.Username,
  642. Accessibles: groups,
  643. Permission: "anyone",
  644. AllowLivePreview: true,
  645. }
  646. //Store results on two map to make sure O(1) Lookup time
  647. s.fileToUrlMap.Store(rpath, &shareOption)
  648. s.urlToFileMap.Store(shareUUID, &shareOption)
  649. //Write object to database
  650. s.options.Database.Write("share", shareUUID, shareOption)
  651. return &shareOption, nil
  652. }
  653. }
  654. //Delete the share on this vpath
  655. func (s *Manager) DeleteShare(userinfo *user.User, vpath string) error {
  656. //Translate the vpath to realpath
  657. rpath, err := userinfo.VirtualPathToRealPath(vpath)
  658. if err != nil {
  659. return errors.New("Unable to find the file on disk")
  660. }
  661. //Check if the share already exists. If yes, use the previous link
  662. val, ok := s.fileToUrlMap.Load(rpath)
  663. if ok {
  664. //Exists. Send back the old share url
  665. uuid := val.(*ShareOption).UUID
  666. //Remove this from the database
  667. err = s.options.Database.Delete("share", uuid)
  668. if err != nil {
  669. return err
  670. }
  671. //Remove this form the current sync map
  672. s.urlToFileMap.Delete(uuid)
  673. s.fileToUrlMap.Delete(rpath)
  674. return nil
  675. } else {
  676. //Already deleted from buffered record.
  677. return nil
  678. }
  679. }
  680. func (s *Manager) GetShareUUIDFromPath(rpath string) string {
  681. targetShareObject := s.GetShareObjectFromRealPath(rpath)
  682. if (targetShareObject) != nil {
  683. return targetShareObject.UUID
  684. }
  685. return ""
  686. }
  687. func (s *Manager) GetShareObjectFromRealPath(rpath string) *ShareOption {
  688. rpath = filepath.ToSlash(filepath.Clean(rpath))
  689. var targetShareOption *ShareOption
  690. s.fileToUrlMap.Range(func(k, v interface{}) bool {
  691. filePath := k.(string)
  692. shareObject := v.(*ShareOption)
  693. if filepath.ToSlash(filepath.Clean(filePath)) == rpath {
  694. targetShareOption = shareObject
  695. }
  696. return true
  697. })
  698. return targetShareOption
  699. }
  700. func (s *Manager) GetShareObjectFromUUID(uuid string) *ShareOption {
  701. var targetShareOption *ShareOption
  702. s.urlToFileMap.Range(func(k, v interface{}) bool {
  703. thisUuid := k.(string)
  704. shareObject := v.(*ShareOption)
  705. if thisUuid == uuid {
  706. targetShareOption = shareObject
  707. }
  708. return true
  709. })
  710. return targetShareOption
  711. }
  712. func (s *Manager) FileIsShared(rpath string) bool {
  713. shareUUID := s.GetShareUUIDFromPath(rpath)
  714. return shareUUID != ""
  715. }
  716. func ServePermissionDeniedPage(w http.ResponseWriter) {
  717. w.WriteHeader(http.StatusForbidden)
  718. pageContent := []byte("Permissioned Denied")
  719. if fileExists("system/share/permissionDenied.html") {
  720. content, err := ioutil.ReadFile("system/share/permissionDenied.html")
  721. if err == nil {
  722. pageContent = content
  723. }
  724. }
  725. w.Write([]byte(pageContent))
  726. }
  727. /*
  728. Validate Share Mode string
  729. will return
  730. 1. bool => Is valid
  731. 2. permission type: {basic / groups / users}
  732. 3. mode string
  733. */
  734. func validateShareModes(mode string) (bool, string, []string) {
  735. // user:a,b,c,d
  736. validModes := []string{"anyone", "signedin", "samegroup"}
  737. if inArray(validModes, mode) {
  738. //Standard modes
  739. return true, mode, []string{}
  740. } else if len(mode) > 7 && mode[:7] == "groups:" {
  741. //Handle custom group case like groups:a,b,c,d
  742. groupList := mode[7:]
  743. if len(groupList) > 0 {
  744. groups := strings.Split(groupList, ",")
  745. return true, "groups", groups
  746. } else {
  747. //Invalid configuration
  748. return false, "groups", []string{}
  749. }
  750. } else if len(mode) > 6 && mode[:6] == "users:" {
  751. //Handle custom usersname like users:a,b,c,d
  752. userList := mode[6:]
  753. if len(userList) > 0 {
  754. users := strings.Split(userList, ",")
  755. return true, "users", users
  756. } else {
  757. //Invalid configuration
  758. return false, "users", []string{}
  759. }
  760. }
  761. return false, "", []string{}
  762. }
  763. func (s *Manager) RemoveShareByRealpath(rpath string) error {
  764. _, ok := s.fileToUrlMap.Load(rpath)
  765. if ok {
  766. s.fileToUrlMap.Delete(rpath)
  767. } else {
  768. return errors.New("Share with given realpath not exists")
  769. }
  770. return nil
  771. }
  772. func (s *Manager) RemoveShareByUUID(uuid string) error {
  773. _, ok := s.urlToFileMap.Load(uuid)
  774. if ok {
  775. s.urlToFileMap.Delete(uuid)
  776. } else {
  777. return errors.New("Share with given uuid not exists")
  778. }
  779. return nil
  780. }
  781. //Check and clear shares that its pointinf files no longe exists
  782. func (s *Manager) ValidateAndClearShares() {
  783. //Iterate through all shares within the system
  784. s.fileToUrlMap.Range(func(k, v interface{}) bool {
  785. thisRealPath := k.(string)
  786. if !fileExists(thisRealPath) {
  787. //This share source file don't exists anymore. Remove it
  788. thisFileShareOption := v.(*ShareOption)
  789. //Delete this task from both sync map
  790. s.RemoveShareByRealpath(thisRealPath)
  791. s.RemoveShareByUUID(thisFileShareOption.UUID)
  792. //Remove share from database
  793. s.options.Database.Delete("share", thisFileShareOption.UUID)
  794. log.Println("*Share* Removing share to file: " + thisRealPath + " as it no longer exists")
  795. }
  796. return true
  797. })
  798. }