001/*
002 * Copyright 2022-2026 Revetware LLC.
003 *
004 * Licensed under the Apache License, Version 2.0 (the "License");
005 * you may not use this file except in compliance with the License.
006 * You may obtain a copy of the License at
007 *
008 * http://www.apache.org/licenses/LICENSE-2.0
009 *
010 * Unless required by applicable law or agreed to in writing, software
011 * distributed under the License is distributed on an "AS IS" BASIS,
012 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
013 * See the License for the specific language governing permissions and
014 * limitations under the License.
015 */
016
017package com.soklet;
018
019import org.jspecify.annotations.NonNull;
020import org.jspecify.annotations.Nullable;
021
022import javax.annotation.concurrent.NotThreadSafe;
023import javax.annotation.concurrent.ThreadSafe;
024import java.io.IOException;
025import java.io.InputStream;
026import java.io.UncheckedIOException;
027import java.nio.channels.Channels;
028import java.nio.channels.SeekableByteChannel;
029import java.nio.charset.StandardCharsets;
030import java.nio.file.Files;
031import java.nio.file.FileSystemException;
032import java.nio.file.FileSystemLoopException;
033import java.nio.file.AccessDeniedException;
034import java.nio.file.AccessMode;
035import java.nio.file.NoSuchFileException;
036import java.nio.file.NotDirectoryException;
037import java.nio.file.InvalidPathException;
038import java.nio.file.LinkOption;
039import java.nio.file.Path;
040import java.nio.file.attribute.BasicFileAttributes;
041import java.security.MessageDigest;
042import java.security.NoSuchAlgorithmException;
043import java.time.Instant;
044import java.util.Collections;
045import java.util.HexFormat;
046import java.util.LinkedHashMap;
047import java.util.ArrayList;
048import java.util.HashSet;
049import java.util.List;
050import java.util.Map;
051import java.util.Optional;
052
053import static java.lang.String.format;
054import static java.util.Objects.requireNonNull;
055
056/**
057 * Helper for serving files from an explicitly trusted, immutable root directory.
058 * The builder requires {@link Builder#trustedImmutableRoot(Boolean) trustedImmutableRoot(true)}:
059 * only the application operator may control the root, its ancestors, links, and files, and they
060 * must remain unchanged while the helper or its responses are in use. Upload directories and
061 * other attacker-writable trees are not supported.
062 * <p>
063 * Delivery uses public NIO APIs, with {@link java.nio.file.SecureDirectoryStream} where available
064 * and a checked pathname fallback otherwise (including macOS Java 21 and Windows). Providers
065 * without file keys use creation time, size, and modification time to detect observed replacement.
066 * Checks reject observed changes; they do not make concurrent mutation safe. Public Java APIs cannot bind regular-file attributes to an opened channel, and copying
067 * bytes does not close that identity race. No JDK internals, native-access flags, or retained
068 * directory descriptors are used.
069 * <p>
070 * The resolved root identity is captured at construction. Rebuild the helper when intentionally
071 * switching deployment roots, after in-flight responses have completed. Search-only directories
072 * use checked pathname access when public secure-directory handles cannot be acquired.
073 *
074
075 * @author <a href="https://www.revetkn.com">Mark Allen</a>
076 */
077@ThreadSafe
078public final class StaticFiles {
079        @NonNull
080        private static final Integer MAX_RELATIVE_PATH_UTF_8_LENGTH;
081        @NonNull
082        private static final Integer MAX_RELATIVE_PATH_SEGMENTS;
083        private static final int MAX_PATH_SEGMENT_UTF_8_LENGTH = 255;
084        private static final int MAX_SYMLINK_EXPANSIONS = 64;
085        @NonNull
086        private static final Integer CONTENT_HASH_BUFFER_SIZE;
087        @NonNull
088        private static final HexFormat HEX_FORMAT;
089
090        static {
091                MAX_RELATIVE_PATH_UTF_8_LENGTH = 4096;
092                MAX_RELATIVE_PATH_SEGMENTS = 256;
093                CONTENT_HASH_BUFFER_SIZE = 8192;
094                HEX_FORMAT = HexFormat.of();
095        }
096
097        @NonNull
098        private final Path root;
099        @NonNull
100        private final Path noFollowRoot;
101        @NonNull
102        private final Path followRoot;
103        @NonNull
104        private final SecureStaticFileRoot secureRoot;
105        @NonNull
106        private final List<@NonNull String> indexFileNames;
107        @NonNull
108        private final MimeTypeResolver mimeTypeResolver;
109        @NonNull
110        private final EntityTagResolver entityTagResolver;
111        @NonNull
112        private final AccessResolver accessResolver;
113        @NonNull
114        private final LastModifiedResolver lastModifiedResolver;
115        @NonNull
116        private final CacheControlResolver cacheControlResolver;
117        @NonNull
118        private final HeadersResolver headersResolver;
119        @NonNull
120        private final RangeRequestsResolver rangeRequestsResolver;
121        @NonNull
122        private final Boolean followSymlinks;
123
124        /**
125         * Begins configuration for serving files under {@code root}.
126         * <p>
127         * Relative roots are resolved against the JVM's current working directory when the builder is
128         * built. Production deployments should generally pass an absolute path.
129         * <p>
130         * File matching follows the underlying filesystem's case-sensitivity and Unicode normalization
131         * rules. Production deployments that need portable behavior across operating systems should
132         * standardize on ASCII-safe asset names.
133         *
134         * @param root the static-file root directory
135         * @return a builder for static-file responses
136         */
137        @NonNull
138        public static Builder withRoot(@NonNull Path root) {
139                requireNonNull(root);
140                return new Builder(root);
141        }
142
143        private StaticFiles(@NonNull Builder builder) {
144                requireNonNull(builder);
145
146                if (!Boolean.TRUE.equals(builder.trustedImmutableRoot))
147                        throw new IllegalArgumentException("StaticFiles requires trustedImmutableRoot(true): the root, ancestors, links, and files must be operator-controlled and immutable while in use.");
148
149                this.root = builder.root.toAbsolutePath().normalize();
150                this.followSymlinks = builder.followSymlinks == null ? false : builder.followSymlinks;
151                this.indexFileNames = List.copyOf(builder.indexFileNames == null ? List.of() : builder.indexFileNames);
152                this.mimeTypeResolver = defaultingMimeTypeResolver(builder.mimeTypeResolver);
153                this.entityTagResolver = builder.entityTagResolver == null ? EntityTagResolver.defaultInstance() : builder.entityTagResolver;
154                this.accessResolver = builder.accessResolver == null ? AccessResolver.allowAllInstance() : builder.accessResolver;
155                this.lastModifiedResolver = builder.lastModifiedResolver == null ? LastModifiedResolver.fromAttributes() : builder.lastModifiedResolver;
156                this.cacheControlResolver = builder.cacheControlResolver == null ? CacheControlResolver.disabledInstance() : builder.cacheControlResolver;
157                this.headersResolver = builder.headersResolver == null ? HeadersResolver.disabledInstance() : builder.headersResolver;
158                this.rangeRequestsResolver = builder.rangeRequestsResolver == null ? RangeRequestsResolver.enabledInstance() : builder.rangeRequestsResolver;
159
160                for (String indexFileName : this.indexFileNames) {
161                        validateIndexFileName(indexFileName);
162                        try {
163                                this.root.resolve(indexFileName);
164                        } catch (java.nio.file.InvalidPathException failure) {
165                                throw new IllegalArgumentException(format("Invalid index file name '%s'.", indexFileName), failure);
166                        }
167                }
168
169                try {
170                        this.followRoot = this.root.toRealPath();
171                        // Preserve the configured spelling for no-follow resolver paths. The
172                        // delivery root identity is captured below, so observed replacement fails closed.
173                        this.noFollowRoot = this.root;
174                } catch (IOException e) {
175                        throw new UncheckedIOException(format("Unable to resolve static file root '%s'.", this.root), e);
176                }
177
178                if (getFollowSymlinks()) {
179                        if (!Files.isDirectory(this.followRoot))
180                                throw new IllegalArgumentException(format("Static file root '%s' is not a directory.", this.root));
181                } else if (Files.isSymbolicLink(this.noFollowRoot)) {
182                        throw new IllegalArgumentException(format("Static file root '%s' is a symbolic link; enable followSymlinks to use it.", this.root));
183                } else if (!Files.isDirectory(this.noFollowRoot, LinkOption.NOFOLLOW_LINKS)) {
184                        throw new IllegalArgumentException(format("Static file root '%s' is not a directory.", this.root));
185                }
186                this.secureRoot = new SecureStaticFileRoot(getResolutionRoot(), this.root);
187        }
188
189        /**
190         * Produces a marshaled response for {@code relativePath}, if the request targets a safe, readable
191         * file under the configured root.
192         * <p>
193         * Returns {@link Optional#empty()} for HTTP methods other than {@link HttpMethod#GET} and
194         * {@link HttpMethod#HEAD}, unsafe path input, directories without a configured index file,
195         * unreadable files, and missing files. Once a path resolves, non-{@code 200} file responses such as
196         * {@code 206}, {@code 304}, {@code 412}, and {@code 416} are returned inside the optional.
197         * Root-relative input is limited to 4,096 UTF-8 bytes, 256 path segments, and 255 UTF-8 bytes
198         * per segment. These portable input limits apply on every filesystem; providers may impose
199         * stricter limits, whose unclassified failures propagate as I/O errors.
200         * <p>
201         * Resolvers receive the resolved file path after index-file resolution, not the original
202         * {@code relativePath}.
203         *
204         * @param relativePath the root-relative file path
205         * @param request the incoming request
206         * @return the marshaled response, if a static file was resolved
207         * @throws UncheckedIOException if filesystem access fails for a reason other than a missing,
208         *         inaccessible, or changed file, including a provider that cannot open files without following links
209         */
210        @NonNull
211        public Optional<@NonNull MarshaledResponse> marshaledResponseFor(@NonNull String relativePath,
212                                                                                                                                                                                                                                        @NonNull Request request) {
213                requireNonNull(relativePath);
214                requireNonNull(request);
215
216                if (request.getHttpMethod() != HttpMethod.GET && request.getHttpMethod() != HttpMethod.HEAD)
217                        return Optional.empty();
218
219                ResolvedFile resolvedFile = resolvedFileFor(relativePath).orElse(null);
220
221                if (resolvedFile == null)
222                        return Optional.empty();
223
224                Path file = resolvedFile.path();
225                BasicFileAttributes attributes = resolvedFile.attributes();
226                // Path resolution can race a rename of an ancestor. Check the selected
227                // object against the captured root before any application resolver sees its
228                // metadata. These checks supplement the required immutable-root contract.
229                try (SeekableByteChannel ignored = secureRoot.open(file, attributes)) {
230                        // The selected path still matches its expected identity and containment.
231                } catch (IOException failure) {
232                        return unresolvedFile(failure);
233                }
234                Access access = requireNonNull(getAccessResolver().accessFor(file, attributes), "accessResolver returned null; return Access.ALLOW, Access.DENY, or Access.HIDE.");
235
236                if (access == Access.HIDE)
237                        return Optional.empty();
238
239                if (access == Access.DENY)
240                        // Access denial is not a file representation, so validators and file headers do not apply.
241                        return Optional.of(MarshaledResponse.fromStatusCode(StatusCode.HTTP_403.getStatusCode()));
242
243                EntityTag entityTag;
244                if (getEntityTagResolver() == ContentHashEntityTagResolver.defaultInstance()) {
245                        // The built-in content hash must read the same approved object class as
246                        // delivery. In particular, do not follow a link swapped in by a resolver.
247                        try (SeekableByteChannel channel = secureRoot.open(file, attributes)) {
248                                entityTag = ContentHashEntityTagResolver.entityTagFor(channel);
249                        } catch (IOException failure) {
250                                return unresolvedFile(failure);
251                        }
252                } else {
253                        entityTag = requireNonNull(getEntityTagResolver().entityTagFor(file, attributes),
254                                        "entityTagResolver returned null; use Optional.empty() to omit the header.").orElse(null);
255                }
256                Instant lastModified = requireNonNull(getLastModifiedResolver().lastModifiedFor(file, attributes), "lastModifiedResolver returned null; use Optional.empty() to omit the header.").orElse(null);
257                String cacheControl = requireNonNull(getCacheControlResolver().cacheControlFor(file, attributes), "cacheControlResolver returned null; use Optional.empty() to omit the header.").orElse(null);
258                Map<String, List<String>> headers = requireNonNull(getHeadersResolver().headersFor(file, attributes), "headersResolver returned null; return an empty map to omit extra headers.");
259                FileResponse.rejectControlledHeaderConflicts(headers, "StaticFiles.HeadersResolver");
260                Boolean rangeRequests = requireNonNull(getRangeRequestsResolver().rangeRequestsFor(file, attributes), "rangeRequestsResolver returned null; return false to disable range requests.");
261                String contentType = requireNonNull(getMimeTypeResolver().contentTypeFor(file), "mimeTypeResolver returned null; use Optional.empty() to omit Content-Type.").orElse(null);
262
263                // Resolvers can execute application code. Recheck the selected path and identity
264                // before response creation; delivery checks again against the captured root.
265                ResolvedFile current = getFollowSymlinks()
266                                ? followedRegularFile(file).orElse(null)
267                                : noFollowResolvedFileForCandidate(file).orElse(null);
268                if (current == null || !current.path().equals(file)
269                                || !sameFileIdentity(attributes, current.attributes()))
270                        return Optional.empty();
271                try (SeekableByteChannel ignored = secureRoot.open(file, attributes)) {
272                        // Bodyless responses need the same post-resolver validation as body responses.
273                } catch (IOException failure) {
274                        return unresolvedFile(failure);
275                }
276
277                MarshaledResponse response = MarshaledResponse.withFile(file, request, attributes)
278                                .contentType(contentType)
279                                .entityTag(entityTag)
280                                .lastModified(lastModified)
281                                .cacheControl(cacheControl)
282                                .headers(headers)
283                                .rangeRequests(rangeRequests)
284                                .build();
285                if (response.getBody().orElse(null) instanceof MarshaledResponseBody.File fileBody) {
286                        response = response.copy().body(new MarshaledResponseBody.SecureFile(
287                                        secureRoot, fileBody.getPath(),
288                                        fileBody.getOffset(), fileBody.getCount(), attributes)).finish();
289                }
290
291                return Optional.of(response);
292        }
293
294        @NonNull
295        private Path getResolutionRoot() {
296                return getFollowSymlinks() ? this.followRoot : this.noFollowRoot;
297        }
298
299        @NonNull
300        private Boolean getFollowSymlinks() {
301                return this.followSymlinks;
302        }
303
304        @NonNull
305        private List<@NonNull String> getIndexFileNames() {
306                return this.indexFileNames;
307        }
308
309        @NonNull
310        private MimeTypeResolver getMimeTypeResolver() {
311                return this.mimeTypeResolver;
312        }
313
314        @NonNull
315        private EntityTagResolver getEntityTagResolver() {
316                return this.entityTagResolver;
317        }
318
319        @NonNull
320        private AccessResolver getAccessResolver() {
321                return this.accessResolver;
322        }
323
324        @NonNull
325        private LastModifiedResolver getLastModifiedResolver() {
326                return this.lastModifiedResolver;
327        }
328
329        @NonNull
330        private CacheControlResolver getCacheControlResolver() {
331                return this.cacheControlResolver;
332        }
333
334        @NonNull
335        private HeadersResolver getHeadersResolver() {
336                return this.headersResolver;
337        }
338
339        @NonNull
340        private RangeRequestsResolver getRangeRequestsResolver() {
341                return this.rangeRequestsResolver;
342        }
343
344        @NonNull
345        private Optional<@NonNull ResolvedFile> resolvedFileFor(@NonNull String relativePath) {
346                requireNonNull(relativePath);
347
348                if (relativePath.getBytes(StandardCharsets.UTF_8).length > MAX_RELATIVE_PATH_UTF_8_LENGTH)
349                        return Optional.empty();
350
351                String[] segments = relativePath.split("/", -1);
352                if (segments.length > MAX_RELATIVE_PATH_SEGMENTS)
353                        return Optional.empty();
354                for (String segment : segments)
355                        if (segment.getBytes(StandardCharsets.UTF_8).length > MAX_PATH_SEGMENT_UTF_8_LENGTH)
356                                return Optional.empty();
357
358                if (containsControlCharacter(relativePath))
359                        return Optional.empty();
360
361                if (relativePath.isEmpty() && getIndexFileNames().isEmpty())
362                        return Optional.empty();
363
364                if (looksLikeWindowsDrivePath(relativePath) || looksLikeUncPath(relativePath) || relativePath.indexOf('\\') >= 0)
365                        return Optional.empty();
366
367                Path relative;
368
369                try {
370                        relative = getResolutionRoot().getFileSystem().getPath(relativePath);
371                } catch (InvalidPathException e) {
372                        return Optional.empty();
373                }
374
375                if (relative.isAbsolute())
376                        return Optional.empty();
377
378                for (Path segment : relative) {
379                        if ("..".equals(segment.toString()))
380                                return Optional.empty();
381                }
382
383                Path candidate = getResolutionRoot().resolve(relative).normalize();
384
385                if (!candidate.startsWith(getResolutionRoot()))
386                        return Optional.empty();
387
388                return resolvedFileForCandidate(candidate);
389        }
390
391        @NonNull
392        private Optional<@NonNull ResolvedFile> resolvedFileForCandidate(@NonNull Path candidate) {
393                requireNonNull(candidate);
394
395                if (getFollowSymlinks())
396                        return followedResolvedFileForCandidate(candidate);
397
398                return noFollowResolvedFileForCandidate(candidate);
399        }
400
401        @NonNull
402        private Optional<@NonNull ResolvedFile> noFollowResolvedFileForCandidate(@NonNull Path candidate) {
403                requireNonNull(candidate);
404
405                Path canonicalCandidate = canonicalNoFollowPath(candidate).orElse(null);
406                if (canonicalCandidate == null || hasSymlinkComponent(canonicalCandidate))
407                        return Optional.empty();
408                candidate = canonicalCandidate;
409
410                BasicFileAttributes attributes;
411                try {
412                        attributes = Files.readAttributes(candidate, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
413                } catch (IOException failure) {
414                        return unresolvedFile(failure);
415                }
416                if (attributes.isDirectory()) {
417                        for (String indexFileName : getIndexFileNames()) {
418                                Path indexCandidate = canonicalNoFollowPath(candidate.resolve(indexFileName).normalize()).orElse(null);
419
420                                if (indexCandidate == null || !indexCandidate.startsWith(getResolutionRoot()) || hasSymlinkComponent(indexCandidate))
421                                        continue;
422
423                                Optional<ResolvedFile> resolvedIndexFile = readableIndex(noFollowRegularFile(indexCandidate));
424
425                                if (resolvedIndexFile.isPresent())
426                                        return resolvedIndexFile;
427                        }
428
429                        return Optional.empty();
430                }
431
432                return noFollowRegularFile(candidate);
433        }
434
435        @NonNull
436        private Optional<@NonNull Path> canonicalNoFollowPath(@NonNull Path candidate) {
437                if (!candidate.startsWith(this.noFollowRoot) || Files.isSymbolicLink(this.noFollowRoot)
438                                || hasSymlinkComponent(candidate))
439                        return Optional.empty();
440                try {
441                        Path realRoot = this.noFollowRoot.toRealPath();
442                        Path realCandidate = candidate.toRealPath();
443                        if (!realCandidate.startsWith(realRoot))
444                                return Optional.empty();
445                        // Native real-path resolution avoids directory scans. Alias spelling depends
446                        // on the filesystem provider; preserve distinct hard-link names as policy paths.
447                        Path canonical = this.noFollowRoot.resolve(realRoot.relativize(realCandidate));
448                        return Files.isSymbolicLink(this.noFollowRoot) || hasSymlinkComponent(candidate)
449                                        || hasSymlinkComponent(canonical) ? Optional.empty() : Optional.of(canonical);
450                } catch (IOException e) {
451                        return unresolvedFile(e, candidate);
452                }
453        }
454
455        private <T> @NonNull Optional<T> unresolvedFile(@NonNull IOException failure, @NonNull Path candidate) {
456                // The Unix provider reports ENOTDIR as a generic FileSystemException.
457                // Inspect existing ancestors rather than relying on localized reason text.
458                if (failure instanceof FileSystemException) {
459                        if (getFollowSymlinks() && hasUnresolvableSymlinkChain(candidate))
460                                return Optional.empty();
461                        for (Path parent = candidate.getParent(); parent != null && parent.startsWith(getResolutionRoot());
462                                        parent = parent.getParent()) {
463                                try {
464                                        if (!Files.readAttributes(parent, BasicFileAttributes.class).isDirectory())
465                                                return Optional.empty();
466                                } catch (NoSuchFileException | NotDirectoryException missing) {
467                                        return Optional.empty();
468                                } catch (IOException ignored) {
469                                        // Preserve the original acquisition failure when this probe also fails.
470                                }
471                        }
472                }
473                return unresolvedFile(failure);
474        }
475
476        private boolean hasUnresolvableSymlinkChain(@NonNull Path candidate) {
477                // A generic I/O failure on a path containing a symlink is not itself a loop.
478                // Prove a repeated expansion (or reject excessive expansion) using only
479                // public no-follow metadata. Preserve the original failure if probing fails.
480                Path original = candidate;
481                Path root = getResolutionRoot();
482                var expansions = new HashSet<Path>();
483                expansions.add(candidate);
484                int links = 0;
485                try {
486                        while (candidate.startsWith(root)) {
487                                Path relative = root.relativize(candidate);
488                                Path current = root;
489                                boolean expanded = false;
490                                for (int index = 0; index < relative.getNameCount(); index++) {
491                                        current = current.resolve(relative.getName(index));
492                                        BasicFileAttributes attributes = Files.readAttributes(current, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
493                                        // Check each prefix before resolving the next component. On JDK 21,
494                                        // lstat(file/child) may report ENOTDIR as a generic I/O failure.
495                                        if (!attributes.isSymbolicLink() && !attributes.isDirectory()
496                                                        && index + 1 < relative.getNameCount())
497                                                return true;
498                                        if (!attributes.isSymbolicLink())
499                                                continue;
500                                        Path target = Files.readSymbolicLink(current);
501                                        Path parent = current.getParent();
502                                        if (!target.isAbsolute() && parent == null)
503                                                return false; // Cannot prove an unsafe chain; preserve the original I/O failure.
504                                        Path next = target.isAbsolute() ? target : parent.resolve(target);
505                                        if (index + 1 < relative.getNameCount())
506                                                next = next.resolve(relative.subpath(index + 1, relative.getNameCount()));
507                                        candidate = next.normalize();
508                                        if (++links > MAX_SYMLINK_EXPANSIONS || !expansions.add(candidate))
509                                                return true;
510                                        expanded = true;
511                                        break;
512                                }
513                                if (!expanded) {
514                                        if (candidate.equals(original))
515                                                return false;
516                                        // The OS may exhaust its symlink budget before our explicit
517                                        // expansion does. A resolvable terminal path proves that
518                                        // the failed spelling was an excessive traversal.
519                                        return Files.exists(candidate.toRealPath());
520                                }
521                        }
522                        return true; // A resolved target outside the static root is always rejected.
523                } catch (NoSuchFileException | NotDirectoryException | FileSystemLoopException | AccessDeniedException failure) {
524                        return true;
525                } catch (IOException | UnsupportedOperationException failure) {
526                        return false;
527                }
528        }
529
530        private static <T> @NonNull Optional<T> unresolvedFile(@NonNull IOException failure) {
531                if (failure instanceof NoSuchFileException || failure instanceof NotDirectoryException || failure instanceof FileSystemLoopException
532                                || failure instanceof AccessDeniedException || failure instanceof SecureStaticFileRoot.FileChangedException)
533                        return Optional.empty();
534                throw new UncheckedIOException("Unable to acquire static file.", failure);
535        }
536
537        private @NonNull Optional<@NonNull ResolvedFile> readableIndex(@NonNull Optional<@NonNull ResolvedFile> candidate) {
538                if (candidate.isEmpty())
539                        return candidate;
540                Path path = candidate.orElseThrow().path();
541                try {
542                        path.getFileSystem().provider().checkAccess(path, AccessMode.READ);
543                        return candidate;
544                } catch (IOException failure) {
545                        return unresolvedFile(failure, path);
546                }
547        }
548
549        private static boolean sameFileIdentity(@NonNull BasicFileAttributes first, @NonNull BasicFileAttributes second) {
550                return SecureStaticFileRoot.sameIdentity(first, second);
551        }
552
553        @NonNull
554        private Optional<@NonNull ResolvedFile> noFollowRegularFile(@NonNull Path candidate) {
555                requireNonNull(candidate);
556
557                try {
558                        BasicFileAttributes attributes = Files.readAttributes(candidate, BasicFileAttributes.class, LinkOption.NOFOLLOW_LINKS);
559                        return attributes.isRegularFile() ? Optional.of(new ResolvedFile(candidate, attributes)) : Optional.empty();
560                } catch (IOException e) {
561                        return unresolvedFile(e, candidate);
562                }
563        }
564
565        @NonNull
566        private Optional<@NonNull ResolvedFile> followedResolvedFileForCandidate(@NonNull Path candidate) {
567                requireNonNull(candidate);
568
569                Path realCandidate;
570
571                try {
572                        realCandidate = candidate.toRealPath();
573                } catch (IOException e) {
574                        return unresolvedFile(e, candidate);
575                }
576
577                if (!realCandidate.startsWith(this.followRoot))
578                        return Optional.empty();
579
580                BasicFileAttributes attributes;
581                try {
582                        attributes = Files.readAttributes(realCandidate, BasicFileAttributes.class);
583                } catch (IOException failure) {
584                        return unresolvedFile(failure);
585                }
586                if (attributes.isDirectory()) {
587                        for (String indexFileName : getIndexFileNames()) {
588                                Path indexCandidate = realCandidate.resolve(indexFileName).normalize();
589
590                                if (!indexCandidate.startsWith(this.followRoot))
591                                        continue;
592
593                                Optional<ResolvedFile> resolvedIndexFile = readableIndex(followedRegularFile(indexCandidate));
594
595                                if (resolvedIndexFile.isPresent())
596                                        return resolvedIndexFile;
597                        }
598
599                        return Optional.empty();
600                }
601
602                return followedRegularFile(realCandidate);
603        }
604
605        @NonNull
606        private Optional<@NonNull ResolvedFile> followedRegularFile(@NonNull Path candidate) {
607                requireNonNull(candidate);
608
609                try {
610                        Path realCandidate = candidate.toRealPath();
611
612                        if (!realCandidate.startsWith(this.followRoot))
613                                return Optional.empty();
614
615                        BasicFileAttributes attributes = Files.readAttributes(realCandidate, BasicFileAttributes.class);
616                        return attributes.isRegularFile() ? Optional.of(new ResolvedFile(realCandidate, attributes)) : Optional.empty();
617                } catch (IOException e) {
618                        return unresolvedFile(e, candidate);
619                }
620        }
621
622        @NonNull
623        private Boolean hasSymlinkComponent(@NonNull Path candidate) {
624                requireNonNull(candidate);
625
626                Path relative = getResolutionRoot().relativize(candidate);
627                Path current = getResolutionRoot();
628
629                for (Path segment : relative) {
630                        current = current.resolve(segment);
631
632                        if (Files.isSymbolicLink(current))
633                                return true;
634                }
635
636                return false;
637        }
638
639        private static void validateIndexFileName(@NonNull String indexFileName) {
640                requireNonNull(indexFileName);
641
642                if (indexFileName.isEmpty()
643                                || indexFileName.getBytes(StandardCharsets.UTF_8).length > MAX_PATH_SEGMENT_UTF_8_LENGTH
644                                || containsControlCharacter(indexFileName)
645                                || indexFileName.indexOf('/') >= 0
646                                || indexFileName.indexOf('\\') >= 0
647                                || ".".equals(indexFileName)
648                                || "..".equals(indexFileName)
649                                || looksLikeWindowsDrivePath(indexFileName)
650                                || looksLikeUncPath(indexFileName))
651                        throw new IllegalArgumentException(format("Invalid index file name '%s'.", indexFileName));
652        }
653
654        @NonNull
655        private static Boolean containsControlCharacter(@NonNull String value) {
656                requireNonNull(value);
657
658                for (int i = 0; i < value.length(); i++) {
659                        if (Character.isISOControl(value.charAt(i)))
660                                return true;
661                }
662
663                return false;
664        }
665
666        @NonNull
667        private static Boolean looksLikeWindowsDrivePath(@NonNull String value) {
668                requireNonNull(value);
669                return value.length() >= 2 && Character.isLetter(value.charAt(0)) && value.charAt(1) == ':';
670        }
671
672        @NonNull
673        private static Boolean looksLikeUncPath(@NonNull String value) {
674                requireNonNull(value);
675                return value.startsWith("//") || value.startsWith("\\\\");
676        }
677
678        @NonNull
679        private static MimeTypeResolver defaultingMimeTypeResolver(@Nullable MimeTypeResolver userResolver) {
680                return userResolver == null ? MimeTypeResolver.defaultInstance() : userResolver;
681        }
682
683        @NonNull
684        private static Map<@NonNull String, @NonNull List<@NonNull String>> copyHeaders(
685                        @NonNull Map<@NonNull String, @NonNull List<@NonNull String>> headers) {
686                requireNonNull(headers);
687
688                Map<String, List<String>> copiedHeaders = new LinkedHashMap<>();
689
690                for (Map.Entry<String, List<String>> entry : headers.entrySet()) {
691                        String headerName = requireNonNull(entry.getKey());
692                        List<String> copiedHeaderValues = new ArrayList<>(requireNonNull(entry.getValue()));
693                        copiedHeaderValues.forEach(value -> requireNonNull(value, format("Header '%s' includes a null value.", headerName)));
694                        copiedHeaders.put(headerName, Collections.unmodifiableList(copiedHeaderValues));
695                }
696
697                return Collections.unmodifiableMap(copiedHeaders);
698        }
699
700        private record ResolvedFile(@NonNull Path path,
701                                                                                                                        @NonNull BasicFileAttributes attributes) {}
702
703        /**
704         * Builder for {@link StaticFiles} instances.
705         *
706         * @author <a href="https://www.revetkn.com">Mark Allen</a>
707         */
708        @NotThreadSafe
709        public static final class Builder {
710                @NonNull
711                private final Path root;
712                @Nullable
713                private List<@NonNull String> indexFileNames;
714                @Nullable
715                private MimeTypeResolver mimeTypeResolver;
716                @Nullable
717                private EntityTagResolver entityTagResolver;
718                @Nullable
719                private AccessResolver accessResolver;
720                @Nullable
721                private LastModifiedResolver lastModifiedResolver;
722                @Nullable
723                private CacheControlResolver cacheControlResolver;
724                @Nullable
725                private HeadersResolver headersResolver;
726                @Nullable
727                private RangeRequestsResolver rangeRequestsResolver;
728                @Nullable
729                private Boolean followSymlinks;
730                @Nullable
731                private Boolean trustedImmutableRoot;
732
733                private Builder(@NonNull Path root) {
734                        requireNonNull(root);
735                        this.root = root;
736                }
737
738                /**
739                 * Declares that the root, its ancestors, links, and files are controlled exclusively by the
740                 * application operator and remain unchanged while this helper or its responses are in use.
741                 * <p>
742                 * This declaration is required on every platform. It does not set filesystem permissions or
743                 * freeze files. Do not enable it for uploads, tenant-writable directories, or any tree that
744                 * untrusted code can mutate. Public NIO checks cannot exclude all path-replacement races.
745                 * Passing {@code false} or {@code null} withdraws the declaration and makes {@link #build()}
746                 * fail closed. Deploy a new helper for a new immutable asset tree.
747                 *
748                 * @param trustedImmutableRoot {@code true} to accept the immutable-root contract
749                 * @return this builder
750                 */
751                @NonNull
752                public Builder trustedImmutableRoot(@Nullable Boolean trustedImmutableRoot) {
753                        this.trustedImmutableRoot = trustedImmutableRoot;
754                        return this;
755                }
756
757                /**
758                 * Sets the index file names to try when a request path resolves to a directory.
759                 * <p>
760                 * Names are tried in list order. Each name must be a single file name, not a path; blank
761                 * names, {@code .}, {@code ..}, path separators, control characters, Windows drive paths, and
762                 * UNC-style paths are rejected when the builder is built.
763                 * <p>
764                 * Each call replaces the complete previously configured list; it does not append. Passing
765                 * {@code null} or an empty list clears the index file names.
766                 *
767                 * @param indexFileNames the replacement index file names, or {@code null} to clear them
768                 * @return this builder
769                 */
770                @NonNull
771                public Builder indexFileNames(@Nullable List<@NonNull String> indexFileNames) {
772                        this.indexFileNames = indexFileNames;
773                        return this;
774                }
775
776                /**
777                 * Sets the resolver used to produce {@code Content-Type} values.
778                 * <p>
779                 * The configured resolver fully replaces the default resolver. Soklet's default resolver uses a
780                 * curated deterministic set of common web-asset extensions, returns {@link Optional#empty()} for
781                 * unknown extensions, and does not call {@link Files#probeContentType(Path)}. Applications that
782                 * need OS-level MIME database behavior can configure a resolver that calls
783                 * {@code Files.probeContentType(...)} directly.
784                 *
785                 * @param mimeTypeResolver the resolver to use, or {@code null} to restore the default resolver
786                 * @return this builder
787                 */
788                @NonNull
789                public Builder mimeTypeResolver(@Nullable MimeTypeResolver mimeTypeResolver) {
790                        this.mimeTypeResolver = mimeTypeResolver;
791                        return this;
792                }
793
794                /**
795                 * Sets the resolver used to produce {@code ETag} values.
796                 * <p>
797                 * Passing {@code null} restores the default weak metadata-based resolver.
798                 *
799                 * @param entityTagResolver the resolver to use, or {@code null} to restore the default resolver
800                 * @return this builder
801                 */
802                @NonNull
803                public Builder entityTagResolver(@Nullable EntityTagResolver entityTagResolver) {
804                        this.entityTagResolver = entityTagResolver;
805                        return this;
806                }
807
808                /**
809                 * Sets the resolver used to decide whether resolved files are served, denied, or hidden.
810                 * <p>
811                 * The access resolver runs after path safety, index-file resolution, symlink policy,
812                 * readability, regular-file checks, and attribute reads, but before MIME, validator,
813                 * cache-control, extra-header, and range-request resolvers. It receives the resolved file path,
814                 * not the original request path.
815                 *
816                 * @param accessResolver the resolver to use, or {@code null} to restore the allow-all default
817                 * @return this builder
818                 */
819                @NonNull
820                public Builder accessResolver(@Nullable AccessResolver accessResolver) {
821                        this.accessResolver = accessResolver;
822                        return this;
823                }
824
825                /**
826                 * Sets the resolver used to produce {@code Last-Modified} values.
827                 * <p>
828                 * Passing {@code null} restores the default resolver, which uses the file attributes read for
829                 * the response.
830                 *
831                 * @param lastModifiedResolver the resolver to use, or {@code null} to restore the default resolver
832                 * @return this builder
833                 */
834                @NonNull
835                public Builder lastModifiedResolver(@Nullable LastModifiedResolver lastModifiedResolver) {
836                        this.lastModifiedResolver = lastModifiedResolver;
837                        return this;
838                }
839
840                /**
841                 * Sets the resolver used to produce {@code Cache-Control} values.
842                 * <p>
843                 * Passing {@code null} restores the disabled resolver, which omits {@code Cache-Control}.
844                 *
845                 * @param cacheControlResolver the resolver to use, or {@code null} to omit {@code Cache-Control}
846                 * @return this builder
847                 */
848                @NonNull
849                public Builder cacheControlResolver(@Nullable CacheControlResolver cacheControlResolver) {
850                        this.cacheControlResolver = cacheControlResolver;
851                        return this;
852                }
853
854                /**
855                 * Sets the resolver used to produce extra response headers.
856                 * <p>
857                 * Passing {@code null} restores the disabled resolver, which emits no extra headers.
858                 * Managed file headers cannot be supplied here; see {@link HeadersResolver} for the
859                 * controlled names and dedicated resolver alternatives.
860                 *
861                 * @param headersResolver the resolver to use, or {@code null} to omit extra headers
862                 * @return this builder
863                 */
864                @NonNull
865                public Builder headersResolver(@Nullable HeadersResolver headersResolver) {
866                        this.headersResolver = headersResolver;
867                        return this;
868                }
869
870                /**
871                 * Sets the resolver used to decide whether byte range requests are honored.
872                 * <p>
873                 * Passing {@code null} restores the default resolver, which enables range requests.
874                 *
875                 * @param rangeRequestsResolver the resolver to use, or {@code null} to enable range requests
876                 * @return this builder
877                 */
878                @NonNull
879                public Builder rangeRequestsResolver(@Nullable RangeRequestsResolver rangeRequestsResolver) {
880                        this.rangeRequestsResolver = rangeRequestsResolver;
881                        return this;
882                }
883
884                /**
885                 * Sets whether symbolic links are followed while resolving static-file paths.
886                 * <p>
887                 * Passing {@code null} restores the default of {@code false}. When disabled, any symbolic-link
888                 * component under the static root causes the candidate path to be hidden. Enabling this option
889                 * resolves links inside the configured root. Links that resolve outside the root are hidden.
890                 * The required trusted immutable-root contract applies to links and their targets too;
891                 * observed replacement links are rejected during delivery.
892                 *
893                 * @param followSymlinks {@code true} to follow symlinks, {@code false} to reject them, or
894                 * {@code null} for the default
895                 * @return this builder
896                 */
897                @NonNull
898                public Builder followSymlinks(@Nullable Boolean followSymlinks) {
899                        this.followSymlinks = followSymlinks;
900                        return this;
901                }
902
903                /**
904                 * Builds the static-file helper.
905                 * <p>
906                 * The configured root is validated as a directory when this method is called.
907                 * With {@code followSymlinks} enabled it is resolved to a real path; otherwise
908                 * a symbolic-link root is rejected. The resolved root identity is captured without retaining
909                 * an open directory handle. Both modes require {@link #trustedImmutableRoot(Boolean)} to be
910                 * explicitly set to {@code true} and a provider with stable file identities. Rebuild the helper
911                 * when intentionally switching deployment roots, after in-flight responses have completed.
912                 * Pass the root's {@link Path#toRealPath} value explicitly to use its
913                 * resolved directory without enabling symlink traversal.
914                 *
915                 * @return the configured static-file helper
916                 */
917                @NonNull
918                public StaticFiles build() {
919                        return new StaticFiles(this);
920                }
921        }
922
923        /**
924         * Resolves {@code ETag} values for static-file responses.
925         *
926         * @author <a href="https://www.revetkn.com">Mark Allen</a>
927         */
928        @FunctionalInterface
929        @ThreadSafe
930        public interface EntityTagResolver {
931                /**
932                 * Returns the default weak metadata-based ETag resolver.
933                 * <p>
934                 * The default resolver produces a weak ETag derived from the file's last-modified epoch second
935                 * and size. This is deterministic across processes serving the same filesystem. Configure a
936                 * custom resolver, such as a content-hash resolver, when serving from filesystems that do not
937                 * preserve modification times, when same-second overwrites are common, or when stronger
938                 * collision resistance is required.
939                 *
940                 * @return the default entity-tag resolver
941                 */
942                @NonNull
943                static EntityTagResolver defaultInstance() {
944                        return DefaultEntityTagResolver.defaultInstance();
945                }
946
947                /**
948                 * Returns a resolver that omits {@code ETag}.
949                 *
950                 * @return the disabled entity-tag resolver
951                 */
952                @NonNull
953                static EntityTagResolver disabledInstance() {
954                        return DisabledEntityTagResolver.defaultInstance();
955                }
956
957                /**
958                 * Returns a strong content-hash ETag resolver.
959                 * <p>
960                 * This resolver streams the served file through SHA-256 on the request-handling thread and
961                 * emits strong ETags with values of the form {@code sha256-<lowercase-hex>}. When used by
962                 * {@link StaticFiles}, it hashes a channel acquired under the helper's root and file checks. It does not
963                 * cache digests and it fully reads the file for {@link HttpMethod#HEAD} requests as well as
964                 * {@link HttpMethod#GET} requests. Applications serving large files or HEAD-heavy traffic should
965                 * prefer a manifest-backed resolver.
966                 *
967                 * @return a strong content-hash entity-tag resolver
968                 */
969                @NonNull
970                static EntityTagResolver fromContentHash() {
971                        return ContentHashEntityTagResolver.defaultInstance();
972                }
973
974                /**
975                 * Resolves the ETag for the file being served.
976                 * <p>
977                 * Implementations must be thread-safe; {@link StaticFiles} invokes resolvers concurrently from
978                 * request-handling threads. Resolvers run on the request-handling thread, so expensive work such
979                 * as content hashing or network calls should be cached or precomputed.
980                 *
981                 * @param path the resolved file path being served
982                 * @param attributes the file attributes read for this response
983                 * @return the ETag to emit, or {@link Optional#empty()} to omit it
984                 */
985                @NonNull
986                Optional<@NonNull EntityTag> entityTagFor(@NonNull Path path,
987                                                                                                                                                 @NonNull BasicFileAttributes attributes);
988        }
989
990        /**
991         * Access outcome for a resolved static file.
992         *
993         * <p>
994         * This type may gain reviewed constants in Soklet 4.x; use a forward-compatible default when switching over its values.
995         *
996         * @author <a href="https://www.revetkn.com">Mark Allen</a>
997         */
998        public enum Access {
999                /**
1000                 * Continue normal static-file response generation.
1001                 */
1002                ALLOW,
1003                /**
1004                 * Return a bodyless {@code 403 Forbidden} response.
1005                 */
1006                DENY,
1007                /**
1008                 * Return {@link Optional#empty()} from {@link StaticFiles#marshaledResponseFor(String, Request)}.
1009                 */
1010                HIDE
1011        }
1012
1013        /**
1014         * Resolves whether a resolved static file should be served, denied, or hidden.
1015         *
1016         * @author <a href="https://www.revetkn.com">Mark Allen</a>
1017         */
1018        @FunctionalInterface
1019        @ThreadSafe
1020        public interface AccessResolver {
1021                /**
1022                 * Returns a resolver that allows all resolved static files.
1023                 *
1024                 * @return the allow-all access resolver
1025                 */
1026                @NonNull
1027                static AccessResolver allowAllInstance() {
1028                        return AllowAllAccessResolver.defaultInstance();
1029                }
1030
1031                /**
1032                 * Resolves static-file access for the file being served.
1033                 * <p>
1034                 * Implementations must be thread-safe; {@link StaticFiles} invokes resolvers concurrently from
1035                 * request-handling threads. This resolver is intentionally path- and attribute-based. For
1036                 * request-aware access decisions, gate {@link StaticFiles#marshaledResponseFor(String, Request)}
1037                 * from the resource method or another higher application layer.
1038                 *
1039                 * @param path the resolved file path being served
1040                 * @param attributes the file attributes read for this response
1041                 * @return the access outcome
1042                 */
1043                @NonNull
1044                Access accessFor(@NonNull Path path,
1045                                                                                 @NonNull BasicFileAttributes attributes);
1046        }
1047
1048        /**
1049         * Resolves {@code Last-Modified} values for static-file responses.
1050         *
1051         * @author <a href="https://www.revetkn.com">Mark Allen</a>
1052         */
1053        @FunctionalInterface
1054        @ThreadSafe
1055        public interface LastModifiedResolver {
1056                /**
1057                 * Returns a resolver that emits the file's last-modified timestamp from its attributes.
1058                 *
1059                 * @return the attribute-based last-modified resolver
1060                 */
1061                @NonNull
1062                static LastModifiedResolver fromAttributes() {
1063                        return DefaultLastModifiedResolver.defaultInstance();
1064                }
1065
1066                /**
1067                 * Returns a resolver that omits {@code Last-Modified}.
1068                 *
1069                 * @return the disabled last-modified resolver
1070                 */
1071                @NonNull
1072                static LastModifiedResolver disabledInstance() {
1073                        return DisabledLastModifiedResolver.defaultInstance();
1074                }
1075
1076                /**
1077                 * Resolves the {@code Last-Modified} value for the file being served.
1078                 * <p>
1079                 * Implementations must be thread-safe; {@link StaticFiles} invokes resolvers concurrently from
1080                 * request-handling threads.
1081                 *
1082                 * @param path the resolved file path being served
1083                 * @param attributes the file attributes read for this response
1084                 * @return the last-modified instant to emit, or {@link Optional#empty()} to omit it
1085                 */
1086                @NonNull
1087                Optional<@NonNull Instant> lastModifiedFor(@NonNull Path path,
1088                                                                                                                                                        @NonNull BasicFileAttributes attributes);
1089        }
1090
1091        /**
1092         * Resolves {@code Cache-Control} values for static-file responses.
1093         *
1094         * @author <a href="https://www.revetkn.com">Mark Allen</a>
1095         */
1096        @FunctionalInterface
1097        @ThreadSafe
1098        public interface CacheControlResolver {
1099                /**
1100                 * Returns a resolver that always emits the supplied {@code Cache-Control} value.
1101                 *
1102                 * @param cacheControl the cache-control value to emit
1103                 * @return the constant cache-control resolver
1104                 */
1105                @NonNull
1106                static CacheControlResolver fromValue(@NonNull String cacheControl) {
1107                        requireNonNull(cacheControl);
1108                        String normalizedCacheControl = Utilities.trimAggressivelyToNull(cacheControl);
1109
1110                        if (normalizedCacheControl == null)
1111                                throw new IllegalArgumentException("Cache-Control value must not be blank.");
1112
1113                        return (path, attributes) -> Optional.of(normalizedCacheControl);
1114                }
1115
1116                /**
1117                 * Returns a resolver that omits {@code Cache-Control}.
1118                 *
1119                 * @return the disabled cache-control resolver
1120                 */
1121                @NonNull
1122                static CacheControlResolver disabledInstance() {
1123                        return DisabledCacheControlResolver.defaultInstance();
1124                }
1125
1126                /**
1127                 * Resolves the {@code Cache-Control} value for the file being served.
1128                 * <p>
1129                 * Implementations must be thread-safe; {@link StaticFiles} invokes resolvers concurrently from
1130                 * request-handling threads.
1131                 *
1132                 * @param path the resolved file path being served
1133                 * @param attributes the file attributes read for this response
1134                 * @return the cache-control value to emit, or {@link Optional#empty()} to omit it
1135                 */
1136                @NonNull
1137                Optional<@NonNull String> cacheControlFor(@NonNull Path path,
1138                                                                                                                                                 @NonNull BasicFileAttributes attributes);
1139        }
1140
1141        /**
1142         * Resolves extra response headers for static-file responses.
1143         * <p>
1144         * Header names are checked case-insensitively. {@code Content-Length}, {@code Content-Range},
1145         * {@code Accept-Ranges}, {@code Content-Type}, {@code Content-Encoding}, {@code Cache-Control},
1146         * {@code ETag}, {@code Last-Modified}, and {@code Transfer-Encoding} are managed by file responses
1147         * and must not be returned here. Use the builder's {@link Builder#mimeTypeResolver(MimeTypeResolver)},
1148         * {@link Builder#cacheControlResolver(CacheControlResolver)}, {@link Builder#entityTagResolver(EntityTagResolver)},
1149         * {@link Builder#lastModifiedResolver(LastModifiedResolver)}, or
1150         * {@link Builder#rangeRequestsResolver(RangeRequestsResolver)} where applicable; framing is computed by the transport.
1151         *
1152         * @author <a href="https://www.revetkn.com">Mark Allen</a>
1153         */
1154        @FunctionalInterface
1155        @ThreadSafe
1156        public interface HeadersResolver {
1157                /**
1158                 * Returns a resolver that always emits the supplied headers.
1159                 * <p>
1160                 * The header map and nested value sets are defensively copied.
1161                 * Managed headers listed on {@link HeadersResolver} are rejected immediately.
1162                 *
1163                 * @param headers the headers to emit
1164                 * @return the constant headers resolver
1165                 * @throws IllegalArgumentException if a header is controlled by file responses
1166                 */
1167                @NonNull
1168                static HeadersResolver fromHeaders(@NonNull Map<@NonNull String, @NonNull List<@NonNull String>> headers) {
1169                        requireNonNull(headers);
1170                        Map<String, List<String>> copiedHeaders = copyHeaders(headers);
1171                        FileResponse.rejectControlledHeaderConflicts(copiedHeaders, "StaticFiles.HeadersResolver");
1172                        return (path, attributes) -> copiedHeaders;
1173                }
1174
1175                /**
1176                 * Returns a resolver that emits no extra headers.
1177                 *
1178                 * @return the disabled headers resolver
1179                 */
1180                @NonNull
1181                static HeadersResolver disabledInstance() {
1182                        return DisabledHeadersResolver.defaultInstance();
1183                }
1184
1185                /**
1186                 * Resolves extra response headers for the file being served.
1187                 * Managed headers listed on {@link HeadersResolver} are rejected when the response is produced.
1188                 * <p>
1189                 * Implementations must be thread-safe; {@link StaticFiles} invokes resolvers concurrently from
1190                 * request-handling threads.
1191                 *
1192                 * @param path the resolved file path being served
1193                 * @param attributes the file attributes read for this response
1194                 * @return extra headers to emit
1195                 */
1196                @NonNull
1197                Map<@NonNull String, @NonNull List<@NonNull String>> headersFor(@NonNull Path path,
1198                                                                                                                                                                                                                                                                         @NonNull BasicFileAttributes attributes);
1199        }
1200
1201        /**
1202         * Resolves whether byte range requests are honored for static-file responses.
1203         *
1204         * @author <a href="https://www.revetkn.com">Mark Allen</a>
1205         */
1206        @FunctionalInterface
1207        @ThreadSafe
1208        public interface RangeRequestsResolver {
1209                /**
1210                 * Returns a resolver that enables byte range requests.
1211                 *
1212                 * @return the range-request-enabled resolver
1213                 */
1214                @NonNull
1215                static RangeRequestsResolver enabledInstance() {
1216                        return EnabledRangeRequestsResolver.defaultInstance();
1217                }
1218
1219                /**
1220                 * Returns a resolver that disables byte range requests.
1221                 *
1222                 * @return the range-request-disabled resolver
1223                 */
1224                @NonNull
1225                static RangeRequestsResolver disabledInstance() {
1226                        return DisabledRangeRequestsResolver.defaultInstance();
1227                }
1228
1229                /**
1230                 * Resolves whether byte range requests are enabled for the file being served.
1231                 * <p>
1232                 * Implementations must be thread-safe; {@link StaticFiles} invokes resolvers concurrently from
1233                 * request-handling threads.
1234                 *
1235                 * @param path the resolved file path being served
1236                 * @param attributes the file attributes read for this response
1237                 * @return {@code true} if range requests should be honored, otherwise {@code false}
1238                 */
1239                @NonNull
1240                Boolean rangeRequestsFor(@NonNull Path path,
1241                                                                                                                 @NonNull BasicFileAttributes attributes);
1242        }
1243
1244        @ThreadSafe
1245        private static final class DisabledEntityTagResolver implements EntityTagResolver {
1246                @NonNull
1247                private static final DisabledEntityTagResolver INSTANCE;
1248
1249                static {
1250                        INSTANCE = new DisabledEntityTagResolver();
1251                }
1252
1253                @NonNull
1254                static DisabledEntityTagResolver defaultInstance() {
1255                        return INSTANCE;
1256                }
1257
1258                @Override
1259                @NonNull
1260                public Optional<@NonNull EntityTag> entityTagFor(@NonNull Path path,
1261                                                                                                                                                                                @NonNull BasicFileAttributes attributes) {
1262                        requireNonNull(path);
1263                        requireNonNull(attributes);
1264                        return Optional.empty();
1265                }
1266        }
1267
1268        @ThreadSafe
1269        private static final class ContentHashEntityTagResolver implements EntityTagResolver {
1270                @NonNull
1271                private static final ContentHashEntityTagResolver INSTANCE;
1272
1273                static {
1274                        INSTANCE = new ContentHashEntityTagResolver();
1275                }
1276
1277                @NonNull
1278                static ContentHashEntityTagResolver defaultInstance() {
1279                        return INSTANCE;
1280                }
1281
1282                @Override
1283                @NonNull
1284                public Optional<@NonNull EntityTag> entityTagFor(@NonNull Path path,
1285                                                                                                                                                                                @NonNull BasicFileAttributes attributes) {
1286                        requireNonNull(path);
1287                        requireNonNull(attributes);
1288                        try (InputStream inputStream = Files.newInputStream(path)) {
1289                                return Optional.of(hash(inputStream));
1290                        } catch (IOException e) {
1291                                throw new UncheckedIOException(format("Unable to hash static file '%s'.", path), e);
1292                        }
1293                }
1294
1295                @NonNull
1296                static EntityTag entityTagFor(@NonNull SeekableByteChannel channel) throws IOException {
1297                        return hash(Channels.newInputStream(channel));
1298                }
1299
1300                @NonNull
1301                private static EntityTag hash(@NonNull InputStream inputStream) throws IOException {
1302                        MessageDigest messageDigest;
1303
1304                        try {
1305                                messageDigest = MessageDigest.getInstance("SHA-256");
1306                        } catch (NoSuchAlgorithmException e) {
1307                                throw new IllegalStateException("SHA-256 message digest is not available.", e);
1308                        }
1309
1310                        byte[] buffer = new byte[CONTENT_HASH_BUFFER_SIZE];
1311
1312                        for (int bytesRead = inputStream.read(buffer); bytesRead >= 0; bytesRead = inputStream.read(buffer))
1313                                if (bytesRead > 0)
1314                                        messageDigest.update(buffer, 0, bytesRead);
1315
1316                        return EntityTag.fromStrongValue(format("sha256-%s", HEX_FORMAT.formatHex(messageDigest.digest())));
1317                }
1318        }
1319
1320        @ThreadSafe
1321        private static final class AllowAllAccessResolver implements AccessResolver {
1322                @NonNull
1323                private static final AllowAllAccessResolver INSTANCE;
1324
1325                static {
1326                        INSTANCE = new AllowAllAccessResolver();
1327                }
1328
1329                @NonNull
1330                static AllowAllAccessResolver defaultInstance() {
1331                        return INSTANCE;
1332                }
1333
1334                @Override
1335                @NonNull
1336                public Access accessFor(@NonNull Path path,
1337                                                                                                                @NonNull BasicFileAttributes attributes) {
1338                        requireNonNull(path);
1339                        requireNonNull(attributes);
1340                        return Access.ALLOW;
1341                }
1342        }
1343
1344        @ThreadSafe
1345        private static final class DefaultLastModifiedResolver implements LastModifiedResolver {
1346                @NonNull
1347                private static final DefaultLastModifiedResolver INSTANCE;
1348
1349                static {
1350                        INSTANCE = new DefaultLastModifiedResolver();
1351                }
1352
1353                @NonNull
1354                static DefaultLastModifiedResolver defaultInstance() {
1355                        return INSTANCE;
1356                }
1357
1358                @Override
1359                @NonNull
1360                public Optional<@NonNull Instant> lastModifiedFor(@NonNull Path path,
1361                                                                                                                                                                                 @NonNull BasicFileAttributes attributes) {
1362                        requireNonNull(path);
1363                        requireNonNull(attributes);
1364                        return Optional.of(Instant.ofEpochSecond(attributes.lastModifiedTime().toInstant().getEpochSecond()));
1365                }
1366        }
1367
1368        @ThreadSafe
1369        private static final class DisabledLastModifiedResolver implements LastModifiedResolver {
1370                @NonNull
1371                private static final DisabledLastModifiedResolver INSTANCE;
1372
1373                static {
1374                        INSTANCE = new DisabledLastModifiedResolver();
1375                }
1376
1377                @NonNull
1378                static DisabledLastModifiedResolver defaultInstance() {
1379                        return INSTANCE;
1380                }
1381
1382                @Override
1383                @NonNull
1384                public Optional<@NonNull Instant> lastModifiedFor(@NonNull Path path,
1385                                                                                                                                                                                 @NonNull BasicFileAttributes attributes) {
1386                        requireNonNull(path);
1387                        requireNonNull(attributes);
1388                        return Optional.empty();
1389                }
1390        }
1391
1392        @ThreadSafe
1393        private static final class DefaultEntityTagResolver implements EntityTagResolver {
1394                @NonNull
1395                private static final DefaultEntityTagResolver INSTANCE;
1396
1397                static {
1398                        INSTANCE = new DefaultEntityTagResolver();
1399                }
1400
1401                @NonNull
1402                static DefaultEntityTagResolver defaultInstance() {
1403                        return INSTANCE;
1404                }
1405
1406                @Override
1407                @NonNull
1408                public Optional<@NonNull EntityTag> entityTagFor(@NonNull Path path,
1409                                                                                                                                                                                @NonNull BasicFileAttributes attributes) {
1410                        requireNonNull(path);
1411                        requireNonNull(attributes);
1412                        Long epochSecond = attributes.lastModifiedTime().toInstant().getEpochSecond();
1413                        Long size = attributes.size();
1414                        return Optional.of(EntityTag.fromWeakValue("mtime-" + epochSecond + "-size-" + size));
1415                }
1416        }
1417
1418        @ThreadSafe
1419        private static final class DisabledCacheControlResolver implements CacheControlResolver {
1420                @NonNull
1421                private static final DisabledCacheControlResolver INSTANCE;
1422
1423                static {
1424                        INSTANCE = new DisabledCacheControlResolver();
1425                }
1426
1427                @NonNull
1428                static DisabledCacheControlResolver defaultInstance() {
1429                        return INSTANCE;
1430                }
1431
1432                @Override
1433                @NonNull
1434                public Optional<@NonNull String> cacheControlFor(@NonNull Path path,
1435                                                                                                                                                                                @NonNull BasicFileAttributes attributes) {
1436                        requireNonNull(path);
1437                        requireNonNull(attributes);
1438                        return Optional.empty();
1439                }
1440        }
1441
1442        @ThreadSafe
1443        private static final class DisabledHeadersResolver implements HeadersResolver {
1444                @NonNull
1445                private static final DisabledHeadersResolver INSTANCE;
1446
1447                static {
1448                        INSTANCE = new DisabledHeadersResolver();
1449                }
1450
1451                @NonNull
1452                static DisabledHeadersResolver defaultInstance() {
1453                        return INSTANCE;
1454                }
1455
1456                @Override
1457                @NonNull
1458                public Map<@NonNull String, @NonNull List<@NonNull String>> headersFor(@NonNull Path path,
1459                                                                                                                                                                                                                                                                                                        @NonNull BasicFileAttributes attributes) {
1460                        requireNonNull(path);
1461                        requireNonNull(attributes);
1462                        return Map.of();
1463                }
1464        }
1465
1466        @ThreadSafe
1467        private static final class EnabledRangeRequestsResolver implements RangeRequestsResolver {
1468                @NonNull
1469                private static final EnabledRangeRequestsResolver INSTANCE;
1470
1471                static {
1472                        INSTANCE = new EnabledRangeRequestsResolver();
1473                }
1474
1475                @NonNull
1476                static EnabledRangeRequestsResolver defaultInstance() {
1477                        return INSTANCE;
1478                }
1479
1480                @Override
1481                @NonNull
1482                public Boolean rangeRequestsFor(@NonNull Path path,
1483                                                                                                                                                @NonNull BasicFileAttributes attributes) {
1484                        requireNonNull(path);
1485                        requireNonNull(attributes);
1486                        return true;
1487                }
1488        }
1489
1490        @ThreadSafe
1491        private static final class DisabledRangeRequestsResolver implements RangeRequestsResolver {
1492                @NonNull
1493                private static final DisabledRangeRequestsResolver INSTANCE;
1494
1495                static {
1496                        INSTANCE = new DisabledRangeRequestsResolver();
1497                }
1498
1499                @NonNull
1500                static DisabledRangeRequestsResolver defaultInstance() {
1501                        return INSTANCE;
1502                }
1503
1504                @Override
1505                @NonNull
1506                public Boolean rangeRequestsFor(@NonNull Path path,
1507                                                                                                                                                @NonNull BasicFileAttributes attributes) {
1508                        requireNonNull(path);
1509                        requireNonNull(attributes);
1510                        return false;
1511                }
1512        }
1513
1514}