| 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 java.io.IOException; | |
| 11 | import java.net.SocketException; | |
| 12 | import java.net.SocketTimeoutException; | |
| 13 | import java.nio.charset.StandardCharsets; | |
| 14 | import java.nio.file.Files; | |
| 15 | import java.nio.file.Path; | |
| 16 | import java.time.ZoneId; | |
| 17 | import java.time.ZonedDateTime; | |
| 18 | import java.time.format.DateTimeFormatter; | |
| 19 | import java.util.*; | |
| 20 | ||
| 21 | import static com.renomad.minum.utils.FileUtils.checkFileIsWithinDirectory; | |
| 22 | import static com.renomad.minum.utils.FileUtils.checkForBadFilePatterns; | |
| 23 | import static com.renomad.minum.web.StatusLine.StatusCode.*; | |
| 24 | import static com.renomad.minum.web.WebEngine.HTTP_CRLF; | |
| 25 | ||
| 26 | /** | |
| 27 | * This class is responsible for the HTTP handling after socket connection. | |
| 28 | * <p> | |
| 29 | * The public methods are for registering endpoints - code that will be | |
| 30 | * run for a given combination of HTTP method and path. See documentation | |
| 31 | * for the methods in this class. | |
| 32 | * </p> | |
| 33 | */ | |
| 34 | public final class WebFramework { | |
| 35 | ||
| 36 | private final Constants constants; | |
| 37 | private final IInputStreamUtils inputStreamUtils; | |
| 38 | private final IBodyProcessor bodyProcessor; | |
| 39 | /** | |
| 40 | * This is a variable storing a pseudo-random (non-secure) number | |
| 41 | * that is shown to users when a serious error occurs, which | |
| 42 | * will also be put in the logs, to make finding it easier. | |
| 43 | */ | |
| 44 | private final Random randomErrorCorrelationId; | |
| 45 | private final RequestLine emptyRequestLine; | |
| 46 | private final RequestLine validRequestLine; | |
| 47 | private final ITheBrig theBrig; | |
| 48 | ||
| 49 | public Map<String,String> getSuffixToMimeMappings() { | |
| 50 |
1
1. getSuffixToMimeMappings : replaced return value with Collections.emptyMap for com/renomad/minum/web/WebFramework::getSuffixToMimeMappings → KILLED |
return new HashMap<>(fileSuffixToMime); |
| 51 | } | |
| 52 | ||
| 53 | /** | |
| 54 | * This is used as a key when registering endpoints | |
| 55 | */ | |
| 56 | record MethodPath(RequestLine.Method method, String path) { } | |
| 57 | ||
| 58 | /** | |
| 59 | * The list of paths that our system is registered to handle. | |
| 60 | */ | |
| 61 | private final Map<MethodPath, ThrowingFunction<IRequest, IResponse>> registeredDynamicPaths; | |
| 62 | ||
| 63 | /** | |
| 64 | * These are registrations for paths that partially match, for example, | |
| 65 | * if the client sends us GET /.well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX | |
| 66 | * and we want to match ".well-known/acme-challenge" | |
| 67 | */ | |
| 68 | private final Map<MethodPath, ThrowingFunction<IRequest, IResponse>> registeredPartialPaths; | |
| 69 | ||
| 70 | /** | |
| 71 | * A function that will be run instead of the ordinary business code. Has | |
| 72 | * provisions for running the business code as well. See {@link #registerPreHandler(ThrowingFunction)} | |
| 73 | */ | |
| 74 | private ThrowingFunction<PreHandlerInputs, IResponse> preHandler; | |
| 75 | ||
| 76 | /** | |
| 77 | * A function run after the ordinary business code | |
| 78 | */ | |
| 79 | private ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler; | |
| 80 | ||
| 81 | private final IFileReader fileReader; | |
| 82 | private final Map<String, String> fileSuffixToMime; | |
| 83 | ||
| 84 | // This is just used for testing. If it's null, we use the real time. | |
| 85 | private final ZonedDateTime overrideForDateTime; | |
| 86 | private final FullSystem fs; | |
| 87 | private final ILogger logger; | |
| 88 | ||
| 89 | /** | |
| 90 | * This is the minimum number of bytes in a text response to apply gzip. | |
| 91 | */ | |
| 92 | private static final int MINIMUM_NUMBER_OF_BYTES_TO_COMPRESS = 2048; | |
| 93 | ||
| 94 | void httpProcessing(ISocketWrapper sw) throws Exception { | |
| 95 | try (sw) { | |
| 96 | dumpIfAttacker(sw, fs); | |
| 97 | final var is = sw.getInputStream(); | |
| 98 | ||
| 99 | // By default, browsers expect the server to run in keep-alive mode. | |
| 100 | // We'll break out later if we find that the browser doesn't do keep-alive | |
| 101 | while (true) { | |
| 102 | final String rawStartLine = inputStreamUtils.readLine(is); | |
| 103 | long startMillis = System.currentTimeMillis(); | |
| 104 |
2
1. httpProcessing : negated conditional → KILLED 2. httpProcessing : negated conditional → KILLED |
if (rawStartLine == null || rawStartLine.isEmpty()) { |
| 105 | // here, the client connected, sent nothing, and closed. | |
| 106 | // nothing to do but return. | |
| 107 | logger.logTrace(() -> "rawStartLine was empty. Returning."); | |
| 108 | break; | |
| 109 | } | |
| 110 | final RequestLine requestLine = getProcessedRequestLine(sw, rawStartLine); | |
| 111 | ||
| 112 |
1
1. httpProcessing : negated conditional → KILLED |
if (requestLine.equals(emptyRequestLine)) { |
| 113 | // here, the client sent something we cannot parse. | |
| 114 | // nothing to do but return. | |
| 115 | logger.logTrace(() -> "RequestLine was unparseable. Returning."); | |
| 116 | break; | |
| 117 | } | |
| 118 | // check if the user is seeming to attack us. | |
| 119 |
1
1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::checkIfSuspiciousPath → SURVIVED |
checkIfSuspiciousPath(sw, requestLine); |
| 120 | ||
| 121 | // React to what the user requested, generate a result | |
| 122 | Headers headers = getHeaders(sw); | |
| 123 | boolean isKeepAlive = determineIfKeepAlive(requestLine, headers, logger); | |
| 124 | IRequest request = new Request(headers, requestLine, sw.getRemoteAddr(), sw, bodyProcessor); | |
| 125 | IResponse response = processRequest(request, sw, requestLine, headers); | |
| 126 | ||
| 127 | // check that the response is non-null. If it is null, that suggests | |
| 128 | // the developer made a mistake. | |
| 129 |
1
1. httpProcessing : negated conditional → TIMED_OUT |
if (response == null) { |
| 130 | throw new WebServerException("The returned value for the endpoint \"%s\" was null.".formatted(request.getRequestLine().getPathDetails().getIsolatedPath())); | |
| 131 | } | |
| 132 | ||
| 133 | // calculate proper headers for the response | |
| 134 | StringBuilder headerStringBuilder = addDefaultHeaders(response); | |
| 135 |
1
1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addOptionalExtraHeaders → TIMED_OUT |
addOptionalExtraHeaders(response, headerStringBuilder); |
| 136 |
1
1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::addKeepAliveTimeout → KILLED |
addKeepAliveTimeout(isKeepAlive, headerStringBuilder); |
| 137 | ||
| 138 | // inspect the response being sent, see whether we can compress the data. | |
| 139 | IResponse adjustedResponse = potentiallyCompress(request.getHeaders(), response, headerStringBuilder); | |
| 140 |
1
1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::applyContentLength → KILLED |
applyContentLength(headerStringBuilder, adjustedResponse.getBodyLength()); |
| 141 |
1
1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::confirmBodyHasContentType → KILLED |
confirmBodyHasContentType(request, response); |
| 142 | ||
| 143 | // send the headers | |
| 144 |
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)); |
| 145 | ||
| 146 | // if the user sent a HEAD request, we send everything back except the body. | |
| 147 | // even though we skip the body, this requires full processing to get the | |
| 148 | // numbers right, like content-length. | |
| 149 |
1
1. httpProcessing : negated conditional → TIMED_OUT |
if (request.getRequestLine().getMethod().equals(RequestLine.Method.HEAD)) { |
| 150 | logger.logDebug(() -> "client " + request.getRemoteRequester() + | |
| 151 | " is requesting HEAD for " + request.getRequestLine().getPathDetails().getIsolatedPath() + | |
| 152 | ". Excluding body from response"); | |
| 153 | } else { | |
| 154 | // send the body | |
| 155 |
1
1. httpProcessing : removed call to com/renomad/minum/web/IResponse::sendBody → TIMED_OUT |
adjustedResponse.sendBody(sw); |
| 156 | } | |
| 157 | ||
| 158 |
1
1. httpProcessing : removed call to com/renomad/minum/web/ISocketWrapper::flush → TIMED_OUT |
sw.flush(); |
| 159 | ||
| 160 | // print how long this processing took | |
| 161 | long endMillis = System.currentTimeMillis(); | |
| 162 | logger.logTrace(() -> String.format("full processing (including communication time) of %s %s took %d millis", sw, requestLine, endMillis - startMillis)); | |
| 163 |
1
1. httpProcessing : negated conditional → KILLED |
if (!isKeepAlive) break; |
| 164 | } | |
| 165 | } catch (SocketException | SocketTimeoutException ex) { | |
| 166 |
1
1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::handleReadTimedOut → KILLED |
handleReadTimedOut(sw, ex, logger); |
| 167 | } catch (ForbiddenUseException ex) { | |
| 168 |
1
1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::handleForbiddenUse → KILLED |
handleForbiddenUse(sw, ex, logger, theBrig, constants.vulnSeekingJailDuration); |
| 169 | } catch (IOException ex) { | |
| 170 |
1
1. httpProcessing : removed call to com/renomad/minum/web/WebFramework::handleIOException → KILLED |
handleIOException(sw, ex, logger, theBrig, constants.vulnSeekingJailDuration, constants.suspiciousErrors); |
| 171 | } | |
| 172 | } | |
| 173 | ||
| 174 | ||
| 175 | static void handleIOException(ISocketWrapper sw, IOException ex, ILogger logger, ITheBrig theBrig, int vulnSeekingJailDuration, Set<String> suspiciousErrors) { | |
| 176 | logger.logDebug(() -> ex.getMessage() + " (at Server.start)"); | |
| 177 | ||
| 178 |
2
1. handleIOException : negated conditional → KILLED 2. handleIOException : negated conditional → KILLED |
if (suspiciousErrors.contains(ex.getMessage()) && theBrig != null) { |
| 179 | logger.logDebug(() -> sw.getRemoteAddr() + " is looking for vulnerabilities, for this: " + ex.getMessage()); | |
| 180 | theBrig.sendToJail(sw.getRemoteAddr() + "_vuln_seeking", vulnSeekingJailDuration); | |
| 181 | } | |
| 182 | } | |
| 183 | ||
| 184 | static void handleForbiddenUse(ISocketWrapper sw, ForbiddenUseException ex, ILogger logger, ITheBrig theBrig, int vulnSeekingJailDuration) { | |
| 185 | logger.logDebug(() -> sw.getRemoteAddr() + " is looking for vulnerabilities, for this: " + ex.getMessage()); | |
| 186 |
1
1. handleForbiddenUse : negated conditional → KILLED |
if (theBrig != null) { |
| 187 | theBrig.sendToJail(sw.getRemoteAddr() + "_vuln_seeking", vulnSeekingJailDuration); | |
| 188 | } else { | |
| 189 | logger.logDebug(() -> "theBrig is null at handleForbiddenUse, will not store address in database"); | |
| 190 | } | |
| 191 | } | |
| 192 | ||
| 193 | static void handleReadTimedOut(ISocketWrapper sw, IOException ex, ILogger logger) { | |
| 194 | /* | |
| 195 | if we close the application on the server side, there's a good | |
| 196 | likelihood a SocketException will come bubbling through here. | |
| 197 | NOTE: | |
| 198 | it seems that Socket closed is what we get when the client closes the connection in non-SSL, and conversely, | |
| 199 | if we are operating in secure (i.e. SSL/TLS) mode, we get "an established connection..." | |
| 200 | */ | |
| 201 |
1
1. handleReadTimedOut : negated conditional → KILLED |
if (ex.getMessage().equals("Read timed out")) { |
| 202 | logger.logTrace(() -> "Read timed out - remote address: " + sw.getRemoteAddrWithPort()); | |
| 203 | } else { | |
| 204 | logger.logDebug(() -> ex.getMessage() + " - remote address: " + sw.getRemoteAddrWithPort()); | |
| 205 | } | |
| 206 | } | |
| 207 | ||
| 208 | /** | |
| 209 | * Logic for how to process an incoming request. For example, did the developer | |
| 210 | * write a function to handle this? Is it a request for a static file, like an image | |
| 211 | * or script? Did the user provide a "pre" or "post" handler? | |
| 212 | */ | |
| 213 | IResponse processRequest( | |
| 214 | IRequest clientRequest, | |
| 215 | ISocketWrapper sw, | |
| 216 | RequestLine requestLine, | |
| 217 | Headers requestHeaders) throws Exception { | |
| 218 | IResponse response; | |
| 219 | ThrowingFunction<IRequest, IResponse> endpoint = findEndpointForThisStartline(requestLine, requestHeaders); | |
| 220 |
1
1. processRequest : negated conditional → KILLED |
if (endpoint == null) { |
| 221 | response = Response.buildLeanResponse(CODE_404_NOT_FOUND); | |
| 222 | } else { | |
| 223 | long millisAtStart = System.currentTimeMillis(); | |
| 224 | try { | |
| 225 |
1
1. processRequest : negated conditional → KILLED |
if (preHandler != null) { |
| 226 | response = preHandler.apply(new PreHandlerInputs(clientRequest, endpoint, sw)); | |
| 227 | } else { | |
| 228 | response = endpoint.apply(clientRequest); | |
| 229 | } | |
| 230 | } catch (Exception ex) { | |
| 231 | // if an error happens while running an endpoint's code, this is the | |
| 232 | // last-chance handling of that error where we return a 500 and a | |
| 233 | // random code to the client, so a developer can find the detailed | |
| 234 | // information in the logs, which have that same value. | |
| 235 | int randomNumber = randomErrorCorrelationId.nextInt(); | |
| 236 | logger.logAsyncError(() -> "error while running endpoint " + endpoint + ". Code: " + randomNumber + ". Error: " + StacktraceUtils.stackTraceToString(ex)); | |
| 237 | response = Response.buildResponse(CODE_500_INTERNAL_SERVER_ERROR, Map.of("Content-Type", "text/plain;charset=UTF-8"), "Server error: " + randomNumber); | |
| 238 | } | |
| 239 | long millisAtEnd = System.currentTimeMillis(); | |
| 240 | logger.logTrace(() -> String.format("handler processing of %s %s took %d millis", sw, requestLine, millisAtEnd - millisAtStart)); | |
| 241 | } | |
| 242 | ||
| 243 | // if the user has chosen to customize the response based on status code, that will | |
| 244 | // be applied now, and it will override the previous response. | |
| 245 |
1
1. processRequest : negated conditional → KILLED |
if (lastMinuteHandler != null) { |
| 246 | response = lastMinuteHandler.apply(new LastMinuteHandlerInputs(clientRequest, response)); | |
| 247 | } | |
| 248 | ||
| 249 |
1
1. processRequest : replaced return value with null for com/renomad/minum/web/WebFramework::processRequest → KILLED |
return response; |
| 250 | } | |
| 251 | ||
| 252 | private Headers getHeaders(ISocketWrapper sw) { | |
| 253 | /* | |
| 254 | next we will read the headers (e.g. Content-Type: foo/bar) one-by-one. | |
| 255 | ||
| 256 | the headers tell us vital information about the | |
| 257 | body. If, for example, we're getting a POST and receiving a | |
| 258 | www form url encoded, there will be a header of "content-length" | |
| 259 | that will mention how many bytes to read. On the other hand, if | |
| 260 | we're receiving a multipart, there will be no content-length, but | |
| 261 | the content-type will include the boundary string. | |
| 262 | */ | |
| 263 | List<String> allHeaders = Headers.getAllHeaders(sw.getInputStream(), inputStreamUtils); | |
| 264 | Headers hi = new Headers(allHeaders); | |
| 265 | logger.logTrace(() -> "The headers are: " + hi.getHeaderStrings()); | |
| 266 |
1
1. getHeaders : replaced return value with null for com/renomad/minum/web/WebFramework::getHeaders → TIMED_OUT |
return hi; |
| 267 | } | |
| 268 | ||
| 269 | /** | |
| 270 | * determine if we are in a keep-alive connection | |
| 271 | */ | |
| 272 | static boolean determineIfKeepAlive(RequestLine sl, Headers hi, ILogger logger) { | |
| 273 | boolean isKeepAlive = false; | |
| 274 |
1
1. determineIfKeepAlive : negated conditional → TIMED_OUT |
if (sl.getVersion() == HttpVersion.ONE_DOT_ZERO) { |
| 275 | isKeepAlive = hi.hasKeepAlive(); | |
| 276 |
1
1. determineIfKeepAlive : negated conditional → KILLED |
} else if (sl.getVersion() == HttpVersion.ONE_DOT_ONE) { |
| 277 |
1
1. determineIfKeepAlive : negated conditional → KILLED |
isKeepAlive = ! hi.hasConnectionClose(); |
| 278 | } | |
| 279 | boolean finalIsKeepAlive = isKeepAlive; | |
| 280 | logger.logTrace(() -> "Is this a keep-alive connection? " + finalIsKeepAlive); | |
| 281 |
2
1. determineIfKeepAlive : replaced boolean return with false for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED 2. determineIfKeepAlive : replaced boolean return with true for com/renomad/minum/web/WebFramework::determineIfKeepAlive → KILLED |
return isKeepAlive; |
| 282 | } | |
| 283 | ||
| 284 | RequestLine getProcessedRequestLine(ISocketWrapper sw, String rawStartLine) { | |
| 285 | logger.logTrace(() -> sw + ": raw request line received: " + rawStartLine); | |
| 286 | ||
| 287 | RequestLine extractedRequestLine = validRequestLine.extractRequestLine(rawStartLine); | |
| 288 | logger.logTrace(() -> sw + ": RequestLine has been derived: " + extractedRequestLine); | |
| 289 |
1
1. getProcessedRequestLine : replaced return value with null for com/renomad/minum/web/WebFramework::getProcessedRequestLine → KILLED |
return extractedRequestLine; |
| 290 | } | |
| 291 | ||
| 292 | void checkIfSuspiciousPath(ISocketWrapper sw, RequestLine requestLine) { | |
| 293 |
1
1. checkIfSuspiciousPath : negated conditional → KILLED |
if (constants.suspiciousPaths.contains(requestLine.getPathDetails().getIsolatedPath())) { |
| 294 | String msg = sw.getRemoteAddr() + " is looking for a vulnerability, for this: " + requestLine.getPathDetails().getIsolatedPath(); | |
| 295 | throw new ForbiddenUseException(msg); | |
| 296 | } | |
| 297 | } | |
| 298 | ||
| 299 | /** | |
| 300 | * Drops the connection immediately if the client is recognized | |
| 301 | * as someone we consider an attacker, by dint of having been | |
| 302 | * added to a blacklist in {@link com.renomad.minum.security.TheBrig}. | |
| 303 | */ | |
| 304 | boolean dumpIfAttacker(ISocketWrapper sw, FullSystem fs) { | |
| 305 |
1
1. dumpIfAttacker : negated conditional → TIMED_OUT |
if (fs == null) { |
| 306 |
1
1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED |
return false; |
| 307 |
1
1. dumpIfAttacker : negated conditional → KILLED |
} else if (fs.getTheBrig() == null) { |
| 308 |
1
1. dumpIfAttacker : replaced boolean return with true for com/renomad/minum/web/WebFramework::dumpIfAttacker → KILLED |
return false; |
| 309 | } else { | |
| 310 |
1
1. dumpIfAttacker : removed call to com/renomad/minum/web/WebFramework::dumpIfAttacker → TIMED_OUT |
dumpIfAttacker(sw, fs.getTheBrig()); |
| 311 |
1
1. dumpIfAttacker : replaced boolean return with false for com/renomad/minum/web/WebFramework::dumpIfAttacker → TIMED_OUT |
return true; |
| 312 | } | |
| 313 | } | |
| 314 | ||
| 315 | void dumpIfAttacker(ISocketWrapper sw, ITheBrig theBrig) { | |
| 316 | String remoteClient = sw.getRemoteAddr(); | |
| 317 |
1
1. dumpIfAttacker : negated conditional → KILLED |
if (theBrig.isInJail(remoteClient + "_vuln_seeking")) { |
| 318 | // if this client is a vulnerability seeker, throw an exception, | |
| 319 | // causing them to get dumped unceremoniously | |
| 320 | String message = "closing the socket on " + remoteClient + " due to being found in the brig"; | |
| 321 | logger.logDebug(() -> message); | |
| 322 | throw new ForbiddenUseException(message); | |
| 323 | } | |
| 324 | } | |
| 325 | ||
| 326 | /** | |
| 327 | * Prepare some of the basic server response headers, like the status code, the | |
| 328 | * date-time stamp, the server name. | |
| 329 | */ | |
| 330 | private StringBuilder addDefaultHeaders(IResponse response) { | |
| 331 | ||
| 332 |
1
1. lambda$addDefaultHeaders$17 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$addDefaultHeaders$17 → KILLED |
String date = Objects.requireNonNullElseGet(overrideForDateTime, () -> ZonedDateTime.now(ZoneId.of("UTC"))).format(DateTimeFormatter.RFC_1123_DATE_TIME); |
| 333 | ||
| 334 | // we'll store the status line and headers in this | |
| 335 | StringBuilder headerStringBuilder = new StringBuilder(600); // 600 is just a magic arbitrary number I picked, because our response headers | |
| 336 | // are not usually too large - even if the user added a bunch, there is a good | |
| 337 | // chance it would be far under 600. If that turns out to be wrong, adjust/redesign | |
| 338 | ||
| 339 | // add the status line | |
| 340 | headerStringBuilder.append("HTTP/1.1 ").append(response.getStatusCode().code).append(" ").append(response.getStatusCode().shortDescription).append(HTTP_CRLF); | |
| 341 | ||
| 342 | // add a date-timestamp | |
| 343 | headerStringBuilder.append("Date: ").append(date).append(HTTP_CRLF); | |
| 344 | ||
| 345 | // add the server name | |
| 346 | headerStringBuilder.append("Server: minum").append(HTTP_CRLF); | |
| 347 | ||
| 348 |
1
1. addDefaultHeaders : replaced return value with null for com/renomad/minum/web/WebFramework::addDefaultHeaders → TIMED_OUT |
return headerStringBuilder; |
| 349 | } | |
| 350 | ||
| 351 | /** | |
| 352 | * Add extra headers specified by the business logic (set by the developer) | |
| 353 | */ | |
| 354 | private static void addOptionalExtraHeaders(IResponse response, StringBuilder stringBuilder) { | |
| 355 | for (Map.Entry<String,String> header : response.getExtraHeaders().entrySet()) { | |
| 356 | stringBuilder.append(header.getKey()) | |
| 357 | .append(": ") | |
| 358 | .append(header.getValue()) | |
| 359 | .append(HTTP_CRLF); | |
| 360 | } | |
| 361 | } | |
| 362 | ||
| 363 | /** | |
| 364 | * If a response body exists, it needs to have a content-type specified, | |
| 365 | * or throw an exception. Otherwise, the user could totally miss they did | |
| 366 | * not set a content-type, because the browser will inspect the data and | |
| 367 | * do sort-of-the-right-thing a lot of the time, but we want to enforce correctness. | |
| 368 | */ | |
| 369 | static void confirmBodyHasContentType(IRequest request, IResponse response) { | |
| 370 | // check the correctness of the content-type header versus the data length (if any data, that is) | |
| 371 |
2
1. lambda$confirmBodyHasContentType$18 : replaced boolean return with false for com/renomad/minum/web/WebFramework::lambda$confirmBodyHasContentType$18 → TIMED_OUT 2. lambda$confirmBodyHasContentType$18 : replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$confirmBodyHasContentType$18 → KILLED |
boolean hasContentType = response.getExtraHeaders().keySet().stream().anyMatch(x -> x.toLowerCase(Locale.ROOT).equals("content-type")); |
| 372 | ||
| 373 | // if there *is* data, we had better be returning a content type | |
| 374 |
3
1. confirmBodyHasContentType : negated conditional → KILLED 2. confirmBodyHasContentType : negated conditional → KILLED 3. confirmBodyHasContentType : changed conditional boundary → KILLED |
if (response.getBodyLength() > 0 && !hasContentType) { |
| 375 | throw new WebServerException("a Content-Type header must be specified in the Response object if it returns data. Response details: " + response + " Request: " + request); | |
| 376 | } | |
| 377 | } | |
| 378 | ||
| 379 | /** | |
| 380 | * If this is a keep-alive communication, add a header specifying the | |
| 381 | * socket timeout for the browser. | |
| 382 | */ | |
| 383 | private void addKeepAliveTimeout(boolean isKeepAlive, StringBuilder stringBuilder) { | |
| 384 | // if we're a keep-alive connection, reply with a keep-alive header | |
| 385 |
1
1. addKeepAliveTimeout : negated conditional → TIMED_OUT |
if (isKeepAlive) { |
| 386 | stringBuilder.append("Keep-Alive: timeout=").append(constants.keepAliveTimeoutSeconds).append(HTTP_CRLF); | |
| 387 | } | |
| 388 | } | |
| 389 | ||
| 390 | /** | |
| 391 | * The rules regarding the content-length header are byzantine. Even in the cases | |
| 392 | * where you aren't returning anything, servers can use this header to determine when the | |
| 393 | * response is finished. | |
| 394 | * See <a href="https://www.rfc-editor.org/rfc/rfc9110.html#name-content-length">Content-Length in the HTTP spec</a> | |
| 395 | */ | |
| 396 | private static void applyContentLength(StringBuilder stringBuilder, long bodyLength) { | |
| 397 | stringBuilder.append("Content-Length: ").append(bodyLength).append(HTTP_CRLF); | |
| 398 | } | |
| 399 | ||
| 400 | /** | |
| 401 | * This method will examine the request headers and response content-type, and | |
| 402 | * compress the outgoing data if necessary. | |
| 403 | */ | |
| 404 | static IResponse potentiallyCompress(Headers requestHeaders, IResponse response, StringBuilder headerStringBuilder) throws IOException { | |
| 405 | // we may make modifications to the response body at this point, specifically | |
| 406 | // we may compress the data, if the client requested it. | |
| 407 | // see https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Accept-encoding | |
| 408 | List<String> acceptEncoding = requestHeaders.valueByKey("accept-encoding"); | |
| 409 | ||
| 410 |
1
1. potentiallyCompress : negated conditional → KILLED |
if (response.isBodyText()) { |
| 411 |
1
1. potentiallyCompress : replaced return value with null for com/renomad/minum/web/WebFramework::potentiallyCompress → KILLED |
return compressBodyIfRequested(response, acceptEncoding, headerStringBuilder, MINIMUM_NUMBER_OF_BYTES_TO_COMPRESS); |
| 412 | } | |
| 413 |
1
1. potentiallyCompress : replaced return value with null for com/renomad/minum/web/WebFramework::potentiallyCompress → KILLED |
return response; |
| 414 | } | |
| 415 | ||
| 416 | /** | |
| 417 | * This method will examine the content-encoding headers, and if "gzip" is | |
| 418 | * requested by the client, we will replace the body bytes with compressed | |
| 419 | * bytes, using the GZIP compression algorithm, as long as the response body | |
| 420 | * is greater than minNumberBytes bytes. | |
| 421 | * | |
| 422 | * @param acceptEncoding headers sent by the client about what compression | |
| 423 | * algorithms will be understood. | |
| 424 | * @param stringBuilder the string we are gradually building up to send back to | |
| 425 | * the client for the status line and headers. We'll use it | |
| 426 | * here if we need to append a content-encoding - that is, | |
| 427 | * if we successfully compress data as gzip. | |
| 428 | * @param minNumberBytes number of bytes must be larger than this to compress. | |
| 429 | */ | |
| 430 | static IResponse compressBodyIfRequested(IResponse response, List<String> acceptEncoding, StringBuilder stringBuilder, int minNumberBytes) throws IOException { | |
| 431 |
1
1. compressBodyIfRequested : negated conditional → KILLED |
String allContentEncodingHeaders = acceptEncoding != null ? String.join(";", acceptEncoding) : ""; |
| 432 |
3
1. compressBodyIfRequested : negated conditional → KILLED 2. compressBodyIfRequested : changed conditional boundary → KILLED 3. compressBodyIfRequested : negated conditional → KILLED |
if (response.getBodyLength() >= minNumberBytes && allContentEncodingHeaders.contains("gzip")) { |
| 433 | stringBuilder.append("Content-Encoding: gzip").append(HTTP_CRLF); | |
| 434 | stringBuilder.append("Vary: accept-encoding").append(HTTP_CRLF); | |
| 435 |
1
1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED |
return ((Response)response).compressBody(); |
| 436 | } | |
| 437 |
1
1. compressBodyIfRequested : replaced return value with null for com/renomad/minum/web/WebFramework::compressBodyIfRequested → KILLED |
return response; |
| 438 | } | |
| 439 | ||
| 440 | /** | |
| 441 | * Looks through the mappings of {@link MethodPath} and path to registered endpoints | |
| 442 | * or the static cache and returns the appropriate one (If we | |
| 443 | * do not find anything, return null) | |
| 444 | */ | |
| 445 | ThrowingFunction<IRequest, IResponse> findEndpointForThisStartline(RequestLine sl, Headers requestHeaders) { | |
| 446 | ThrowingFunction<IRequest, IResponse> handler; | |
| 447 | logger.logTrace(() -> "Seeking a handler for " + sl); | |
| 448 | ||
| 449 | // first we check if there's a simple direct match | |
| 450 | String requestedPath = sl.getPathDetails().getIsolatedPath().toLowerCase(Locale.ROOT); | |
| 451 | ||
| 452 | // if the user is asking for a HEAD request, they want to run a GET command | |
| 453 | // but don't want the body. We'll simply exclude sending the body, later on, when returning the data | |
| 454 |
1
1. findEndpointForThisStartline : negated conditional → KILLED |
RequestLine.Method method = sl.getMethod() == RequestLine.Method.HEAD ? RequestLine.Method.GET : sl.getMethod(); |
| 455 | ||
| 456 | MethodPath key = new MethodPath(method, requestedPath); | |
| 457 | handler = registeredDynamicPaths.get(key); | |
| 458 | ||
| 459 |
1
1. findEndpointForThisStartline : negated conditional → KILLED |
if (handler == null) { |
| 460 | logger.logTrace(() -> "No direct handler found. looking for a partial match for " + requestedPath); | |
| 461 | handler = findHandlerByPartialMatch(sl); | |
| 462 | } | |
| 463 | ||
| 464 |
1
1. findEndpointForThisStartline : negated conditional → KILLED |
if (handler == null) { |
| 465 | logger.logTrace(() -> "No partial match found, checking files on disk for " + requestedPath ); | |
| 466 | handler = findHandlerByFilesOnDisk(sl, requestHeaders); | |
| 467 | } | |
| 468 | ||
| 469 | // we'll return this, and it could be a null. | |
| 470 |
1
1. findEndpointForThisStartline : replaced return value with null for com/renomad/minum/web/WebFramework::findEndpointForThisStartline → TIMED_OUT |
return handler; |
| 471 | } | |
| 472 | ||
| 473 | /** | |
| 474 | * last ditch effort - look on disk. This response will either | |
| 475 | * be the file to return, or null if we didn't find anything. | |
| 476 | */ | |
| 477 | private ThrowingFunction<IRequest, IResponse> findHandlerByFilesOnDisk(RequestLine sl, Headers requestHeaders) { | |
| 478 |
2
1. findHandlerByFilesOnDisk : negated conditional → KILLED 2. findHandlerByFilesOnDisk : negated conditional → KILLED |
if (sl.getMethod() != RequestLine.Method.GET && sl.getMethod() != RequestLine.Method.HEAD) { |
| 479 | return null; | |
| 480 | } | |
| 481 | String requestedPath = sl.getPathDetails().getIsolatedPath(); | |
| 482 | IResponse response = readStaticFile(requestedPath, requestHeaders); | |
| 483 |
2
1. lambda$findHandlerByFilesOnDisk$22 : replaced return value with null for com/renomad/minum/web/WebFramework::lambda$findHandlerByFilesOnDisk$22 → KILLED 2. findHandlerByFilesOnDisk : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByFilesOnDisk → KILLED |
return request -> response; |
| 484 | } | |
| 485 | ||
| 486 | ||
| 487 | /** | |
| 488 | * Get a file from a path and create a response for it with a mime type. | |
| 489 | * <p> | |
| 490 | * Parent directories are made unavailable by searching the path for | |
| 491 | * bad characters. see {@link FileUtils#checkForBadFilePatterns} | |
| 492 | * </p> | |
| 493 | * | |
| 494 | * @return a response with the file contents and caching headers and mime if valid. | |
| 495 | * if the path has invalid characters, we'll return a "bad request" response. | |
| 496 | */ | |
| 497 | IResponse readStaticFile(String path, Headers requestHeaders) { | |
| 498 | try { | |
| 499 |
1
1. readStaticFile : removed call to com/renomad/minum/utils/FileUtils::checkForBadFilePatterns → KILLED |
checkForBadFilePatterns(path); |
| 500 | } catch (Exception ex) { | |
| 501 | logger.logDebug(() -> String.format("Bad path requested at readStaticFile: %s. Exception: %s", path, ex.getMessage())); | |
| 502 |
1
1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED |
return Response.buildLeanResponse(CODE_400_BAD_REQUEST); |
| 503 | } | |
| 504 | String mimeType = null; | |
| 505 | ||
| 506 | try { | |
| 507 |
1
1. readStaticFile : removed call to com/renomad/minum/utils/FileUtils::checkFileIsWithinDirectory → KILLED |
checkFileIsWithinDirectory(path, constants.staticFilesDirectory); |
| 508 | } catch (Exception ex) { | |
| 509 | logger.logDebug(() -> String.format("Unable to find %s in allowed directories", path)); | |
| 510 |
1
1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED |
return Response.buildLeanResponse(CODE_404_NOT_FOUND); |
| 511 | } | |
| 512 | ||
| 513 | try { | |
| 514 | Path staticFilePath = Path.of(constants.staticFilesDirectory).resolve(path); | |
| 515 |
1
1. readStaticFile : negated conditional → KILLED |
if (!Files.isRegularFile(staticFilePath)) { |
| 516 | logger.logDebug(() -> String.format("No readable regular file found at %s", path)); | |
| 517 |
1
1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED |
return Response.buildLeanResponse(CODE_404_NOT_FOUND); |
| 518 | } | |
| 519 | ||
| 520 | // if the provided path has a dot in it, use that | |
| 521 | // to obtain a suffix for determining file type | |
| 522 | int suffixBeginIndex = path.lastIndexOf('.'); | |
| 523 |
2
1. readStaticFile : negated conditional → KILLED 2. readStaticFile : changed conditional boundary → KILLED |
if (suffixBeginIndex > 0) { |
| 524 |
1
1. readStaticFile : Replaced integer addition with subtraction → KILLED |
String suffix = path.substring(suffixBeginIndex+1); |
| 525 | mimeType = fileSuffixToMime.get(suffix); | |
| 526 | } | |
| 527 | ||
| 528 | // if we don't find any registered mime types for this | |
| 529 | // suffix, or if it doesn't have a suffix, set the mime type | |
| 530 | // to application/octet-stream | |
| 531 |
1
1. readStaticFile : negated conditional → KILLED |
if (mimeType == null) { |
| 532 | mimeType = "application/octet-stream"; | |
| 533 | } | |
| 534 | ||
| 535 |
2
1. readStaticFile : changed conditional boundary → TIMED_OUT 2. readStaticFile : negated conditional → KILLED |
if (Files.size(staticFilePath) < 100_000) { |
| 536 | var fileContents = fileReader.readFile(staticFilePath.toString()); | |
| 537 |
1
1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED |
return createOkResponseForStaticFiles(fileContents, mimeType); |
| 538 | } else { | |
| 539 |
1
1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED |
return createOkResponseForLargeStaticFiles(mimeType, staticFilePath, requestHeaders); |
| 540 | } | |
| 541 | ||
| 542 | } catch (IOException e) { | |
| 543 | logger.logAsyncError(() -> String.format("Error while reading file: %s. %s", path, StacktraceUtils.stackTraceToString(e))); | |
| 544 |
1
1. readStaticFile : replaced return value with null for com/renomad/minum/web/WebFramework::readStaticFile → KILLED |
return Response.buildLeanResponse(CODE_400_BAD_REQUEST); |
| 545 | } | |
| 546 | } | |
| 547 | ||
| 548 | /** | |
| 549 | * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds | |
| 550 | */ | |
| 551 | private IResponse createOkResponseForStaticFiles(byte[] fileContents, String mimeType) { | |
| 552 | var headers = Map.of( | |
| 553 | "cache-control", "max-age=" + constants.staticFileCacheTime, | |
| 554 | "content-type", mimeType); | |
| 555 | ||
| 556 |
1
1. createOkResponseForStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForStaticFiles → KILLED |
return Response.buildResponse( |
| 557 | CODE_200_OK, | |
| 558 | headers, | |
| 559 | fileContents); | |
| 560 | } | |
| 561 | ||
| 562 | /** | |
| 563 | * All static responses will get a cache time of STATIC_FILE_CACHE_TIME seconds | |
| 564 | */ | |
| 565 | private IResponse createOkResponseForLargeStaticFiles(String mimeType, Path filePath, Headers requestHeaders) throws IOException { | |
| 566 | var headers = Map.of( | |
| 567 | "cache-control", "max-age=" + constants.staticFileCacheTime, | |
| 568 | "content-type", mimeType, | |
| 569 | "Accept-Ranges", "bytes" | |
| 570 | ); | |
| 571 | ||
| 572 |
1
1. createOkResponseForLargeStaticFiles : replaced return value with null for com/renomad/minum/web/WebFramework::createOkResponseForLargeStaticFiles → KILLED |
return Response.buildLargeFileResponse( |
| 573 | headers, | |
| 574 | filePath.toString(), | |
| 575 | requestHeaders | |
| 576 | ); | |
| 577 | } | |
| 578 | ||
| 579 | ||
| 580 | /** | |
| 581 | * These are the default starting values for mappings | |
| 582 | * between file suffixes and appropriate mime types | |
| 583 | */ | |
| 584 | private void addDefaultValuesForMimeMap() { | |
| 585 | fileSuffixToMime.put("css", "text/css"); | |
| 586 | fileSuffixToMime.put("js", "application/javascript"); | |
| 587 | fileSuffixToMime.put("webp", "image/webp"); | |
| 588 | fileSuffixToMime.put("jpg", "image/jpeg"); | |
| 589 | fileSuffixToMime.put("jpeg", "image/jpeg"); | |
| 590 | fileSuffixToMime.put("htm", "text/html"); | |
| 591 | fileSuffixToMime.put("html", "text/html"); | |
| 592 | } | |
| 593 | ||
| 594 | ||
| 595 | /** | |
| 596 | * let's see if we can match the registered paths against a **portion** of the startline | |
| 597 | */ | |
| 598 | ThrowingFunction<IRequest, IResponse> findHandlerByPartialMatch(RequestLine sl) { | |
| 599 | String requestedPath = sl.getPathDetails().getIsolatedPath(); | |
| 600 | var methodPathFunctionEntry = registeredPartialPaths.entrySet().stream() | |
| 601 |
2
1. lambda$findHandlerByPartialMatch$27 : negated conditional → KILLED 2. lambda$findHandlerByPartialMatch$27 : replaced boolean return with true for com/renomad/minum/web/WebFramework::lambda$findHandlerByPartialMatch$27 → KILLED |
.filter(x -> requestedPath.startsWith(x.getKey().path()) && |
| 602 |
1
1. lambda$findHandlerByPartialMatch$27 : negated conditional → KILLED |
x.getKey().method().equals(sl.getMethod())) |
| 603 | .findFirst().orElse(null); | |
| 604 |
1
1. findHandlerByPartialMatch : negated conditional → KILLED |
if (methodPathFunctionEntry != null) { |
| 605 |
1
1. findHandlerByPartialMatch : replaced return value with null for com/renomad/minum/web/WebFramework::findHandlerByPartialMatch → KILLED |
return methodPathFunctionEntry.getValue(); |
| 606 | } else { | |
| 607 | return null; | |
| 608 | } | |
| 609 | } | |
| 610 | ||
| 611 | /** | |
| 612 | * This constructor is used for the real production system | |
| 613 | */ | |
| 614 | WebFramework(Context context) { | |
| 615 | this(context, null, null); | |
| 616 | } | |
| 617 | ||
| 618 | WebFramework(Context context, ZonedDateTime overrideForDateTime) { | |
| 619 | this(context, overrideForDateTime, null); | |
| 620 | } | |
| 621 | ||
| 622 | /** | |
| 623 | * This provides the ZonedDateTime as a parameter so we | |
| 624 | * can set the current date (for testing purposes) | |
| 625 | * @param overrideForDateTime for those test cases where we need to control the time | |
| 626 | */ | |
| 627 | WebFramework(Context context, ZonedDateTime overrideForDateTime, IFileReader fileReader) { | |
| 628 | this.fs = context.getFullSystem(); | |
| 629 |
1
1. <init> : negated conditional → KILLED |
this.theBrig = this.fs != null ? this.fs.getTheBrig() : null; |
| 630 | this.logger = context.getLogger(); | |
| 631 | this.constants = context.getConstants(); | |
| 632 | this.overrideForDateTime = overrideForDateTime; | |
| 633 | this.registeredDynamicPaths = new HashMap<>(); | |
| 634 | this.registeredPartialPaths = new HashMap<>(); | |
| 635 | this.inputStreamUtils = new InputStreamUtils(constants.maxReadLineSizeBytes); | |
| 636 | this.bodyProcessor = new BodyProcessor(context); | |
| 637 | ||
| 638 | // This random value is purely to help provide correlation between | |
| 639 | // error messages in the UI and error logs. There are no security concerns. | |
| 640 | this.randomErrorCorrelationId = new Random(); | |
| 641 | this.validRequestLine = new RequestLine( | |
| 642 | RequestLine.Method.NONE, | |
| 643 | PathDetails.empty, | |
| 644 | HttpVersion.NONE, | |
| 645 | "", logger); | |
| 646 | this.emptyRequestLine = RequestLine.EMPTY; | |
| 647 | ||
| 648 | // this allows us to inject a IFileReader for deeper testing | |
| 649 |
1
1. <init> : negated conditional → KILLED |
if (fileReader != null) { |
| 650 | this.fileReader = fileReader; | |
| 651 | } else { | |
| 652 | this.fileReader = new FileReader( | |
| 653 | LRUCache.getLruCache(constants.maxElementsLruCacheStaticFiles), | |
| 654 | constants.useCacheForStaticFiles, | |
| 655 | logger); | |
| 656 | } | |
| 657 | this.fileSuffixToMime = new HashMap<>(); | |
| 658 |
1
1. <init> : removed call to com/renomad/minum/web/WebFramework::addDefaultValuesForMimeMap → KILLED |
addDefaultValuesForMimeMap(); |
| 659 |
1
1. <init> : removed call to com/renomad/minum/web/WebFramework::readExtraMimeMappings → TIMED_OUT |
readExtraMimeMappings(constants.extraMimeMappings); |
| 660 | } | |
| 661 | ||
| 662 | void readExtraMimeMappings(List<String> input) { | |
| 663 |
2
1. readExtraMimeMappings : negated conditional → KILLED 2. readExtraMimeMappings : negated conditional → KILLED |
if (input == null || input.isEmpty()) return; |
| 664 |
2
1. readExtraMimeMappings : Replaced integer modulus with multiplication → KILLED 2. readExtraMimeMappings : negated conditional → KILLED |
if (input.size() % 2 != 0) { |
| 665 | throw new WebServerException("input must be even (key + value = 2 items). Your input: " + input); | |
| 666 | } | |
| 667 | ||
| 668 |
2
1. readExtraMimeMappings : negated conditional → KILLED 2. readExtraMimeMappings : changed conditional boundary → KILLED |
for (int i = 0; i < input.size(); i += 2) { |
| 669 | String fileSuffix = input.get(i); | |
| 670 |
1
1. readExtraMimeMappings : Replaced integer addition with subtraction → KILLED |
String mime = input.get(i+1); |
| 671 | logger.logTrace(() -> "Adding mime mapping: " + fileSuffix + " -> " + mime); | |
| 672 | fileSuffixToMime.put(fileSuffix, mime); | |
| 673 | } | |
| 674 | } | |
| 675 | ||
| 676 | /** | |
| 677 | * Add a new handler in the web application for a combination | |
| 678 | * of a {@link RequestLine.Method}, a path, and then provide | |
| 679 | * the code to handle a request. | |
| 680 | * <br> | |
| 681 | * Note that the path text expected is *after* the first forward slash, | |
| 682 | * so for example with {@code http://foo.com/mypath}, provide "mypath" as the path. | |
| 683 | * @throws WebServerException if duplicate paths are registered, or if the path is prefixed with a slash | |
| 684 | */ | |
| 685 | public void registerPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) { | |
| 686 |
2
1. registerPath : negated conditional → KILLED 2. registerPath : negated conditional → KILLED |
if (pathName.startsWith("\\") || pathName.startsWith("/")) { |
| 687 | throw new WebServerException( | |
| 688 | String.format("Path should not be prefixed with a slash. Corrected version: registerPath(%s, \"%s\", ... )", method.name(), pathName.substring(1))); | |
| 689 | } | |
| 690 | ||
| 691 | var result = registeredDynamicPaths.put(new MethodPath(method, pathName), webHandler); | |
| 692 |
1
1. registerPath : negated conditional → KILLED |
if (result != null) { |
| 693 | throw new WebServerException("Duplicate endpoint registered: " + new MethodPath(method, pathName)); | |
| 694 | } | |
| 695 | } | |
| 696 | ||
| 697 | /** | |
| 698 | * Similar to {@link WebFramework#registerPath(RequestLine.Method, String, ThrowingFunction)} except that the paths | |
| 699 | * registered here may be partially matched. | |
| 700 | * <p> | |
| 701 | * For example, if you register {@code .well-known/acme-challenge} then it | |
| 702 | * can match a client request for {@code .well-known/acme-challenge/HGr8U1IeTW4kY_Z6UIyaakzOkyQgPr_7ArlLgtZE8SX} | |
| 703 | * </p> | |
| 704 | * <p> | |
| 705 | * Be careful here, be thoughtful - partial paths will match a lot, and may | |
| 706 | * overlap with other URL's for your app, such as endpoints and static files. | |
| 707 | * </p> | |
| 708 | * @throws WebServerException if duplicate paths are registered, or if the path is prefixed with a slash | |
| 709 | */ | |
| 710 | public void registerPartialPath(RequestLine.Method method, String pathName, ThrowingFunction<IRequest, IResponse> webHandler) { | |
| 711 |
2
1. registerPartialPath : negated conditional → KILLED 2. registerPartialPath : negated conditional → KILLED |
if (pathName.startsWith("\\") || pathName.startsWith("/")) { |
| 712 | throw new WebServerException( | |
| 713 | String.format("Path should not be prefixed with a slash. Corrected version: registerPartialPath(%s, \"%s\", ... )", method.name(), pathName.substring(1))); | |
| 714 | } | |
| 715 | var result = registeredPartialPaths.put(new MethodPath(method, pathName), webHandler); | |
| 716 |
1
1. registerPartialPath : negated conditional → KILLED |
if (result != null) { |
| 717 | throw new WebServerException("Duplicate partial-path endpoint registered: " + new MethodPath(method, pathName)); | |
| 718 | } | |
| 719 | } | |
| 720 | ||
| 721 | /** | |
| 722 | * Sets a handler to process all requests across the board. | |
| 723 | * <br> | |
| 724 | * <p> | |
| 725 | * This is an <b>unusual</b> method. Setting a handler here allows the user to run code of his | |
| 726 | * choosing before the regular business code is run. Note that by defining this value, the ordinary | |
| 727 | * call to endpoint.apply(request) will not be run. | |
| 728 | * </p> | |
| 729 | * <p>Here is an example</p> | |
| 730 | * <pre>{@code | |
| 731 | * | |
| 732 | * webFramework.registerPreHandler(preHandlerInputs -> preHandlerCode(preHandlerInputs, auth, context)); | |
| 733 | * | |
| 734 | * ... | |
| 735 | * | |
| 736 | * private IResponse preHandlerCode(PreHandlerInputs preHandlerInputs, AuthUtils auth, Context context) throws Exception { | |
| 737 | * int secureServerPort = context.getConstants().secureServerPort; | |
| 738 | * Request request = preHandlerInputs.clientRequest(); | |
| 739 | * ThrowingFunction<IRequest, IResponse> endpoint = preHandlerInputs.endpoint(); | |
| 740 | * ISocketWrapper sw = preHandlerInputs.sw(); | |
| 741 | * | |
| 742 | * // log all requests | |
| 743 | * logger.logTrace(() -> String.format("Request: %s by %s", | |
| 744 | * request.requestLine().getRawValue(), | |
| 745 | * request.remoteRequester()) | |
| 746 | * ); | |
| 747 | * | |
| 748 | * // redirect to https if they are on the plain-text connection and the path is "login" | |
| 749 | * | |
| 750 | * // get the path from the request line | |
| 751 | * String path = request.getRequestLine().getPathDetails().getIsolatedPath(); | |
| 752 | * | |
| 753 | * // redirect to https on the configured secure port if they are on the plain-text connection and the path contains "login" | |
| 754 | * if (path.contains("login") && | |
| 755 | * sw.getServerType().equals(HttpServerType.PLAIN_TEXT_HTTP)) { | |
| 756 | * return Response.redirectTo("https://%s:%d/%s".formatted(sw.getHostName(), secureServerPort, path)); | |
| 757 | * } | |
| 758 | * | |
| 759 | * // adjust behavior if non-authenticated and path includes "secure/" | |
| 760 | * if (path.contains("secure/")) { | |
| 761 | * AuthResult authResult = auth.processAuth(request); | |
| 762 | * if (authResult.isAuthenticated()) { | |
| 763 | * return endpoint.apply(request); | |
| 764 | * } else { | |
| 765 | * return Response.buildLeanResponse(CODE_403_FORBIDDEN); | |
| 766 | * } | |
| 767 | * } | |
| 768 | * | |
| 769 | * // if the path does not include /secure, just move the request along unchanged. | |
| 770 | * return endpoint.apply(request); | |
| 771 | * } | |
| 772 | * }</pre> | |
| 773 | */ | |
| 774 | public void registerPreHandler(ThrowingFunction<PreHandlerInputs, IResponse> preHandler) { | |
| 775 | this.preHandler = preHandler; | |
| 776 | } | |
| 777 | ||
| 778 | /** | |
| 779 | * Sets a handler to be executed after running the ordinary handler, just | |
| 780 | * before sending the response. | |
| 781 | * <p> | |
| 782 | * This is an <b>unusual</b> method, so please be aware of its proper use. Its | |
| 783 | * purpose is to allow the user to inject code to run after ordinary code, across | |
| 784 | * all requests. | |
| 785 | * </p> | |
| 786 | * <p> | |
| 787 | * For example, if the system would have returned a 404 NOT FOUND response, | |
| 788 | * code can handle that situation in a switch case and adjust the response according | |
| 789 | * to your programming. | |
| 790 | * </p> | |
| 791 | * <p>Here is an example</p> | |
| 792 | * <pre>{@code | |
| 793 | * | |
| 794 | * | |
| 795 | * webFramework.registerLastMinuteHandler(TheRegister::lastMinuteHandlerCode); | |
| 796 | * | |
| 797 | * ... | |
| 798 | * | |
| 799 | * private static IResponse lastMinuteHandlerCode(LastMinuteHandlerInputs inputs) { | |
| 800 | * switch (inputs.response().statusCode()) { | |
| 801 | * case CODE_404_NOT_FOUND -> { | |
| 802 | * return Response.buildResponse( | |
| 803 | * CODE_404_NOT_FOUND, | |
| 804 | * Map.of("Content-Type", "text/html; charset=UTF-8"), | |
| 805 | * "<p>No document was found</p>")); | |
| 806 | * } | |
| 807 | * case CODE_500_INTERNAL_SERVER_ERROR -> { | |
| 808 | * return Response.buildResponse( | |
| 809 | * CODE_500_INTERNAL_SERVER_ERROR, | |
| 810 | * Map.of("Content-Type", "text/html; charset=UTF-8"), | |
| 811 | * "<p>Server error occurred.</p>" )); | |
| 812 | * } | |
| 813 | * default -> { | |
| 814 | * return inputs.response(); | |
| 815 | * } | |
| 816 | * } | |
| 817 | * } | |
| 818 | * } | |
| 819 | * </pre> | |
| 820 | * @param lastMinuteHandler a function that will take a request and return a response, exactly like | |
| 821 | * we use in the other registration methods for this class. | |
| 822 | */ | |
| 823 | public void registerLastMinuteHandler(ThrowingFunction<LastMinuteHandlerInputs, IResponse> lastMinuteHandler) { | |
| 824 | this.lastMinuteHandler = lastMinuteHandler; | |
| 825 | } | |
| 826 | ||
| 827 | /** | |
| 828 | * This allows users to add extra mappings | |
| 829 | * between file suffixes and mime types, in case | |
| 830 | * a user needs one that was not provided. | |
| 831 | * <p> | |
| 832 | * This is made available through the | |
| 833 | * web framework. | |
| 834 | * </p> | |
| 835 | * <p> | |
| 836 | * Example: | |
| 837 | * </p> | |
| 838 | * <pre> | |
| 839 | * {@code webFramework.addMimeForSuffix().put("foo","text/foo")} | |
| 840 | * </pre> | |
| 841 | */ | |
| 842 | public void addMimeForSuffix(String suffix, String mimeType) { | |
| 843 | fileSuffixToMime.put(suffix, mimeType); | |
| 844 | } | |
| 845 | } | |
Mutations | ||
| 50 |
1.1 |
|
| 104 |
1.1 2.2 |
|
| 112 |
1.1 |
|
| 119 |
1.1 |
|
| 129 |
1.1 |
|
| 135 |
1.1 |
|
| 136 |
1.1 |
|
| 140 |
1.1 |
|
| 141 |
1.1 |
|
| 144 |
1.1 |
|
| 149 |
1.1 |
|
| 155 |
1.1 |
|
| 158 |
1.1 |
|
| 163 |
1.1 |
|
| 166 |
1.1 |
|
| 168 |
1.1 |
|
| 170 |
1.1 |
|
| 178 |
1.1 2.2 |
|
| 186 |
1.1 |
|
| 201 |
1.1 |
|
| 220 |
1.1 |
|
| 225 |
1.1 |
|
| 245 |
1.1 |
|
| 249 |
1.1 |
|
| 266 |
1.1 |
|
| 274 |
1.1 |
|
| 276 |
1.1 |
|
| 277 |
1.1 |
|
| 281 |
1.1 2.2 |
|
| 289 |
1.1 |
|
| 293 |
1.1 |
|
| 305 |
1.1 |
|
| 306 |
1.1 |
|
| 307 |
1.1 |
|
| 308 |
1.1 |
|
| 310 |
1.1 |
|
| 311 |
1.1 |
|
| 317 |
1.1 |
|
| 332 |
1.1 |
|
| 348 |
1.1 |
|
| 371 |
1.1 2.2 |
|
| 374 |
1.1 2.2 3.3 |
|
| 385 |
1.1 |
|
| 410 |
1.1 |
|
| 411 |
1.1 |
|
| 413 |
1.1 |
|
| 431 |
1.1 |
|
| 432 |
1.1 2.2 3.3 |
|
| 435 |
1.1 |
|
| 437 |
1.1 |
|
| 454 |
1.1 |
|
| 459 |
1.1 |
|
| 464 |
1.1 |
|
| 470 |
1.1 |
|
| 478 |
1.1 2.2 |
|
| 483 |
1.1 2.2 |
|
| 499 |
1.1 |
|
| 502 |
1.1 |
|
| 507 |
1.1 |
|
| 510 |
1.1 |
|
| 515 |
1.1 |
|
| 517 |
1.1 |
|
| 523 |
1.1 2.2 |
|
| 524 |
1.1 |
|
| 531 |
1.1 |
|
| 535 |
1.1 2.2 |
|
| 537 |
1.1 |
|
| 539 |
1.1 |
|
| 544 |
1.1 |
|
| 556 |
1.1 |
|
| 572 |
1.1 |
|
| 601 |
1.1 2.2 |
|
| 602 |
1.1 |
|
| 604 |
1.1 |
|
| 605 |
1.1 |
|
| 629 |
1.1 |
|
| 649 |
1.1 |
|
| 658 |
1.1 |
|
| 659 |
1.1 |
|
| 663 |
1.1 2.2 |
|
| 664 |
1.1 2.2 |
|
| 668 |
1.1 2.2 |
|
| 670 |
1.1 |
|
| 686 |
1.1 2.2 |
|
| 692 |
1.1 |
|
| 711 |
1.1 2.2 |
|
| 716 |
1.1 |