share.go 24 KB

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