share.go 24 KB

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