fs.go 47 KB

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