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