Files
usdt/ruoyi-system/src/main/java/com/ruoyi/system/rental/RentalHttp.java
T

96 lines
3.8 KiB
Java

package com.ruoyi.system.rental;
import static com.ruoyi.system.rental.RentalValues.*;
import okhttp3.*;
import java.io.IOException;
import java.net.InetAddress;
import java.net.URI;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
/** 回调专用HTTP客户端:HTTPS、解析结果逐一检查、实际连接复用该DNS结果、拒绝重定向。 */
public final class RentalHttp {
private RentalHttp() {}
public static void checkUrl(String url) {
URI uri = URI.create(url);
require(
"https".equalsIgnoreCase(uri.getScheme())
&& uri.getHost() != null
&& uri.getUserInfo() == null
&& uri.getFragment() == null
&& uri.getQuery() == null
&& (uri.getPort() == -1 || uri.getPort() == 443)
&& url.length() <= 512,
"回调仅允许标准HTTPS地址");
}
public static boolean publicAddress(InetAddress address) {
byte[] bytes = address.getAddress();
if (address.isAnyLocalAddress()
|| address.isLoopbackAddress()
|| address.isLinkLocalAddress()
|| address.isSiteLocalAddress()
|| address.isMulticastAddress()) {
return false;
}
if (bytes.length == 16) {
return (bytes[0] & 0xe0) == 0x20;
}
int a = bytes[0] & 255;
int b = bytes[1] & 255;
return a != 0
&& a != 10
&& a != 127
&& a < 224
&& !(a == 100 && b >= 64 && b <= 127)
&& !(a == 169 && b == 254)
&& !(a == 172 && b >= 16 && b <= 31)
&& !(a == 192 && b == 168)
&& !(a == 198 && (b == 18 || b == 19))
&& !(a == 192 && b == 0);
}
public static OkHttpClient callbackClient() {
return new OkHttpClient.Builder()
.connectTimeout(5, TimeUnit.SECONDS)
.readTimeout(5, TimeUnit.SECONDS)
.callTimeout(10, TimeUnit.SECONDS)
.followRedirects(false)
.followSslRedirects(false)
.retryOnConnectionFailure(false)
.dns(
host -> {
InetAddress[] addresses = InetAddress.getAllByName(host);
for (InetAddress address : addresses) {
if (!publicAddress(address)) {
throw new java.net.UnknownHostException("回调目标非公网地址");
}
}
return Arrays.asList(addresses);
})
.build();
}
public static String body(Response response) throws IOException {
return body(response, 1024 * 1024);
}
/** 完整区块JSON可能超过普通RPC的1MiB限制;仅受信区块查询允许显式提高至16MiB。 */
public static String body(Response response, int maxBytes) throws IOException {
require(maxBytes > 0 && maxBytes <= 16 * 1024 * 1024, "RPC响应上限配置错误");
require(response.isSuccessful() && response.body() != null, "RPC响应失败");
java.io.InputStream stream = response.body().byteStream();
java.io.ByteArrayOutputStream output = new java.io.ByteArrayOutputStream();
byte[] buffer = new byte[4096];
int count;
while ((count = stream.read(buffer)) != -1) {
require(output.size() + count <= maxBytes, "RPC响应超过限制");
output.write(buffer, 0, count);
}
return new String(output.toByteArray(), java.nio.charset.StandardCharsets.UTF_8);
}
}