001/*
002 * Licensed to the Apache Software Foundation (ASF) under one
003 * or more contributor license agreements.  See the NOTICE file
004 * distributed with this work for additional information
005 * regarding copyright ownership.  The ASF licenses this file
006 * to you under the Apache License, Version 2.0 (the
007 * "License"); you may not use this file except in compliance
008 * with the License.  You may obtain a copy of the License at
009 *
010 *   http://www.apache.org/licenses/LICENSE-2.0
011 *
012 * Unless required by applicable law or agreed to in writing,
013 * software distributed under the License is distributed on an
014 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
015 * KIND, either express or implied.  See the License for the
016 * specific language governing permissions and limitations
017 * under the License.
018 */
019package org.eclipse.aether.internal.test.util.http;
020
021import java.io.File;
022import java.io.IOException;
023import java.net.DatagramSocket;
024import java.net.ServerSocket;
025import java.net.URI;
026import java.nio.channels.SeekableByteChannel;
027import java.nio.charset.StandardCharsets;
028import java.nio.file.Files;
029import java.nio.file.StandardOpenOption;
030import java.util.ArrayList;
031import java.util.Base64;
032import java.util.Collection;
033import java.util.Collections;
034import java.util.List;
035import java.util.Map;
036import java.util.TreeMap;
037import java.util.concurrent.CountDownLatch;
038import java.util.concurrent.ThreadLocalRandom;
039import java.util.concurrent.atomic.AtomicInteger;
040import java.util.regex.Matcher;
041import java.util.regex.Pattern;
042import java.util.stream.Collectors;
043
044import com.google.gson.Gson;
045import jakarta.servlet.http.HttpServletResponse;
046import org.eclipse.aether.internal.impl.checksum.Sha1ChecksumAlgorithmFactory;
047import org.eclipse.aether.spi.connector.checksum.ChecksumAlgorithmHelper;
048import org.eclipse.aether.spi.connector.transport.http.RFC9457.RFC9457Payload;
049import org.eclipse.jetty.alpn.server.ALPNServerConnectionFactory;
050import org.eclipse.jetty.compression.server.CompressionConfig;
051import org.eclipse.jetty.compression.server.CompressionHandler;
052import org.eclipse.jetty.http.DateGenerator;
053import org.eclipse.jetty.http.HttpField;
054import org.eclipse.jetty.http.HttpFields;
055import org.eclipse.jetty.http.HttpHeader;
056import org.eclipse.jetty.http.HttpMethod;
057import org.eclipse.jetty.http.HttpURI;
058import org.eclipse.jetty.http.HttpVersion;
059import org.eclipse.jetty.http.pathmap.MatchedResource;
060import org.eclipse.jetty.http.pathmap.PathMappings;
061import org.eclipse.jetty.http.pathmap.PathSpec;
062import org.eclipse.jetty.http2.server.HTTP2ServerConnectionFactory;
063import org.eclipse.jetty.http3.server.HTTP3ServerConnectionFactory;
064import org.eclipse.jetty.http3.server.HTTP3ServerQuicConfiguration;
065import org.eclipse.jetty.io.ByteBufferPool;
066import org.eclipse.jetty.io.Content;
067import org.eclipse.jetty.io.DatagramChannelEndPoint;
068import org.eclipse.jetty.io.EndPoint;
069import org.eclipse.jetty.quic.quiche.server.QuicheServerConnector;
070import org.eclipse.jetty.quic.quiche.server.QuicheServerQuicConfiguration;
071import org.eclipse.jetty.server.Handler;
072import org.eclipse.jetty.server.HttpConfiguration;
073import org.eclipse.jetty.server.HttpConnectionFactory;
074import org.eclipse.jetty.server.Request;
075import org.eclipse.jetty.server.Response;
076import org.eclipse.jetty.server.SecureRequestCustomizer;
077import org.eclipse.jetty.server.Server;
078import org.eclipse.jetty.server.ServerConnector;
079import org.eclipse.jetty.server.SslConnectionFactory;
080import org.eclipse.jetty.util.Blocker;
081import org.eclipse.jetty.util.Callback;
082import org.eclipse.jetty.util.ssl.SslContextFactory;
083import org.slf4j.Logger;
084import org.slf4j.LoggerFactory;
085
086public class HttpServer {
087
088    public static class LogEntry {
089        private final HttpVersion version;
090
091        private final String method;
092
093        private final String path;
094
095        private final Map<String, String> requestHeaders;
096
097        private Map<String, String> responseHeaders;
098
099        CountDownLatch responseHeadersAvailableSignal = new CountDownLatch(1);
100
101        public LogEntry(HttpVersion version, String method, String path, Map<String, String> requestHeaders) {
102            this.version = version;
103            this.method = method;
104            this.path = path;
105            this.requestHeaders = requestHeaders;
106        }
107
108        public HttpVersion getVersion() {
109            return version;
110        }
111
112        public String getMethod() {
113            return method;
114        }
115
116        public String getPath() {
117            return path;
118        }
119
120        public Map<String, String> getRequestHeaders() {
121            return requestHeaders;
122        }
123
124        /**
125         * This method blocks until the response headers are available.
126         * @return the response headers
127         */
128        public Map<String, String> getResponseHeaders() {
129            try {
130                if (!responseHeadersAvailableSignal.await(30, java.util.concurrent.TimeUnit.SECONDS)) {
131                    throw new IllegalStateException("Timeout waiting for response headers to be available");
132                }
133            } catch (InterruptedException e) {
134                Thread.currentThread().interrupt();
135                throw new IllegalStateException("Interrupted while waiting for response headers to be available", e);
136            }
137            return responseHeaders;
138        }
139
140        public void setResponseHeaders(Map<String, String> responseHeaders) {
141            this.responseHeaders = responseHeaders;
142            responseHeadersAvailableSignal.countDown();
143        }
144
145        @Override
146        public String toString() {
147            return version + " " + method + " " + path;
148        }
149    }
150
151    public enum ExpectContinue {
152        FAIL,
153        PROPER,
154        BROKEN
155    }
156
157    public enum ChecksumHeader {
158        NEXUS,
159        XCHECKSUM,
160        XCHECKSUM_GOOGLE,
161        XCHECKSUM_AMAZON
162    }
163
164    private static final Logger LOGGER = LoggerFactory.getLogger(HttpServer.class);
165
166    private File repoDir;
167
168    private boolean rangeSupport = true;
169
170    private boolean webDav;
171
172    private ExpectContinue expectContinue = ExpectContinue.PROPER;
173
174    private ChecksumHeader checksumHeader;
175
176    private Server server;
177
178    private ServerConnector httpConnector;
179
180    private ServerConnector httpsConnector;
181
182    private QuicheServerConnector http3Connector;
183
184    private String username;
185
186    private String password;
187
188    private String proxyUsername;
189
190    private String proxyPassword;
191
192    private final AtomicInteger connectionsToClose = new AtomicInteger(0);
193
194    private final AtomicInteger serverErrorsBeforeWorks = new AtomicInteger(0);
195
196    private int serverErrorStatusCode;
197
198    private final List<LogEntry> logEntries = Collections.synchronizedList(new ArrayList<>());
199
200    private String responseBodyForPut;
201
202    private Map<String, String> serverErrorHeaders = Collections.emptyMap();
203
204    public String getHost() {
205        return "localhost";
206    }
207
208    public int getHttpPort() {
209        return httpConnector != null ? httpConnector.getLocalPort() : -1;
210    }
211
212    public int getHttpsPort() {
213        return httpsConnector != null ? httpsConnector.getLocalPort() : -1;
214    }
215
216    public int getHttp3Port() {
217        return http3Connector != null ? http3Connector.getLocalPort() : -1;
218    }
219
220    public String getHttpUrl() {
221        return "http://" + getHost() + ":" + getHttpPort();
222    }
223
224    public String getHttpsUrl() {
225        return "https://" + getHost() + ":" + getHttpsPort();
226    }
227
228    public String getHttp3Url() {
229        return "https://" + getHost() + ":" + getHttp3Port();
230    }
231
232    public HttpServer addHttp2ConnectorWithMutualTLS() {
233        return addHttp2Connector(true, true, -1);
234    }
235
236    public HttpServer addHttp2Connector() {
237        return addHttp2Connector(false, true, -1);
238    }
239
240    public HttpServer addHttp2OnlyConnector() {
241        return addHttp2Connector(false, false, -1);
242    }
243
244    public HttpServer addHttp2OnlyConnectorWithMutualTLS() {
245        return addHttp2Connector(true, false, -1);
246    }
247
248    public HttpServer addHttp2OnlyConnectorWithMutualTLS(int port) {
249        return addHttp2Connector(true, false, port);
250    }
251
252    private HttpServer addHttp2Connector(boolean needClientAuth, boolean needHttp11, int port) {
253        if (httpsConnector == null) {
254            SslContextFactory.Server ssl = createServerSslContextFactory(needClientAuth);
255
256            HttpConfiguration httpsConfig = new HttpConfiguration();
257            SecureRequestCustomizer customizer = new SecureRequestCustomizer();
258            customizer.setSniHostCheck(false);
259            httpsConfig.addCustomizer(customizer);
260
261            HttpConnectionFactory http1 = null;
262            if (needHttp11) {
263                http1 = new HttpConnectionFactory(httpsConfig);
264            }
265
266            HTTP2ServerConnectionFactory http2 = new HTTP2ServerConnectionFactory(httpsConfig);
267
268            ALPNServerConnectionFactory alpn = new ALPNServerConnectionFactory();
269            alpn.setDefaultProtocol(http1 != null ? http1.getProtocol() : http2.getProtocol());
270
271            SslConnectionFactory tls = new SslConnectionFactory(ssl, alpn.getProtocol());
272            if (http1 != null) {
273                httpsConnector = new ServerConnector(server, tls, alpn, http2, http1);
274            } else {
275                httpsConnector = new ServerConnector(server, tls, alpn, http2);
276            }
277
278            if (port != -1) {
279                httpsConnector.setPort(port);
280            }
281
282            server.addConnector(httpsConnector);
283            try {
284                httpsConnector.start();
285            } catch (Exception e) {
286                throw new IllegalStateException(e);
287            }
288        }
289        return this;
290    }
291
292    private SslContextFactory.Server createServerSslContextFactory(boolean needClientAuth) {
293        SslContextFactory.Server ssl = new SslContextFactory.Server();
294        ssl.setSniRequired(false);
295        ssl.setKeyStorePath(SslTestSupport.SERVER_STORE_PATH.toAbsolutePath().toString());
296        ssl.setKeyStorePassword("server-pwd");
297        ssl.setNeedClientAuth(needClientAuth);
298        if (needClientAuth) {
299            ssl.setTrustStorePath(
300                    SslTestSupport.CLIENT_STORE_PATH.toAbsolutePath().toString());
301            ssl.setTrustStorePassword("client-pwd");
302        }
303        return ssl;
304    }
305
306    public HttpServer addHttp3Connector(boolean needClientAuth) {
307        return addHttp3Connector(needClientAuth, -1);
308    }
309
310    public HttpServer addHttp3Connector(boolean needClientAuth, int port) {
311        if (http3Connector == null) {
312            QuicheServerQuicConfiguration serverQuicConfig = HTTP3ServerQuicConfiguration.configure(
313                    new QuicheServerQuicConfiguration(SslTestSupport.PEM_QUICHE_SERVER_PATH));
314            http3Connector = new QuicheServerConnector(
315                    server,
316                    createServerSslContextFactory(needClientAuth),
317                    serverQuicConfig,
318                    new HTTP3ServerConnectionFactory());
319            if (port != -1) {
320                http3Connector.setPort(port);
321            }
322            server.addConnector(http3Connector);
323            try {
324                http3Connector.start();
325            } catch (Exception e) {
326                throw new IllegalStateException(e);
327            }
328        }
329        return this;
330    }
331
332    /**
333     * Finds a port that is free for both TCP and UDP, so that the HTTP/2 (TCP) and HTTP/3 (UDP) connectors can be
334     * bound to the same port number. TCP and UDP port spaces are independent, so a port that is free for one may be
335     * taken, or reserved by the OS, for the other.
336     * <p>
337     * Candidates are drawn at random rather than taken from the OS: Windows hands out ephemeral ports in sequence and
338     * Hyper-V reserves UDP port blocks 100 ports wide, so probing OS-assigned ports one after another could walk
339     * through an entire reserved block without finding a free pair (MRESOLVER-2142). The candidate range stays below
340     * the ephemeral ranges of Linux (32768+) and Windows (49152+) to limit races with other processes' client sockets
341     * between the probe and the connector's own bind.
342     *
343     * @return a port number that is (at probe time) free for both TCP and UDP
344     */
345    int findFreeTcpAndUdpPort() {
346        ThreadLocalRandom random = ThreadLocalRandom.current();
347        for (int i = 0; i < 100; i++) {
348            int port = random.nextInt(10_000, 32_768);
349            try (ServerSocket tcp = new ServerSocket(port);
350                    DatagramSocket udp = new DatagramSocket(port)) {
351                return port;
352            } catch (IOException e) {
353                // taken or reserved for one of the protocols: try another candidate
354            }
355        }
356        throw new IllegalStateException("Failed to find a port free for both TCP and UDP");
357    }
358
359    public List<LogEntry> getLogEntries() {
360        return logEntries;
361    }
362
363    public HttpServer setRepoDir(File repoDir) {
364        this.repoDir = repoDir;
365        return this;
366    }
367
368    public HttpServer setRangeSupport(boolean rangeSupport) {
369        this.rangeSupport = rangeSupport;
370        return this;
371    }
372
373    public HttpServer setResponseBodyForPut(String body) {
374        this.responseBodyForPut = body;
375        return this;
376    }
377
378    public HttpServer setWebDav(boolean webDav) {
379        this.webDav = webDav;
380        return this;
381    }
382
383    public HttpServer setExpectSupport(ExpectContinue expectContinue) {
384        this.expectContinue = expectContinue;
385        return this;
386    }
387
388    public HttpServer setChecksumHeader(ChecksumHeader checksumHeader) {
389        this.checksumHeader = checksumHeader;
390        return this;
391    }
392
393    public HttpServer setAuthentication(String username, String password) {
394        this.username = username;
395        this.password = password;
396        return this;
397    }
398
399    public HttpServer setProxyAuthentication(String username, String password) {
400        proxyUsername = username;
401        proxyPassword = password;
402        return this;
403    }
404
405    public HttpServer setConnectionsToClose(int connectionsToClose) {
406        this.connectionsToClose.set(connectionsToClose);
407        return this;
408    }
409
410    public HttpServer setServerErrorsBeforeWorks(int serverErrorsBeforeWorks) {
411        return setServerErrorsBeforeWorks(serverErrorsBeforeWorks, HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
412    }
413
414    public HttpServer setServerErrorsBeforeWorks(int serverErrorsBeforeWorks, int errorStatusCode) {
415        return setServerErrorsBeforeWorks(serverErrorsBeforeWorks, errorStatusCode, Collections.emptyMap());
416    }
417
418    public HttpServer setServerErrorsBeforeWorks(
419            int serverErrorsBeforeWorks, int errorStatusCode, Map<String, String> headers) {
420        this.serverErrorsBeforeWorks.set(serverErrorsBeforeWorks);
421        this.serverErrorStatusCode = errorStatusCode;
422        this.serverErrorHeaders = headers;
423        return this;
424    }
425
426    public HttpServer start() throws Exception {
427        if (server != null) {
428            return this;
429        }
430
431        server = new Server();
432        httpConnector = new ServerConnector(server);
433        // always add the HTTP 1.1 connector
434        server.addConnector(httpConnector);
435
436        server.setHandler(new LogHandler(new CompressionEnforcingHandler(new Handler.Sequence(
437                new ConnectionClosingHandler(),
438                new ServerErrorHandler(),
439                new ProxyAuthHandler(),
440                new AuthHandler(),
441                new RedirectHandler(),
442                new RepoHandler(),
443                new RFC9457Handler()))));
444        server.start();
445
446        return this;
447    }
448
449    public void stop() throws Exception {
450        if (server != null) {
451            server.stop();
452            server = null;
453            httpConnector = null;
454            httpsConnector = null;
455        }
456    }
457
458    public int getNumConnectedEndPoints() {
459        if (server.isStopped()) {
460            throw new IllegalStateException("Server is stopped");
461        }
462        Collection<EndPoint> connectedEndPoints = new ArrayList<>();
463        if (httpConnector != null) {
464            connectedEndPoints.addAll(httpConnector.getConnectedEndPoints());
465        }
466        if (httpsConnector != null) {
467            connectedEndPoints.addAll(httpsConnector.getConnectedEndPoints());
468        }
469        if (http3Connector != null) {
470            // filter out the always present DatagramChannelEndPoint, which is not a real live connection
471            // (https://github.com/jetty/jetty.project/issues/15436)
472            http3Connector.getConnectedEndPoints().stream()
473                    .filter(endPoint -> !(endPoint instanceof DatagramChannelEndPoint))
474                    .forEach(connectedEndPoints::add);
475        }
476        return connectedEndPoints.size();
477    }
478
479    private class CompressionEnforcingHandler extends CompressionHandler {
480        // duplicate of CompressionHandler.pathConfigs which is private
481        private final PathMappings<CompressionConfig> pathConfigs = new PathMappings<>();
482
483        CompressionEnforcingHandler(Handler handler) {
484            super(handler);
485            this.putConfiguration(
486                    "/br/*",
487                    CompressionConfig.builder().compressIncludeEncoding("br").build());
488            this.putConfiguration(
489                    "/zstd/*",
490                    CompressionConfig.builder().compressIncludeEncoding("zstd").build());
491            this.putConfiguration(
492                    "/gzip/*",
493                    CompressionConfig.builder().compressIncludeEncoding("gzip").build());
494            this.putConfiguration(
495                    "/deflate/*",
496                    CompressionConfig.builder()
497                            .compressIncludeEncoding("deflate")
498                            .build());
499        }
500
501        @Override
502        public CompressionConfig putConfiguration(PathSpec pathSpec, CompressionConfig config) {
503            // deliberately not set it in the super class yet
504            return pathConfigs.put(pathSpec, config);
505        }
506
507        @Override
508        public boolean handle(Request request, Response response, Callback callback) throws Exception {
509            Handler next = getHandler();
510            if (next == null) {
511                return false;
512            }
513            String pathInContext = Request.getPathInContext(request);
514            MatchedResource<CompressionConfig> matchedConfig = this.pathConfigs.getMatched(pathInContext);
515            if (matchedConfig == null) {
516                if (LOGGER.isDebugEnabled()) {
517                    LOGGER.debug("skipping compression: path {} has no matching compression config", pathInContext);
518                }
519                // No configuration, skip
520                return next.handle(request, response, callback);
521            }
522
523            // set the matched config in the super class for further processing, but for all paths
524            // no need to reset it later as this handler is not used among multiple requests
525            super.putConfiguration(PathSpec.from("/*"), matchedConfig.getResource());
526            // first path segment determines the encoding, remove it from the request path for further processing
527            return super.handle(new StripLeadingPathSegmentsRequestWrapper(request, 1), response, callback);
528        }
529    }
530
531    private static class StripLeadingPathSegmentsRequestWrapper extends Request.Wrapper {
532        private final HttpURI modifiedURI;
533
534        StripLeadingPathSegmentsRequestWrapper(Request wrapped, int segmentsToStrip) {
535            super(wrapped);
536            this.modifiedURI = stripPathSegments(wrapped.getHttpURI(), segmentsToStrip);
537        }
538
539        private static HttpURI stripPathSegments(HttpURI originalURI, int segmentsToStrip) {
540            if (segmentsToStrip <= 0) {
541                return originalURI;
542            }
543
544            String originalPath = originalURI.getPath();
545            if (originalPath == null || originalPath.isEmpty()) {
546                return originalURI;
547            }
548
549            // Split path into segments
550            String[] segments = originalPath.split("/");
551            StringBuilder newPath = new StringBuilder();
552
553            // Skip empty first segment (from leading /) and the specified number of segments
554            int skipCount = 0;
555            for (int i = 0; i < segments.length; i++) {
556                if (segments[i].isEmpty() && i == 0) {
557                    // Skip leading empty segment from leading /
558                    continue;
559                }
560                if (skipCount < segmentsToStrip) {
561                    skipCount++;
562                    continue;
563                }
564                newPath.append("/").append(segments[i]);
565            }
566
567            // If we stripped everything, return root path
568            if (newPath.isEmpty()) {
569                newPath.append("/");
570            }
571
572            // Build new URI with modified path
573            return org.eclipse.jetty.http.HttpURI.build(originalURI)
574                    .path(newPath.toString())
575                    .asImmutable();
576        }
577
578        @Override
579        public HttpURI getHttpURI() {
580            return modifiedURI;
581        }
582    }
583
584    private class ConnectionClosingHandler extends Handler.Abstract {
585
586        @Override
587        public boolean handle(Request request, Response response, Callback callback) throws Exception {
588            if (connectionsToClose.getAndDecrement() > 0) {
589                request.getConnectionMetaData().getConnection().close();
590            }
591            return false;
592        }
593    }
594
595    private class ServerErrorHandler extends Handler.Abstract {
596        @Override
597        public boolean handle(Request request, Response response, Callback callback) throws IOException {
598            if (serverErrorsBeforeWorks.getAndDecrement() > 0) {
599                response.setStatus(serverErrorStatusCode);
600                for (Map.Entry<String, String> header : serverErrorHeaders.entrySet()) {
601                    response.getHeaders().add(header.getKey(), header.getValue());
602                }
603                writeResponseBodyMessage(request, response, "Oops, come back later!");
604                return true;
605            }
606            return false;
607        }
608    }
609
610    private class LogHandler extends Handler.Wrapper {
611
612        LogHandler(Handler handler) {
613            super(handler);
614        }
615
616        @Override
617        public boolean handle(Request req, Response response, Callback callback) throws Exception {
618
619            LOGGER.info(
620                    "{} {} {}{}",
621                    req.getConnectionMetaData().getHttpVersion(),
622                    req.getMethod(),
623                    req.getHttpURI().getDecodedPath(),
624                    req.getHttpURI().getQuery() != null ? "?" + req.getHttpURI().getQuery() : "");
625
626            Map<String, String> requestHeaders =
627                    toUnmodifiableMap(req.getHeaders()); // capture request headers before other handlers modify them
628            LogEntry logEntry = new LogEntry(
629                    req.getConnectionMetaData().getHttpVersion(),
630                    req.getMethod(),
631                    req.getHttpURI().getPathQuery(),
632                    requestHeaders);
633            logEntries.add(logEntry);
634            // prevent closing the response before logging (assume all writes are synchronous for simplicity)
635            boolean result = super.handle(req, response, callback);
636            // capture response headers after other handlers modified them
637            // at this point in time the connection may have been already closed (i.e. last chunk already sent)
638            logEntry.setResponseHeaders(toUnmodifiableMap(response.getHeaders()));
639            if (result) {
640                callback.succeeded();
641            }
642            return result;
643        }
644
645        Map<String, String> toUnmodifiableMap(HttpFields headers) {
646            Map<String, String> map = new TreeMap<>(String.CASE_INSENSITIVE_ORDER);
647            for (HttpField header : headers) {
648                map.put(header.getName(), header.getValueList().stream().collect(Collectors.joining(", ")));
649            }
650            return Collections.unmodifiableMap(map);
651        }
652    }
653
654    private static final Pattern SIMPLE_RANGE = Pattern.compile("bytes=([0-9])+-");
655
656    private class RepoHandler extends Handler.Abstract {
657        @Override
658        public boolean handle(Request req, Response response, Callback callback) throws Exception {
659            String path = req.getHttpURI().getDecodedPath().substring(1);
660
661            if (!path.startsWith("repo/")) {
662                return false;
663            }
664
665            if (ExpectContinue.FAIL.equals(expectContinue) && req.getHeaders().get(HttpHeader.EXPECT) != null) {
666                response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED);
667                writeResponseBodyMessage(req, response, "Expectation was set to fail");
668                return true;
669            }
670
671            File file = new File(repoDir, path.substring(5));
672            if (HttpMethod.GET.is(req.getMethod()) || HttpMethod.HEAD.is(req.getMethod())) {
673                if (!file.isFile() || path.endsWith("/")) {
674                    response.setStatus(HttpServletResponse.SC_NOT_FOUND);
675                    writeResponseBodyMessage(req, response, "Not found");
676                    return true;
677                }
678
679                long ifUnmodifiedSince = req.getHeaders().getDateField(HttpHeader.IF_UNMODIFIED_SINCE);
680                if (ifUnmodifiedSince != -1L && file.lastModified() > ifUnmodifiedSince) {
681                    response.setStatus(HttpServletResponse.SC_PRECONDITION_FAILED);
682                    writeResponseBodyMessage(req, response, "Precondition failed");
683                    return true;
684                }
685
686                long offset = 0L;
687                String range = req.getHeaders().get(HttpHeader.RANGE);
688                if (range != null && rangeSupport) {
689                    Matcher m = SIMPLE_RANGE.matcher(range);
690                    if (m.matches()) {
691                        offset = Long.parseLong(m.group(1));
692                        if (offset >= file.length()) {
693                            response.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
694                            writeResponseBodyMessage(req, response, "Range not satisfiable");
695                            return true;
696                        }
697                    }
698                    String encoding = req.getHeaders().get(HttpHeader.ACCEPT_ENCODING);
699                    if ((encoding != null && !"identity".equals(encoding)) || ifUnmodifiedSince == -1L) {
700                        response.setStatus(HttpServletResponse.SC_BAD_REQUEST);
701                        return true;
702                    }
703                }
704
705                response.setStatus((offset > 0L) ? HttpServletResponse.SC_PARTIAL_CONTENT : HttpServletResponse.SC_OK);
706                response.getHeaders().add(HttpHeader.LAST_MODIFIED, DateGenerator.formatDate(file.lastModified()));
707                response.getHeaders().add(HttpHeader.CONTENT_LENGTH, Long.toString(file.length() - offset));
708                if (offset > 0L) {
709                    response.getHeaders()
710                            .add(
711                                    HttpHeader.CONTENT_RANGE,
712                                    "bytes " + offset + "-" + (file.length() - 1L) + "/" + file.length());
713                }
714                if (checksumHeader != null) {
715                    Map<String, String> checksums = ChecksumAlgorithmHelper.calculate(
716                            file, Collections.singletonList(new Sha1ChecksumAlgorithmFactory()));
717                    if (checksumHeader == ChecksumHeader.NEXUS) {
718                        response.getHeaders().add(HttpHeader.ETAG.asString(), "{SHA1{" + checksums.get("SHA-1") + "}}");
719                    } else if (checksumHeader == ChecksumHeader.XCHECKSUM) {
720                        response.getHeaders().add("x-checksum-sha1", checksums.get(Sha1ChecksumAlgorithmFactory.NAME));
721                    } else if (checksumHeader == ChecksumHeader.XCHECKSUM_GOOGLE) {
722                        response.getHeaders()
723                                .add("x-goog-meta-checksum-sha1", checksums.get(Sha1ChecksumAlgorithmFactory.NAME));
724                    } else if (checksumHeader == ChecksumHeader.XCHECKSUM_AMAZON) {
725                        response.getHeaders()
726                                .add("x-amz-meta-checksum-sha1", checksums.get(Sha1ChecksumAlgorithmFactory.NAME));
727                    }
728                }
729                if (HttpMethod.HEAD.is(req.getMethod())) {
730                    return true;
731                }
732                Content.Source contentSource =
733                        Content.Source.from(new ByteBufferPool.Sized(null), file.toPath(), offset, -1);
734                try (Blocker.Callback fileReadCallback = Blocker.callback()) {
735                    Content.copy(contentSource, response, fileReadCallback);
736                    fileReadCallback.block();
737                }
738            } else if (HttpMethod.PUT.is(req.getMethod())) {
739                if (!webDav) {
740                    file.getParentFile().mkdirs();
741                }
742                if (file.getParentFile().exists()) {
743                    try (SeekableByteChannel channel = Files.newByteChannel(
744                                    file.toPath(),
745                                    StandardOpenOption.CREATE,
746                                    StandardOpenOption.WRITE,
747                                    StandardOpenOption.TRUNCATE_EXISTING);
748                            Blocker.Callback fileWriteCallback = Blocker.callback()) {
749                        Content.copy(req, Content.Sink.from(channel), fileWriteCallback);
750                        fileWriteCallback.block();
751                    } catch (IOException e) {
752                        LOGGER.warn("Failed to write file {}", file.getAbsolutePath(), e);
753                        file.delete();
754                        throw e;
755                    }
756                    // optionally add some response body to test that the client can handle it, even though Maven
757                    // Repository Protocol doesn't mention it
758                    if (responseBodyForPut != null) {
759                        writeResponseBodyMessage(req, response, responseBodyForPut);
760                        response.setStatus(HttpServletResponse.SC_CREATED);
761                    } else {
762                        response.setStatus(HttpServletResponse.SC_NO_CONTENT);
763                    }
764                } else {
765                    response.setStatus(HttpServletResponse.SC_FORBIDDEN);
766                }
767            } else if (HttpMethod.OPTIONS.is(req.getMethod())) {
768                if (webDav) {
769                    response.getHeaders().add("DAV", "1,2");
770                }
771                response.getHeaders().add(HttpHeader.ALLOW, "GET, PUT, HEAD, OPTIONS");
772                response.setStatus(HttpServletResponse.SC_OK);
773            } else if (webDav && "MKCOL".equals(req.getMethod())) {
774                if (file.exists()) {
775                    response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
776                } else if (file.mkdir()) {
777                    response.setStatus(HttpServletResponse.SC_CREATED);
778                } else {
779                    response.setStatus(HttpServletResponse.SC_CONFLICT);
780                }
781            } else {
782                response.setStatus(HttpServletResponse.SC_METHOD_NOT_ALLOWED);
783            }
784            return true;
785        }
786    }
787
788    private void writeResponseBodyMessage(Request request, Response response, String message) throws IOException {
789        // write synchronously to avoid closing the response too early
790        try (Blocker.Callback callback = Blocker.callback()) {
791            Content.Sink.write(response, false, message, callback);
792            callback.block();
793        }
794    }
795
796    private class RFC9457Handler extends Handler.Abstract {
797        @Override
798        public boolean handle(Request req, Response response, Callback callback) throws Exception {
799            String path = req.getHttpURI().getPath().substring(1);
800
801            if (!path.startsWith("rfc9457/")) {
802                return false;
803            }
804
805            if (HttpMethod.GET.is(req.getMethod())) {
806                response.setStatus(HttpServletResponse.SC_FORBIDDEN);
807                response.getHeaders().add(HttpHeader.CONTENT_TYPE.asString(), "application/problem+json");
808                RFC9457Payload rfc9457Payload;
809                if (path.endsWith("missing_fields.txt")) {
810                    rfc9457Payload = new RFC9457Payload(null, null, null, null, null);
811                } else {
812                    rfc9457Payload = new RFC9457Payload(
813                            URI.create("https://example.com/probs/out-of-credit"),
814                            HttpServletResponse.SC_FORBIDDEN,
815                            "You do not have enough credit.",
816                            "Your current balance is 30, but that costs 50.",
817                            URI.create("/account/12345/msgs/abc"));
818                }
819                writeResponseBodyMessage(req, response, buildRFC9457Message(rfc9457Payload));
820            }
821            return true;
822        }
823    }
824
825    private String buildRFC9457Message(RFC9457Payload payload) {
826        return new Gson().toJson(payload, RFC9457Payload.class);
827    }
828
829    private class RedirectHandler extends Handler.Abstract {
830        @Override
831        public boolean handle(Request req, Response response, Callback callback) throws Exception {
832            String path = req.getHttpURI().getPath();
833            if (!path.startsWith("/redirect/")) {
834                return false;
835            }
836            StringBuilder location = new StringBuilder(128);
837            var parameters = Request.getParameters(req);
838            String scheme = parameters.getValue("scheme");
839            String host = parameters.getValue("host");
840            location.append(scheme != null ? scheme : req.getHttpURI().getScheme());
841            location.append("://");
842            location.append(host != null ? host : Request.getServerName(req));
843            location.append(":");
844            if ("http".equalsIgnoreCase(scheme)) {
845                location.append(getHttpPort());
846            } else if ("https".equalsIgnoreCase(scheme)) {
847                location.append(getHttpsPort());
848            } else {
849                location.append(Request.getServerPort(req));
850            }
851            location.append("/repo").append(path.substring(9));
852            Response.sendRedirect(
853                    req, response, callback, HttpServletResponse.SC_MOVED_PERMANENTLY, location.toString(), false);
854            return true;
855        }
856    }
857
858    private class AuthHandler extends Handler.Abstract {
859        @Override
860        public boolean handle(Request request, Response response, Callback callback) throws Exception {
861            if (ExpectContinue.BROKEN.equals(expectContinue)
862                    && "100-continue".equalsIgnoreCase(request.getHeaders().get(HttpHeader.EXPECT))) {
863                // TODO: what is this for?
864                Request.asInputStream(request);
865            }
866
867            if (username != null && password != null) {
868                if (checkBasicAuth(request.getHeaders().get(HttpHeader.AUTHORIZATION), username, password)) {
869                    return false;
870                }
871                response.getHeaders().add(HttpHeader.WWW_AUTHENTICATE, "Basic realm=\"Test-Realm\"");
872                response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
873                return true;
874            }
875            return false;
876        }
877    }
878
879    private class ProxyAuthHandler extends Handler.Abstract {
880        @Override
881        public boolean handle(Request req, Response response, Callback callback) throws Exception {
882            if (proxyUsername != null && proxyPassword != null) {
883                if (checkBasicAuth(
884                        req.getHeaders().get(HttpHeader.PROXY_AUTHORIZATION), proxyUsername, proxyPassword)) {
885                    return false;
886                }
887                response.getHeaders().add(HttpHeader.PROXY_AUTHENTICATE, "basic realm=\"Test-Realm\"");
888                response.setStatus(HttpServletResponse.SC_PROXY_AUTHENTICATION_REQUIRED);
889                return true;
890            } else {
891                return false;
892            }
893        }
894    }
895
896    static boolean checkBasicAuth(String credentials, String username, String password) {
897        if (credentials != null) {
898            int space = credentials.indexOf(' ');
899            if (space > 0) {
900                String method = credentials.substring(0, space);
901                if ("basic".equalsIgnoreCase(method)) {
902                    credentials = credentials.substring(space + 1);
903                    credentials = new String(Base64.getDecoder().decode(credentials), StandardCharsets.ISO_8859_1);
904                    int i = credentials.indexOf(':');
905                    if (i > 0) {
906                        String user = credentials.substring(0, i);
907                        String pass = credentials.substring(i + 1);
908                        if (username.equals(user) && password.equals(pass)) {
909                            return true;
910                        }
911                    }
912                }
913            }
914        }
915        return false;
916    }
917}