-
Notifications
You must be signed in to change notification settings - Fork 787
/
FileService.scala
379 lines (345 loc) · 13.4 KB
/
FileService.scala
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
/*
* Copyright 2014 http4s.org
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.http4s
package server
package staticcontent
import cats.data.Kleisli
import cats.data.NonEmptyList
import cats.data.OptionT
import cats.effect.kernel.Async
import cats.syntax.all._
import fs2.io.file.Files
import fs2.io.file.NoSuchFileException
import fs2.io.file.Path
import org.http4s.headers.Range.SubRange
import org.http4s.headers._
import org.http4s.server.middleware.TranslateUri
import org.typelevel.ci._
import java.io.File
import scala.annotation.nowarn
import scala.util.control.NoStackTrace
object FileService {
private[this] val logger = Platform.loggerFactory.getLogger
@deprecated("use FileService.Fs2PathCollector", "0.23.8")
type PathCollector[F[_]] = (File, Config[F], Request[F]) => OptionT[F, Response[F]]
type Fs2PathCollector[F[_]] = (Path, Config[F], Request[F]) => OptionT[F, Response[F]]
/** [[org.http4s.server.staticcontent.FileService]] configuration
*
* @param systemPath path prefix to the folder from which content will be served
* @param fs2PathCollector function that performs the work of collecting the file or rendering the directory into a response.
* @param pathPrefix prefix of Uri from which content will be served
* @param cacheStrategy strategy to use for caching purposes. Default to no caching.
* @param bufferSize buffer size to use for internal read buffers
*/
final class Config[F[_]](
val systemPath: String,
val fs2PathCollector: Fs2PathCollector[F],
val pathPrefix: String,
val cacheStrategy: CacheStrategy[F],
val bufferSize: Int,
) extends Product
with Serializable
with Equals {
/** For binary compatibility.
* @param systemPath path prefix to the folder from which content will be served
* @param pathCollector function that performs the work of collecting the file or rendering the directory into a response.
* @param pathPrefix prefix of Uri from which content will be served
* @param bufferSize buffer size to use for internal read buffers
* @param cacheStrategy strategy to use for caching purposes. Default to no caching.
*/
@deprecated("use the constructor with fs2PathCollector", "0.23.8")
def this(
systemPath: String,
pathCollector: PathCollector[F],
pathPrefix: String,
bufferSize: Int,
cacheStrategy: CacheStrategy[F],
) =
this(
systemPath,
(path: Path, config: Config[F], request: Request[F]) =>
pathCollector(
path.toNioPath.toFile,
config,
request,
),
pathPrefix,
cacheStrategy,
bufferSize,
)
/** For binary compatibility.
* @return an instance of PathCollector[F] created (converted) from fs2PathCollector
*/
@deprecated("use fs2PathCollector", "0.23.8")
def pathCollector: PathCollector[F] = (file, config, request) =>
fs2PathCollector(
Path.fromNioPath(file.toPath()),
config,
request,
)
@deprecated(
"Config is no longer a case class. The copy method is provided for binary compatibility.",
"0.23.8",
)
def copy(
systemPath: String = this.systemPath,
@nowarn pathCollector: PathCollector[F] = this.pathCollector,
pathPrefix: String = this.pathPrefix,
bufferSize: Int = this.bufferSize,
cacheStrategy: CacheStrategy[F] = this.cacheStrategy,
): Config[F] = new Config[F](
systemPath,
fs2PathCollector,
pathPrefix,
cacheStrategy,
bufferSize,
)
@deprecated(
"Config is no longer a case class. The productArity method is provided for binary compatibility.",
"0.23.8",
)
override def productArity: Int = 5
@deprecated(
"Config is no longer a case class. The productElement method is provided for binary compatibility.",
"0.23.8",
)
override def productElement(n: Int): Any = n match {
case 0 => systemPath
case 1 => if (Platform.isJvm) pathCollector else fs2PathCollector
case 2 => pathPrefix
case 3 => bufferSize
case 4 => cacheStrategy
}
@deprecated(
"Config is no longer a case class. The _1 method is provided for binary compatibility.",
"0.23.8",
)
def _1: String = systemPath
@deprecated(
"Config is no longer a case class. The _2 method is provided for binary compatibility.",
"0.23.8",
)
def _2: Function3[_, _, _, _] =
if (Platform.isJvm) pathCollector else fs2PathCollector
@deprecated(
"Config is no longer a case class. The _3 method is provided for binary compatibility.",
"0.23.8",
)
def _3: String = pathPrefix
@deprecated(
"Config is no longer a case class. The _4 method is provided for binary compatibility.",
"0.23.8",
)
def _4: Int = bufferSize
@deprecated(
"Config is no longer a case class. The _5 method is provided for binary compatibility.",
"0.23.8",
)
def _5: CacheStrategy[F] = cacheStrategy
override def canEqual(that: Any): Boolean = that match {
case _: Config[_] => true
case _ => false
}
override def equals(other: Any): Boolean = other match {
case that: Config[_] =>
systemPath == that.systemPath &&
fs2PathCollector == that.fs2PathCollector &&
pathPrefix == that.pathPrefix &&
cacheStrategy == that.cacheStrategy &&
bufferSize == that.bufferSize
case _ => false
}
override def hashCode(): Int = {
val state = Seq[Any](systemPath, fs2PathCollector, pathPrefix, bufferSize, cacheStrategy)
state.map(_.hashCode()).foldLeft(0)((a, b) => 31 * a + b)
}
override def toString: String =
s"Config($systemPath, $fs2PathCollector, $pathPrefix, $bufferSize, $cacheStrategy)"
}
object Config extends FileServiceConfigCompanionCompat {
/** Creates an instance of [[org.http4s.server.staticcontent.FileService]] configuration.
*
* @param systemPath path prefix to the folder from which content will be served
* @param fs2PathCollector function that performs the work of collecting the file or rendering the directory into a response.
* @param pathPrefix prefix of Uri from which content will be served
* @param cacheStrategy strategy to use for caching purposes. Default to no caching.
* @param bufferSize buffer size to use for internal read buffers
*/
def apply[F[_]](
systemPath: String,
fs2PathCollector: Fs2PathCollector[F],
pathPrefix: String,
cacheStrategy: CacheStrategy[F],
bufferSize: Int,
): Config[F] =
new Config[F](systemPath, fs2PathCollector, pathPrefix, cacheStrategy, bufferSize)
/** Creates an instance of [[org.http4s.server.staticcontent.FileService]] configuration.
* A constructor that accepts PathCollector[F] for binary compatibility.
*
* @param systemPath path prefix to the folder from which content will be served
* @param pathCollector function that performs the work of collecting the file or rendering the directory into a response.
* @param pathPrefix prefix of Uri from which content will be served
* @param bufferSize buffer size to use for internal read buffers
* @param cacheStrategy strategy to use for caching purposes. Default to no caching.
*/
@deprecated(
"use FileService.Config(systemPath: String, fs2PathCollector: Fs2PathCollector[F], ...)",
"0.23.8",
)
def apply[F[_]](
systemPath: String,
pathCollector: PathCollector[F],
pathPrefix: String,
bufferSize: Int,
cacheStrategy: CacheStrategy[F],
): Config[F] = new Config[F](
systemPath,
pathCollector,
pathPrefix,
bufferSize,
cacheStrategy,
)
def apply[F[_]: Async](
systemPath: String,
pathPrefix: String = "",
bufferSize: Int = 50 * 1024,
cacheStrategy: CacheStrategy[F] = NoopCacheStrategy[F],
): Config[F] = {
val pathCollector: Fs2PathCollector[F] = (f, c, r) => filesOnly(f, c, r)
Config(systemPath, pathCollector, pathPrefix, cacheStrategy, bufferSize)
}
}
/** Make a new [[org.http4s.HttpRoutes]] that serves static files. */
private[staticcontent] def apply[F[_]](config: Config[F])(implicit F: Async[F]): HttpRoutes[F] = {
object BadTraversal extends Exception with NoStackTrace
def withPath(rootPath: Path)(request: Request[F]): OptionT[F, Response[F]] = {
val resolvePath: F[Path] =
if (request.pathInfo.isEmpty) F.pure(rootPath)
else {
val segments = request.pathInfo.segments.map(_.decoded(plusIsSpace = true))
F.catchNonFatal {
segments.foldLeft(rootPath) {
case (_, "" | "." | "..") => throw BadTraversal
case (path, segment) => path.resolve(segment)
}
}
}
val matchingPath: F[Option[Path]] =
for {
path <- resolvePath
existsPath <- Files[F].exists(path, false)
} yield
if (existsPath && path.startsWith(rootPath))
Some(path.absolute.normalize)
else None
OptionT(matchingPath)
.flatMap(path => config.fs2PathCollector(path, config, request))
.semiflatMap(config.cacheStrategy.cache(request.pathInfo, _))
.recoverWith { case BadTraversal => OptionT.some(Response(Status.BadRequest)) }
}
val readPath: F[Path] = Files[F].realPath(Path(config.systemPath))
val inner: F[HttpRoutes[F]] = readPath.attempt.flatMap {
case Right(rootPath) =>
TranslateUri(config.pathPrefix)(Kleisli(withPath(rootPath))).pure
case Left(_: NoSuchFileException) =>
logger
.error(
s"Could not find root path from FileService config: systemPath = ${config.systemPath}, pathPrefix = ${config.pathPrefix}. All requests will return none."
)
.to[F]
.as(HttpRoutes.empty)
case Left(e) =>
logger
.error(e)(
s"Could not resolve root path from FileService config: systemPath = ${config.systemPath}, pathPrefix = ${config.pathPrefix}. All requests will fail with a 500."
)
.to[F]
.as(HttpRoutes.pure(Response(Status.InternalServerError)))
}
Kleisli((_: Any) => OptionT.liftF(inner)).flatten
}
private def filesOnly[F[_]](path: Path, config: Config[F], req: Request[F])(implicit
F: Async[F]
): OptionT[F, Response[F]] =
OptionT(Files[F].getBasicFileAttributes(path).flatMap { attr =>
if (attr.isDirectory)
StaticFile
.fromPath(path / "index.html", Some(req))
.value
else if (!attr.isRegularFile) F.pure(None)
else
OptionT(getPartialContentFile(path, config, req))
.orElse(
StaticFile
.fromPath(path, config.bufferSize, Some(req), StaticFile.calculateETag)
.map(_.putHeaders(AcceptRangeHeader))
)
.value
})
private def validRange(start: Long, end: Option[Long], fileLength: Long): Boolean =
start < fileLength && (end match {
case Some(end) => start >= 0 && start <= end
case None => start >= 0 || fileLength + start - 1 >= 0
})
// Attempt to find a Range header and collect only the subrange of content requested
private def getPartialContentFile[F[_]](file: Path, config: Config[F], req: Request[F])(implicit
F: Async[F]
): F[Option[Response[F]]] =
Files[F].getBasicFileAttributes(file).flatMap { attr =>
def nope: F[Option[Response[F]]] =
Some(
Response[F](
status = Status.RangeNotSatisfiable,
headers = Headers
.apply(
AcceptRangeHeader,
`Content-Range`(SubRange(0, attr.size - 1), Some(attr.size)),
),
)
).pure[F].widen
req.headers.get[Range] match {
case Some(Range(RangeUnit.Bytes, NonEmptyList(SubRange(s, e), Nil))) =>
if (validRange(s, e, attr.size)) {
val size = attr.size
val start = if (s >= 0) s else math.max(0, size + s)
val end = math.min(size - 1, e.getOrElse(size - 1)) // end is inclusive
StaticFile
.fromPath(
file,
start,
end + 1,
config.bufferSize,
Some(req),
StaticFile.calculateETag,
)
.map { resp =>
val hs = resp.headers
.put(AcceptRangeHeader, `Content-Range`(SubRange(start, end), Some(size)))
resp.copy(status = Status.PartialContent, headers = hs)
}
.value
} else nope
case _ =>
req.headers.get(ci"Range") match {
case Some(_) =>
// It exists, but it didn't parse
nope
case None =>
F.pure(None)
}
}
}
}