share.go 26 KB

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