1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419
| import okhttp3.*; import okio.BufferedSink; import org.slf4j.Logger; import org.slf4j.LoggerFactory;
import javax.net.ssl.*; import javax.servlet.ServletException; import javax.servlet.ServletInputStream; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.io.InputStream; import java.security.SecureRandom; import java.security.cert.CertificateException; import java.security.cert.X509Certificate; import java.util.*; import java.util.concurrent.TimeUnit;
public class ProxyServlet extends HttpServlet { protected static final Logger log = LoggerFactory.getLogger(ProxyServlet.class);
protected final OkHttpClient client; protected final String targetUrl; protected final boolean corsControl; protected final boolean allowCORS; protected final boolean logEnable; protected final boolean forwardIp; protected final boolean preserveHost; protected final boolean preserveCookie; protected final String logFormat;
protected final List<String> allowCORSHeaders = Arrays.asList( "access-control-allow-origin", "access-control-allow-methods", "access-control-allow-headers", "access-control-allow-credentials", "access-control-expose-headers", "access-control-max-age", "access-control-request-method", "access-control-request-headers" );
protected final String[] hopByHopHeaders = new String[]{ "Connection", "Keep-Alive", "Proxy-Authenticate", "Proxy-Authorization", "TE", "Trailers", "Transfer-Encoding", "Upgrade"};
public static final String LOG_FORMAT_DEFAULT = "{method} -- {userAgent} -- {remoteAddr}:{remotePort} -- {source} --> {target} -- {statusCode} consumed {consumedMills} ms";
protected void doLog(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, long startMills) { if (logEnable) { String queryString = httpServletRequest.getQueryString(); String logInfo = logFormat.replace("{method}", httpServletRequest.getMethod()) .replace("{userAgent}", httpServletRequest.getHeader("User-Agent")) .replace("{remoteAddr}", httpServletRequest.getRemoteAddr()) .replace("{remotePort}", String.valueOf(httpServletRequest.getRemotePort())) .replace("{source}", queryString == null ? httpServletRequest.getRequestURL() : httpServletRequest.getRequestURL() + "?" + queryString) .replace("{target}", rewriteUrlFromRequest(httpServletRequest)) .replace("{statusCode}", String.valueOf(httpServletResponse.getStatus())) .replace("{consumedMills}", String.valueOf(System.currentTimeMillis() - startMills)); log.info("{}: {}", getServletName(), logInfo); } }
protected boolean containsHopByHopHeader(String name) { for (String header : hopByHopHeaders) { if (header.equalsIgnoreCase(name)) { return true; } } return false; }
protected String getTargetUrl(HttpServletRequest request) { String uri = request.getPathInfo(); if (uri == null || uri.isEmpty()) { return targetUrl; } else { return targetUrl + uri; } }
protected String rewriteUrlFromRequest(HttpServletRequest request) { String targetUrl = getTargetUrl(request); String queryString = request.getQueryString(); return queryString == null ? targetUrl : targetUrl + "?" + queryString; }
protected String rewriteUrlFromResponse(HttpServletRequest request, String locationUrl) { String targetUrl = getTargetUrl(request); if (locationUrl != null && locationUrl.startsWith(targetUrl)) { StringBuffer curUrl = request.getRequestURL(); int pos; if ((pos = curUrl.indexOf("://")) >= 0) { if ((pos = curUrl.indexOf("/", pos + 3)) >= 0) { curUrl.setLength(pos); } } curUrl.append(request.getContextPath()); curUrl.append(request.getServletPath()); curUrl.append(locationUrl, targetUrl.length(), locationUrl.length()); return curUrl.toString(); } return locationUrl; }
public ProxyServlet(OkHttpClient client, String targetUrl, boolean corsControl, boolean allowCORS, boolean logEnable, String logFormat, boolean forwardIp, boolean preserveHost, boolean preserveCookie) { this.client = client; this.targetUrl = targetUrl; this.corsControl = corsControl; this.allowCORS = allowCORS; this.logEnable = logEnable; this.forwardIp = forwardIp; this.preserveHost = preserveHost; this.preserveCookie = preserveCookie; this.logFormat = logFormat; }
public ProxyServlet(OkHttpClient client, String targetUrl) { this(client, targetUrl, false, false, true, LOG_FORMAT_DEFAULT, false, false, false); }
public void setXForwardedForHeader(HttpServletRequest request, Request.Builder requestBuilder) { if (forwardIp) { String forHeaderName = "X-Forwarded-For"; String forHeader = request.getRemoteAddr(); String existingForHeader = request.getHeader(forHeader); if (existingForHeader != null) { forHeader = existingForHeader + ", " + forHeader; } requestBuilder.header(forHeaderName, forHeader); String protoHeaderName = "X-Forwarded-Proto"; String protoHeader = request.getScheme(); requestBuilder.header(protoHeaderName, protoHeader); } }
@Override protected void service(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException { long start = System.currentTimeMillis(); try { if (httpServletRequest.getMethod().equalsIgnoreCase("options") && corsControl && allowCORS) { httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin")); httpServletResponse.setHeader("Access-Control-Allow-Methods", "*"); httpServletResponse.setHeader("Access-Control-Allow-Headers", "*"); httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true"); httpServletResponse.setHeader("Access-Control-Expose-Headers", "*"); httpServletResponse.setStatus(HttpServletResponse.SC_OK); return; } String method = httpServletRequest.getMethod(); String proxyRequestUrl = rewriteUrlFromRequest(httpServletRequest); Request.Builder requestBuilder = getInitRequestBuilder(httpServletRequest, httpServletResponse); requestBuilder.url(proxyRequestUrl); if ("get".equalsIgnoreCase(method)) { requestBuilder.method(method, null); } else { RequestBody requestBody; if (httpServletRequest.getHeader("Content-Length") != null || httpServletRequest.getHeader("Transfer-Encoding") != null) { try { ServletInputStream inputStream = httpServletRequest.getInputStream(); requestBody = new StreamingRequestBody(MediaType.parse(httpServletRequest.getContentType()), inputStream); } catch (Exception e) { writeGatewayError(httpServletResponse, e.getMessage()); return; } } else { requestBody = RequestBody.create(null, new byte[0]); } requestBuilder.method(method, requestBody); }
copyRequestHeaders(httpServletRequest, requestBuilder); setXForwardedForHeader(httpServletRequest, requestBuilder); try (Response response = client.newCall(requestBuilder.build()).execute()) { httpServletResponse.setStatus(response.code()); copyResponseHeaders(httpServletRequest, httpServletResponse, response); if (response.code() == 304) { httpServletResponse.setIntHeader("Content-Length", 0); } else { ResponseBody responseBody = response.body(); if (responseBody != null) { ServletOutputStream os = httpServletResponse.getOutputStream(); InputStream is = responseBody.byteStream(); int len; byte[] buffer = new byte[8192]; while ((len = is.read(buffer)) != -1) { os.write(buffer, 0, len); } os.flush(); } } } catch (Exception e) { writeGatewayError(httpServletResponse, e.getMessage()); return; } } finally { doLog(httpServletRequest, httpServletResponse, start); } }
protected Request.Builder getInitRequestBuilder(HttpServletRequest request, HttpServletResponse response) { return new Request.Builder(); }
protected void copyResponseHeaders(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Response response) { Set<String> names = response.headers().names(); Map<String, String> needSetHeaderMap = new LinkedHashMap<>(); for (String name : names) { if (containsHopByHopHeader(name)) { continue; } if ("Location".equalsIgnoreCase(name)) { needSetHeaderMap.put(name, rewriteUrlFromResponse(httpServletRequest, response.header(name))); } else if ("Set-Cookie".equalsIgnoreCase(name) || "Set-Cookie2".equalsIgnoreCase(name)) { if (preserveCookie) { needSetHeaderMap.put(name, response.header(name)); } } else { needSetHeaderMap.put(name, response.header(name)); } }
if (corsControl) {
Iterator<Map.Entry<String, String>> iterator = needSetHeaderMap.entrySet().iterator(); while (iterator.hasNext()) { Map.Entry<String, String> entry = iterator.next(); String keyIgnoreCase = entry.getKey().toLowerCase(Locale.ROOT); if (allowCORSHeaders.contains(keyIgnoreCase)) { iterator.remove(); } } if (allowCORS) { needSetHeaderMap.put("Access-Control-Allow-Origin", httpServletRequest.getHeader("origin")); needSetHeaderMap.put("Access-Control-Allow-Methods", "*"); needSetHeaderMap.put("Access-Control-Allow-Headers", "*"); needSetHeaderMap.put("Access-Control-Allow-Credentials", "true"); needSetHeaderMap.put("Access-Control-Expose-Headers", "*"); } } for (String header : needSetHeaderMap.keySet()) { httpServletResponse.setHeader(header, needSetHeaderMap.get(header)); } }
protected void copyRequestHeaders(HttpServletRequest httpServletRequest, Request.Builder requestBuilder) { Enumeration<String> headerNames = httpServletRequest.getHeaderNames(); while (headerNames.hasMoreElements()) { String key = headerNames.nextElement(); if ("host".equalsIgnoreCase(key)) { if (preserveHost) { requestBuilder.header(key, httpServletRequest.getHeader(key)); } } else if ("cookie".equalsIgnoreCase(key)) { if (preserveCookie) { requestBuilder.header(key, httpServletRequest.getHeader(key)); } } else { requestBuilder.header(key, httpServletRequest.getHeader(key)); } } }
protected void writeGatewayError(HttpServletResponse httpServletResponse, String msg) { httpServletResponse.setStatus(502); httpServletResponse.setContentType("text/html;charset=utf-8"); try { httpServletResponse.getWriter().write(msg); } catch (Exception ignore) {
} }
class StreamingRequestBody extends RequestBody {
private final MediaType contentType; private final InputStream inputStream;
public StreamingRequestBody(MediaType contentType, InputStream inputStream) { this.contentType = contentType; this.inputStream = inputStream; }
@Override public MediaType contentType() { return contentType; }
@Override public void writeTo(BufferedSink sink) throws IOException { byte[] buffer = new byte[8192]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { sink.write(buffer, 0, bytesRead); } } }
private static OkHttpClient okHttpClient;
public synchronized static OkHttpClient okHttpClient() { if (okHttpClient == null) { OkHttpClient.Builder builder = new OkHttpClient().newBuilder() .connectionPool(new ConnectionPool(2, 60, TimeUnit.SECONDS)) .connectTimeout(10, TimeUnit.SECONDS) .readTimeout(30, TimeUnit.SECONDS) .writeTimeout(30, TimeUnit.SECONDS); builder.followRedirects(false); builder.followSslRedirects(true); builder.hostnameVerifier(new HostnameVerifier() { @Override public boolean verify(final String s, final SSLSession sslSession) { return true; }
@Override public final String toString() { return "NO_OP"; } }); try { X509TrustManager x509TrustManager = new X509TrustManager() { @Override public void checkClientTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override public void checkServerTrusted(X509Certificate[] x509Certificates, String s) throws CertificateException {
}
@Override public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; } }; TrustManager[] trustManagers = { x509TrustManager }; SSLContext sslContext = SSLContext.getInstance("SSL"); sslContext.init(null, trustManagers, new SecureRandom()); builder.sslSocketFactory(sslContext.getSocketFactory(), x509TrustManager); } catch (Exception ignore) {
} okHttpClient = builder.build(); } return okHttpClient; } }
|