fs.go 48 KB

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