Files
src
build.gradle
settings.gradle
Code
8 582
src/main/java/ru/praydein/atwanalytics/PhpCgiHandler.java
package ru.praydein.atwanalytics;
import com.sun.net.httpserver.Headers;
import com.sun.net.httpserver.HttpExchange;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.nio.file.Path;
import java.util.Locale;
import java.util.Map;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicReference;
final class PhpCgiHandler {
private static final byte[] PHP_UNAVAILABLE = "PHP-CGI could not be started".getBytes(StandardCharsets.UTF_8);
private static final byte[] PHP_TIMEOUT = "PHP script timed out".getBytes(StandardCharsets.UTF_8);
private static final byte[] PHP_FAILED = "PHP script failed".getBytes(StandardCharsets.UTF_8);
private PhpCgiHandler() {
}
static void handle(HttpExchange exchange, Path siteRoot, Path script, String executable, int timeoutSeconds)
throws IOException {
byte[] requestBody = exchange.getRequestBody().readAllBytes();
ProcessBuilder builder = new ProcessBuilder(executable, "-f", script.toString());
configureEnvironment(builder.environment(), exchange, siteRoot, script, requestBody.length);
Process process;
try {
process = builder.start();
} catch (IOException exception) {
sendError(exchange, 502, PHP_UNAVAILABLE, exchange.getRequestMethod().equalsIgnoreCase("HEAD"));
return;
}
AtomicReference<byte[]> output = new AtomicReference<>();
AtomicReference<byte[]> errorOutput = new AtomicReference<>();
AtomicReference<IOException> readFailure = new AtomicReference<>();
Thread outputReader = readStream(process.getInputStream(), output, readFailure);
Thread errorReader = readStream(process.getErrorStream(), errorOutput, readFailure);
try {
try (var input = process.getOutputStream()) {
input.write(requestBody);
}
if (!process.waitFor(timeoutSeconds, TimeUnit.SECONDS)) {
process.destroyForcibly();
outputReader.join(1000);
errorReader.join(1000);
sendError(exchange, 504, PHP_TIMEOUT, exchange.getRequestMethod().equalsIgnoreCase("HEAD"));
return;
}
outputReader.join();
errorReader.join();
if (process.exitValue() != 0 || readFailure.get() != null || output.get() == null) {
sendError(exchange, 502, PHP_FAILED, exchange.getRequestMethod().equalsIgnoreCase("HEAD"));
return;
}
sendCgiResponse(exchange, output.get());
} catch (InterruptedException exception) {
process.destroyForcibly();
Thread.currentThread().interrupt();
sendError(exchange, 502, PHP_FAILED, exchange.getRequestMethod().equalsIgnoreCase("HEAD"));
} catch (IOException exception) {
process.destroyForcibly();
sendError(exchange, 502, PHP_FAILED, exchange.getRequestMethod().equalsIgnoreCase("HEAD"));
}
}
private static void configureEnvironment(Map<String, String> environment, HttpExchange exchange, Path siteRoot, Path script,
int contentLength) {
String requestPath = exchange.getRequestURI().getPath();
String query = exchange.getRequestURI().getRawQuery();
String host = exchange.getRequestHeaders().getFirst("Host");
environment.put("GATEWAY_INTERFACE", "CGI/1.1");
environment.put("REDIRECT_STATUS", "200");
environment.put("REQUEST_METHOD", exchange.getRequestMethod());
environment.put("SCRIPT_FILENAME", script.toString());
environment.put("SCRIPT_NAME", requestPath);
environment.put("PHP_SELF", requestPath);
environment.put("DOCUMENT_ROOT", siteRoot.toString());
environment.put("REQUEST_URI", exchange.getRequestURI().toString());
environment.put("QUERY_STRING", query == null ? "" : query);
environment.put("SERVER_PROTOCOL", exchange.getProtocol());
environment.put("SERVER_SOFTWARE", "ATW-WebServer");
environment.put("SERVER_NAME", host == null ? "localhost" : host);
environment.put("SERVER_PORT", Integer.toString(exchange.getLocalAddress().getPort()));
environment.put("REMOTE_ADDR", exchange.getRemoteAddress().getAddress().getHostAddress());
environment.put("CONTENT_LENGTH", Integer.toString(contentLength));
String contentType = exchange.getRequestHeaders().getFirst("Content-Type");
if (contentType != null) {
environment.put("CONTENT_TYPE", contentType);
}
exchange.getRequestHeaders().forEach((name, values) -> {
if (!name.equalsIgnoreCase("Content-Type") && !name.equalsIgnoreCase("Content-Length")) {
environment.put("HTTP_" + name.toUpperCase(Locale.ROOT).replace('-', '_'), String.join(",", values));
}
});
}
private static Thread readStream(InputStream stream, AtomicReference<byte[]> result,
AtomicReference<IOException> failure) {
return Thread.ofVirtual().start(() -> {
try (stream) {
result.set(stream.readAllBytes());
} catch (IOException exception) {
failure.compareAndSet(null, exception);
}
});
}
private static void sendCgiResponse(HttpExchange exchange, byte[] output) throws IOException {
int separator = findHeaderSeparator(output);
if (separator < 0) {
sendError(exchange, 502, PHP_FAILED, exchange.getRequestMethod().equalsIgnoreCase("HEAD"));
return;
}
String headerText = new String(output, 0, separator, StandardCharsets.ISO_8859_1);
int bodyStart = separator + (output[separator] == '\r' ? 4 : 2);
byte[] body = java.util.Arrays.copyOfRange(output, bodyStart, output.length);
Headers responseHeaders = exchange.getResponseHeaders();
int status = 200;
for (String line : headerText.split("\\r?\\n")) {
int colon = line.indexOf(':');
if (colon <= 0) {
continue;
}
String name = line.substring(0, colon).trim();
String value = line.substring(colon + 1).trim();
if (name.equalsIgnoreCase("Status")) {
try {
status = Integer.parseInt(value.split("\\s+", 2)[0]);
} catch (NumberFormatException ignored) {
status = 200;
}
} else if (!name.equalsIgnoreCase("Content-Length")
&& !name.equalsIgnoreCase("Transfer-Encoding")
&& !name.equalsIgnoreCase("Connection")) {
responseHeaders.add(name, value);
}
}
responseHeaders.set("X-Content-Type-Options", "nosniff");
if (!responseHeaders.containsKey("Content-Type")) {
responseHeaders.set("Content-Type", "text/html; charset=utf-8");
}
boolean headRequest = exchange.getRequestMethod().equalsIgnoreCase("HEAD");
if (headRequest) {
responseHeaders.set("Content-Length", Integer.toString(body.length));
}
exchange.sendResponseHeaders(status, headRequest ? -1 : body.length);
if (!headRequest && body.length > 0) {
try (var response = exchange.getResponseBody()) {
response.write(body);
}
}
}
private static int findHeaderSeparator(byte[] output) {
for (int i = 0; i < output.length - 1; i++) {
if (output[i] == '\n' && output[i + 1] == '\n') {
return i;
}
if (i + 3 < output.length && output[i] == '\r' && output[i + 1] == '\n'
&& output[i + 2] == '\r' && output[i + 3] == '\n') {
return i;
}
}
return -1;
}
private static void sendError(HttpExchange exchange, int status, byte[] body, boolean headRequest)
throws IOException {
exchange.getResponseHeaders().set("Content-Type", "text/plain; charset=utf-8");
exchange.getResponseHeaders().set("X-Content-Type-Options", "nosniff");
exchange.sendResponseHeaders(status, headRequest ? -1 : body.length);
if (!headRequest) {
try (var response = exchange.getResponseBody()) {
response.write(body);
}
}
}
}