-
Notifications
You must be signed in to change notification settings - Fork 135
Expand file tree
/
Copy pathstatic_handler.dart
More file actions
303 lines (257 loc) · 10.3 KB
/
static_handler.dart
File metadata and controls
303 lines (257 loc) · 10.3 KB
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
// Copyright (c) 2015, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
import 'dart:async';
import 'dart:io';
import 'dart:math' as math;
import 'package:convert/convert.dart';
import 'package:http_parser/http_parser.dart';
import 'package:mime/mime.dart';
import 'package:path/path.dart' as p;
import 'package:shelf/shelf.dart';
import 'directory_listing.dart';
import 'util.dart';
/// The default resolver for MIME types based on file extensions.
final _defaultMimeTypeResolver = MimeTypeResolver();
// TODO option to exclude hidden files?
/// Creates a Shelf [Handler] that serves files from the provided
/// [fileSystemPath].
///
/// Accessing a path containing symbolic links will succeed only if the resolved
/// path is within [fileSystemPath]. To allow access to paths outside of
/// [fileSystemPath], set [serveFilesOutsidePath] to `true`.
///
/// When a existing directory is requested and a [defaultDocument] is specified
/// the directory is checked for a file with that name. If it exists, it is
/// served.
///
/// If no [defaultDocument] is found and [listDirectories] is true, then the
/// handler produces a listing of the directory.
///
/// If [useHeaderBytesForContentType] is `true`, the contents of the
/// file will be used along with the file path to determine the content type.
///
/// Specify a custom [contentTypeResolver] to customize automatic content type
/// detection.
///
/// The [Response.context] will be populated with "shelf_static:file" or
/// "shelf_static:file_not_found" with the resolved [File] for the [Response].
/// If the path resolves to a [Directory], it will populate
/// "shelf_static:directory". If the path is considered not found because it is
/// outside of the [fileSystemPath] and [serveFilesOutsidePath] is false,
/// then none of the keys will be included in the context.
Handler createStaticHandler(String fileSystemPath,
{bool serveFilesOutsidePath = false,
String? defaultDocument,
bool listDirectories = false,
bool useHeaderBytesForContentType = false,
MimeTypeResolver? contentTypeResolver}) {
final rootDir = Directory(fileSystemPath);
if (!rootDir.existsSync()) {
throw ArgumentError('A directory corresponding to fileSystemPath '
'"$fileSystemPath" could not be found');
}
fileSystemPath = rootDir.resolveSymbolicLinksSync();
if (defaultDocument != null) {
if (defaultDocument != p.basename(defaultDocument)) {
throw ArgumentError('defaultDocument must be a file name.');
}
}
final mimeResolver = contentTypeResolver ?? _defaultMimeTypeResolver;
return (Request request) {
final segs = [fileSystemPath, ...request.url.pathSegments];
final fsPath = p.joinAll(segs);
final entityType = FileSystemEntity.typeSync(fsPath);
File? fileFound;
if (entityType == FileSystemEntityType.file) {
fileFound = File(fsPath);
} else if (entityType == FileSystemEntityType.directory) {
fileFound = _tryDefaultFile(fsPath, defaultDocument);
if (fileFound == null && listDirectories) {
final uri = request.requestedUri;
if (!uri.path.endsWith('/')) {
return _redirectToAddTrailingSlash(uri, fsPath);
}
return listDirectory(fileSystemPath, fsPath);
}
}
if (fileFound == null) {
File? fileNotFound = File(fsPath);
// Do not expose a file path outside of the original fileSystemPath:
if (!serveFilesOutsidePath &&
!p.isWithin(fileSystemPath, fileNotFound.path) &&
!p.equals(fileSystemPath, fileNotFound.path)) {
fileNotFound = null;
}
return Response.notFound(
'Not Found',
context: buildResponseContext(fileNotFound: fileNotFound),
);
}
final file = fileFound;
if (!serveFilesOutsidePath) {
final resolvedPath = file.resolveSymbolicLinksSync();
// Do not serve a file outside of the original fileSystemPath
if (!p.isWithin(fileSystemPath, resolvedPath)) {
return Response.notFound('Not Found');
}
}
// when serving the default document for a directory, if the requested
// path doesn't end with '/', redirect to the path with a trailing '/'
final uri = request.requestedUri;
if (entityType == FileSystemEntityType.directory &&
!uri.path.endsWith('/')) {
return _redirectToAddTrailingSlash(uri, fsPath);
}
return _handleFile(request, file, () async {
if (useHeaderBytesForContentType) {
final length =
math.min(mimeResolver.magicNumbersMaxLength, file.lengthSync());
final byteSink = ByteAccumulatorSink();
await file.openRead(0, length).listen(byteSink.add).asFuture<void>();
return mimeResolver.lookup(file.path, headerBytes: byteSink.bytes);
} else {
return mimeResolver.lookup(file.path);
}
});
};
}
Response _redirectToAddTrailingSlash(Uri uri, String fsPath) {
final location = Uri(
scheme: uri.scheme,
userInfo: uri.userInfo,
host: uri.host,
port: uri.port,
path: '${uri.path}/',
query: uri.query);
return Response.movedPermanently(location.toString(),
context: buildResponseContext(directory: Directory(fsPath)));
}
File? _tryDefaultFile(String dirPath, String? defaultFile) {
if (defaultFile == null) return null;
final filePath = p.join(dirPath, defaultFile);
final file = File(filePath);
if (file.existsSync()) {
return file;
}
return null;
}
/// Creates a shelf [Handler] that serves the file at [path].
///
/// This returns a 404 response for any requests whose [Request.url] doesn't
/// match [url]. The [url] defaults to the basename of [path].
///
/// This uses the given [contentType] for the Content-Type header. It defaults
/// to looking up a content type based on [path]'s file extension, and failing
/// that doesn't sent a [contentType] header at all.
///
/// The [Response.context] will be populated with "shelf_static:file" or
/// "shelf_static:file_not_found" with the resolved [File] for the [Response].
/// If the path is considered not found because it is
/// outside of the [fileSystemPath] and [serveFilesOutsidePath] is false,
/// then neither key will be included in the context.
Handler createFileHandler(String path, {String? url, String? contentType}) {
final file = File(path);
if (!file.existsSync()) {
throw ArgumentError.value(path, 'path', 'does not exist.');
} else if (url != null && !p.url.isRelative(url)) {
throw ArgumentError.value(url, 'url', 'must be relative.');
}
final parent = file.parent;
final mimeType = contentType ?? _defaultMimeTypeResolver.lookup(path);
url ??= p.toUri(p.basename(path)).toString();
return (request) {
if (request.url.path != url) {
var fileNotFound =
File(p.joinAll([parent.path, ...p.split(request.url.path)]));
return Response.notFound(
'Not Found',
context: buildResponseContext(fileNotFound: fileNotFound),
);
}
return _handleFile(request, file, () => mimeType);
};
}
/// Serves the contents of [file] in response to [request].
///
/// This handles caching, and sends a 304 Not Modified response if the request
/// indicates that it has the latest version of a file. Otherwise, it calls
/// [getContentType] and uses it to populate the Content-Type header.
Future<Response> _handleFile(Request request, File file,
FutureOr<String?> Function() getContentType) async {
final stat = file.statSync();
final ifModifiedSince = request.ifModifiedSince;
if (ifModifiedSince != null) {
final fileChangeAtSecResolution = toSecondResolution(stat.modified);
if (!fileChangeAtSecResolution.isAfter(ifModifiedSince)) {
return Response.notModified(
context: buildResponseContext(file: file),
);
}
}
final contentType = await getContentType();
final headers = {
HttpHeaders.lastModifiedHeader: formatHttpDate(stat.modified),
HttpHeaders.acceptRangesHeader: 'bytes',
if (contentType != null) HttpHeaders.contentTypeHeader: contentType,
};
return _fileRangeResponse(request, file, headers) ??
Response.ok(
request.method == 'HEAD' ? null : file.openRead(),
headers: headers..[HttpHeaders.contentLengthHeader] = '${stat.size}',
context: buildResponseContext(file: file),
);
}
final _bytesMatcher = RegExp(r'^bytes=(\d*)-(\d*)$');
/// Serves a range of [file], if [request] is valid 'bytes' range request.
///
/// If the request does not specify a range, specifies a range of the wrong
/// type, or has a syntactic error the range is ignored and `null` is returned.
///
/// If the range request is valid but the file is not long enough to include the
/// start of the range a range not satisfiable response is returned.
///
/// Ranges that end past the end of the file are truncated.
Response? _fileRangeResponse(
Request request, File file, Map<String, Object> headers) {
final range = request.headers[HttpHeaders.rangeHeader];
if (range == null) return null;
final matches = _bytesMatcher.firstMatch(range);
// Ignore ranges other than bytes
if (matches == null) return null;
final actualLength = file.lengthSync();
final startMatch = matches[1]!;
final endMatch = matches[2]!;
if (startMatch.isEmpty && endMatch.isEmpty) return null;
int start; // First byte position - inclusive.
int end; // Last byte position - inclusive.
if (startMatch.isEmpty) {
start = actualLength - int.parse(endMatch);
if (start < 0) start = 0;
end = actualLength - 1;
} else {
start = int.parse(startMatch);
end = endMatch.isEmpty ? actualLength - 1 : int.parse(endMatch);
}
// If the range is syntactically invalid the Range header
// MUST be ignored (RFC 2616 section 14.35.1).
if (start > end) return null;
if (end >= actualLength) {
end = actualLength - 1;
}
if (start >= actualLength) {
return Response(
HttpStatus.requestedRangeNotSatisfiable,
headers: headers,
context: buildResponseContext(file: file),
);
}
return Response(
HttpStatus.partialContent,
body: request.method == 'HEAD' ? null : file.openRead(start, end + 1),
headers: headers
..[HttpHeaders.contentLengthHeader] = (end - start + 1).toString()
..[HttpHeaders.contentRangeHeader] = 'bytes $start-$end/$actualLength',
context: buildResponseContext(file: file),
);
}