share.go 34 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172
  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. "fmt"
  10. "image"
  11. "image/color"
  12. "image/draw"
  13. "image/jpeg"
  14. "io"
  15. "io/fs"
  16. "io/ioutil"
  17. "log"
  18. "math"
  19. "net/http"
  20. "net/url"
  21. "os"
  22. "path/filepath"
  23. "strconv"
  24. "strings"
  25. "time"
  26. "github.com/golang/freetype"
  27. "github.com/nfnt/resize"
  28. uuid "github.com/satori/go.uuid"
  29. "github.com/valyala/fasttemplate"
  30. "imuslab.com/arozos/mod/auth"
  31. "imuslab.com/arozos/mod/common"
  32. filesystem "imuslab.com/arozos/mod/filesystem"
  33. "imuslab.com/arozos/mod/filesystem/metadata"
  34. "imuslab.com/arozos/mod/share/shareEntry"
  35. "imuslab.com/arozos/mod/user"
  36. )
  37. type Options struct {
  38. AuthAgent *auth.AuthAgent
  39. UserHandler *user.UserHandler
  40. ShareEntryTable *shareEntry.ShareEntryTable
  41. HostName string
  42. TmpFolder string
  43. }
  44. type Manager struct {
  45. options Options
  46. }
  47. //Create a new Share Manager
  48. func NewShareManager(options Options) *Manager {
  49. //Return a new manager object
  50. return &Manager{
  51. options: options,
  52. }
  53. }
  54. func (s *Manager) HandleOPGServing(w http.ResponseWriter, r *http.Request, shareID string) {
  55. shareEntry := s.GetShareObjectFromUUID(shareID)
  56. if shareEntry == nil {
  57. //This share is not valid
  58. http.NotFound(w, r)
  59. return
  60. }
  61. //Overlap and generate opg
  62. //Load in base template
  63. baseTemplate, err := os.Open("./system/share/default_opg.png")
  64. if err != nil {
  65. fmt.Println("[share/opg] " + err.Error())
  66. http.NotFound(w, r)
  67. return
  68. }
  69. base, _, err := image.Decode(baseTemplate)
  70. if err != nil {
  71. fmt.Println("[share/opg] " + err.Error())
  72. http.NotFound(w, r)
  73. return
  74. }
  75. //Create base canvas
  76. rx := image.Rectangle{image.Point{0, 0}, base.Bounds().Size()}
  77. resultopg := image.NewRGBA(rx)
  78. draw.Draw(resultopg, base.Bounds(), base, image.Point{0, 0}, draw.Src)
  79. //Append filename to the image
  80. fontBytes, err := ioutil.ReadFile("./system/share/fonts/TaipeiSansTCBeta-Light.ttf")
  81. if err != nil {
  82. fmt.Println("[share/opg] " + err.Error())
  83. http.NotFound(w, r)
  84. return
  85. }
  86. utf8Font, err := freetype.ParseFont(fontBytes)
  87. if err != nil {
  88. fmt.Println("[share/opg] " + err.Error())
  89. http.NotFound(w, r)
  90. return
  91. }
  92. fontSize := float64(42)
  93. ctx := freetype.NewContext()
  94. ctx.SetDPI(72)
  95. ctx.SetFont(utf8Font)
  96. ctx.SetFontSize(fontSize)
  97. ctx.SetClip(resultopg.Bounds())
  98. ctx.SetDst(resultopg)
  99. ctx.SetSrc(image.NewUniform(color.RGBA{255, 255, 255, 255}))
  100. //Check if we need to split the filename into two lines
  101. filename := filepath.Base(shareEntry.FileRealPath)
  102. filenameOnly := strings.TrimSuffix(filename, filepath.Ext(filename))
  103. fs := filesystem.GetFileSize(shareEntry.FileRealPath)
  104. shareMeta := filepath.Ext(shareEntry.FileRealPath) + " / " + filesystem.GetFileDisplaySize(fs, 2)
  105. if isDir(shareEntry.FileRealPath) {
  106. fs, fc := filesystem.GetDirctorySize(shareEntry.FileRealPath, false)
  107. shareMeta = strconv.Itoa(fc) + " items / " + filesystem.GetFileDisplaySize(fs, 2)
  108. }
  109. if len([]rune(filename)) > 20 {
  110. //Split into lines
  111. lines := []string{}
  112. for i := 0; i < len([]rune(filenameOnly)); i += 20 {
  113. endPos := int(math.Min(float64(len([]rune(filenameOnly))), float64(i+20)))
  114. lines = append(lines, string([]rune(filenameOnly)[i:endPos]))
  115. }
  116. for j, line := range lines {
  117. pt := freetype.Pt(100, (j+1)*60+int(ctx.PointToFixed(fontSize)>>6))
  118. _, err = ctx.DrawString(line, pt)
  119. if err != nil {
  120. fmt.Println("[share/opg] " + err.Error())
  121. return
  122. }
  123. }
  124. fontSize = 36
  125. ctx.SetFontSize(fontSize)
  126. pt := freetype.Pt(100, (len(lines)+1)*60+int(ctx.PointToFixed(fontSize)>>6))
  127. _, err = ctx.DrawString(shareMeta, pt)
  128. if err != nil {
  129. fmt.Println("[share/opg] " + err.Error())
  130. http.NotFound(w, r)
  131. return
  132. }
  133. } else {
  134. //One liner
  135. pt := freetype.Pt(100, 60+int(ctx.PointToFixed(fontSize)>>6))
  136. _, err = ctx.DrawString(filenameOnly, pt)
  137. if err != nil {
  138. fmt.Println("[share/opg] " + err.Error())
  139. http.NotFound(w, r)
  140. return
  141. }
  142. fontSize = 36
  143. ctx.SetFontSize(fontSize)
  144. pt = freetype.Pt(100, 120+int(ctx.PointToFixed(fontSize)>>6))
  145. _, err = ctx.DrawString(shareMeta, pt)
  146. if err != nil {
  147. fmt.Println("[share/opg] " + err.Error())
  148. http.NotFound(w, r)
  149. return
  150. }
  151. }
  152. //Get thumbnail
  153. ownerinfo, err := s.options.UserHandler.GetUserInfoFromUsername(shareEntry.Owner)
  154. if err != nil {
  155. fmt.Println("[share/opg] " + err.Error())
  156. http.NotFound(w, r)
  157. return
  158. }
  159. fsh, err := ownerinfo.GetFileSystemHandlerFromVirtualPath(shareEntry.FileVirtualPath)
  160. if err != nil {
  161. fmt.Println("[share/opg] " + err.Error())
  162. http.NotFound(w, r)
  163. return
  164. }
  165. rpath, _ := fsh.FileSystemAbstraction.VirtualPathToRealPath(shareEntry.FileVirtualPath, shareEntry.Owner)
  166. cacheFileImagePath, err := metadata.GetCacheFilePath(fsh, rpath)
  167. if err == nil {
  168. //We got a thumbnail for this file. Render it as well
  169. thumbnailFile, err := os.Open(cacheFileImagePath)
  170. if err != nil {
  171. fmt.Println("[share/opg] " + err.Error())
  172. http.NotFound(w, r)
  173. return
  174. }
  175. thumb, _, err := image.Decode(thumbnailFile)
  176. if err != nil {
  177. fmt.Println("[share/opg] " + err.Error())
  178. http.NotFound(w, r)
  179. return
  180. }
  181. resizedThumb := resize.Resize(250, 0, thumb, resize.Lanczos3)
  182. draw.Draw(resultopg, resultopg.Bounds(), resizedThumb, image.Point{-(resultopg.Bounds().Dx() - resizedThumb.Bounds().Dx() - 90), -60}, draw.Over)
  183. } else if isDir(shareEntry.FileRealPath) {
  184. //Is directory but no thumbnail. Use default foldr share thumbnail
  185. thumbnailFile, err := os.Open("./system/share/folder.png")
  186. if err != nil {
  187. fmt.Println("[share/opg] " + err.Error())
  188. http.NotFound(w, r)
  189. return
  190. }
  191. thumb, _, err := image.Decode(thumbnailFile)
  192. if err != nil {
  193. fmt.Println("[share/opg] " + err.Error())
  194. http.NotFound(w, r)
  195. return
  196. }
  197. resizedThumb := resize.Resize(250, 0, thumb, resize.Lanczos3)
  198. draw.Draw(resultopg, resultopg.Bounds(), resizedThumb, image.Point{-(resultopg.Bounds().Dx() - resizedThumb.Bounds().Dx() - 90), -60}, draw.Over)
  199. }
  200. w.Header().Set("Content-Type", "image/jpeg")
  201. jpeg.Encode(w, resultopg, nil)
  202. }
  203. //Main function for handle share. Must be called with http.HandleFunc (No auth)
  204. func (s *Manager) HandleShareAccess(w http.ResponseWriter, r *http.Request) {
  205. //New download method variables
  206. subpathElements := []string{}
  207. directDownload := false
  208. directServe := false
  209. relpath := ""
  210. id, err := mv(r, "id", false)
  211. if err != nil {
  212. //ID is not defined in the URL paramter. New ID defination is based on the subpath content
  213. requestURI := filepath.ToSlash(filepath.Clean(r.URL.Path))
  214. subpathElements = strings.Split(requestURI[1:], "/")
  215. if len(subpathElements) == 2 {
  216. //E.g. /share/{id} => Show the download page
  217. id = subpathElements[1]
  218. //Check if there is missing / at the end. Redirect if true
  219. if r.URL.Path[len(r.URL.Path)-1:] != "/" {
  220. http.Redirect(w, r, r.URL.Path+"/", http.StatusTemporaryRedirect)
  221. return
  222. }
  223. } else if len(subpathElements) >= 3 {
  224. //E.g. /share/download/{uuid} or /share/preview/{uuid}
  225. id = subpathElements[2]
  226. if subpathElements[1] == "download" {
  227. directDownload = true
  228. //Check if this contain a subpath
  229. if len(subpathElements) > 3 {
  230. relpath = strings.Join(subpathElements[3:], "/")
  231. }
  232. } else if subpathElements[1] == "preview" {
  233. directServe = true
  234. } else if len(subpathElements) == 3 {
  235. //Check if the last element is the filename
  236. if strings.Contains(subpathElements[2], ".") {
  237. //Share link contain filename. Redirect to share interface
  238. http.Redirect(w, r, "./", http.StatusTemporaryRedirect)
  239. return
  240. } else {
  241. //Incorrect operation type
  242. w.WriteHeader(http.StatusBadRequest)
  243. w.Header().Set("Content-Type", "text/plain") // this
  244. w.Write([]byte("400 - Operation type not supported: " + subpathElements[1]))
  245. return
  246. }
  247. } else if len(subpathElements) >= 4 {
  248. if subpathElements[1] == "opg" {
  249. //Handle serving opg preview image, usually with
  250. // /share/opg/{req.timestamp}/{uuid}
  251. s.HandleOPGServing(w, r, subpathElements[3])
  252. return
  253. }
  254. //Invalid operation type
  255. w.WriteHeader(http.StatusBadRequest)
  256. w.Header().Set("Content-Type", "text/plain") // this
  257. w.Write([]byte("400 - Operation type not supported: " + subpathElements[1]))
  258. return
  259. }
  260. } else if len(subpathElements) == 1 {
  261. //ID is missing. Serve the id input page
  262. content, err := ioutil.ReadFile("system/share/index.html")
  263. if err != nil {
  264. //Handling index not found. Is server updated correctly?
  265. w.WriteHeader(http.StatusInternalServerError)
  266. w.Write([]byte("500 - Internal Server Error"))
  267. return
  268. }
  269. t := fasttemplate.New(string(content), "{{", "}}")
  270. s := t.ExecuteString(map[string]interface{}{
  271. "hostname": s.options.HostName,
  272. })
  273. w.Write([]byte(s))
  274. return
  275. } else {
  276. http.NotFound(w, r)
  277. return
  278. }
  279. } else {
  280. //Parse and redirect to new share path
  281. download, _ := mv(r, "download", false)
  282. if download == "true" {
  283. directDownload = true
  284. }
  285. serve, _ := mv(r, "serve", false)
  286. if serve == "true" {
  287. directServe = true
  288. }
  289. relpath, _ = mv(r, "rel", false)
  290. redirectURL := "./" + id + "/"
  291. if directDownload == true {
  292. redirectURL = "./download/" + id + "/"
  293. }
  294. http.Redirect(w, r, redirectURL, http.StatusTemporaryRedirect)
  295. return
  296. }
  297. //Check if id exists
  298. val, ok := s.options.ShareEntryTable.UrlToFileMap.Load(id)
  299. if ok {
  300. //Parse the option structure
  301. shareOption := val.(*shareEntry.ShareOption)
  302. //Check for permission
  303. if shareOption.Permission == "anyone" {
  304. //OK to proceed
  305. } else if shareOption.Permission == "signedin" {
  306. if !s.options.AuthAgent.CheckAuth(r) {
  307. //Redirect to login page
  308. if directDownload || directServe {
  309. w.WriteHeader(http.StatusUnauthorized)
  310. w.Write([]byte("401 - Unauthorized"))
  311. } else {
  312. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/preview/?id="+id, 307)
  313. }
  314. return
  315. } else {
  316. //Ok to proccedd
  317. }
  318. } else if shareOption.Permission == "samegroup" {
  319. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  320. if err != nil {
  321. if directDownload || directServe {
  322. w.WriteHeader(http.StatusUnauthorized)
  323. w.Write([]byte("401 - Unauthorized"))
  324. } else {
  325. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/preview/?id="+id, 307)
  326. }
  327. return
  328. }
  329. //Check if all the user groups are inside the share owner groups
  330. valid := true
  331. thisUsersGroupByName := []string{}
  332. for _, pg := range thisuserinfo.PermissionGroup {
  333. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  334. }
  335. for _, allowedpg := range shareOption.Accessibles {
  336. if inArray(thisUsersGroupByName, allowedpg) {
  337. //This required group is inside this user's group. OK
  338. } else {
  339. //This required group is not inside user's group. Reject
  340. valid = false
  341. }
  342. }
  343. if !valid {
  344. //Serve permission denied page
  345. if directDownload || directServe {
  346. w.WriteHeader(http.StatusForbidden)
  347. w.Write([]byte("401 - Forbidden"))
  348. } else {
  349. ServePermissionDeniedPage(w)
  350. }
  351. return
  352. }
  353. } else if shareOption.Permission == "users" {
  354. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  355. if err != nil {
  356. //User not logged in. Redirect to login page
  357. if directDownload || directServe {
  358. w.WriteHeader(http.StatusUnauthorized)
  359. w.Write([]byte("401 - Unauthorized"))
  360. } else {
  361. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  362. }
  363. return
  364. }
  365. //Check if username in the allowed user list
  366. if !inArray(shareOption.Accessibles, thisuserinfo.Username) && shareOption.Owner != thisuserinfo.Username {
  367. //Serve permission denied page
  368. if directDownload || directServe {
  369. w.WriteHeader(http.StatusForbidden)
  370. w.Write([]byte("401 - Forbidden"))
  371. } else {
  372. ServePermissionDeniedPage(w)
  373. }
  374. return
  375. }
  376. } else if shareOption.Permission == "groups" {
  377. thisuserinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  378. if err != nil {
  379. //User not logged in. Redirect to login page
  380. if directDownload || directServe {
  381. w.WriteHeader(http.StatusUnauthorized)
  382. w.Write([]byte("401 - Unauthorized"))
  383. } else {
  384. http.Redirect(w, r, common.ConstructRelativePathFromRequestURL(r.RequestURI, "login.system")+"?redirect=/share/"+id, 307)
  385. }
  386. return
  387. }
  388. allowAccess := false
  389. thisUsersGroupByName := []string{}
  390. for _, pg := range thisuserinfo.PermissionGroup {
  391. thisUsersGroupByName = append(thisUsersGroupByName, pg.Name)
  392. }
  393. for _, thisUserPg := range thisUsersGroupByName {
  394. if inArray(shareOption.Accessibles, thisUserPg) {
  395. allowAccess = true
  396. }
  397. }
  398. if !allowAccess {
  399. //Serve permission denied page
  400. if directDownload || directServe {
  401. w.WriteHeader(http.StatusForbidden)
  402. w.Write([]byte("401 - Forbidden"))
  403. } else {
  404. ServePermissionDeniedPage(w)
  405. }
  406. return
  407. }
  408. } else {
  409. //Unsupported mode. Show notfound
  410. http.NotFound(w, r)
  411. return
  412. }
  413. //Resolve the fsh from the entry
  414. owner, err := s.options.UserHandler.GetUserInfoFromUsername(shareOption.Owner)
  415. if err != nil {
  416. w.WriteHeader(http.StatusForbidden)
  417. w.Write([]byte("401 - Share account not exists"))
  418. return
  419. }
  420. targetFsh, err := owner.GetFileSystemHandlerFromVirtualPath(shareOption.FileVirtualPath)
  421. if err != nil {
  422. w.WriteHeader(http.StatusInternalServerError)
  423. w.Write([]byte("500 - Unable to load Shared File"))
  424. return
  425. }
  426. targetFshAbs := targetFsh.FileSystemAbstraction
  427. fileRuntimeAbsPath, _ := targetFshAbs.VirtualPathToRealPath(shareOption.FileVirtualPath, owner.Username)
  428. if !targetFshAbs.FileExists(fileRuntimeAbsPath) {
  429. http.NotFound(w, r)
  430. return
  431. }
  432. //Serve the download page
  433. if targetFshAbs.IsDir(fileRuntimeAbsPath) {
  434. //This share is a folder
  435. type File struct {
  436. Filename string
  437. RelPath string
  438. Filesize string
  439. IsDir bool
  440. }
  441. if directDownload {
  442. if relpath != "" {
  443. //User specified a specific file within the directory. Escape the relpath
  444. targetFilepath := filepath.Join(fileRuntimeAbsPath, relpath)
  445. //Check if file exists
  446. if !targetFshAbs.FileExists(targetFilepath) {
  447. http.NotFound(w, r)
  448. return
  449. }
  450. //Validate the absolute path to prevent path escape
  451. reqPath := filepath.ToSlash(filepath.Clean(targetFilepath))
  452. rootPath, _ := targetFshAbs.VirtualPathToRealPath(shareOption.FileVirtualPath, shareOption.Owner)
  453. if !strings.HasPrefix(reqPath, rootPath) {
  454. //Directory escape detected
  455. w.WriteHeader(http.StatusBadRequest)
  456. w.Write([]byte("400 - Bad Request: Invalid relative path"))
  457. return
  458. }
  459. //Serve the target file
  460. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(targetFilepath)), "+", "%20"))
  461. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  462. //http.ServeFile(w, r, targetFilepath)
  463. f, _ := targetFshAbs.ReadStream(targetFilepath)
  464. io.Copy(w, f)
  465. f.Close()
  466. } else {
  467. //Download this folder as zip
  468. //Create a zip using ArOZ Zipper, tmp zip files are located under tmp/share-cache/*.zip
  469. tmpFolder := s.options.TmpFolder
  470. tmpFolder = filepath.Join(tmpFolder, "share-cache")
  471. os.MkdirAll(tmpFolder, 0755)
  472. targetZipFilename := filepath.Join(tmpFolder, filepath.Base(fileRuntimeAbsPath)) + ".zip"
  473. //Check if the target fs require buffer
  474. zippingSource := shareOption.FileRealPath
  475. localBuff := ""
  476. if targetFsh.RequireBuffer {
  477. //Buffer all the required files for zipping
  478. localBuff = filepath.Join(tmpFolder, uuid.NewV4().String(), filepath.Base(fileRuntimeAbsPath))
  479. os.MkdirAll(localBuff, 0755)
  480. //Buffer all files into tmp folder
  481. targetFshAbs.Walk(fileRuntimeAbsPath, func(path string, info fs.FileInfo, err error) error {
  482. relPath := strings.TrimPrefix(filepath.ToSlash(path), filepath.ToSlash(fileRuntimeAbsPath))
  483. localPath := filepath.Join(localBuff, relPath)
  484. if info.IsDir() {
  485. os.MkdirAll(localPath, 0755)
  486. } else {
  487. f, err := targetFshAbs.ReadStream(path)
  488. if err != nil {
  489. log.Println("[Share] Buffer and zip download operation failed: ", err)
  490. }
  491. dest, err := os.OpenFile(localPath, os.O_CREATE|os.O_WRONLY, 0775)
  492. if err != nil {
  493. log.Println("[Share] Buffer and zip download operation failed: ", err)
  494. }
  495. _, err = io.Copy(dest, f)
  496. if err != nil {
  497. log.Println("[Share] Buffer and zip download operation failed: ", err)
  498. }
  499. f.Close()
  500. }
  501. return nil
  502. })
  503. zippingSource = localBuff
  504. }
  505. //Build a filelist
  506. err := filesystem.ArozZipFile([]string{zippingSource}, targetZipFilename, false)
  507. if err != nil {
  508. //Failed to create zip file
  509. w.WriteHeader(http.StatusInternalServerError)
  510. w.Write([]byte("500 - Internal Server Error: Zip file creation failed"))
  511. log.Println("Failed to create zip file for share download: " + err.Error())
  512. return
  513. }
  514. //Serve thje zip file
  515. w.Header().Set("Content-Disposition", "attachment; filename*=UTF-8''"+strings.ReplaceAll(url.QueryEscape(filepath.Base(shareOption.FileRealPath)), "+", "%20")+".zip")
  516. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  517. http.ServeFile(w, r, targetZipFilename)
  518. //Remove the buffer file if exists
  519. if targetFsh.RequireBuffer {
  520. os.RemoveAll(filepath.Dir(localBuff))
  521. }
  522. }
  523. } else if directServe {
  524. //Folder provide no direct serve method.
  525. w.WriteHeader(http.StatusBadRequest)
  526. w.Write([]byte("400 - Cannot preview folder type shares"))
  527. return
  528. } else {
  529. //Show download page. Do not allow serving
  530. content, err := ioutil.ReadFile("./system/share/downloadPageFolder.html")
  531. if err != nil {
  532. http.NotFound(w, r)
  533. return
  534. }
  535. //Get file size
  536. fsize, fcount := targetFsh.GetDirctorySizeFromRealPath(fileRuntimeAbsPath, false)
  537. //Build the tree list of the folder
  538. treeList := map[string][]File{}
  539. err = targetFshAbs.Walk(filepath.Clean(fileRuntimeAbsPath), func(file string, info os.FileInfo, err error) error {
  540. if err != nil {
  541. //If error skip this
  542. return nil
  543. }
  544. if filepath.Base(file)[:1] != "." {
  545. fileSize := targetFshAbs.GetFileSize(file)
  546. if targetFshAbs.IsDir(file) {
  547. fileSize, _ = targetFsh.GetDirctorySizeFromRealPath(file, false)
  548. }
  549. relPath, err := filepath.Rel(fileRuntimeAbsPath, file)
  550. if err != nil {
  551. relPath = ""
  552. }
  553. relPath = filepath.ToSlash(filepath.Clean(relPath))
  554. relDir := filepath.ToSlash(filepath.Dir(relPath))
  555. if relPath == "." {
  556. //The root file object. Skip this
  557. return nil
  558. }
  559. treeList[relDir] = append(treeList[relDir], File{
  560. Filename: filepath.Base(file),
  561. RelPath: filepath.ToSlash(relPath),
  562. Filesize: filesystem.GetFileDisplaySize(fileSize, 2),
  563. IsDir: targetFshAbs.IsDir(file),
  564. })
  565. }
  566. return nil
  567. })
  568. if err != nil {
  569. w.WriteHeader(http.StatusInternalServerError)
  570. w.Write([]byte("500 - Internal Server Error"))
  571. return
  572. }
  573. tl, _ := json.Marshal(treeList)
  574. //Get modification time
  575. fmodtime, _ := targetFshAbs.GetModTime(fileRuntimeAbsPath)
  576. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  577. t := fasttemplate.New(string(content), "{{", "}}")
  578. s := t.ExecuteString(map[string]interface{}{
  579. "hostname": s.options.HostName,
  580. "host": r.Host,
  581. "reqid": id,
  582. "mime": "application/x-directory",
  583. "size": filesystem.GetFileDisplaySize(fsize, 2),
  584. "filecount": strconv.Itoa(fcount),
  585. "modtime": timeString,
  586. "downloadurl": "../../share/download/" + id,
  587. "filename": filepath.Base(fileRuntimeAbsPath),
  588. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  589. "requri": "//" + r.Host + r.URL.Path,
  590. "opg_image": "/share/opg/" + strconv.Itoa(int(time.Now().Unix())) + "/" + id,
  591. "treelist": tl,
  592. "downloaduuid": id,
  593. })
  594. w.Write([]byte(s))
  595. return
  596. }
  597. } else {
  598. //This share is a file
  599. if directDownload {
  600. //Serve the file directly
  601. w.Header().Set("Content-Disposition", "attachment; filename=\""+filepath.Base(shareOption.FileVirtualPath)+"\"")
  602. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  603. f, _ := targetFshAbs.ReadStream(fileRuntimeAbsPath)
  604. io.Copy(w, f)
  605. f.Close()
  606. } else if directServe {
  607. w.Header().Set("Access-Control-Allow-Origin", "*")
  608. w.Header().Set("Access-Control-Allow-Headers", "Content-Type")
  609. w.Header().Set("Content-Type", r.Header.Get("Content-Type"))
  610. f, _ := targetFshAbs.ReadStream(fileRuntimeAbsPath)
  611. io.Copy(w, f)
  612. f.Close()
  613. } else {
  614. //Serve the download page
  615. content, err := ioutil.ReadFile("./system/share/downloadPage.html")
  616. if err != nil {
  617. http.NotFound(w, r)
  618. return
  619. }
  620. //Get file mime type
  621. mime, ext, err := filesystem.GetMime(fileRuntimeAbsPath)
  622. if err != nil {
  623. mime = "Unknown"
  624. }
  625. //Load the preview template
  626. templateRoot := "./system/share/"
  627. previewTemplate := ""
  628. if ext == ".mp4" || ext == ".webm" {
  629. previewTemplate = filepath.Join(templateRoot, "video.html")
  630. } else if ext == ".mp3" || ext == ".wav" || ext == ".flac" || ext == ".ogg" {
  631. previewTemplate = filepath.Join(templateRoot, "audio.html")
  632. } else if ext == ".png" || ext == ".jpg" || ext == ".jpeg" || ext == ".webp" {
  633. previewTemplate = filepath.Join(templateRoot, "image.html")
  634. } else if ext == ".pdf" {
  635. previewTemplate = filepath.Join(templateRoot, "iframe.html")
  636. } else {
  637. //Format do not support preview. Use the default.html
  638. previewTemplate = filepath.Join(templateRoot, "default.html")
  639. }
  640. tp, err := ioutil.ReadFile(previewTemplate)
  641. if err != nil {
  642. tp = []byte("")
  643. }
  644. //Merge two templates
  645. content = []byte(strings.ReplaceAll(string(content), "{{previewer}}", string(tp)))
  646. //Get file size
  647. fsize := targetFshAbs.GetFileSize(fileRuntimeAbsPath)
  648. //Get modification time
  649. fmodtime, _ := targetFshAbs.GetModTime(fileRuntimeAbsPath)
  650. timeString := time.Unix(fmodtime, 0).Format("02-01-2006 15:04:05")
  651. //Check if ext match with filepath ext
  652. displayExt := ext
  653. if ext != filepath.Ext(fileRuntimeAbsPath) {
  654. displayExt = filepath.Ext(fileRuntimeAbsPath) + " (" + ext + ")"
  655. }
  656. t := fasttemplate.New(string(content), "{{", "}}")
  657. s := t.ExecuteString(map[string]interface{}{
  658. "hostname": s.options.HostName,
  659. "host": r.Host,
  660. "reqid": id,
  661. "requri": "//" + r.Host + r.URL.Path,
  662. "mime": mime,
  663. "ext": displayExt,
  664. "size": filesystem.GetFileDisplaySize(fsize, 2),
  665. "modtime": timeString,
  666. "downloadurl": "../../share/download/" + id + "/" + filepath.Base(fileRuntimeAbsPath),
  667. "preview_url": "/share/preview/" + id + "/",
  668. "filename": filepath.Base(fileRuntimeAbsPath),
  669. "opg_image": "/share/opg/" + strconv.Itoa(int(time.Now().Unix())) + "/" + id,
  670. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  671. })
  672. w.Write([]byte(s))
  673. return
  674. }
  675. }
  676. } else {
  677. //This share not exists
  678. if directDownload {
  679. //Send 404 header
  680. http.NotFound(w, r)
  681. return
  682. } else {
  683. //Send not found page
  684. content, err := ioutil.ReadFile("./system/share/notfound.html")
  685. if err != nil {
  686. http.NotFound(w, r)
  687. return
  688. }
  689. t := fasttemplate.New(string(content), "{{", "}}")
  690. s := t.ExecuteString(map[string]interface{}{
  691. "hostname": s.options.HostName,
  692. "reqid": id,
  693. "reqtime": strconv.Itoa(int(time.Now().Unix())),
  694. })
  695. w.Write([]byte(s))
  696. return
  697. }
  698. }
  699. }
  700. //Check if a file is shared
  701. func (s *Manager) HandleShareCheck(w http.ResponseWriter, r *http.Request) {
  702. //Get the vpath from paramters
  703. vpath, err := mv(r, "path", true)
  704. if err != nil {
  705. sendErrorResponse(w, "Invalid path given")
  706. return
  707. }
  708. //Get userinfo
  709. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  710. if err != nil {
  711. sendErrorResponse(w, "User not logged in")
  712. return
  713. }
  714. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  715. pathHash := shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
  716. type Result struct {
  717. IsShared bool
  718. ShareUUID *shareEntry.ShareOption
  719. }
  720. //Check if share exists
  721. shareExists := s.options.ShareEntryTable.FileIsShared(pathHash)
  722. if !shareExists {
  723. //Share not exists
  724. js, _ := json.Marshal(Result{
  725. IsShared: false,
  726. ShareUUID: &shareEntry.ShareOption{},
  727. })
  728. sendJSONResponse(w, string(js))
  729. } else {
  730. //Share exists
  731. thisSharedInfo := s.options.ShareEntryTable.GetShareObjectFromPathHash(pathHash)
  732. js, _ := json.Marshal(Result{
  733. IsShared: true,
  734. ShareUUID: thisSharedInfo,
  735. })
  736. sendJSONResponse(w, string(js))
  737. }
  738. }
  739. //Create new share from the given path
  740. func (s *Manager) HandleCreateNewShare(w http.ResponseWriter, r *http.Request) {
  741. //Get the vpath from paramters
  742. vpath, err := mv(r, "path", true)
  743. if err != nil {
  744. sendErrorResponse(w, "Invalid path given")
  745. return
  746. }
  747. //Get userinfo
  748. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  749. if err != nil {
  750. sendErrorResponse(w, "User not logged in")
  751. return
  752. }
  753. //Get the target fsh that this vpath come from
  754. vpathSourceFsh := userinfo.GetRootFSHFromVpathInUserScope(vpath)
  755. if vpathSourceFsh == nil {
  756. sendErrorResponse(w, "Invalid vpath given")
  757. return
  758. }
  759. share, err := s.CreateNewShare(userinfo, vpathSourceFsh, vpath)
  760. if err != nil {
  761. sendErrorResponse(w, err.Error())
  762. return
  763. }
  764. js, _ := json.Marshal(share)
  765. sendJSONResponse(w, string(js))
  766. }
  767. // Handle Share Edit.
  768. // For allowing groups / users, use the following syntax
  769. // groups:group1,group2,group3
  770. // users:user1,user2,user3
  771. // For basic modes, use the following keywords
  772. // anyone / signedin / samegroup
  773. // anyone: Anyone who has the link
  774. // signedin: Anyone logged in to this system
  775. // samegroup: The requesting user has the same (or more) user group as the share owner
  776. func (s *Manager) HandleEditShare(w http.ResponseWriter, r *http.Request) {
  777. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  778. if err != nil {
  779. sendErrorResponse(w, "User not logged in")
  780. return
  781. }
  782. uuid, err := mv(r, "uuid", true)
  783. if err != nil {
  784. sendErrorResponse(w, "Invalid path given")
  785. return
  786. }
  787. shareMode, _ := mv(r, "mode", true)
  788. if shareMode == "" {
  789. shareMode = "signedin"
  790. }
  791. //Check if share exists
  792. so := s.options.ShareEntryTable.GetShareObjectFromUUID(uuid)
  793. if so == nil {
  794. //This share url not exists
  795. sendErrorResponse(w, "Share UUID not exists")
  796. return
  797. }
  798. //Check if the user has permission to edit this share
  799. if so.Owner != userinfo.Username && !userinfo.IsAdmin() {
  800. //This file is not shared by this user and this user is not admin. Block this request
  801. sendErrorResponse(w, "Permission denied")
  802. return
  803. }
  804. //Validate and extract the storage mode
  805. ok, sharetype, settings := validateShareModes(shareMode)
  806. if !ok {
  807. sendErrorResponse(w, "Invalid share setting")
  808. return
  809. }
  810. //Analysis the sharetype
  811. if sharetype == "anyone" || sharetype == "signedin" || sharetype == "samegroup" {
  812. //Basic types.
  813. so.Permission = sharetype
  814. if sharetype == "samegroup" {
  815. //Write user groups into accessible (Must be all match inorder to allow access)
  816. userpg := []string{}
  817. for _, pg := range userinfo.PermissionGroup {
  818. userpg = append(userpg, pg.Name)
  819. }
  820. so.Accessibles = userpg
  821. }
  822. //Write changes to database
  823. s.options.ShareEntryTable.Database.Write("share", uuid, so)
  824. } else if sharetype == "groups" || sharetype == "users" {
  825. //Username or group is listed = ok
  826. so.Permission = sharetype
  827. so.Accessibles = settings
  828. //Write changes to database
  829. s.options.ShareEntryTable.Database.Write("share", uuid, so)
  830. }
  831. sendOK(w)
  832. }
  833. func (s *Manager) HandleDeleteShare(w http.ResponseWriter, r *http.Request) {
  834. //Get the vpath from paramters
  835. vpath, err := mv(r, "path", true)
  836. if err != nil {
  837. sendErrorResponse(w, "Invalid path given")
  838. return
  839. }
  840. //Get userinfo
  841. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  842. if err != nil {
  843. sendErrorResponse(w, "User not logged in")
  844. return
  845. }
  846. //Delete the share setting
  847. err = s.DeleteShare(userinfo, vpath)
  848. if err != nil {
  849. sendErrorResponse(w, err.Error())
  850. } else {
  851. sendOK(w)
  852. }
  853. }
  854. func (s *Manager) HandleListAllShares(w http.ResponseWriter, r *http.Request) {
  855. userinfo, err := s.options.UserHandler.GetUserInfoFromRequest(w, r)
  856. if err != nil {
  857. common.SendErrorResponse(w, "User not logged in")
  858. return
  859. }
  860. fshId, _ := common.Mv(r, "fsh", false)
  861. results := []*shareEntry.ShareOption{}
  862. if fshId == "" {
  863. //List all
  864. allFsh := userinfo.GetAllFileSystemHandler()
  865. for _, thisFsh := range allFsh {
  866. allShares := s.ListAllShareByFshId(thisFsh.UUID, userinfo)
  867. for _, thisShare := range allShares {
  868. if s.ShareIsValid(thisShare) {
  869. results = append(results, thisShare)
  870. }
  871. }
  872. }
  873. } else {
  874. //List fsh onlya
  875. targetFsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(fshId)
  876. if err != nil {
  877. common.SendErrorResponse(w, err.Error())
  878. return
  879. }
  880. sharesInThisFsh := s.ListAllShareByFshId(targetFsh.UUID, userinfo)
  881. for _, thisShare := range sharesInThisFsh {
  882. if s.ShareIsValid(thisShare) {
  883. results = append(results, thisShare)
  884. }
  885. }
  886. }
  887. js, _ := json.Marshal(results)
  888. common.SendJSONResponse(w, string(js))
  889. }
  890. //Craete a new file or folder share
  891. func (s *Manager) CreateNewShare(userinfo *user.User, srcFsh *filesystem.FileSystemHandler, vpath string) (*shareEntry.ShareOption, error) {
  892. //Translate the vpath to realpath
  893. return s.options.ShareEntryTable.CreateNewShare(srcFsh, vpath, userinfo.Username, userinfo.GetUserPermissionGroupNames())
  894. }
  895. func ServePermissionDeniedPage(w http.ResponseWriter) {
  896. w.WriteHeader(http.StatusForbidden)
  897. pageContent := []byte("Permissioned Denied")
  898. if fileExists("system/share/permissionDenied.html") {
  899. content, err := ioutil.ReadFile("system/share/permissionDenied.html")
  900. if err == nil {
  901. pageContent = content
  902. }
  903. }
  904. w.Write([]byte(pageContent))
  905. }
  906. /*
  907. Validate Share Mode string
  908. will return
  909. 1. bool => Is valid
  910. 2. permission type: {basic / groups / users}
  911. 3. mode string
  912. */
  913. func validateShareModes(mode string) (bool, string, []string) {
  914. // user:a,b,c,d
  915. validModes := []string{"anyone", "signedin", "samegroup"}
  916. if inArray(validModes, mode) {
  917. //Standard modes
  918. return true, mode, []string{}
  919. } else if len(mode) > 7 && mode[:7] == "groups:" {
  920. //Handle custom group case like groups:a,b,c,d
  921. groupList := mode[7:]
  922. if len(groupList) > 0 {
  923. groups := strings.Split(groupList, ",")
  924. return true, "groups", groups
  925. } else {
  926. //Invalid configuration
  927. return false, "groups", []string{}
  928. }
  929. } else if len(mode) > 6 && mode[:6] == "users:" {
  930. //Handle custom usersname like users:a,b,c,d
  931. userList := mode[6:]
  932. if len(userList) > 0 {
  933. users := strings.Split(userList, ",")
  934. return true, "users", users
  935. } else {
  936. //Invalid configuration
  937. return false, "users", []string{}
  938. }
  939. }
  940. return false, "", []string{}
  941. }
  942. func (s *Manager) ListAllShareByFshId(fshId string, userinfo *user.User) []*shareEntry.ShareOption {
  943. results := []*shareEntry.ShareOption{}
  944. s.options.ShareEntryTable.FileToUrlMap.Range(func(k, v interface{}) bool {
  945. thisShareOption := v.(*shareEntry.ShareOption)
  946. if (!userinfo.IsAdmin() && thisShareOption.IsAccessibleBy(userinfo.Username, userinfo.GetUserPermissionGroupNames())) || userinfo.IsAdmin() {
  947. id, _, _ := filesystem.GetIDFromVirtualPath(thisShareOption.FileVirtualPath)
  948. if id == fshId {
  949. results = append(results, thisShareOption)
  950. }
  951. }
  952. return true
  953. })
  954. return results
  955. }
  956. func (s *Manager) ShareIsValid(thisShareOption *shareEntry.ShareOption) bool {
  957. vpath := thisShareOption.FileVirtualPath
  958. userinfo, _ := s.options.UserHandler.GetUserInfoFromUsername(thisShareOption.Owner)
  959. fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  960. if err != nil {
  961. return false
  962. }
  963. fshAbs := fsh.FileSystemAbstraction
  964. rpath, _ := fshAbs.VirtualPathToRealPath(vpath, userinfo.Username)
  965. if !fshAbs.FileExists(rpath) {
  966. return false
  967. }
  968. return true
  969. }
  970. func (s *Manager) GetPathHashFromShare(thisShareOption *shareEntry.ShareOption) (string, error) {
  971. vpath := thisShareOption.FileVirtualPath
  972. userinfo, _ := s.options.UserHandler.GetUserInfoFromUsername(thisShareOption.Owner)
  973. fsh, err := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  974. if err != nil {
  975. return "", err
  976. }
  977. pathHash := shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
  978. return pathHash, nil
  979. }
  980. //Check and clear shares that its pointinf files no longe exists
  981. func (s *Manager) ValidateAndClearShares() {
  982. //Iterate through all shares within the system
  983. s.options.ShareEntryTable.FileToUrlMap.Range(func(k, v interface{}) bool {
  984. thisShareOption := v.(*shareEntry.ShareOption)
  985. pathHash, err := s.GetPathHashFromShare(thisShareOption)
  986. if err != nil {
  987. //Unable to resolve path hash. Filesystem handler is gone?
  988. //s.options.ShareEntryTable.RemoveShareByUUID(thisShareOption.UUID)
  989. return true
  990. }
  991. if !s.ShareIsValid(thisShareOption) {
  992. //This share source file don't exists anymore. Remove it
  993. s.options.ShareEntryTable.RemoveShareByPathHash(pathHash)
  994. log.Println("*Share* Removing share to file: " + thisShareOption.FileRealPath + " as it no longer exists")
  995. }
  996. return true
  997. })
  998. }
  999. func (s *Manager) DeleteShare(userinfo *user.User, vpath string) error {
  1000. ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
  1001. return s.options.ShareEntryTable.DeleteShareByPathHash(ps)
  1002. }
  1003. func (s *Manager) GetShareUUIDFromUserAndVpath(userinfo *user.User, vpath string) string {
  1004. ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
  1005. return s.options.ShareEntryTable.GetShareUUIDFromPathHash(ps)
  1006. }
  1007. func (s *Manager) GetShareObjectFromUserAndVpath(userinfo *user.User, vpath string) *shareEntry.ShareOption {
  1008. ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
  1009. return s.options.ShareEntryTable.GetShareObjectFromPathHash(ps)
  1010. }
  1011. func (s *Manager) GetShareObjectFromUUID(uuid string) *shareEntry.ShareOption {
  1012. return s.options.ShareEntryTable.GetShareObjectFromUUID(uuid)
  1013. }
  1014. func (s *Manager) FileIsShared(userinfo *user.User, vpath string) bool {
  1015. ps := getPathHashFromUsernameAndVpath(userinfo, vpath)
  1016. return s.options.ShareEntryTable.FileIsShared(ps)
  1017. }
  1018. func (s *Manager) RemoveShareByUUID(uuid string) error {
  1019. return s.options.ShareEntryTable.RemoveShareByUUID(uuid)
  1020. }
  1021. func getPathHashFromUsernameAndVpath(userinfo *user.User, vpath string) string {
  1022. fsh, _ := userinfo.GetFileSystemHandlerFromVirtualPath(vpath)
  1023. return shareEntry.GetPathHash(fsh, vpath, userinfo.Username)
  1024. }