WebFramework.java

1
package com.renomad.minum.web;
2
3
import com.renomad.minum.logging.ILogger;
4
import com.renomad.minum.security.ForbiddenUseException;
5
import com.renomad.minum.security.ITheBrig;
6
import com.renomad.minum.state.Constants;
7
import com.renomad.minum.state.Context;
8
import com.renomad.minum.utils.*;
9
10
import javax.net.ssl.SSLException;
11
import java.io.ByteArrayOutputStream;
12
import java.io.IOException;
13
import java.io.OutputStream;
14
import java.net.SocketException;
15
import java.net.SocketTimeoutException;
16
import java.nio.charset.StandardCharsets;
17
import java.nio.file.Path;
18
import java.time.ZoneId;
19
import java.time.ZonedDateTime;
20
import java.time.format.DateTimeFormatter;
21
import java.util.*;
22
import java.util.concurrent.ConcurrentHashMap;
23
import java.util.concurrent.locks.ReentrantLock;
24
import java.util.function.Function;
25
import java.util.zip.GZIPOutputStream;
26
27
import static com.renomad.minum.utils.FileUtils.checkForBadFilePatterns;
28
import static com.renomad.minum.web.StatusLine.StatusCode.*;
29
import static com.renomad.minum.web.WebEngine.HTTP_CRLF;
30
31
/**
32
 * This class is responsible for the HTTP handling after socket connection.
33
 * <p>
34
 *     The public methods are for registering endpoints - code that will be
35
 *     run for a given combination of HTTP method and path.  See documentation
36
 *     for the methods in this class.
37
 * </p>
38
 */
39
public final class WebFramework {
40
41
    private final Constants constants;
42
    private final IInputStreamUtils inputStreamUtils;
43
    private final IBodyProcessor bodyProcessor;
44
    /**
45
     * This is a variable storing a pseudo-random (non-secure) number
46
     * that is shown to users when a serious error occurs, which
47
     * will also be put in the logs, to make finding it easier.
48
     */
49
    private final Random randomErrorCorrelationId;
50
    private final RequestLine validRequestLine;
51
    private final ITheBrig theBrig;
52
    private final IFileUtils fileUtils;
53
54
    /**
55
     * This contains the directory path to the static files, as
56
     * specified in the configuration file.  See {@link Constants#staticFilesDirectory}
57
     */
58
    private final Path staticFilesDirectoryPathBase;
59
60
    public Map<String,String> getSuffixToMimeMappings() {
61 1 1. getSuffixToMimeMappings : replaced return value with Collections.emptyMap for com/renomad/minum/web/WebFramework::getSuffixToMimeMappings → KILLED
        return new HashMap<>(fileSuffixToMime);
62
    }
63
64
    /**
65
     * This is used as a key when registering endpoints
66
     */
67
    record MethodPath(RequestLine.Method method, String path) { }
68
69
    /**
70
     * The list of paths that our system is registered to handle.
71
     */
72
    private final Map<MethodPath, ThrowingFunction<IRequest, IResponse>> registeredDynamicPaths;
73
74
    /**
75
     * These are registrations for cases where the function depends on parts of the path conditionally.
76
     * Like if the client sends us GET /.well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX
77
     * and we want to match ".well-known/acme-challenge"
78
     */
79
    private final Map<RequestLine.Method, List<Function<String, ThrowingFunction<IRequest, IResponse>>>> registeredPathFunctions;
80
81
    /**
82
     * A special path function that checks if the path starts with the defined one.
83
     * It's here to retain the duplication check on {@link #registerPartialPath(RequestLine.Method, String, ThrowingFunction)},
84
     */
85
    private record PartialPathFunction(String pathName, ThrowingFunction<IRequest, IResponse> handler) implements Function<String, ThrowingFunction<IRequest, IResponse>> {
86
        @Override
87
        public ThrowingFunction<IRequest, IResponse> apply(String path) {
88 1 1. apply : negated conditional → KILLED
            return path.startsWith(pathName) ? handler : null;
89
        }
90
    }
91
92
    /**
93
     * A function that will be run instead of the ordinary business code. Has
94
     * provisions for running the business code as well.  See {@link #registerPreHandler(ThrowingFunction)}
95
     */
96
    private ThrowingFunction<PreHandlerInputs, IResponse> preHandler;
97
98
    /**
99
     * A function run after the ordinary business code
100
     */
101
    private ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler;
102
103
    private final IFileReader fileReader;
104
105
    /**
106
     * A map between a key of file suffixes and a value of mime type,
107
     * used for determining a proper mime for response on a file in
108
     * the static files directory
109
     */
110
    private final Map<String, String> fileSuffixToMime;
111
112
    /**
113
     * This is a map of path to a boolean valuable for whether the
114
     * file benefits from compression.
115
     */
116
    private final Map<String, Boolean> fileIsCompressible;
117
118
    // This is just used for testing.  If it's null, we use the real time.
119
    private final ZonedDateTime overrideForDateTime;
120
    private final FullSystem fs;
121
    private final ILogger logger;
122
123
    /**
124
     * For static files (See {@link Constants#staticFilesDirectory}), This is
125
     * the cutoff for the maximum quantity of bytes where we will
126
     * use {@link FileReader#readFile(String)} and caching for the data.
127
     * Past this point, we will use {@link #createOkResponseForLargeStaticFiles}
128
     * and not use caching.
129
     */
130
    static final int MAX_CACHED_BYTES = 100_000;
131
132
    void httpProcessing(ISocketWrapper sw) {
133
        try (sw) {
134
            final var is = sw.getInputStream();
135
136
            // By default, browsers expect the server to run in keep-alive mode.
137
            // We'll break out later if we find that the browser doesn't do keep-alive
138
            while (true) {
139
                dumpIfAttacker(sw, fs);
140
                // we'll store the status line and headers in this
141
                StringBuilder headerStringBuilder = new StringBuilder(600); // 600 is just a magic arbitrary number I picked, because our response headers
142
                // are not usually too large - even if the user added a bunch, there is a good
143
                // chance it would be far under 600.  If that turns out to be wrong, adjust/redesign
144
145
                // set some basic variables we'll need access to throughout
146
                long startMillis = System.currentTimeMillis();
147
                RequestLine requestLine;
148
                IRequest request;
149
                Headers headers;
150
                IResponse response;
151
                boolean isKeepAlive;
152
                IResponse adjustedResponse;
153
                boolean isHeadRequest = false;
154
155
                final String rawStartLine = inputStreamUtils.readLine(is);
156
157
                try {
158 2 1. httpProcessing : negated conditional → TIMED_OUT
2. httpProcessing : negated conditional → TIMED_OUT
                    if (rawStartLine == null || rawStartLine.isEmpty()) {
159
                        // here, the client connected, sent nothing, and closed.
160
                        // nothing to do but return.
161
                        logger.logTrace(() -> "rawStartLine was empty.  Returning.");
162
                        break;
163
                    }
164
                    requestLine = getProcessedRequestLine(sw, rawStartLine);
165
166
                    // check if the user is seeming to attack us.
167 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::checkIfSuspiciousPath → TIMED_OUT
                    checkIfSuspiciousPath(sw, requestLine);
168
169
                    // React to what the user requested, generate a result
170
                    headers = getHeaders(sw);
171
                    request = new Request(headers, requestLine, sw.getRemoteAddr(), sw, bodyProcessor, false);
172
                    response = processRequest(request, sw, requestLine, headers);
173
174
                    // check that the response is non-null.  If it is null, that suggests
175
                    // the developer made a mistake.
176 1 1. httpProcessing : negated conditional → KILLED
                    if (response == null) {
177
                        throw new WebServerException("The returned value for the endpoint \"%s\" was null.".formatted(request.getRequestLine().getPathDetails().getIsolatedPath()));
178
                    }
179
180
                    isKeepAlive = determineIfKeepAlive(request, logger, request.hasAccessedBody());
181
182
                    // calculate proper headers for the response
183 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → TIMED_OUT
                    addDefaultHeaders(response, headerStringBuilder);
184 1 1. httpProcessing : removed call to com/renomad/minum/web/Headers::appendHeadersToBuilder → KILLED
                    response.getExtraHeaders().appendHeadersToBuilder(headerStringBuilder);
185 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addKeepAliveTimeout → TIMED_OUT
                    addKeepAliveTimeout(isKeepAlive, headerStringBuilder);
186
187
                    // if the response is text (i.e. probably good compressibility) and large enough
188
                    // to be worth compressing, we'll compress it.
189 3 1. httpProcessing : negated conditional → TIMED_OUT
2. httpProcessing : negated conditional → TIMED_OUT
3. httpProcessing : changed conditional boundary → KILLED
                    if (response.isBodyText() && response.getBodyLength() > 500) {
190
                        List<String> acceptEncoding = headers.valueByKey("accept-encoding");
191
                        adjustedResponse = compressBodyIfRequested(response, acceptEncoding, headerStringBuilder, logger, request.getRequestLine().getRawValue());
192
                    } else {
193
                        adjustedResponse = response;
194
                    }
195
196 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::applyContentLength → TIMED_OUT
                    applyContentLength(headerStringBuilder, adjustedResponse.getBodyLength());
197 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::confirmBodyHasContentType → KILLED
                    confirmBodyHasContentType(request, response);
198
199
                    // if the user sent a HEAD request, we send everything back except the body.
200
                    // even though we skip the body, this requires full processing to get the
201
                    // numbers right, like content-length.
202 1 1. httpProcessing : negated conditional → KILLED
                    if (request.getRequestLine().getMethod().equals(RequestLine.Method.HEAD)) {
203
                        logger.logDebug(() -> "client " + request.getRemoteRequester() +
204
                                " is requesting HEAD for " + request.getRequestLine().getPathDetails().getIsolatedPath() +
205
                                ".  Excluding body from response");
206
                        isHeadRequest = true;
207
                    }
208
209
                } catch (BadRequestException ex) {
210
                    // this catch block needs to be down below the scope where
211
                    // the request variable is needed.
212 1 1. httpProcessing : removed call to java/lang/StringBuilder::setLength → TIMED_OUT
                    headerStringBuilder.setLength(0); // clear the contents
213
                    adjustedResponse = handleBadRequestException(ex);
214 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → KILLED
                    addDefaultHeaders(adjustedResponse, headerStringBuilder);
215
                    isKeepAlive = false;
216
                    headerStringBuilder.append("Content-Length: ").append(adjustedResponse.getBodyLength()).append(HTTP_CRLF);
217
                }
218
219
                // send the headers
220 1 1. httpProcessing : removed call to com/renomad/minum/web/ISocketWrapper::send → TIMED_OUT
                sw.send(headerStringBuilder.append(HTTP_CRLF).toString().getBytes(StandardCharsets.US_ASCII));
221
222 1 1. httpProcessing : negated conditional → KILLED
                if (!isHeadRequest) {
223
                    // send the body
224 1 1. httpProcessing : removed call to com/renomad/minum/web/IResponse::sendBody → TIMED_OUT
                    adjustedResponse.sendBody(sw);
225
                }
226
227
                // ship it out
228 1 1. httpProcessing : removed call to com/renomad/minum/web/ISocketWrapper::flush → TIMED_OUT
                sw.flush();
229
230
                // print how long this processing took
231
                long endMillis = System.currentTimeMillis();
232
                logger.logTrace(() -> String.format("full processing (including communication time) of %s %s took %d millis", sw, rawStartLine, endMillis - startMillis));
233
234 1 1. httpProcessing : negated conditional → TIMED_OUT
                if (!isKeepAlive) {
235
                    logger.logTrace(() -> "We will not keep-alive this connection - exiting loop and closing socket");
236
                    break;
237
                }
238
239
            }
240
        } catch (ForbiddenUseException ex) {
241 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::handleForbiddenUse → KILLED
            handleForbiddenUse(sw, ex, logger, theBrig, constants.vulnSeekingJailDuration);
242
        } catch (Exception ex) {
243 1 1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::finalExceptionHandler → TIMED_OUT
            finalExceptionHandler(sw, ex, logger, theBrig, constants.vulnSeekingJailDuration, constants.suspiciousErrors);
244
        }
245
    }
246
247
248
    /**
249
     * Last-chance handler for any exceptions originating in WebFramework.httpProcessing
250
     */
251
    static void finalExceptionHandler(ISocketWrapper sw, Throwable ex, ILogger logger, ITheBrig theBrig,
252
                                      long vulnSeekingJailDuration, Set<String> suspiciousErrors) {
253
        // This first section catches a lot when clients make eager connections in anticipation of
254
        // parallel requests, but then let them time out.
255 2 1. finalExceptionHandler : negated conditional → KILLED
2. finalExceptionHandler : negated conditional → KILLED
        if (ex instanceof SocketException || ex instanceof SocketTimeoutException) {
256 1 1. finalExceptionHandler : negated conditional → SURVIVED
            if (ex.getMessage().equals("Read timed out")) {
257
                logger.logTrace(() -> "Read timed out - remote address: " + sw.getRemoteAddrWithPort());
258
            } else {
259
                logger.logDebug(() -> ex.getMessage() + " - remote address: " + sw.getRemoteAddrWithPort());
260
            }
261 2 1. finalExceptionHandler : negated conditional → KILLED
2. finalExceptionHandler : negated conditional → KILLED
        } else if (suspiciousErrors.contains(ex.getMessage()) && theBrig != null) {
262
            logger.logDebug(() -> sw.getRemoteAddr() + " is looking for vulnerabilities, for this: " + ex.getMessage());
263
            theBrig.sendToJail(sw.getRemoteAddr() + "_vuln_seeking", vulnSeekingJailDuration);
264 1 1. finalExceptionHandler : negated conditional → KILLED
        } else if (ex instanceof SSLException) {
265
            // at this point we just want to catch some of the common garbage exceptions that bubble up
266
            // as a result of clients force-closing their SSl connections
267
            logger.logTrace(() -> ex.getMessage() + "for remote address: " + sw.getRemoteAddrWithPort());
268
        } else {
269
            logger.logWarn(() -> "Exception caught in WebFramework.finalExceptionHandler: " + StacktraceUtils.stackTraceToString(ex));
270
        }
271
    }
272
273
    static void handleForbiddenUse(ISocketWrapper sw, ForbiddenUseException ex, ILogger logger, ITheBrig theBrig, long vulnSeekingJailDuration) {
274
        logger.logDebug(() -> sw.getRemoteAddr() + " is looking for vulnerabilities, for this: " + ex.getMessage());
275 1 1. handleForbiddenUse : negated conditional → KILLED
        if (theBrig != null) {
276
            theBrig.sendToJail(sw.getRemoteAddr() + "_vuln_seeking", vulnSeekingJailDuration);
277
        } else {
278
            logger.logDebug(() -> "theBrig is null at handleForbiddenUse, will not store address in database");
279
        }
280
    }
281
282
    /**
283
     * if an error happens in parsing a request, and it's not considered an attack (which
284
     * would instead use ForbiddenUseException), this is the
285
     * last-chance handling of that error where we return a 400 Bad Request response and a
286
     * random code to the client, so a developer can find the detailed
287
     * information in the logs, which have that same value.
288
     */
289
    IResponse handleBadRequestException(BadRequestException ex) {
290
        int randomNumber = randomErrorCorrelationId.nextInt();
291
        logger.logDebug(() -> "Bad data in request. Code: " + randomNumber + " Error: " + ex.getMessage() + (ex.getCause() == null ? "" : " Cause: " + ex.getCause().getMessage()));
292 1 1. handleBadRequestException : replaced return value with null for com/renomad/minum/web/WebFramework::handleBadRequestException → TIMED_OUT
        return Response.buildResponse(CODE_400_BAD_REQUEST, new Headers(List.of("Content-Type: text/plain;charset=UTF-8")), "Bad request from user (HTTP 400) error: " + randomNumber);
293
    }
294
295
    /**
296
     * Logic for how to process an incoming request.  For example, did the developer
297
     * write a function to handle this? Is it a request for a static file, like an image
298
     * or script?  Did the user provide a "pre" or "post" handler?
299
     */
300
    IResponse processRequest(
301
            IRequest clientRequest,
302
            ISocketWrapper sw,
303
            RequestLine requestLine,
304
            Headers requestHeaders) throws Exception {
305
        IResponse response;
306
        ThrowingFunction<IRequest, IResponse> endpoint = findEndpointForThisStartline(requestLine, requestHeaders);
307 1 1. processRequest : negated conditional → KILLED
        if (endpoint == null) {
308
            response = Response.buildLeanResponse(CODE_404_NOT_FOUND);
309
        } else {
310
            long millisAtStart = System.currentTimeMillis();
311
            try {
312 1 1. processRequest : negated conditional → TIMED_OUT
                if (preHandler != null) {
313
                    response = preHandler.apply(new PreHandlerInputs(clientRequest, endpoint, sw));
314
                } else {
315
                    response = endpoint.apply(clientRequest);
316
                }
317
            } catch (Exception ex) {
318
                // if an error happens while running an endpoint's code, this is the
319
                // last-chance handling of that error where we return a 500 and a
320
                // random code to the client, so a developer can find the detailed
321
                // information in the logs, which have that same value.
322
                int randomNumber = randomErrorCorrelationId.nextInt();
323
                logger.logAsyncError(() -> "error while running endpoint " + endpoint + ". Code: " + randomNumber + ". Error: " + StacktraceUtils.stackTraceToString(ex));
324
                response = Response.buildResponse(CODE_500_INTERNAL_SERVER_ERROR, new Headers(List.of("Content-Type: text/plain;charset=UTF-8")), "Server error: " + randomNumber);
325
            }
326
            long millisAtEnd = System.currentTimeMillis();
327
            logger.logTrace(() -> String.format("handler processing of %s %s took %d millis", sw, requestLine, millisAtEnd - millisAtStart));
328
        }
329
330 1 1. processRequest : negated conditional → TIMED_OUT
        if (lastMinuteHandler != null) {
331
            response = lastMinuteHandler.apply(new LastMinuteHandlerInputs(clientRequest, response));
332
        }
333
334 1 1. processRequest : replaced return value with null for com/renomad/minum/web/WebFramework::processRequest → KILLED
        return response;
335
    }
336
337
    private Headers getHeaders(ISocketWrapper sw) throws IOException {
338
    /*
339
       next we will read the headers (e.g. Content-Type: foo/bar) one-by-one.
340
341
       the headers tell us vital information about the
342
       body.  If, for example, we're getting a POST and receiving a
343
       www form url encoded, there will be a header of "content-length"
344
       that will mention how many bytes to read.  On the other hand, if
345
       we're receiving a multipart, there will be no content-length, but
346
       the content-type will include the boundary string.
347
    */
348
        List<String> allHeaders = Headers.getAllHeaders(sw.getInputStream(), inputStreamUtils);
349
        Headers hi = new Headers(allHeaders);
350
        logger.logTrace(() -> "The headers are: " + hi.getHeaderStrings());
351 1 1. getHeaders : replaced return value with null for com/renomad/minum/web/WebFramework::getHeaders → TIMED_OUT
        return hi;
352
    }
353
354
    /**
355
     * determine if we are in a keep-alive connection.
356
     * <p>
357
     *     This checks the headers and request-line for characteristics
358
     *     which require keep-alive on or off.
359
     * </p>
360
     * <p>
361
     *     It also checks whether there are lingering unread bytes from
362
     *     a request.  If there are, it will set keep-alive to false, so
363
     *     that the following request will encounter a clean starting point.
364
     *     Lingering bytes could occur if the responsible handler does not
365
     *     read the body bytes sent to it.
366
     * </p>
367
     * <p>
368
     *     The algorithm is:
369
     *     <ul>
370
     *         <li>If the HTTP version is 1.0, then we keep-alive if there is a header telling us to</li>
371
     *         <li>If the HTTP version is 1.1, then we *stop* keep-alive if there is a header telling us to</li>
372
     *         <li>If we are keep-alive, but there are lingering body bytes that have not been read by
373
     *         the handler, set keep-alive to false</li>
374
     *     </ul>
375
     * </p>
376
     * @param hasAccessedBody pulled from request.hasAccessedBody(), which is set true if the handler
377
     *                        has accessed the body of this request.
378
     */
379
    static boolean determineIfKeepAlive(IRequest request, ILogger logger, boolean hasAccessedBody) {
380
        boolean isKeepAlive = false;
381 1 1. determineIfKeepAlive : negated conditional → KILLED
        if (request.getRequestLine().getVersion() == HttpVersion.ONE_DOT_ZERO) {
382
            isKeepAlive = request.getHeaders().hasKeepAlive();
383 1 1. determineIfKeepAlive : negated conditional → KILLED
        } else if (request.getRequestLine().getVersion() == HttpVersion.ONE_DOT_ONE) {
384 1 1. determineIfKeepAlive : negated conditional → TIMED_OUT
            isKeepAlive = ! request.getHeaders().hasConnectionClose();
385
        }
386
387 4 1. determineIfKeepAlive : negated conditional → TIMED_OUT
2. determineIfKeepAlive : negated conditional → TIMED_OUT
3. determineIfKeepAlive : changed conditional boundary → KILLED
4. determineIfKeepAlive : negated conditional → KILLED
        if (isKeepAlive && request.getHeaders().contentLength() >= 0 && !hasAccessedBody) {
388
            // if there was a body and the user has not read it by this point, we will log the
389
            // discrepancy and close the socket.
390
            logger.logDebug(() -> ("A body sized %d bytes was included in the request, but the endpoint (%s) did not access the body. " +
391
                    "Closing socket after request is finished").formatted(request.getHeaders().contentLength(), request.getRequestLine().getPathDetails().getIsolatedPath()));
392
            isKeepAlive = false;
393
        }
394
395
        boolean finalIsKeepAlive = isKeepAlive;
396
397
        logger.logTrace(() -> "Is this a keep-alive connection? %s".formatted(finalIsKeepAlive));
398 2 1. determineIfKeepAlive : replaced boolean return with true for com/renomad/minum/web/WebFramework::determineIfKeepAlive → TIMED_OUT
2. determineIfKeepAlive : replaced boolean return with false for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED
        return finalIsKeepAlive;
399
    }
400
401
    RequestLine getProcessedRequestLine(ISocketWrapper sw, String rawStartLine) {
402
        logger.logTrace(() -> sw + ": raw request line received: " + rawStartLine);
403
404
        RequestLine extractedRequestLine = validRequestLine.extractRequestLine(rawStartLine);
405
        logger.logTrace(() -> sw + ": RequestLine has been derived: " + extractedRequestLine);
406 1 1. getProcessedRequestLine : replaced return value with null for com/renomad/minum/web/WebFramework::getProcessedRequestLine → TIMED_OUT
        return extractedRequestLine;
407
    }
408
409
    void checkIfSuspiciousPath(ISocketWrapper sw, RequestLine requestLine) {
410 1 1. checkIfSuspiciousPath : negated conditional → KILLED
        if (constants.suspiciousPaths.contains(requestLine.getPathDetails().getIsolatedPath())) {
411
            String msg = sw.getRemoteAddr() + " is looking for a vulnerability, for this: " + requestLine.getPathDetails().getIsolatedPath();
412
            throw new ForbiddenUseException(msg);
413
        }
414
    }
415
416
    /**
417
     * Drops the connection immediately if the client is recognized
418
     * as someone we consider an attacker, by dint of having been
419
     * added to a blacklist in {@link com.renomad.minum.security.TheBrig}
420
     * with a suffix of "_vuln_seeking"
421
     */
422
    boolean dumpIfAttacker(ISocketWrapper sw, FullSystem fs) {
423 1 1. dumpIfAttacker : negated conditional → KILLED
        if (fs == null) {
424 1 1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return false;
425 1 1. dumpIfAttacker : negated conditional → KILLED
        } else if (fs.getTheBrig() == null) {
426 1 1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return false;
427
        } else {
428 1 1. dumpIfAttacker : removed call to com/renomad/minum/web/WebFramework::dumpIfAttacker → TIMED_OUT
            dumpIfAttacker(sw, fs.getTheBrig());
429 1 1. dumpIfAttacker : replaced boolean return with false for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED
            return true;
430
        }
431
    }
432
433
    /**
434
     * For documentation, see {@link #dumpIfAttacker(ISocketWrapper, FullSystem)}
435
     */
436
    void dumpIfAttacker(ISocketWrapper sw, ITheBrig theBrig) {
437
        String remoteClient = sw.getRemoteAddr();
438 1 1. dumpIfAttacker : negated conditional → KILLED
        if (theBrig.isInJail(remoteClient + "_vuln_seeking")) {
439
            // if this client is a vulnerability seeker, throw an exception,
440
            // causing them to get dumped unceremoniously
441
            String message = "closing the socket on " + remoteClient + " due to being found in the brig";
442
            logger.logDebug(() -> message);
443
            throw new ForbiddenUseException(message);
444
        }
445
    }
446
447
    /**
448
     * Prepare some of the basic server response headers, like the status code, the
449
     * date-time stamp, the server name.
450
     */
451
    private void addDefaultHeaders(IResponse response, StringBuilder headerStringBuilder) {
452
        String date = Objects.requireNonNullElseGet(overrideForDateTime,
453 1 1. lambda$addDefaultHeaders$20 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$addDefaultHeaders$20 → TIMED_OUT
                () -> ZonedDateTime.now(ZoneId.of("UTC"))).format(DateTimeFormatter.RFC_1123_DATE_TIME);
454
455
        // add the status line
456
        headerStringBuilder.append("HTTP/1.1 ").append(response.getStatusCode().code).append(" ").append(response.getStatusCode().shortDescription).append(HTTP_CRLF);
457
458
        // add a date-timestamp
459
        headerStringBuilder.append("Date: ").append(date).append(HTTP_CRLF);
460
461
        // add the server name
462
        headerStringBuilder.append("Server: minum").append(HTTP_CRLF);
463
    }
464
465
    /**
466
     * If a response body exists, it needs to have a content-type specified,
467
     * or throw an exception. Otherwise, the user could totally miss they did
468
     * not set a content-type, because the browser will inspect the data and
469
     * do sort-of-the-right-thing a lot of the time, but we want to enforce correctness.
470
     */
471
    static void confirmBodyHasContentType(IRequest request, IResponse response) {
472
        // check the correctness of the content-type header versus the data length (if any data, that is)
473 1 1. confirmBodyHasContentType : negated conditional → KILLED
        boolean hasContentType = response.getExtraHeaders().valueByKey("content-type") != null;
474
475
        // if there *is* data, we had better be returning a content type
476 3 1. confirmBodyHasContentType : changed conditional boundary → TIMED_OUT
2. confirmBodyHasContentType : negated conditional → KILLED
3. confirmBodyHasContentType : negated conditional → KILLED
        if (response.getBodyLength() > 0 && !hasContentType) {
477
            throw new WebServerException("a Content-Type header must be specified in the Response object if it returns data. Response details: " + response + " Request: " + request);
478
        }
479
    }
480
481
    /**
482
     * If this is a keep-alive communication, add a header specifying the
483
     * socket timeout for the browser.
484
     */
485
    private void addKeepAliveTimeout(boolean isKeepAlive, StringBuilder stringBuilder) {
486
        // if we're a keep-alive connection, reply with a keep-alive header
487 1 1. addKeepAliveTimeout : negated conditional → KILLED
        if (isKeepAlive) {
488
            stringBuilder.append("Keep-Alive: timeout=").append(constants.keepAliveTimeoutSeconds).append(HTTP_CRLF);
489
        }
490
    }
491
492
    /**
493
     * The rules regarding the content-length header are byzantine.  Even in the cases
494
     * where you aren't returning anything, servers can use this header to determine when the
495
     * response is finished.
496
     * See <a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-content-length">Content-Length in the HTTP spec</a>
497
     */
498
    private static void applyContentLength(StringBuilder stringBuilder, long bodyLength) {
499
        stringBuilder.append("Content-Length: ").append(bodyLength).append(HTTP_CRLF);
500
    }
501
502
    /**
503
     * This method will examine the content-encoding headers, and if "gzip" is
504
     * requested by the client, we will replace the body bytes with compressed
505
     * bytes, using the GZIP compression algorithm.
506
     *
507
     * @param acceptEncoding headers sent by the client about what compression
508
     *                       algorithms will be understood.
509
     * @param stringBuilder  the string we are gradually building up to send back to
510
     *                       the client for the status line and headers. We'll use it
511
     *                       here if we need to append a content-encoding - that is,
512
     *                       if we successfully compress data as gzip.
513
     * @param endpointPath the endpoint whose data we are compressing, e.g. "foo?bar=baz",
514
     *                     used for logging.
515
     */
516
    static IResponse compressBodyIfRequested(IResponse response, List<String> acceptEncoding, StringBuilder stringBuilder, ILogger logger, String endpointPath) {
517 1 1. compressBodyIfRequested : negated conditional → KILLED
        String allContentEncodingHeaders = acceptEncoding != null ? String.join(";", acceptEncoding) : "";
518 1 1. compressBodyIfRequested : negated conditional → TIMED_OUT
        if (allContentEncodingHeaders.contains("gzip")) {
519
            stringBuilder.append("Content-Encoding: gzip").append(HTTP_CRLF);
520
            stringBuilder.append("Vary: accept-encoding").append(HTTP_CRLF);
521
            var out = new ByteArrayOutputStream();
522 1 1. compressBodyIfRequested : removed call to com/renomad/minum/web/WebFramework::compressBody → SURVIVED
            compressBody(out, response.getBody());
523
            logger.logTrace(() -> "Compressing results of %s.  Compression ratio: %d%%. Original size: %d bytes. Compressed size: %d bytes".formatted(endpointPath,
524 2 1. lambda$compressBodyIfRequested$21 : Replaced double multiplication with division → SURVIVED
2. lambda$compressBodyIfRequested$21 : Replaced double division with multiplication → SURVIVED
                    Math.round(((double) out.size() / (double) response.getBodyLength()) * 100), response.getBodyLength(), out.size()));
525 1 1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED
            return Response.buildResponse(
526
                    response.getStatusCode(),
527
                    response.getExtraHeaders(),
528
                    out.toByteArray()
529
            );
530
        }
531 1 1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED
        return response;
532
    }
533
534
    /**
535
     * Compress the data in this body using gzip.
536
     * <br>
537
     * This operates by getting the body field from this instance of {@link Response} and
538
     * creating a new Response with the compressed data.
539
     * @param out this is provided as a parameter for better control during testing
540
     */
541
    static void compressBody(OutputStream out, byte[] body) {
542
        try (var gos = new GZIPOutputStream(out)) {
543 1 1. compressBody : removed call to java/util/zip/GZIPOutputStream::write → KILLED
            gos.write(body);
544 1 1. compressBody : removed call to java/util/zip/GZIPOutputStream::finish → SURVIVED
            gos.finish();
545
        } catch (IOException e) {
546
            throw new WebServerException("Error in Response.compressBody", e);
547
        }
548
    }
549
550
    /**
551
     * Looks through the mappings of {@link MethodPath} and path to registered endpoints
552
     * or the static cache and returns the appropriate one (If we
553
     * do not find anything, return null)
554
     */
555
    ThrowingFunction<IRequest, IResponse> findEndpointForThisStartline(RequestLine sl, Headers requestHeaders) {
556
        ThrowingFunction<IRequest, IResponse> handler;
557
        logger.logTrace(() -> "Seeking a handler for " + sl);
558
559
        // first we check if there's a simple direct match
560
        String requestedPath = sl.getPathDetails().getIsolatedPath().toLowerCase(Locale.ROOT);
561
562
        // if the user is asking for a HEAD request, they want to run a GET command
563
        // but don't want the body.  We'll simply exclude sending the body, later on, when returning the data
564 1 1. findEndpointForThisStartline : negated conditional → TIMED_OUT
        RequestLine.Method method = sl.getMethod() == RequestLine.Method.HEAD ? RequestLine.Method.GET : sl.getMethod();
565
566
        MethodPath key = new MethodPath(method, requestedPath);
567
        handler = registeredDynamicPaths.get(key);
568
569 1 1. findEndpointForThisStartline : negated conditional → TIMED_OUT
        if (handler == null) {
570
            logger.logTrace(() -> "No direct handler found.  looking for a partial match for " + requestedPath);
571
            handler = findHandlerByPathFunction(sl);
572
        }
573
574 1 1. findEndpointForThisStartline : negated conditional → KILLED
        if (handler == null) {
575
            logger.logTrace(() -> "No partial match found, checking files on disk for " + requestedPath );
576
            handler = findHandlerByFilesOnDisk(sl, requestHeaders);
577
        }
578
579
        // we'll return this, and it could be a null.
580 1 1. findEndpointForThisStartline : replaced return value with null for com/renomad/minum/web/WebFramework::findEndpointForThisStartline → TIMED_OUT
        return handler;
581
    }
582
583
    /**
584
     * last ditch effort - look on disk.  This response will either
585
     * be the file to return, or null if we didn't find anything.
586
     * The request method has to be GET or HEAD.
587
     */
588
    private ThrowingFunction<IRequest, IResponse> findHandlerByFilesOnDisk(RequestLine sl, Headers requestHeaders) {
589 2 1. findHandlerByFilesOnDisk : negated conditional → TIMED_OUT
2. findHandlerByFilesOnDisk : negated conditional → KILLED
        if (sl.getMethod() == RequestLine.Method.GET || sl.getMethod() == RequestLine.Method.HEAD) {
590
            String requestedPath = sl.getPathDetails().getIsolatedPath();
591
            IResponse response = readStaticFile(requestedPath, requestHeaders);
592 2 1. findHandlerByFilesOnDisk : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByFilesOnDisk → KILLED
2. lambda$findHandlerByFilesOnDisk$25 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$25 → KILLED
            return request -> response;
593
        } else {
594
            return null;
595
        }
596
    }
597
598
599
    /**
600
     * Get a file from a path and create a response for it with a mime type.
601
     * <p>
602
     *     Parent directories are made unavailable by searching the path for
603
     *     bad characters. see {@link FileUtils#checkForBadFilePatterns}
604
     * </p>
605
     *
606
     * @return a response with the file contents and caching headers and mime if valid.
607
     *  if the path has invalid characters, we'll return a "bad request" response.
608
     */
609
    IResponse readStaticFile(String path, Headers requestHeaders) {
610
        String mimeType = getMimeString(path);
611
        Path staticFilePath;
612
        try {
613
            staticFilePath = staticFilesDirectoryPathBase.resolve(path);
614
        } catch (Exception e) {
615
            throw new BadRequestException("Error creating a valid path from: " + path);
616
        }
617
618
        // move value to a variable - used in several places, may as well
619
        String staticFilePathString = staticFilePath.toString();
620
621 1 1. readStaticFile : negated conditional → KILLED
        if (constants.useCacheForStaticFiles) {
622
            ReentrantLock cacheLock = fileReader.getCacheLock();
623 1 1. readStaticFile : removed call to java/util/concurrent/locks/ReentrantLock::lock → KILLED
            cacheLock.lock();
624
            try {
625
                byte[] fileContents = fileReader.getLruCache().get(staticFilePathString);
626 1 1. readStaticFile : negated conditional → KILLED
                if (fileContents != null) {
627
                    logger.logTrace(() -> "%d bytes of data found in cache for request of %s".formatted(fileContents.length, staticFilePath));
628 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                    return createOkResponseForStaticFiles(fileContents, mimeType, staticFilePathString);
629
                }
630
            } finally {
631 1 1. readStaticFile : removed call to java/util/concurrent/locks/ReentrantLock::unlock → TIMED_OUT
                cacheLock.unlock();
632
            }
633
        }
634
635
        try {
636 1 1. readStaticFile : removed call to com/renomad/minum/utils/FileUtils::checkForBadFilePatterns → KILLED
            checkForBadFilePatterns(path);
637
        } catch (Exception ex) {
638
            logger.logDebug(() -> String.format("Bad path requested at readStaticFile: %s.  Exception: %s", path, ex.getMessage()));
639 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_400_BAD_REQUEST);
640
        }
641
642
        try {
643 1 1. readStaticFile : removed call to com/renomad/minum/utils/IFileUtils::checkFileIsWithinDirectory → TIMED_OUT
            fileUtils.checkFileIsWithinDirectory(path, constants.staticFilesDirectory);
644
        } catch (Exception ex) {
645
            logger.logDebug(() -> String.format("Unable to find %s in allowed directories", path));
646 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
            return Response.buildLeanResponse(CODE_404_NOT_FOUND);
647
        }
648
649
        try {
650 1 1. readStaticFile : negated conditional → KILLED
            if (!fileUtils.isRegularFile(staticFilePath)) {
651
                logger.logDebug(() -> String.format("No readable regular file found at %s", path));
652 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return Response.buildLeanResponse(CODE_404_NOT_FOUND);
653
            }
654
655
            long size = fileUtils.size(staticFilePath);
656 1 1. readStaticFile : negated conditional → KILLED
            if (size == 0) {
657
                logger.logTrace(() -> "Requested file, %s, was empty.  Returning 200 OK, content-length 0, with mime of %s".formatted(staticFilePath, mimeType));
658 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → TIMED_OUT
                return Response.buildLeanResponse(CODE_200_OK, Map.of("Content-Type", mimeType));
659 2 1. readStaticFile : changed conditional boundary → KILLED
2. readStaticFile : negated conditional → KILLED
            } else if (size < (long) MAX_CACHED_BYTES) {
660
                logger.logTrace(() -> "Size of static file, %s was %d bytes.  Since less than max allowed (%d), caching allowed.".formatted(staticFilePath, size, MAX_CACHED_BYTES));
661
                var fileContents = fileReader.readFile(staticFilePathString);
662 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return createOkResponseForStaticFiles(fileContents, mimeType, staticFilePathString);
663
            } else {
664
                logger.logTrace(() -> "Size of static file, %s was %d bytes.  Since greater than max allowed (%d), no caching allowed.".formatted(staticFilePath, size, MAX_CACHED_BYTES));
665 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED
                return createOkResponseForLargeStaticFiles(mimeType, staticFilePath, requestHeaders);
666
            }
667
668
        } catch (IOException e) {
669
            logger.logAsyncError(() -> String.format("Error while reading file: %s. %s", path, StacktraceUtils.stackTraceToString(e)));
670 1 1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → SURVIVED
            return Response.buildLeanResponse(CODE_400_BAD_REQUEST);
671
        }
672
    }
673
674
    private String getMimeString(String path) {
675
        String mimeType = null;
676
        // if the provided path has a dot in it, use that
677
        // to obtain a suffix for determining file type
678
        int suffixBeginIndex = path.lastIndexOf('.');
679 2 1. getMimeString : changed conditional boundary → SURVIVED
2. getMimeString : negated conditional → KILLED
        if (suffixBeginIndex > 0) {
680 1 1. getMimeString : Replaced integer addition with subtraction → KILLED
            String suffix = path.substring(suffixBeginIndex+1);
681
            mimeType = fileSuffixToMime.get(suffix);
682
        }
683
684
        // if we don't find any registered mime types for this
685
        // suffix, or if it doesn't have a suffix, set the mime type
686
        // to application/octet-stream
687 1 1. getMimeString : negated conditional → KILLED
        if (mimeType == null) {
688
            mimeType = "application/octet-stream";
689
        }
690 1 1. getMimeString : replaced return value with "" for com/renomad/minum/web/WebFramework::getMimeString → KILLED
        return mimeType;
691
    }
692
693
    /**
694
     * A method used for handling smaller files in the static files directory
695
     * (less than {@link #MAX_CACHED_BYTES})
696
     * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds
697
     */
698
    private IResponse createOkResponseForStaticFiles(byte[] fileContents, String mimeType, String path) {
699
        var headers = new Headers(List.of(
700
                "Cache-Control: max-age=" + constants.staticFileCacheTime,
701
                "Content-Type: " + mimeType));
702
        // if the map does not have this key, then we haven't analyzed this file yet.
703 1 1. createOkResponseForStaticFiles : negated conditional → KILLED
        if (!fileIsCompressible.containsKey(path)) {
704
            ByteArrayOutputStream out = new ByteArrayOutputStream();
705 1 1. createOkResponseForStaticFiles : removed call to com/renomad/minum/web/WebFramework::compressBody → KILLED
            compressBody(out, fileContents);
706
707
            // we only want to compress it if we get a decent compression.
708
            // 30% smaller seems fine.
709 2 1. createOkResponseForStaticFiles : Replaced double division with multiplication → KILLED
2. createOkResponseForStaticFiles : Replaced double multiplication with division → KILLED
            long compressionRatio = Math.round(((double) out.size() / (double) fileContents.length) * 100);
710 2 1. createOkResponseForStaticFiles : changed conditional boundary → SURVIVED
2. createOkResponseForStaticFiles : negated conditional → KILLED
            boolean isWorthCompressing = compressionRatio < 70;
711
            logger.logTrace(() -> "static file %s worth compressing? %s.  Compression ratio: %d%%.  Original size: %d bytes. Compressed size: %d bytes".formatted(
712
                    path, isWorthCompressing, compressionRatio, fileContents.length, out.size()));
713
            fileIsCompressible.put(path, isWorthCompressing);
714
        }
715
        logger.logTrace(() -> "Creating OK response for file %s, mime: %s, length: %s, fileIsCompressible: %s".formatted(
716
                path, mimeType, fileContents.length, fileIsCompressible.get(path)));
717 1 1. createOkResponseForStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForStaticFiles → KILLED
        return new Response(CODE_200_OK, headers, fileContents,
718 1 1. lambda$createOkResponseForStaticFiles$36 : removed call to com/renomad/minum/web/ISocketWrapper::send → KILLED
                socketWrapper -> socketWrapper.send(fileContents), fileContents.length, fileIsCompressible.get(path));
719
    }
720
721
    /**
722
     * A method used for handling larger files in the static files directory
723
     * (greater-than or equal to {@link #MAX_CACHED_BYTES})
724
     * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds
725
     */
726
    private IResponse createOkResponseForLargeStaticFiles(String mimeType, Path filePath, Headers requestHeaders) {
727
        var headers = new Headers(List.of(
728
                "Cache-Control: max-age=" + constants.staticFileCacheTime,
729
                "Content-Type: " + mimeType,
730
                "Accept-Ranges: bytes"
731
                ));
732
733 1 1. createOkResponseForLargeStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForLargeStaticFiles → KILLED
        return Response.buildLargeFileResponse(
734
                headers,
735
                filePath.toString(),
736
                requestHeaders,
737
                fileUtils
738
                );
739
    }
740
741
742
    /**
743
     * These are the default starting values for mappings
744
     * between file suffixes and appropriate mime types
745
     */
746
    private void addDefaultValuesForMimeMap() {
747
        fileSuffixToMime.put("css", "text/css");
748
        fileSuffixToMime.put("js", "application/javascript");
749
        fileSuffixToMime.put("webp", "image/webp");
750
        fileSuffixToMime.put("jpg", "image/jpeg");
751
        fileSuffixToMime.put("jpeg", "image/jpeg");
752
        fileSuffixToMime.put("htm", "text/html");
753
        fileSuffixToMime.put("html", "text/html");
754
        fileSuffixToMime.put("txt", "text/plain");
755
    }
756
757
    /**
758
     * let's see if we can match the registered paths against a path function
759
     */
760
    ThrowingFunction<IRequest, IResponse> findHandlerByPathFunction(RequestLine sl) {
761
        var functionList = registeredPathFunctions.get(sl.getMethod());
762 1 1. findHandlerByPathFunction : negated conditional → TIMED_OUT
        if (functionList == null) {
763
            return null;
764
        }
765
        String requestedPath = sl.getPathDetails().getIsolatedPath();
766 1 1. findHandlerByPathFunction : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByPathFunction → TIMED_OUT
        return functionList.stream()
767 1 1. lambda$findHandlerByPathFunction$37 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByPathFunction$37 → TIMED_OUT
                .map(function -> function.apply(requestedPath))
768
                .filter(Objects::nonNull)
769
                .findFirst()
770
                .orElse(null);
771
    }
772
773
    /**
774
     * This constructor is used for the real production system
775
     */
776
    WebFramework(Context context) {
777
        this(context, null, null, null);
778
    }
779
780
    /**
781
     * This constructor is mainly used for testing
782
     */
783
    WebFramework(Context context, ZonedDateTime overrideForDateTime) {
784
        this(context, overrideForDateTime, null, null);
785
    }
786
787
    /**
788
     * A constructor with slots available for testing
789
     * @param overrideForDateTime for those test cases where we need to control the time. Providing null
790
     *                            for this parameter will cause code to use ZonedDateTime.now() instead,
791
     *                            which is the expected behavior during ordinary system use.
792
     * @param fileReader when we want to provide an instance for better control during testing. Providing
793
     *                   null here will cause a FileReader to be instantiated in the constructor.
794
     * @param fileUtils when we want to provide an instance for better control during testing. Providing
795
     *                  null here will cause a FileUtils to be instantiated in the constructor.
796
     */
797
    WebFramework(Context context, ZonedDateTime overrideForDateTime, IFileReader fileReader, IFileUtils fileUtils) {
798
        this.fs = context.getFullSystem();
799 1 1. <init> : negated conditional → KILLED
        this.theBrig = this.fs != null ? this.fs.getTheBrig() : null;
800
        this.logger = context.getLogger();
801
        this.constants = context.getConstants();
802
        this.overrideForDateTime = overrideForDateTime;
803
        this.registeredDynamicPaths = new HashMap<>();
804
        this.registeredPathFunctions = new EnumMap<>(RequestLine.Method.class);
805
        this.inputStreamUtils = new InputStreamUtils(constants.maxReadLineSizeBytes);
806
        this.bodyProcessor = new BodyProcessor(context);
807
        this.staticFilesDirectoryPathBase = Path.of(constants.staticFilesDirectory);
808
809 1 1. <init> : negated conditional → KILLED
        if (fileUtils != null) {
810
            this.fileUtils = fileUtils;
811
        } else {
812
            this.fileUtils = new FileUtils(logger, constants);
813
        }
814
815
        // This random value is purely to help provide correlation between
816
        // error messages in the UI and error logs.  There are no security concerns.
817
        this.randomErrorCorrelationId = new Random();
818
        this.validRequestLine =  new RequestLine(
819
                RequestLine.Method.NONE,
820
                PathDetails.empty,
821
                HttpVersion.NONE,
822
                "", logger);
823
824
        // this allows us to inject a IFileReader for deeper testing
825 1 1. <init> : negated conditional → KILLED
        if (fileReader != null) {
826
            this.fileReader = fileReader;
827
        } else {
828
            this.fileReader = new FileReader(
829
                    LRUCache.getLruCache(constants.maxElementsLruCacheStaticFiles),
830
                    constants.useCacheForStaticFiles,
831
                    logger);
832
        }
833
        this.fileSuffixToMime = new HashMap<>();
834
        this.fileIsCompressible = new ConcurrentHashMap<>();
835 1 1. <init> : removed call to com/renomad/minum/web/WebFramework::addDefaultValuesForMimeMap → TIMED_OUT
        addDefaultValuesForMimeMap();
836 1 1. <init> : removed call to com/renomad/minum/web/WebFramework::readExtraMimeMappings → TIMED_OUT
        readExtraMimeMappings(constants.extraMimeMappings);
837
    }
838
839
    void readExtraMimeMappings(List<String> input) {
840 2 1. readExtraMimeMappings : negated conditional → TIMED_OUT
2. readExtraMimeMappings : negated conditional → KILLED
        if (input == null || input.isEmpty()) return;
841 2 1. readExtraMimeMappings : Replaced integer modulus with multiplication → KILLED
2. readExtraMimeMappings : negated conditional → KILLED
        if (input.size() % 2 != 0) {
842
            throw new WebServerException("input must be even (key + value = 2 items). Your input: " + input);
843
        }
844
845 2 1. readExtraMimeMappings : negated conditional → TIMED_OUT
2. readExtraMimeMappings : changed conditional boundary → KILLED
        for (int i = 0; i < input.size(); i += 2) {
846
            String fileSuffix = input.get(i);
847 1 1. readExtraMimeMappings : Replaced integer addition with subtraction → KILLED
            String mime = input.get(i+1);
848
            logger.logTrace(() -> "Adding mime mapping: " + fileSuffix + " -> " + mime);
849
            fileSuffixToMime.put(fileSuffix, mime);
850
        }
851
    }
852
853
    /**
854
     * Add a new handler in the web application for a combination
855
     * of a {@link RequestLine.Method}, a path, and then provide
856
     * the code to handle a request.
857
     * <br>
858
     * Note that the path text expected is *after* the first forward slash,
859
     * so for example with {@code http://foo.com/mypath}, provide "mypath" as the path.
860
     * @throws WebServerException if duplicate paths are registered, or if the path is prefixed with a slash
861
     */
862
    public void registerPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) {
863 2 1. registerPath : negated conditional → TIMED_OUT
2. registerPath : negated conditional → TIMED_OUT
        if (pathName.startsWith("\\") || pathName.startsWith("/")) {
864
            throw new WebServerException(
865
                    String.format("Path should not be prefixed with a slash.  Corrected version: registerPath(%s, \"%s\", ... )", method.name(), pathName.substring(1)));
866
        }
867
868
        var result = registeredDynamicPaths.put(new MethodPath(method, pathName), webHandler);
869 1 1. registerPath : negated conditional → TIMED_OUT
        if (result != null) {
870
            throw new WebServerException("Duplicate endpoint registered: " + new MethodPath(method, pathName));
871
        }
872
873 1 1. registerPath : removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED
        checkForDuplicatePartialPath(method, pathName);
874
    }
875
876
    /**
877
     * check if the user had already registered a "partial path" with this pathName, which
878
     * means it would be duplicate endpoints, and throw an exception if so.
879
     */
880
    private void checkForDuplicatePartialPath(RequestLine.Method method, String pathName) {
881
        List<Function<String, ThrowingFunction<IRequest, IResponse>>> existingPathFunctions = registeredPathFunctions.get(method);
882 1 1. checkForDuplicatePartialPath : negated conditional → KILLED
        if (existingPathFunctions != null) {
883
            if (existingPathFunctions.stream()
884
                    .filter(PartialPathFunction.class::isInstance)
885
                    .map(PartialPathFunction.class::cast)
886 1 1. lambda$checkForDuplicatePartialPath$39 : replaced return value with "" for com/renomad/minum/web/WebFramework::lambda$checkForDuplicatePartialPath$39 → KILLED
                    .map(function -> function.pathName)
887 1 1. checkForDuplicatePartialPath : negated conditional → TIMED_OUT
                    .anyMatch(pathName::equals)
888
            ) {
889
                throw new WebServerException("Duplicate partial-path endpoint registered: " + new MethodPath(method, pathName));
890
            }
891
        }
892
    }
893
894
    /**
895
     * Allows adding complex path function handling.
896
     * <p>
897
     *     <em>Note:</em> This is advanced functionality to provide extra flexibility
898
     *     to the developer.  It is intended for use in those situations where the
899
     *     minimalist approach is insufficient.  <em>Think hard whether this is truly
900
     *     necessary or if the base assumptions should be reconsidered before going this route</em>
901
     * </p>
902
     * <h4>
903
     *     Example use cases:
904
     * </h4>
905
     * <pre>{@code
906
     *
907
     * // an example helper method by the developer
908
     * private void registerPatternPath(RequestLine.Method method, Pattern pattern, BiFunction<IRequest, Matcher, IResponse> function) {
909
     *     webFramework.registerPath(method, path -> {
910
     *         Matcher matcher = pattern.matcher(path);
911
     *         if (matcher.matches()) {
912
     *             return request -> function.apply(request, matcher);
913
     *         }
914
     *         return null;
915
     *     });
916
     * }
917
     *
918
     * // a regular expression to look for paths like "/projects/123" and to
919
     * // collect the "123" part.
920
     * Pattern idMatcher = Pattern.compile("projects/(\\d+)");
921
     *
922
     * // a regular endpoint, no advanced usage
923
     * webFramework.registerPath(RequestLine.Method.GET, "projects", request -> {
924
     *     return Response.htmlOk("Do GET /projects");
925
     * });
926
     *
927
     * // registering a GET handler for the advanced use case
928
     * registerPatternPath(RequestLine.Method.GET, idMatcher, (request, matcher) -> {
929
     *     int id = Integer.parseInt(matcher.group(1));
930
     *     return Response.htmlOk("Do GET /projects/" + id);
931
     * });
932
     *
933
     * }</pre>
934
     */
935
    public void registerPath(RequestLine.Method method, Function<String, ThrowingFunction<IRequest, IResponse>> pathFunction) {
936 1 1. lambda$registerPath$40 : replaced return value with Collections.emptyList for com/renomad/minum/web/WebFramework::lambda$registerPath$40 → TIMED_OUT
        registeredPathFunctions.computeIfAbsent(method, k -> new ArrayList<>()).add(pathFunction);
937
    }
938
939
    /**
940
     * Similar to {@link WebFramework#registerPath(RequestLine.Method, String, ThrowingFunction)} except that the paths
941
     * registered here may be partially matched.
942
     * <p>
943
     *     For example, if you register {@code .well-known/acme-challenge} then it
944
     *     can match a client request for {@code .well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX}
945
     * </p>
946
     * <p>
947
     *     Be careful here, be thoughtful - partial paths will match a lot, and may
948
     *     overlap with other URL's for your app, such as endpoints and static files.
949
     * </p>
950
     * @throws WebServerException if duplicate paths are registered, or if the path is prefixed with a slash
951
     */
952
    public void registerPartialPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) {
953 2 1. registerPartialPath : negated conditional → KILLED
2. registerPartialPath : negated conditional → KILLED
        if (pathName.startsWith("\\") || pathName.startsWith("/")) {
954
            throw new WebServerException(
955
                    String.format("Path should not be prefixed with a slash.  Corrected version: registerPartialPath(%s, \"%s\", ... )", method.name(), pathName.substring(1)));
956
        }
957
958
        // if the user had previously registered a normal path with this value, it would
959
        // conflict and so we will throw an exception.
960 1 1. registerPartialPath : negated conditional → KILLED
        if (registeredDynamicPaths.containsKey(new MethodPath(method, pathName))) {
961
            throw new WebServerException("Duplicate endpoint registered: " + new MethodPath(method, pathName));
962
        }
963
964 1 1. registerPartialPath : removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → TIMED_OUT
        checkForDuplicatePartialPath(method, pathName);
965 1 1. registerPartialPath : removed call to com/renomad/minum/web/WebFramework::registerPath → KILLED
        registerPath(method, new PartialPathFunction(pathName, webHandler));
966
    }
967
968
    /**
969
     * Sets a handler to process all requests across the board.
970
     * <br>
971
     * <p>
972
     *     This is an <b>unusual</b> method.  Setting a handler here allows the user to run code of his
973
     * choosing before the regular business code is run.  Note that by defining this value, the ordinary
974
     * call to endpoint.apply(request) will not be run.
975
     * </p>
976
     * <p>Here is an example</p>
977
     * <pre>{@code
978
     *
979
     *      webFramework.registerPreHandler(preHandlerInputs -> preHandlerCode(preHandlerInputs, auth, context));
980
     *
981
     *      ...
982
     *
983
     *      private IResponse preHandlerCode(PreHandlerInputs preHandlerInputs, AuthUtils auth, Context context) throws Exception {
984
     *          int secureServerPort = context.getConstants().secureServerPort;
985
     *          Request request = preHandlerInputs.clientRequest();
986
     *          ThrowingFunction<IRequest, IResponse> endpoint = preHandlerInputs.endpoint();
987
     *          ISocketWrapper sw = preHandlerInputs.sw();
988
     *
989
     *          // log all requests
990
     *          logger.logTrace(() -> String.format("Request: %s by %s",
991
     *              request.requestLine().getRawValue(),
992
     *              request.remoteRequester())
993
     *          );
994
     *
995
     *          // redirect to https if they are on the plain-text connection and the path is "login"
996
     *
997
     *          // get the path from the request line
998
     *          String path = request.getRequestLine().getPathDetails().getIsolatedPath();
999
     *
1000
     *          // redirect to https on the configured secure port if they are on the plain-text connection and the path contains "login"
1001
     *          if (path.contains("login") &&
1002
     *              sw.getServerType().equals(HttpServerType.PLAIN_TEXT_HTTP)) {
1003
     *              return Response.redirectTo("https://%s:%d/%s".formatted(sw.getHostName(), secureServerPort, path));
1004
     *          }
1005
     *
1006
     *          // adjust behavior if non-authenticated and path includes "secure/"
1007
     *          if (path.contains("secure/")) {
1008
     *              AuthResult authResult = auth.processAuth(request);
1009
     *              if (authResult.isAuthenticated()) {
1010
     *                  return endpoint.apply(request);
1011
     *              } else {
1012
     *                  return Response.buildLeanResponse(CODE_403_FORBIDDEN);
1013
     *              }
1014
     *          }
1015
     *
1016
     *          // if the path does not include /secure, just move the request along unchanged.
1017
     *          return endpoint.apply(request);
1018
     *      }
1019
     * }</pre>
1020
     */
1021
        public void registerPreHandler(ThrowingFunction<PreHandlerInputs, IResponse> preHandler) {
1022
        this.preHandler = preHandler;
1023
    }
1024
1025
    /**
1026
     * Sets a handler to be executed after running the ordinary handler, just
1027
     * before sending the response.
1028
     * <p>
1029
     *     This is an <b>unusual</b> method, so please be aware of its proper use. Its
1030
     *     purpose is to allow the user to inject code to run after ordinary code, across
1031
     *     all requests.
1032
     * </p>
1033
     * <p>
1034
     *     For example, if the system would have returned a 404 NOT FOUND response,
1035
     *     code can handle that situation in a switch case and adjust the response according
1036
     *     to your programming.
1037
     * </p>
1038
     * <p>Here is an example</p>
1039
     * <pre>{@code
1040
     *
1041
     *     webFramework.registerLastMinuteHandler(TheRegister::lastMinuteHandlerCode);
1042
     *
1043
     *     ...
1044
     *
1045
     *     private static IResponse lastMinuteHandlerCode(LastMinuteHandlerInputs inputs) {
1046
     *         return switch (inputs.response().getStatusCode()) {
1047
     *             case CODE_404_NOT_FOUND -> {
1048
     *                 yield Response.buildResponse(
1049
     *                         CODE_404_NOT_FOUND,
1050
     *                         Map.of("Content-Type", "text/html; charset=UTF-8"),
1051
     *                         "<p>No document was found</p>");
1052
     *             }
1053
     *             case CODE_500_INTERNAL_SERVER_ERROR -> {
1054
     *                 yield Response.buildResponse(
1055
     *                         CODE_500_INTERNAL_SERVER_ERROR,
1056
     *                         Map.of("Content-Type", "text/html; charset=UTF-8"),
1057
     *                         "<p>Server error occurred.</p>" );
1058
     *             }
1059
     *             default -> inputs.response();
1060
     *         }
1061
     *     }
1062
     * }
1063
     * </pre>
1064
     * @param lastMinuteHandler a function that will take a request and return a response, exactly like
1065
     *                   we use in the other registration methods for this class.
1066
     */
1067
    public void registerLastMinuteHandler(ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler) {
1068
        this.lastMinuteHandler = lastMinuteHandler;
1069
    }
1070
1071
    /**
1072
     * This allows users to add extra mappings
1073
     * between file suffixes and mime types, in case
1074
     * a user needs one that was not provided.
1075
     * <p>
1076
     *     This is made available through the
1077
     *     web framework.
1078
     * </p>
1079
     * <p>
1080
     *     Example:
1081
     * </p>
1082
     * <pre>
1083
     * {@code webFramework.addMimeForSuffix().put("foo","text/foo")}
1084
     * </pre>
1085
     */
1086
    public void addMimeForSuffix(String suffix, String mimeType) {
1087
        fileSuffixToMime.put(suffix, mimeType);
1088
    }
1089
}

Mutations

61

1.1
Location : getSuffixToMimeMappings
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with Collections.emptyMap for com/renomad/minum/web/WebFramework::getSuffixToMimeMappings → KILLED

88

1.1
Location : apply
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

158

1.1
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

2.2
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

167

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::checkIfSuspiciousPath → TIMED_OUT

176

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

183

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → TIMED_OUT

184

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
removed call to com/renomad/minum/web/Headers::appendHeadersToBuilder → KILLED

185

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::addKeepAliveTimeout → TIMED_OUT

189

1.1
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

2.2
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

3.3
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
changed conditional boundary → KILLED

196

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::applyContentLength → TIMED_OUT

197

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_PostHandler_IgnoreBody(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/WebFramework::confirmBodyHasContentType → KILLED

202

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

212

1.1
Location : httpProcessing
Killed by : none
removed call to java/lang/StringBuilder::setLength → TIMED_OUT

214

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_BadRequest(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/WebFramework::addDefaultHeaders → KILLED

220

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/ISocketWrapper::send → TIMED_OUT

222

1.1
Location : httpProcessing
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

224

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/IResponse::sendBody → TIMED_OUT

228

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/ISocketWrapper::flush → TIMED_OUT

234

1.1
Location : httpProcessing
Killed by : none
negated conditional → TIMED_OUT

241

1.1
Location : httpProcessing
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/WebFramework::handleForbiddenUse → KILLED

243

1.1
Location : httpProcessing
Killed by : none
removed call to com/renomad/minum/web/WebFramework::finalExceptionHandler → TIMED_OUT

255

1.1
Location : finalExceptionHandler
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

2.2
Location : finalExceptionHandler
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

256

1.1
Location : finalExceptionHandler
Killed by : none
negated conditional → SURVIVED
Covering tests

261

1.1
Location : finalExceptionHandler
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

2.2
Location : finalExceptionHandler
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

264

1.1
Location : finalExceptionHandler
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_IOExceptionThrown_WebFramework(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

275

1.1
Location : handleForbiddenUse
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

292

1.1
Location : handleBadRequestException
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::handleBadRequestException → TIMED_OUT

307

1.1
Location : processRequest
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

312

1.1
Location : processRequest
Killed by : none
negated conditional → TIMED_OUT

330

1.1
Location : processRequest
Killed by : none
negated conditional → TIMED_OUT

334

1.1
Location : processRequest
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
replaced return value with null for com/renomad/minum/web/WebFramework::processRequest → KILLED

351

1.1
Location : getHeaders
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::getHeaders → TIMED_OUT

381

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

383

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

384

1.1
Location : determineIfKeepAlive
Killed by : none
negated conditional → TIMED_OUT

387

1.1
Location : determineIfKeepAlive
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_Response_MultiCookies(com.renomad.minum.FunctionalTests)
changed conditional boundary → KILLED

2.2
Location : determineIfKeepAlive
Killed by : none
negated conditional → TIMED_OUT

3.3
Location : determineIfKeepAlive
Killed by : none
negated conditional → TIMED_OUT

4.4
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

398

1.1
Location : determineIfKeepAlive
Killed by : none
replaced boolean return with true for com/renomad/minum/web/WebFramework::determineIfKeepAlive → TIMED_OUT

2.2
Location : determineIfKeepAlive
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
replaced boolean return with false for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED

406

1.1
Location : getProcessedRequestLine
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::getProcessedRequestLine → TIMED_OUT

410

1.1
Location : checkIfSuspiciousPath
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

423

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

424

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

425

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_Response_MultiCookies(com.renomad.minum.FunctionalTests)
negated conditional → KILLED

426

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebTests
replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

428

1.1
Location : dumpIfAttacker
Killed by : none
removed call to com/renomad/minum/web/WebFramework::dumpIfAttacker → TIMED_OUT

429

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response_Range(com.renomad.minum.FunctionalTests)
replaced boolean return with false for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED

438

1.1
Location : dumpIfAttacker
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

453

1.1
Location : lambda$addDefaultHeaders$20
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::lambda$addDefaultHeaders$20 → TIMED_OUT

473

1.1
Location : confirmBodyHasContentType
Killed by : com.renomad.minum.web.BodyProcessorTests
negated conditional → KILLED

476

1.1
Location : confirmBodyHasContentType
Killed by : com.renomad.minum.web.BodyProcessorTests
negated conditional → KILLED

2.2
Location : confirmBodyHasContentType
Killed by : none
changed conditional boundary → TIMED_OUT

3.3
Location : confirmBodyHasContentType
Killed by : com.renomad.minum.web.BodyProcessorTests
negated conditional → KILLED

487

1.1
Location : addKeepAliveTimeout
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

517

1.1
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

518

1.1
Location : compressBodyIfRequested
Killed by : none
negated conditional → TIMED_OUT

522

1.1
Location : compressBodyIfRequested
Killed by : none
removed call to com/renomad/minum/web/WebFramework::compressBody → SURVIVED
Covering tests

524

1.1
Location : lambda$compressBodyIfRequested$21
Killed by : none
Replaced double multiplication with division → SURVIVED
Covering tests

2.2
Location : lambda$compressBodyIfRequested$21
Killed by : none
Replaced double division with multiplication → SURVIVED Covering tests

525

1.1
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED

531

1.1
Location : compressBodyIfRequested
Killed by : com.renomad.minum.web.WebTests
replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED

543

1.1
Location : compressBody
Killed by : com.renomad.minum.web.CachingAndCompressionTests
removed call to java/util/zip/GZIPOutputStream::write → KILLED

544

1.1
Location : compressBody
Killed by : none
removed call to java/util/zip/GZIPOutputStream::finish → SURVIVED
Covering tests

564

1.1
Location : findEndpointForThisStartline
Killed by : none
negated conditional → TIMED_OUT

569

1.1
Location : findEndpointForThisStartline
Killed by : none
negated conditional → TIMED_OUT

574

1.1
Location : findEndpointForThisStartline
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

580

1.1
Location : findEndpointForThisStartline
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::findEndpointForThisStartline → TIMED_OUT

589

1.1
Location : findHandlerByFilesOnDisk
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

2.2
Location : findHandlerByFilesOnDisk
Killed by : none
negated conditional → TIMED_OUT

592

1.1
Location : findHandlerByFilesOnDisk
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response(com.renomad.minum.FunctionalTests)
replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByFilesOnDisk → KILLED

2.2
Location : lambda$findHandlerByFilesOnDisk$25
Killed by : com.renomad.minum.FunctionalTests.test_PathFunction_Response_Range(com.renomad.minum.FunctionalTests)
replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$25 → KILLED

621

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

623

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
removed call to java/util/concurrent/locks/ReentrantLock::lock → KILLED

626

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

628

1.1
Location : readStaticFile
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

631

1.1
Location : readStaticFile
Killed by : none
removed call to java/util/concurrent/locks/ReentrantLock::unlock → TIMED_OUT

636

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
removed call to com/renomad/minum/utils/FileUtils::checkForBadFilePatterns → KILLED

639

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

643

1.1
Location : readStaticFile
Killed by : none
removed call to com/renomad/minum/utils/IFileUtils::checkFileIsWithinDirectory → TIMED_OUT

646

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

650

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

652

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

656

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

658

1.1
Location : readStaticFile
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → TIMED_OUT

659

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.CachingAndCompressionTests
changed conditional boundary → KILLED

2.2
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

662

1.1
Location : readStaticFile
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

665

1.1
Location : readStaticFile
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED

670

1.1
Location : readStaticFile
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → SURVIVED
Covering tests

679

1.1
Location : getMimeString
Killed by : none
changed conditional boundary → SURVIVED
Covering tests

2.2
Location : getMimeString
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

680

1.1
Location : getMimeString
Killed by : com.renomad.minum.web.WebFrameworkTests
Replaced integer addition with subtraction → KILLED

687

1.1
Location : getMimeString
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

690

1.1
Location : getMimeString
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with "" for com/renomad/minum/web/WebFramework::getMimeString → KILLED

703

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

705

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.CachingAndCompressionTests
removed call to com/renomad/minum/web/WebFramework::compressBody → KILLED

709

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.CachingAndCompressionTests
Replaced double division with multiplication → KILLED

2.2
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.CachingAndCompressionTests
Replaced double multiplication with division → KILLED

710

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.CachingAndCompressionTests
negated conditional → KILLED

2.2
Location : createOkResponseForStaticFiles
Killed by : none
changed conditional boundary → SURVIVED
Covering tests

717

1.1
Location : createOkResponseForStaticFiles
Killed by : com.renomad.minum.web.WebFrameworkTests
replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForStaticFiles → KILLED

718

1.1
Location : lambda$createOkResponseForStaticFiles$36
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/ISocketWrapper::send → KILLED

733

1.1
Location : createOkResponseForLargeStaticFiles
Killed by : com.renomad.minum.FunctionalTests.testEndToEnd_Functional(com.renomad.minum.FunctionalTests)
replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForLargeStaticFiles → KILLED

762

1.1
Location : findHandlerByPathFunction
Killed by : none
negated conditional → TIMED_OUT

766

1.1
Location : findHandlerByPathFunction
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByPathFunction → TIMED_OUT

767

1.1
Location : lambda$findHandlerByPathFunction$37
Killed by : none
replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByPathFunction$37 → TIMED_OUT

799

1.1
Location : <init>
Killed by : com.renomad.minum.web.WebEngineTests
negated conditional → KILLED

809

1.1
Location : <init>
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

825

1.1
Location : <init>
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

835

1.1
Location : <init>
Killed by : none
removed call to com/renomad/minum/web/WebFramework::addDefaultValuesForMimeMap → TIMED_OUT

836

1.1
Location : <init>
Killed by : none
removed call to com/renomad/minum/web/WebFramework::readExtraMimeMappings → TIMED_OUT

840

1.1
Location : readExtraMimeMappings
Killed by : none
negated conditional → TIMED_OUT

2.2
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebFrameworkTests
negated conditional → KILLED

841

1.1
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebEngineTests
Replaced integer modulus with multiplication → KILLED

2.2
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebEngineTests
negated conditional → KILLED

845

1.1
Location : readExtraMimeMappings
Killed by : none
negated conditional → TIMED_OUT

2.2
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebEngineTests
changed conditional boundary → KILLED

847

1.1
Location : readExtraMimeMappings
Killed by : com.renomad.minum.web.WebEngineTests
Replaced integer addition with subtraction → KILLED

863

1.1
Location : registerPath
Killed by : none
negated conditional → TIMED_OUT

2.2
Location : registerPath
Killed by : none
negated conditional → TIMED_OUT

869

1.1
Location : registerPath
Killed by : none
negated conditional → TIMED_OUT

873

1.1
Location : registerPath
Killed by : com.renomad.minum.FunctionalTests.test_EdgeCase_BadRequest(com.renomad.minum.FunctionalTests)
removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → KILLED

882

1.1
Location : checkForDuplicatePartialPath
Killed by : com.renomad.minum.web.WebPerformanceTests.webPerfTest(com.renomad.minum.web.WebPerformanceTests)
negated conditional → KILLED

886

1.1
Location : lambda$checkForDuplicatePartialPath$39
Killed by : com.renomad.minum.web.WebTests
replaced return value with "" for com/renomad/minum/web/WebFramework::lambda$checkForDuplicatePartialPath$39 → KILLED

887

1.1
Location : checkForDuplicatePartialPath
Killed by : none
negated conditional → TIMED_OUT

936

1.1
Location : lambda$registerPath$40
Killed by : none
replaced return value with Collections.emptyList for com/renomad/minum/web/WebFramework::lambda$registerPath$40 → TIMED_OUT

953

1.1
Location : registerPartialPath
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

2.2
Location : registerPartialPath
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

960

1.1
Location : registerPartialPath
Killed by : com.renomad.minum.web.WebTests
negated conditional → KILLED

964

1.1
Location : registerPartialPath
Killed by : none
removed call to com/renomad/minum/web/WebFramework::checkForDuplicatePartialPath → TIMED_OUT

965

1.1
Location : registerPartialPath
Killed by : com.renomad.minum.web.WebTests
removed call to com/renomad/minum/web/WebFramework::registerPath → KILLED

Active mutators

Tests examined


Report generated by PIT 1.17.0