fs.go 39 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453
  1. package fasthttp
  2. import (
  3. "bytes"
  4. "errors"
  5. "fmt"
  6. "html"
  7. "io"
  8. "mime"
  9. "net/http"
  10. "os"
  11. "path/filepath"
  12. "sort"
  13. "strings"
  14. "sync"
  15. "time"
  16. "github.com/andybalholm/brotli"
  17. "github.com/klauspost/compress/gzip"
  18. "github.com/valyala/bytebufferpool"
  19. )
  20. // ServeFileBytesUncompressed returns HTTP response containing file contents
  21. // from the given path.
  22. //
  23. // Directory contents is returned if path points to directory.
  24. //
  25. // ServeFileBytes may be used for saving network traffic when serving files
  26. // with good compression ratio.
  27. //
  28. // See also RequestCtx.SendFileBytes.
  29. //
  30. // WARNING: do not pass any user supplied paths to this function!
  31. // WARNING: if path is based on user input users will be able to request
  32. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  33. func ServeFileBytesUncompressed(ctx *RequestCtx, path []byte) {
  34. ServeFileUncompressed(ctx, b2s(path))
  35. }
  36. // ServeFileUncompressed returns HTTP response containing file contents
  37. // from the given path.
  38. //
  39. // Directory contents is returned if path points to directory.
  40. //
  41. // ServeFile may be used for saving network traffic when serving files
  42. // with good compression ratio.
  43. //
  44. // See also RequestCtx.SendFile.
  45. //
  46. // WARNING: do not pass any user supplied paths to this function!
  47. // WARNING: if path is based on user input users will be able to request
  48. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  49. func ServeFileUncompressed(ctx *RequestCtx, path string) {
  50. ctx.Request.Header.DelBytes(strAcceptEncoding)
  51. ServeFile(ctx, path)
  52. }
  53. // ServeFileBytes returns HTTP response containing compressed file contents
  54. // from the given path.
  55. //
  56. // HTTP response may contain uncompressed file contents in the following cases:
  57. //
  58. // - Missing 'Accept-Encoding: gzip' request header.
  59. // - No write access to directory containing the file.
  60. //
  61. // Directory contents is returned if path points to directory.
  62. //
  63. // Use ServeFileBytesUncompressed is you don't need serving compressed
  64. // file contents.
  65. //
  66. // See also RequestCtx.SendFileBytes.
  67. //
  68. // WARNING: do not pass any user supplied paths to this function!
  69. // WARNING: if path is based on user input users will be able to request
  70. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  71. func ServeFileBytes(ctx *RequestCtx, path []byte) {
  72. ServeFile(ctx, b2s(path))
  73. }
  74. // ServeFile returns HTTP response containing compressed file contents
  75. // from the given path.
  76. //
  77. // HTTP response may contain uncompressed file contents in the following cases:
  78. //
  79. // - Missing 'Accept-Encoding: gzip' request header.
  80. // - No write access to directory containing the file.
  81. //
  82. // Directory contents is returned if path points to directory.
  83. //
  84. // Use ServeFileUncompressed is you don't need serving compressed file contents.
  85. //
  86. // See also RequestCtx.SendFile.
  87. //
  88. // WARNING: do not pass any user supplied paths to this function!
  89. // WARNING: if path is based on user input users will be able to request
  90. // any file on your filesystem! Use fasthttp.FS with a sane Root instead.
  91. func ServeFile(ctx *RequestCtx, path string) {
  92. rootFSOnce.Do(func() {
  93. rootFSHandler = rootFS.NewRequestHandler()
  94. })
  95. if len(path) == 0 || !filepath.IsAbs(path) {
  96. // extend relative path to absolute path
  97. hasTrailingSlash := len(path) > 0 && (path[len(path)-1] == '/' || path[len(path)-1] == '\\')
  98. var err error
  99. path = filepath.FromSlash(path)
  100. if path, err = filepath.Abs(path); err != nil {
  101. ctx.Logger().Printf("cannot resolve path %q to absolute file path: %v", path, err)
  102. ctx.Error("Internal Server Error", StatusInternalServerError)
  103. return
  104. }
  105. if hasTrailingSlash {
  106. path += "/"
  107. }
  108. }
  109. // convert the path to forward slashes regardless the OS in order to set the URI properly
  110. // the handler will convert back to OS path separator before opening the file
  111. path = filepath.ToSlash(path)
  112. ctx.Request.SetRequestURI(path)
  113. rootFSHandler(ctx)
  114. }
  115. var (
  116. rootFSOnce sync.Once
  117. rootFS = &FS{
  118. Root: "",
  119. AllowEmptyRoot: true,
  120. GenerateIndexPages: true,
  121. Compress: true,
  122. CompressBrotli: true,
  123. AcceptByteRange: true,
  124. }
  125. rootFSHandler RequestHandler
  126. )
  127. // PathRewriteFunc must return new request path based on arbitrary ctx
  128. // info such as ctx.Path().
  129. //
  130. // Path rewriter is used in FS for translating the current request
  131. // to the local filesystem path relative to FS.Root.
  132. //
  133. // The returned path must not contain '/../' substrings due to security reasons,
  134. // since such paths may refer files outside FS.Root.
  135. //
  136. // The returned path may refer to ctx members. For example, ctx.Path().
  137. type PathRewriteFunc func(ctx *RequestCtx) []byte
  138. // NewVHostPathRewriter returns path rewriter, which strips slashesCount
  139. // leading slashes from the path and prepends the path with request's host,
  140. // thus simplifying virtual hosting for static files.
  141. //
  142. // Examples:
  143. //
  144. // - host=foobar.com, slashesCount=0, original path="/foo/bar".
  145. // Resulting path: "/foobar.com/foo/bar"
  146. //
  147. // - host=img.aaa.com, slashesCount=1, original path="/images/123/456.jpg"
  148. // Resulting path: "/img.aaa.com/123/456.jpg"
  149. func NewVHostPathRewriter(slashesCount int) PathRewriteFunc {
  150. return func(ctx *RequestCtx) []byte {
  151. path := stripLeadingSlashes(ctx.Path(), slashesCount)
  152. host := ctx.Host()
  153. if n := bytes.IndexByte(host, '/'); n >= 0 {
  154. host = nil
  155. }
  156. if len(host) == 0 {
  157. host = strInvalidHost
  158. }
  159. b := bytebufferpool.Get()
  160. b.B = append(b.B, '/')
  161. b.B = append(b.B, host...)
  162. b.B = append(b.B, path...)
  163. ctx.URI().SetPathBytes(b.B)
  164. bytebufferpool.Put(b)
  165. return ctx.Path()
  166. }
  167. }
  168. var strInvalidHost = []byte("invalid-host")
  169. // NewPathSlashesStripper returns path rewriter, which strips slashesCount
  170. // leading slashes from the path.
  171. //
  172. // Examples:
  173. //
  174. // - slashesCount = 0, original path: "/foo/bar", result: "/foo/bar"
  175. // - slashesCount = 1, original path: "/foo/bar", result: "/bar"
  176. // - slashesCount = 2, original path: "/foo/bar", result: ""
  177. //
  178. // The returned path rewriter may be used as FS.PathRewrite .
  179. func NewPathSlashesStripper(slashesCount int) PathRewriteFunc {
  180. return func(ctx *RequestCtx) []byte {
  181. return stripLeadingSlashes(ctx.Path(), slashesCount)
  182. }
  183. }
  184. // NewPathPrefixStripper returns path rewriter, which removes prefixSize bytes
  185. // from the path prefix.
  186. //
  187. // Examples:
  188. //
  189. // - prefixSize = 0, original path: "/foo/bar", result: "/foo/bar"
  190. // - prefixSize = 3, original path: "/foo/bar", result: "o/bar"
  191. // - prefixSize = 7, original path: "/foo/bar", result: "r"
  192. //
  193. // The returned path rewriter may be used as FS.PathRewrite .
  194. func NewPathPrefixStripper(prefixSize int) PathRewriteFunc {
  195. return func(ctx *RequestCtx) []byte {
  196. path := ctx.Path()
  197. if len(path) >= prefixSize {
  198. path = path[prefixSize:]
  199. }
  200. return path
  201. }
  202. }
  203. // FS represents settings for request handler serving static files
  204. // from the local filesystem.
  205. //
  206. // It is prohibited copying FS values. Create new values instead.
  207. type FS struct {
  208. noCopy noCopy //nolint:unused,structcheck
  209. // Path to the root directory to serve files from.
  210. Root string
  211. // AllowEmptyRoot controls what happens when Root is empty. When false (default) it will default to the
  212. // current working directory. An empty root is mostly useful when you want to use absolute paths
  213. // on windows that are on different filesystems. On linux setting your Root to "/" already allows you to use
  214. // absolute paths on any filesystem.
  215. AllowEmptyRoot bool
  216. // List of index file names to try opening during directory access.
  217. //
  218. // For example:
  219. //
  220. // * index.html
  221. // * index.htm
  222. // * my-super-index.xml
  223. //
  224. // By default the list is empty.
  225. IndexNames []string
  226. // Index pages for directories without files matching IndexNames
  227. // are automatically generated if set.
  228. //
  229. // Directory index generation may be quite slow for directories
  230. // with many files (more than 1K), so it is discouraged enabling
  231. // index pages' generation for such directories.
  232. //
  233. // By default index pages aren't generated.
  234. GenerateIndexPages bool
  235. // Transparently compresses responses if set to true.
  236. //
  237. // The server tries minimizing CPU usage by caching compressed files.
  238. // It adds CompressedFileSuffix suffix to the original file name and
  239. // tries saving the resulting compressed file under the new file name.
  240. // So it is advisable to give the server write access to Root
  241. // and to all inner folders in order to minimize CPU usage when serving
  242. // compressed responses.
  243. //
  244. // Transparent compression is disabled by default.
  245. Compress bool
  246. // Uses brotli encoding and fallbacks to gzip in responses if set to true, uses gzip if set to false.
  247. //
  248. // This value has sense only if Compress is set.
  249. //
  250. // Brotli encoding is disabled by default.
  251. CompressBrotli bool
  252. // Path to the compressed root directory to serve files from. If this value
  253. // is empty, Root is used.
  254. CompressRoot string
  255. // Enables byte range requests if set to true.
  256. //
  257. // Byte range requests are disabled by default.
  258. AcceptByteRange bool
  259. // Path rewriting function.
  260. //
  261. // By default request path is not modified.
  262. PathRewrite PathRewriteFunc
  263. // PathNotFound fires when file is not found in filesystem
  264. // this functions tries to replace "Cannot open requested path"
  265. // server response giving to the programmer the control of server flow.
  266. //
  267. // By default PathNotFound returns
  268. // "Cannot open requested path"
  269. PathNotFound RequestHandler
  270. // Expiration duration for inactive file handlers.
  271. //
  272. // FSHandlerCacheDuration is used by default.
  273. CacheDuration time.Duration
  274. // Suffix to add to the name of cached compressed file.
  275. //
  276. // This value has sense only if Compress is set.
  277. //
  278. // FSCompressedFileSuffix is used by default.
  279. CompressedFileSuffix string
  280. // Suffixes list to add to compressedFileSuffix depending on encoding
  281. //
  282. // This value has sense only if Compress is set.
  283. //
  284. // FSCompressedFileSuffixes is used by default.
  285. CompressedFileSuffixes map[string]string
  286. // If CleanStop is set, the channel can be closed to stop the cleanup handlers
  287. // for the FS RequestHandlers created with NewRequestHandler.
  288. // NEVER close this channel while the handler is still being used!
  289. CleanStop chan struct{}
  290. once sync.Once
  291. h RequestHandler
  292. }
  293. // FSCompressedFileSuffix is the suffix FS adds to the original file names
  294. // when trying to store compressed file under the new file name.
  295. // See FS.Compress for details.
  296. const FSCompressedFileSuffix = ".fasthttp.gz"
  297. // FSCompressedFileSuffixes is the suffixes FS adds to the original file names depending on encoding
  298. // when trying to store compressed file under the new file name.
  299. // See FS.Compress for details.
  300. var FSCompressedFileSuffixes = map[string]string{
  301. "gzip": ".fasthttp.gz",
  302. "br": ".fasthttp.br",
  303. }
  304. // FSHandlerCacheDuration is the default expiration duration for inactive
  305. // file handlers opened by FS.
  306. const FSHandlerCacheDuration = 10 * time.Second
  307. // FSHandler returns request handler serving static files from
  308. // the given root folder.
  309. //
  310. // stripSlashes indicates how many leading slashes must be stripped
  311. // from requested path before searching requested file in the root folder.
  312. // Examples:
  313. //
  314. // - stripSlashes = 0, original path: "/foo/bar", result: "/foo/bar"
  315. // - stripSlashes = 1, original path: "/foo/bar", result: "/bar"
  316. // - stripSlashes = 2, original path: "/foo/bar", result: ""
  317. //
  318. // The returned request handler automatically generates index pages
  319. // for directories without index.html.
  320. //
  321. // The returned handler caches requested file handles
  322. // for FSHandlerCacheDuration.
  323. // Make sure your program has enough 'max open files' limit aka
  324. // 'ulimit -n' if root folder contains many files.
  325. //
  326. // Do not create multiple request handler instances for the same
  327. // (root, stripSlashes) arguments - just reuse a single instance.
  328. // Otherwise goroutine leak will occur.
  329. func FSHandler(root string, stripSlashes int) RequestHandler {
  330. fs := &FS{
  331. Root: root,
  332. IndexNames: []string{"index.html"},
  333. GenerateIndexPages: true,
  334. AcceptByteRange: true,
  335. }
  336. if stripSlashes > 0 {
  337. fs.PathRewrite = NewPathSlashesStripper(stripSlashes)
  338. }
  339. return fs.NewRequestHandler()
  340. }
  341. // NewRequestHandler returns new request handler with the given FS settings.
  342. //
  343. // The returned handler caches requested file handles
  344. // for FS.CacheDuration.
  345. // Make sure your program has enough 'max open files' limit aka
  346. // 'ulimit -n' if FS.Root folder contains many files.
  347. //
  348. // Do not create multiple request handlers from a single FS instance -
  349. // just reuse a single request handler.
  350. func (fs *FS) NewRequestHandler() RequestHandler {
  351. fs.once.Do(fs.initRequestHandler)
  352. return fs.h
  353. }
  354. func (fs *FS) normalizeRoot(root string) string {
  355. // Serve files from the current working directory if Root is empty or if Root is a relative path.
  356. if (!fs.AllowEmptyRoot && len(root) == 0) || (len(root) > 0 && !filepath.IsAbs(root)) {
  357. path, err := os.Getwd()
  358. if err != nil {
  359. path = "."
  360. }
  361. root = path + "/" + root
  362. }
  363. // convert the root directory slashes to the native format
  364. root = filepath.FromSlash(root)
  365. // strip trailing slashes from the root path
  366. for len(root) > 0 && root[len(root)-1] == os.PathSeparator {
  367. root = root[:len(root)-1]
  368. }
  369. return root
  370. }
  371. func (fs *FS) initRequestHandler() {
  372. root := fs.normalizeRoot(fs.Root)
  373. compressRoot := fs.CompressRoot
  374. if len(compressRoot) == 0 {
  375. compressRoot = root
  376. } else {
  377. compressRoot = fs.normalizeRoot(compressRoot)
  378. }
  379. cacheDuration := fs.CacheDuration
  380. if cacheDuration <= 0 {
  381. cacheDuration = FSHandlerCacheDuration
  382. }
  383. compressedFileSuffixes := fs.CompressedFileSuffixes
  384. if len(compressedFileSuffixes["br"]) == 0 || len(compressedFileSuffixes["gzip"]) == 0 ||
  385. compressedFileSuffixes["br"] == compressedFileSuffixes["gzip"] {
  386. compressedFileSuffixes = FSCompressedFileSuffixes
  387. }
  388. if len(fs.CompressedFileSuffix) > 0 {
  389. compressedFileSuffixes["gzip"] = fs.CompressedFileSuffix
  390. compressedFileSuffixes["br"] = FSCompressedFileSuffixes["br"]
  391. }
  392. h := &fsHandler{
  393. root: root,
  394. indexNames: fs.IndexNames,
  395. pathRewrite: fs.PathRewrite,
  396. generateIndexPages: fs.GenerateIndexPages,
  397. compress: fs.Compress,
  398. compressBrotli: fs.CompressBrotli,
  399. compressRoot: compressRoot,
  400. pathNotFound: fs.PathNotFound,
  401. acceptByteRange: fs.AcceptByteRange,
  402. cacheDuration: cacheDuration,
  403. compressedFileSuffixes: compressedFileSuffixes,
  404. cache: make(map[string]*fsFile),
  405. cacheBrotli: make(map[string]*fsFile),
  406. cacheGzip: make(map[string]*fsFile),
  407. }
  408. go func() {
  409. var pendingFiles []*fsFile
  410. clean := func() {
  411. pendingFiles = h.cleanCache(pendingFiles)
  412. }
  413. if fs.CleanStop != nil {
  414. t := time.NewTicker(cacheDuration / 2)
  415. for {
  416. select {
  417. case <-t.C:
  418. clean()
  419. case _, stillOpen := <-fs.CleanStop:
  420. // Ignore values send on the channel, only stop when it is closed.
  421. if !stillOpen {
  422. t.Stop()
  423. return
  424. }
  425. }
  426. }
  427. }
  428. for {
  429. time.Sleep(cacheDuration / 2)
  430. clean()
  431. }
  432. }()
  433. fs.h = h.handleRequest
  434. }
  435. type fsHandler struct {
  436. root string
  437. indexNames []string
  438. pathRewrite PathRewriteFunc
  439. pathNotFound RequestHandler
  440. generateIndexPages bool
  441. compress bool
  442. compressBrotli bool
  443. compressRoot string
  444. acceptByteRange bool
  445. cacheDuration time.Duration
  446. compressedFileSuffixes map[string]string
  447. cache map[string]*fsFile
  448. cacheBrotli map[string]*fsFile
  449. cacheGzip map[string]*fsFile
  450. cacheLock sync.Mutex
  451. smallFileReaderPool sync.Pool
  452. }
  453. type fsFile struct {
  454. h *fsHandler
  455. f *os.File
  456. dirIndex []byte
  457. contentType string
  458. contentLength int
  459. compressed bool
  460. lastModified time.Time
  461. lastModifiedStr []byte
  462. t time.Time
  463. readersCount int
  464. bigFiles []*bigFileReader
  465. bigFilesLock sync.Mutex
  466. }
  467. func (ff *fsFile) NewReader() (io.Reader, error) {
  468. if ff.isBig() {
  469. r, err := ff.bigFileReader()
  470. if err != nil {
  471. ff.decReadersCount()
  472. }
  473. return r, err
  474. }
  475. return ff.smallFileReader()
  476. }
  477. func (ff *fsFile) smallFileReader() (io.Reader, error) {
  478. v := ff.h.smallFileReaderPool.Get()
  479. if v == nil {
  480. v = &fsSmallFileReader{}
  481. }
  482. r := v.(*fsSmallFileReader)
  483. r.ff = ff
  484. r.endPos = ff.contentLength
  485. if r.startPos > 0 {
  486. return nil, errors.New("bug: fsSmallFileReader with non-nil startPos found in the pool")
  487. }
  488. return r, nil
  489. }
  490. // files bigger than this size are sent with sendfile
  491. const maxSmallFileSize = 2 * 4096
  492. func (ff *fsFile) isBig() bool {
  493. return ff.contentLength > maxSmallFileSize && len(ff.dirIndex) == 0
  494. }
  495. func (ff *fsFile) bigFileReader() (io.Reader, error) {
  496. if ff.f == nil {
  497. return nil, errors.New("bug: ff.f must be non-nil in bigFileReader")
  498. }
  499. var r io.Reader
  500. ff.bigFilesLock.Lock()
  501. n := len(ff.bigFiles)
  502. if n > 0 {
  503. r = ff.bigFiles[n-1]
  504. ff.bigFiles = ff.bigFiles[:n-1]
  505. }
  506. ff.bigFilesLock.Unlock()
  507. if r != nil {
  508. return r, nil
  509. }
  510. f, err := os.Open(ff.f.Name())
  511. if err != nil {
  512. return nil, fmt.Errorf("cannot open already opened file: %w", err)
  513. }
  514. return &bigFileReader{
  515. f: f,
  516. ff: ff,
  517. r: f,
  518. }, nil
  519. }
  520. func (ff *fsFile) Release() {
  521. if ff.f != nil {
  522. _ = ff.f.Close()
  523. if ff.isBig() {
  524. ff.bigFilesLock.Lock()
  525. for _, r := range ff.bigFiles {
  526. _ = r.f.Close()
  527. }
  528. ff.bigFilesLock.Unlock()
  529. }
  530. }
  531. }
  532. func (ff *fsFile) decReadersCount() {
  533. ff.h.cacheLock.Lock()
  534. ff.readersCount--
  535. if ff.readersCount < 0 {
  536. panic("BUG: negative fsFile.readersCount!")
  537. }
  538. ff.h.cacheLock.Unlock()
  539. }
  540. // bigFileReader attempts to trigger sendfile
  541. // for sending big files over the wire.
  542. type bigFileReader struct {
  543. f *os.File
  544. ff *fsFile
  545. r io.Reader
  546. lr io.LimitedReader
  547. }
  548. func (r *bigFileReader) UpdateByteRange(startPos, endPos int) error {
  549. if _, err := r.f.Seek(int64(startPos), 0); err != nil {
  550. return err
  551. }
  552. r.r = &r.lr
  553. r.lr.R = r.f
  554. r.lr.N = int64(endPos - startPos + 1)
  555. return nil
  556. }
  557. func (r *bigFileReader) Read(p []byte) (int, error) {
  558. return r.r.Read(p)
  559. }
  560. func (r *bigFileReader) WriteTo(w io.Writer) (int64, error) {
  561. if rf, ok := w.(io.ReaderFrom); ok {
  562. // fast path. Send file must be triggered
  563. return rf.ReadFrom(r.r)
  564. }
  565. // slow path
  566. return copyZeroAlloc(w, r.r)
  567. }
  568. func (r *bigFileReader) Close() error {
  569. r.r = r.f
  570. n, err := r.f.Seek(0, 0)
  571. if err == nil {
  572. if n == 0 {
  573. ff := r.ff
  574. ff.bigFilesLock.Lock()
  575. ff.bigFiles = append(ff.bigFiles, r)
  576. ff.bigFilesLock.Unlock()
  577. } else {
  578. _ = r.f.Close()
  579. err = errors.New("bug: File.Seek(0,0) returned (non-zero, nil)")
  580. }
  581. } else {
  582. _ = r.f.Close()
  583. }
  584. r.ff.decReadersCount()
  585. return err
  586. }
  587. type fsSmallFileReader struct {
  588. ff *fsFile
  589. startPos int
  590. endPos int
  591. }
  592. func (r *fsSmallFileReader) Close() error {
  593. ff := r.ff
  594. ff.decReadersCount()
  595. r.ff = nil
  596. r.startPos = 0
  597. r.endPos = 0
  598. ff.h.smallFileReaderPool.Put(r)
  599. return nil
  600. }
  601. func (r *fsSmallFileReader) UpdateByteRange(startPos, endPos int) error {
  602. r.startPos = startPos
  603. r.endPos = endPos + 1
  604. return nil
  605. }
  606. func (r *fsSmallFileReader) Read(p []byte) (int, error) {
  607. tailLen := r.endPos - r.startPos
  608. if tailLen <= 0 {
  609. return 0, io.EOF
  610. }
  611. if len(p) > tailLen {
  612. p = p[:tailLen]
  613. }
  614. ff := r.ff
  615. if ff.f != nil {
  616. n, err := ff.f.ReadAt(p, int64(r.startPos))
  617. r.startPos += n
  618. return n, err
  619. }
  620. n := copy(p, ff.dirIndex[r.startPos:])
  621. r.startPos += n
  622. return n, nil
  623. }
  624. func (r *fsSmallFileReader) WriteTo(w io.Writer) (int64, error) {
  625. ff := r.ff
  626. var n int
  627. var err error
  628. if ff.f == nil {
  629. n, err = w.Write(ff.dirIndex[r.startPos:r.endPos])
  630. return int64(n), err
  631. }
  632. if rf, ok := w.(io.ReaderFrom); ok {
  633. return rf.ReadFrom(r)
  634. }
  635. curPos := r.startPos
  636. bufv := copyBufPool.Get()
  637. buf := bufv.([]byte)
  638. for err == nil {
  639. tailLen := r.endPos - curPos
  640. if tailLen <= 0 {
  641. break
  642. }
  643. if len(buf) > tailLen {
  644. buf = buf[:tailLen]
  645. }
  646. n, err = ff.f.ReadAt(buf, int64(curPos))
  647. nw, errw := w.Write(buf[:n])
  648. curPos += nw
  649. if errw == nil && nw != n {
  650. errw = errors.New("bug: Write(p) returned (n, nil), where n != len(p)")
  651. }
  652. if err == nil {
  653. err = errw
  654. }
  655. }
  656. copyBufPool.Put(bufv)
  657. if err == io.EOF {
  658. err = nil
  659. }
  660. return int64(curPos - r.startPos), err
  661. }
  662. func (h *fsHandler) cleanCache(pendingFiles []*fsFile) []*fsFile {
  663. var filesToRelease []*fsFile
  664. h.cacheLock.Lock()
  665. // Close files which couldn't be closed before due to non-zero
  666. // readers count on the previous run.
  667. var remainingFiles []*fsFile
  668. for _, ff := range pendingFiles {
  669. if ff.readersCount > 0 {
  670. remainingFiles = append(remainingFiles, ff)
  671. } else {
  672. filesToRelease = append(filesToRelease, ff)
  673. }
  674. }
  675. pendingFiles = remainingFiles
  676. pendingFiles, filesToRelease = cleanCacheNolock(h.cache, pendingFiles, filesToRelease, h.cacheDuration)
  677. pendingFiles, filesToRelease = cleanCacheNolock(h.cacheBrotli, pendingFiles, filesToRelease, h.cacheDuration)
  678. pendingFiles, filesToRelease = cleanCacheNolock(h.cacheGzip, pendingFiles, filesToRelease, h.cacheDuration)
  679. h.cacheLock.Unlock()
  680. for _, ff := range filesToRelease {
  681. ff.Release()
  682. }
  683. return pendingFiles
  684. }
  685. func cleanCacheNolock(cache map[string]*fsFile, pendingFiles, filesToRelease []*fsFile, cacheDuration time.Duration) ([]*fsFile, []*fsFile) {
  686. t := time.Now()
  687. for k, ff := range cache {
  688. if t.Sub(ff.t) > cacheDuration {
  689. if ff.readersCount > 0 {
  690. // There are pending readers on stale file handle,
  691. // so we cannot close it. Put it into pendingFiles
  692. // so it will be closed later.
  693. pendingFiles = append(pendingFiles, ff)
  694. } else {
  695. filesToRelease = append(filesToRelease, ff)
  696. }
  697. delete(cache, k)
  698. }
  699. }
  700. return pendingFiles, filesToRelease
  701. }
  702. func (h *fsHandler) pathToFilePath(path string) string {
  703. return filepath.FromSlash(h.root + path)
  704. }
  705. func (h *fsHandler) filePathToCompressed(filePath string) string {
  706. if h.root == h.compressRoot {
  707. return filePath
  708. }
  709. if !strings.HasPrefix(filePath, h.root) {
  710. return filePath
  711. }
  712. return filepath.FromSlash(h.compressRoot + filePath[len(h.root):])
  713. }
  714. func (h *fsHandler) handleRequest(ctx *RequestCtx) {
  715. var path []byte
  716. if h.pathRewrite != nil {
  717. path = h.pathRewrite(ctx)
  718. } else {
  719. path = ctx.Path()
  720. }
  721. hasTrailingSlash := len(path) > 0 && path[len(path)-1] == '/'
  722. path = stripTrailingSlashes(path)
  723. if n := bytes.IndexByte(path, 0); n >= 0 {
  724. ctx.Logger().Printf("cannot serve path with nil byte at position %d: %q", n, path)
  725. ctx.Error("Are you a hacker?", StatusBadRequest)
  726. return
  727. }
  728. if h.pathRewrite != nil {
  729. // There is no need to check for '/../' if path = ctx.Path(),
  730. // since ctx.Path must normalize and sanitize the path.
  731. if n := bytes.Index(path, strSlashDotDotSlash); n >= 0 {
  732. ctx.Logger().Printf("cannot serve path with '/../' at position %d due to security reasons: %q", n, path)
  733. ctx.Error("Internal Server Error", StatusInternalServerError)
  734. return
  735. }
  736. }
  737. mustCompress := false
  738. fileCache := h.cache
  739. fileEncoding := ""
  740. byteRange := ctx.Request.Header.peek(strRange)
  741. if len(byteRange) == 0 && h.compress {
  742. if h.compressBrotli && ctx.Request.Header.HasAcceptEncodingBytes(strBr) {
  743. mustCompress = true
  744. fileCache = h.cacheBrotli
  745. fileEncoding = "br"
  746. } else if ctx.Request.Header.HasAcceptEncodingBytes(strGzip) {
  747. mustCompress = true
  748. fileCache = h.cacheGzip
  749. fileEncoding = "gzip"
  750. }
  751. }
  752. h.cacheLock.Lock()
  753. ff, ok := fileCache[string(path)]
  754. if ok {
  755. ff.readersCount++
  756. }
  757. h.cacheLock.Unlock()
  758. if !ok {
  759. pathStr := string(path)
  760. filePath := h.pathToFilePath(pathStr)
  761. var err error
  762. ff, err = h.openFSFile(filePath, mustCompress, fileEncoding)
  763. if mustCompress && err == errNoCreatePermission {
  764. ctx.Logger().Printf("insufficient permissions for saving compressed file for %q. Serving uncompressed file. "+
  765. "Allow write access to the directory with this file in order to improve fasthttp performance", filePath)
  766. mustCompress = false
  767. ff, err = h.openFSFile(filePath, mustCompress, fileEncoding)
  768. }
  769. if err == errDirIndexRequired {
  770. if !hasTrailingSlash {
  771. ctx.RedirectBytes(append(path, '/'), StatusFound)
  772. return
  773. }
  774. ff, err = h.openIndexFile(ctx, filePath, mustCompress, fileEncoding)
  775. if err != nil {
  776. ctx.Logger().Printf("cannot open dir index %q: %v", filePath, err)
  777. ctx.Error("Directory index is forbidden", StatusForbidden)
  778. return
  779. }
  780. } else if err != nil {
  781. ctx.Logger().Printf("cannot open file %q: %v", filePath, err)
  782. if h.pathNotFound == nil {
  783. ctx.Error("Cannot open requested path", StatusNotFound)
  784. } else {
  785. ctx.SetStatusCode(StatusNotFound)
  786. h.pathNotFound(ctx)
  787. }
  788. return
  789. }
  790. h.cacheLock.Lock()
  791. ff1, ok := fileCache[pathStr]
  792. if !ok {
  793. fileCache[pathStr] = ff
  794. ff.readersCount++
  795. } else {
  796. ff1.readersCount++
  797. }
  798. h.cacheLock.Unlock()
  799. if ok {
  800. // The file has been already opened by another
  801. // goroutine, so close the current file and use
  802. // the file opened by another goroutine instead.
  803. ff.Release()
  804. ff = ff1
  805. }
  806. }
  807. if !ctx.IfModifiedSince(ff.lastModified) {
  808. ff.decReadersCount()
  809. ctx.NotModified()
  810. return
  811. }
  812. r, err := ff.NewReader()
  813. if err != nil {
  814. ctx.Logger().Printf("cannot obtain file reader for path=%q: %v", path, err)
  815. ctx.Error("Internal Server Error", StatusInternalServerError)
  816. return
  817. }
  818. hdr := &ctx.Response.Header
  819. if ff.compressed {
  820. if fileEncoding == "br" {
  821. hdr.SetContentEncodingBytes(strBr)
  822. } else if fileEncoding == "gzip" {
  823. hdr.SetContentEncodingBytes(strGzip)
  824. }
  825. }
  826. statusCode := StatusOK
  827. contentLength := ff.contentLength
  828. if h.acceptByteRange {
  829. hdr.setNonSpecial(strAcceptRanges, strBytes)
  830. if len(byteRange) > 0 {
  831. startPos, endPos, err := ParseByteRange(byteRange, contentLength)
  832. if err != nil {
  833. _ = r.(io.Closer).Close()
  834. ctx.Logger().Printf("cannot parse byte range %q for path=%q: %v", byteRange, path, err)
  835. ctx.Error("Range Not Satisfiable", StatusRequestedRangeNotSatisfiable)
  836. return
  837. }
  838. if err = r.(byteRangeUpdater).UpdateByteRange(startPos, endPos); err != nil {
  839. _ = r.(io.Closer).Close()
  840. ctx.Logger().Printf("cannot seek byte range %q for path=%q: %v", byteRange, path, err)
  841. ctx.Error("Internal Server Error", StatusInternalServerError)
  842. return
  843. }
  844. hdr.SetContentRange(startPos, endPos, contentLength)
  845. contentLength = endPos - startPos + 1
  846. statusCode = StatusPartialContent
  847. }
  848. }
  849. hdr.setNonSpecial(strLastModified, ff.lastModifiedStr)
  850. if !ctx.IsHead() {
  851. ctx.SetBodyStream(r, contentLength)
  852. } else {
  853. ctx.Response.ResetBody()
  854. ctx.Response.SkipBody = true
  855. ctx.Response.Header.SetContentLength(contentLength)
  856. if rc, ok := r.(io.Closer); ok {
  857. if err := rc.Close(); err != nil {
  858. ctx.Logger().Printf("cannot close file reader: %v", err)
  859. ctx.Error("Internal Server Error", StatusInternalServerError)
  860. return
  861. }
  862. }
  863. }
  864. hdr.noDefaultContentType = true
  865. if len(hdr.ContentType()) == 0 {
  866. ctx.SetContentType(ff.contentType)
  867. }
  868. ctx.SetStatusCode(statusCode)
  869. }
  870. type byteRangeUpdater interface {
  871. UpdateByteRange(startPos, endPos int) error
  872. }
  873. // ParseByteRange parses 'Range: bytes=...' header value.
  874. //
  875. // It follows https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.35 .
  876. func ParseByteRange(byteRange []byte, contentLength int) (startPos, endPos int, err error) {
  877. b := byteRange
  878. if !bytes.HasPrefix(b, strBytes) {
  879. return 0, 0, fmt.Errorf("unsupported range units: %q. Expecting %q", byteRange, strBytes)
  880. }
  881. b = b[len(strBytes):]
  882. if len(b) == 0 || b[0] != '=' {
  883. return 0, 0, fmt.Errorf("missing byte range in %q", byteRange)
  884. }
  885. b = b[1:]
  886. n := bytes.IndexByte(b, '-')
  887. if n < 0 {
  888. return 0, 0, fmt.Errorf("missing the end position of byte range in %q", byteRange)
  889. }
  890. if n == 0 {
  891. v, err := ParseUint(b[n+1:])
  892. if err != nil {
  893. return 0, 0, err
  894. }
  895. startPos := contentLength - v
  896. if startPos < 0 {
  897. startPos = 0
  898. }
  899. return startPos, contentLength - 1, nil
  900. }
  901. if startPos, err = ParseUint(b[:n]); err != nil {
  902. return 0, 0, err
  903. }
  904. if startPos >= contentLength {
  905. return 0, 0, fmt.Errorf("the start position of byte range cannot exceed %d. byte range %q", contentLength-1, byteRange)
  906. }
  907. b = b[n+1:]
  908. if len(b) == 0 {
  909. return startPos, contentLength - 1, nil
  910. }
  911. if endPos, err = ParseUint(b); err != nil {
  912. return 0, 0, err
  913. }
  914. if endPos >= contentLength {
  915. endPos = contentLength - 1
  916. }
  917. if endPos < startPos {
  918. return 0, 0, fmt.Errorf("the start position of byte range cannot exceed the end position. byte range %q", byteRange)
  919. }
  920. return startPos, endPos, nil
  921. }
  922. func (h *fsHandler) openIndexFile(ctx *RequestCtx, dirPath string, mustCompress bool, fileEncoding string) (*fsFile, error) {
  923. for _, indexName := range h.indexNames {
  924. indexFilePath := dirPath + "/" + indexName
  925. ff, err := h.openFSFile(indexFilePath, mustCompress, fileEncoding)
  926. if err == nil {
  927. return ff, nil
  928. }
  929. if !os.IsNotExist(err) {
  930. return nil, fmt.Errorf("cannot open file %q: %w", indexFilePath, err)
  931. }
  932. }
  933. if !h.generateIndexPages {
  934. return nil, fmt.Errorf("cannot access directory without index page. Directory %q", dirPath)
  935. }
  936. return h.createDirIndex(ctx.URI(), dirPath, mustCompress, fileEncoding)
  937. }
  938. var (
  939. errDirIndexRequired = errors.New("directory index required")
  940. errNoCreatePermission = errors.New("no 'create file' permissions")
  941. )
  942. func (h *fsHandler) createDirIndex(base *URI, dirPath string, mustCompress bool, fileEncoding string) (*fsFile, error) {
  943. w := &bytebufferpool.ByteBuffer{}
  944. basePathEscaped := html.EscapeString(string(base.Path()))
  945. _, _ = fmt.Fprintf(w, "<html><head><title>%s</title><style>.dir { font-weight: bold }</style></head><body>", basePathEscaped)
  946. _, _ = fmt.Fprintf(w, "<h1>%s</h1>", basePathEscaped)
  947. _, _ = fmt.Fprintf(w, "<ul>")
  948. if len(basePathEscaped) > 1 {
  949. var parentURI URI
  950. base.CopyTo(&parentURI)
  951. parentURI.Update(string(base.Path()) + "/..")
  952. parentPathEscaped := html.EscapeString(string(parentURI.Path()))
  953. _, _ = fmt.Fprintf(w, `<li><a href="%s" class="dir">..</a></li>`, parentPathEscaped)
  954. }
  955. f, err := os.Open(dirPath)
  956. if err != nil {
  957. return nil, err
  958. }
  959. fileinfos, err := f.Readdir(0)
  960. _ = f.Close()
  961. if err != nil {
  962. return nil, err
  963. }
  964. fm := make(map[string]os.FileInfo, len(fileinfos))
  965. filenames := make([]string, 0, len(fileinfos))
  966. nestedContinue:
  967. for _, fi := range fileinfos {
  968. name := fi.Name()
  969. for _, cfs := range h.compressedFileSuffixes {
  970. if strings.HasSuffix(name, cfs) {
  971. // Do not show compressed files on index page.
  972. continue nestedContinue
  973. }
  974. }
  975. fm[name] = fi
  976. filenames = append(filenames, name)
  977. }
  978. var u URI
  979. base.CopyTo(&u)
  980. u.Update(string(u.Path()) + "/")
  981. sort.Strings(filenames)
  982. for _, name := range filenames {
  983. u.Update(name)
  984. pathEscaped := html.EscapeString(string(u.Path()))
  985. fi := fm[name]
  986. auxStr := "dir"
  987. className := "dir"
  988. if !fi.IsDir() {
  989. auxStr = fmt.Sprintf("file, %d bytes", fi.Size())
  990. className = "file"
  991. }
  992. _, _ = fmt.Fprintf(w, `<li><a href="%s" class="%s">%s</a>, %s, last modified %s</li>`,
  993. pathEscaped, className, html.EscapeString(name), auxStr, fsModTime(fi.ModTime()))
  994. }
  995. _, _ = fmt.Fprintf(w, "</ul></body></html>")
  996. if mustCompress {
  997. var zbuf bytebufferpool.ByteBuffer
  998. if fileEncoding == "br" {
  999. zbuf.B = AppendBrotliBytesLevel(zbuf.B, w.B, CompressDefaultCompression)
  1000. } else if fileEncoding == "gzip" {
  1001. zbuf.B = AppendGzipBytesLevel(zbuf.B, w.B, CompressDefaultCompression)
  1002. }
  1003. w = &zbuf
  1004. }
  1005. dirIndex := w.B
  1006. lastModified := time.Now()
  1007. ff := &fsFile{
  1008. h: h,
  1009. dirIndex: dirIndex,
  1010. contentType: "text/html; charset=utf-8",
  1011. contentLength: len(dirIndex),
  1012. compressed: mustCompress,
  1013. lastModified: lastModified,
  1014. lastModifiedStr: AppendHTTPDate(nil, lastModified),
  1015. t: lastModified,
  1016. }
  1017. return ff, nil
  1018. }
  1019. const (
  1020. fsMinCompressRatio = 0.8
  1021. fsMaxCompressibleFileSize = 8 * 1024 * 1024
  1022. )
  1023. func (h *fsHandler) compressAndOpenFSFile(filePath string, fileEncoding string) (*fsFile, error) {
  1024. f, err := os.Open(filePath)
  1025. if err != nil {
  1026. return nil, err
  1027. }
  1028. fileInfo, err := f.Stat()
  1029. if err != nil {
  1030. _ = f.Close()
  1031. return nil, fmt.Errorf("cannot obtain info for file %q: %w", filePath, err)
  1032. }
  1033. if fileInfo.IsDir() {
  1034. _ = f.Close()
  1035. return nil, errDirIndexRequired
  1036. }
  1037. if strings.HasSuffix(filePath, h.compressedFileSuffixes[fileEncoding]) ||
  1038. fileInfo.Size() > fsMaxCompressibleFileSize ||
  1039. !isFileCompressible(f, fsMinCompressRatio) {
  1040. return h.newFSFile(f, fileInfo, false, "")
  1041. }
  1042. compressedFilePath := h.filePathToCompressed(filePath)
  1043. if compressedFilePath != filePath {
  1044. if err := os.MkdirAll(filepath.Dir(compressedFilePath), os.ModePerm); err != nil {
  1045. return nil, err
  1046. }
  1047. }
  1048. compressedFilePath += h.compressedFileSuffixes[fileEncoding]
  1049. absPath, err := filepath.Abs(compressedFilePath)
  1050. if err != nil {
  1051. _ = f.Close()
  1052. return nil, fmt.Errorf("cannot determine absolute path for %q: %v", compressedFilePath, err)
  1053. }
  1054. flock := getFileLock(absPath)
  1055. flock.Lock()
  1056. ff, err := h.compressFileNolock(f, fileInfo, filePath, compressedFilePath, fileEncoding)
  1057. flock.Unlock()
  1058. return ff, err
  1059. }
  1060. func (h *fsHandler) compressFileNolock(f *os.File, fileInfo os.FileInfo, filePath, compressedFilePath string, fileEncoding string) (*fsFile, error) {
  1061. // Attempt to open compressed file created by another concurrent
  1062. // goroutine.
  1063. // It is safe opening such a file, since the file creation
  1064. // is guarded by file mutex - see getFileLock call.
  1065. if _, err := os.Stat(compressedFilePath); err == nil {
  1066. _ = f.Close()
  1067. return h.newCompressedFSFile(compressedFilePath, fileEncoding)
  1068. }
  1069. // Create temporary file, so concurrent goroutines don't use
  1070. // it until it is created.
  1071. tmpFilePath := compressedFilePath + ".tmp"
  1072. zf, err := os.Create(tmpFilePath)
  1073. if err != nil {
  1074. _ = f.Close()
  1075. if !os.IsPermission(err) {
  1076. return nil, fmt.Errorf("cannot create temporary file %q: %w", tmpFilePath, err)
  1077. }
  1078. return nil, errNoCreatePermission
  1079. }
  1080. if fileEncoding == "br" {
  1081. zw := acquireStacklessBrotliWriter(zf, CompressDefaultCompression)
  1082. _, err = copyZeroAlloc(zw, f)
  1083. if err1 := zw.Flush(); err == nil {
  1084. err = err1
  1085. }
  1086. releaseStacklessBrotliWriter(zw, CompressDefaultCompression)
  1087. } else if fileEncoding == "gzip" {
  1088. zw := acquireStacklessGzipWriter(zf, CompressDefaultCompression)
  1089. _, err = copyZeroAlloc(zw, f)
  1090. if err1 := zw.Flush(); err == nil {
  1091. err = err1
  1092. }
  1093. releaseStacklessGzipWriter(zw, CompressDefaultCompression)
  1094. }
  1095. _ = zf.Close()
  1096. _ = f.Close()
  1097. if err != nil {
  1098. return nil, fmt.Errorf("error when compressing file %q to %q: %w", filePath, tmpFilePath, err)
  1099. }
  1100. if err = os.Chtimes(tmpFilePath, time.Now(), fileInfo.ModTime()); err != nil {
  1101. return nil, fmt.Errorf("cannot change modification time to %v for tmp file %q: %v",
  1102. fileInfo.ModTime(), tmpFilePath, err)
  1103. }
  1104. if err = os.Rename(tmpFilePath, compressedFilePath); err != nil {
  1105. return nil, fmt.Errorf("cannot move compressed file from %q to %q: %w", tmpFilePath, compressedFilePath, err)
  1106. }
  1107. return h.newCompressedFSFile(compressedFilePath, fileEncoding)
  1108. }
  1109. func (h *fsHandler) newCompressedFSFile(filePath string, fileEncoding string) (*fsFile, error) {
  1110. f, err := os.Open(filePath)
  1111. if err != nil {
  1112. return nil, fmt.Errorf("cannot open compressed file %q: %w", filePath, err)
  1113. }
  1114. fileInfo, err := f.Stat()
  1115. if err != nil {
  1116. _ = f.Close()
  1117. return nil, fmt.Errorf("cannot obtain info for compressed file %q: %w", filePath, err)
  1118. }
  1119. return h.newFSFile(f, fileInfo, true, fileEncoding)
  1120. }
  1121. func (h *fsHandler) openFSFile(filePath string, mustCompress bool, fileEncoding string) (*fsFile, error) {
  1122. filePathOriginal := filePath
  1123. if mustCompress {
  1124. filePath += h.compressedFileSuffixes[fileEncoding]
  1125. }
  1126. f, err := os.Open(filePath)
  1127. if err != nil {
  1128. if mustCompress && os.IsNotExist(err) {
  1129. return h.compressAndOpenFSFile(filePathOriginal, fileEncoding)
  1130. }
  1131. return nil, err
  1132. }
  1133. fileInfo, err := f.Stat()
  1134. if err != nil {
  1135. _ = f.Close()
  1136. return nil, fmt.Errorf("cannot obtain info for file %q: %w", filePath, err)
  1137. }
  1138. if fileInfo.IsDir() {
  1139. _ = f.Close()
  1140. if mustCompress {
  1141. return nil, fmt.Errorf("directory with unexpected suffix found: %q. Suffix: %q",
  1142. filePath, h.compressedFileSuffixes[fileEncoding])
  1143. }
  1144. return nil, errDirIndexRequired
  1145. }
  1146. if mustCompress {
  1147. fileInfoOriginal, err := os.Stat(filePathOriginal)
  1148. if err != nil {
  1149. _ = f.Close()
  1150. return nil, fmt.Errorf("cannot obtain info for original file %q: %w", filePathOriginal, err)
  1151. }
  1152. // Only re-create the compressed file if there was more than a second between the mod times.
  1153. // On MacOS the gzip seems to truncate the nanoseconds in the mod time causing the original file
  1154. // to look newer than the gzipped file.
  1155. if fileInfoOriginal.ModTime().Sub(fileInfo.ModTime()) >= time.Second {
  1156. // The compressed file became stale. Re-create it.
  1157. _ = f.Close()
  1158. _ = os.Remove(filePath)
  1159. return h.compressAndOpenFSFile(filePathOriginal, fileEncoding)
  1160. }
  1161. }
  1162. return h.newFSFile(f, fileInfo, mustCompress, fileEncoding)
  1163. }
  1164. func (h *fsHandler) newFSFile(f *os.File, fileInfo os.FileInfo, compressed bool, fileEncoding string) (*fsFile, error) {
  1165. n := fileInfo.Size()
  1166. contentLength := int(n)
  1167. if n != int64(contentLength) {
  1168. _ = f.Close()
  1169. return nil, fmt.Errorf("too big file: %d bytes", n)
  1170. }
  1171. // detect content-type
  1172. ext := fileExtension(fileInfo.Name(), compressed, h.compressedFileSuffixes[fileEncoding])
  1173. contentType := mime.TypeByExtension(ext)
  1174. if len(contentType) == 0 {
  1175. data, err := readFileHeader(f, compressed, fileEncoding)
  1176. if err != nil {
  1177. return nil, fmt.Errorf("cannot read header of the file %q: %w", f.Name(), err)
  1178. }
  1179. contentType = http.DetectContentType(data)
  1180. }
  1181. lastModified := fileInfo.ModTime()
  1182. ff := &fsFile{
  1183. h: h,
  1184. f: f,
  1185. contentType: contentType,
  1186. contentLength: contentLength,
  1187. compressed: compressed,
  1188. lastModified: lastModified,
  1189. lastModifiedStr: AppendHTTPDate(nil, lastModified),
  1190. t: time.Now(),
  1191. }
  1192. return ff, nil
  1193. }
  1194. func readFileHeader(f *os.File, compressed bool, fileEncoding string) ([]byte, error) {
  1195. r := io.Reader(f)
  1196. var (
  1197. br *brotli.Reader
  1198. zr *gzip.Reader
  1199. )
  1200. if compressed {
  1201. var err error
  1202. if fileEncoding == "br" {
  1203. if br, err = acquireBrotliReader(f); err != nil {
  1204. return nil, err
  1205. }
  1206. r = br
  1207. } else if fileEncoding == "gzip" {
  1208. if zr, err = acquireGzipReader(f); err != nil {
  1209. return nil, err
  1210. }
  1211. r = zr
  1212. }
  1213. }
  1214. lr := &io.LimitedReader{
  1215. R: r,
  1216. N: 512,
  1217. }
  1218. data, err := io.ReadAll(lr)
  1219. if _, err := f.Seek(0, 0); err != nil {
  1220. return nil, err
  1221. }
  1222. if br != nil {
  1223. releaseBrotliReader(br)
  1224. }
  1225. if zr != nil {
  1226. releaseGzipReader(zr)
  1227. }
  1228. return data, err
  1229. }
  1230. func stripLeadingSlashes(path []byte, stripSlashes int) []byte {
  1231. for stripSlashes > 0 && len(path) > 0 {
  1232. if path[0] != '/' {
  1233. panic("BUG: path must start with slash")
  1234. }
  1235. n := bytes.IndexByte(path[1:], '/')
  1236. if n < 0 {
  1237. path = path[:0]
  1238. break
  1239. }
  1240. path = path[n+1:]
  1241. stripSlashes--
  1242. }
  1243. return path
  1244. }
  1245. func stripTrailingSlashes(path []byte) []byte {
  1246. for len(path) > 0 && path[len(path)-1] == '/' {
  1247. path = path[:len(path)-1]
  1248. }
  1249. return path
  1250. }
  1251. func fileExtension(path string, compressed bool, compressedFileSuffix string) string {
  1252. if compressed && strings.HasSuffix(path, compressedFileSuffix) {
  1253. path = path[:len(path)-len(compressedFileSuffix)]
  1254. }
  1255. n := strings.LastIndexByte(path, '.')
  1256. if n < 0 {
  1257. return ""
  1258. }
  1259. return path[n:]
  1260. }
  1261. // FileLastModified returns last modified time for the file.
  1262. func FileLastModified(path string) (time.Time, error) {
  1263. f, err := os.Open(path)
  1264. if err != nil {
  1265. return zeroTime, err
  1266. }
  1267. fileInfo, err := f.Stat()
  1268. _ = f.Close()
  1269. if err != nil {
  1270. return zeroTime, err
  1271. }
  1272. return fsModTime(fileInfo.ModTime()), nil
  1273. }
  1274. func fsModTime(t time.Time) time.Time {
  1275. return t.In(time.UTC).Truncate(time.Second)
  1276. }
  1277. var filesLockMap sync.Map
  1278. func getFileLock(absPath string) *sync.Mutex {
  1279. v, _ := filesLockMap.LoadOrStore(absPath, &sync.Mutex{})
  1280. filelock := v.(*sync.Mutex)
  1281. return filelock
  1282. }