LibJF/libjf-web-v1/src/main/java/io/gitlab/jfronny/libjf/web/impl/util/HttpRequestImpl.java

250 lines
7.8 KiB
Java

/*
* This file is part of BlueMap, licensed under the MIT License (MIT).
*
* Copyright (c) Blue (Lukas Rieger) <https://bluecolored.de>
* Copyright (c) contributors
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package io.gitlab.jfronny.libjf.web.impl.util;
import io.gitlab.jfronny.libjf.web.api.v1.*;
import io.gitlab.jfronny.libjf.web.impl.variant.hosted.HttpConnection;
import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class HttpRequestImpl implements HttpRequest {
private static final Pattern REQUEST_PATTERN = Pattern.compile("^(\\w+) (\\S+) (.+)$");
private final String method;
private final String address;
private final String version;
private final Map<String, Set<String>> header;
private final Map<String, Set<String>> headerLC;
private byte[] data;
private String path = null;
private Map<String, String> queryParameters = null;
private String queryString = null;
public HttpRequestImpl(String method, String address, String version, Map<String, Set<String>> header) {
this.method = method;
this.address = address;
this.version = version;
this.header = header;
this.headerLC = new HashMap<>();
for (Entry<String, Set<String>> e : header.entrySet()){
Set<String> values = new HashSet<>();
for (String v : e.getValue()){
values.add(v.toLowerCase());
}
headerLC.put(e.getKey().toLowerCase(), values);
}
this.data = new byte[0];
}
@Override
public String getMethod() {
return method;
}
@Override
public String getAddress(){
return address;
}
@Override
public String getVersion() {
return version;
}
@Override
public Map<String, Set<String>> getHeader() {
return header;
}
@Override
public Map<String, Set<String>> getLowercaseHeader() {
return headerLC;
}
@Override
public Set<String> getHeader(String key){
Set<String> headerValues = header.get(key);
if (headerValues == null) return Collections.emptySet();
return headerValues;
}
@Override
public Set<String> getLowercaseHeader(String key){
Set<String> headerValues = headerLC.get(key.toLowerCase());
if (headerValues == null) return Collections.emptySet();
return headerValues;
}
@Override
public String getPath() {
if (path == null) parseAddress();
return path;
}
@Override
public Map<String, String> getQuery() {
if (queryParameters == null) parseAddress();
return Collections.unmodifiableMap(queryParameters);
}
@Override
public String getQueryString() {
if (queryString == null) parseAddress();
return queryString;
}
private void parseAddress() {
String adress = this.address;
if (adress.isEmpty()) adress = "/";
String[] addressParts = adress.split("\\?", 2);
String path = addressParts[0];
this.queryString = addressParts.length > 1 ? addressParts[1] : "";
Map<String, String> queryParams = new HashMap<>();
for (String queryParam : this.queryString.split("&")){
if (queryParam.isEmpty()) continue;
String[] kv = queryParam.split("=", 2);
String key = kv[0];
String value = kv.length > 1 ? kv[1] : "";
queryParams.put(key, value);
}
this.path = path;
this.queryParameters = queryParams;
}
@Override
public InputStream getData(){
return new ByteArrayInputStream(data);
}
public static HttpRequestImpl read(InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in, StandardCharsets.UTF_8));
HttpRequestImpl request = fromHeaders(extractHeaders(reader));
readData(in, request, reader);
return request;
}
private static void readData(InputStream in, HttpRequestImpl request, BufferedReader reader) throws IOException {
if (request.getLowercaseHeader("Transfer-Encoding").contains("chunked")) {
try {
ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
while (dataStream.size() < 1000000) {
String hexSize = reader.readLine();
int chunkSize = Integer.parseInt(hexSize, 16);
if (chunkSize <= 0) break;
byte[] data = new byte[chunkSize];
in.read(data);
dataStream.write(data);
}
if (dataStream.size() >= 1000000) {
throw new HttpConnection.InvalidRequestException();
}
request.data = dataStream.toByteArray();
} catch (NumberFormatException ex) {
}
} else {
Set<String> clSet = request.getLowercaseHeader("Content-Length");
if (clSet.isEmpty()) return;
try {
int cl = Integer.parseInt(clSet.iterator().next());
byte[] data = new byte[cl];
in.read(data);
request.data = data;
} catch (NumberFormatException ex) {
}
}
}
private static List<String> extractHeaders(BufferedReader reader) throws IOException {
List<String> headers = new ArrayList<>(20);
while (headers.size() < 1000) {
String headerLine = readLine(reader);
if (headerLine.isEmpty()) break;
headers.add(headerLine);
}
return headers;
}
private static HttpRequestImpl fromHeaders(List<String> headers) throws HttpConnection.InvalidRequestException {
if (headers.isEmpty()) throw new HttpConnection.InvalidRequestException();
Matcher m = REQUEST_PATTERN.matcher(headers.remove(0));
if (!m.find()) throw new HttpConnection.InvalidRequestException();
String method = m.group(1);
if (method == null) throw new HttpConnection.InvalidRequestException();
String adress = m.group(2);
if (adress == null) throw new HttpConnection.InvalidRequestException();
String version = m.group(3);
if (version == null) throw new HttpConnection.InvalidRequestException();
return new HttpRequestImpl(method, adress, version, parseExtraHeaders(headers));
}
private static Map<String, Set<String>> parseExtraHeaders(List<String> header) {
Map<String, Set<String>> headerMap = new HashMap<>();
for (String line : header) {
if (line.trim().isEmpty()) continue;
String[] kv = line.split(":", 2);
if (kv.length < 2) continue;
Set<String> values = new HashSet<>();
if (kv[0].trim().equalsIgnoreCase("If-Modified-Since")) {
values.add(kv[1].trim());
} else {
for (String v : kv[1].split(",")) {
values.add(v.trim());
}
}
headerMap.put(kv[0].trim(), values);
}
return headerMap;
}
private static String readLine(BufferedReader in) throws IOException {
String line = in.readLine();
if (line == null) {
throw new HttpConnection.ConnectionClosedException();
}
return line;
}
}