share.go 25 KB

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