📄 reverseproxymethodhandler.java
字号:
return false;
}
private boolean handleReplacementProxy(RequestHandlerRequest request, RequestHandlerResponse response, SessionInfo session,
String uniqueTicket, ReplacementProxyWebForward wf, String proxiedUrl) throws Exception {
// Initialise local fields
OutputStream serverOut = null;
InputStream serverIn = null;
int maxAge = Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null,
"webForwards.cache.maxUserAge")) * 1000 * 60;
User user = session.getUser();
ContentCache cache = getCache(session, user);
CookieMap cookieMap = getCookieMap(session);
final RequestProcessor requestProcessor = new RequestProcessor(cache, user, maxAge, request, session, uniqueTicket, wf,
proxiedUrl);
boolean keepAlive = false;
try {
// Process the request
requestProcessor.processRequest();
// Get the page from cache if the request processor determined it
// could be
if (requestProcessor.isGetFromCache()) {
if (log.isDebugEnabled())
log.debug("Found page in cache");
CacheingOutputStream cos = (CacheingOutputStream) cache.retrieve(requestProcessor.getConnectionPath());
respondFromCache(cos, request, response);
return true;
}
// Send the request to the proxied host
boolean authTried = false;
ProxiedRequestDispatcher requestDispatcher = new ProxiedRequestDispatcher(requestProcessor, user, cookieMap);
while (true) {
if (!requestDispatcher.sendProxiedRequest()) {
response.sendError(requestDispatcher.getResponseCode(), requestDispatcher.getResponseMessage());
return true;
}
//
String credentials = requestDispatcher.getServerResponse().getHeaderField(HttpConstants.HDR_WWW_AUTHENTICATE);
if (credentials != null && requestDispatcher.getResponseCode() == HttpServletResponse.SC_UNAUTHORIZED && !authTried) {
if (log.isInfoEnabled())
log.info("Trying current user credentials for [" + credentials + "]");
int idx = credentials.indexOf(' ');
String method = credentials;
if (idx > -1) {
method = credentials.substring(0, idx);
}
if (method.equalsIgnoreCase("basic")) {
if (log.isDebugEnabled())
log.debug("Trying BASIC authentication using current credentials");
AuthenticationScheme scheme = (AuthenticationScheme) session.getHttpSession().getAttribute(
Constants.AUTH_SESSION);
char[] pw = CoreServlet.getServlet().getLogonController().getPasswordFromCredentials(scheme);
requestProcessor.setHeader(HttpConstants.HDR_AUTHORIZATION, method
+ " "
+ new String(Base64.encode((user.getPrincipalName() + ":" + (pw == null ? "" : new String(
pw))).getBytes())));
} else {
log.warn("Unsupported authentication method " + method + ". Just passing on to browser");
}
authTried = true;
} else {
break;
}
}
// Process the proxied hosts response =
ProxiedResponseProcessor proxiedResponseProcessor = new ProxiedResponseProcessor(requestProcessor, requestDispatcher,
maxAge, cache, cookieMap);
proxiedResponseProcessor.processResponse();
// Send the response
ProxiedResponseDispatcher responseDispatcher = new ProxiedResponseDispatcher(requestProcessor,
proxiedResponseProcessor, response, user, cache);
responseDispatcher.sendResponse();
} catch (Throwable t) {
log.error("Serious error proxying request.", t);
if(t instanceof Exception) {
throw (Exception)t;
}
throw new Exception("Internal error.", t);
} finally {
if (!keepAlive) {
Util.closeStream(serverOut);
Util.closeStream(serverIn);
}
}
return true;
}
public CookieMap getCookieMap(SessionInfo session) {
CookieMap cookieMap = (CookieMap) session.getHttpSession().getAttribute(Constants.ATTR_COOKIE_MAP);
if (cookieMap == null) {
cookieMap = new CookieMap();
session.getHttpSession().setAttribute(Constants.ATTR_COOKIE_MAP, cookieMap);
}
return cookieMap;
}
private ContentCache getCache(SessionInfo session, User user) throws Exception {
ContentCache cache = (ContentCache) session.getHttpSession().getAttribute(Constants.ATTR_CACHE);
if (cache == null) {
int maxObjs = Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null,
"webForwards.cache.maxUserObjects"));
if (maxObjs != 0) {
String dir = CoreUtil.replaceAllTokens(CoreServlet.getServlet().getPropertyDatabase().getProperty(0, null,
"webForwards.cache.directory"), "%TMP%", ContextHolder.getContext().getTempDirectory().getAbsolutePath());
File cacheDir = new File(dir);
if (!cacheDir.exists()) {
if (!cacheDir.mkdirs()) {
throw new Exception("Could not create cache directory " + cacheDir.getAbsolutePath() + ".");
}
}
cache = new ContentCache(user, cacheDir, Integer.parseInt(CoreServlet.getServlet().getPropertyDatabase()
.getProperty(0, null, "webForwards.cache.maxUserSize")), maxObjs);
session.getHttpSession().setAttribute(Constants.ATTR_CACHE, cache);
}
}
return cache;
}
/**
* @param cos
* @param request
* @param response
* @throws IOException
*/
private void respondFromCache(CacheingOutputStream cos, RequestHandlerRequest request, RequestHandlerResponse response)
throws IOException {
for (Iterator i = cos.getHeaders().iterator(); i.hasNext();) {
Header h = (Header) i.next();
response.setField(h.getName(), h.getVal());
}
response.setField("Content-Type", cos.getContentType());
OutputStream out = response.getOutputStream();
byte[] buf = cos.getBytes();
response.setContentLength(buf.length);
out.write(buf);
out.flush();
}
private boolean handleReverseProxy(String path, String params, RequestHandlerRequest request, RequestHandlerResponse response,
ReverseProxyWebForward webForward, SessionInfo session) throws IOException {
// Try and load the web forward again in case it has been removed
WebForward wf = null;
try {
wf = CoreServlet.getServlet().getSystemDatabase().getWebForward(webForward.getResourceId());
if (wf == null) {
throw new Exception();
}
} catch (Exception e1) {
throw new IOException("Could not validate web forward with ID of " + webForward.getResourceId());
}
try {
URL target = new URL(CoreUtil.doStandardReplacements(session, webForward.getDestinationURL()));
if (log.isDebugEnabled()) {
log.debug("Reverse proxy target " + target.toExternalForm());
}
/**
* This code sets the character encoding of the request. This may be overridden because
* some servers assume the character set and there is no way for us work this.
*/
try {
if(((ReverseProxyWebForward)wf).getCharset()!=null && !((ReverseProxyWebForward)wf).getCharset().equals(""))
request.setCharacterEncoding(((ReverseProxyWebForward)wf).getCharset());
} catch(UnsupportedEncodingException ex) {
log.error("Java runtime does not support encoding", ex);
}
String hostname = target.getHost();
boolean isSecure = target.getProtocol().equalsIgnoreCase("https");
int connectPort = target.getPort() == -1 ? (isSecure ? 443 : 80) : target.getPort();
HttpClient client;
SessionClients clients = null;
// CookieMap cookieMap = null;
synchronized (session.getHttpSession()) {
clients = (SessionClients) session.getHttpSession().getAttribute(Constants.HTTP_CLIENTS);
if (clients == null) {
clients = new SessionClients();
session.getHttpSession().setAttribute(Constants.HTTP_CLIENTS, clients);
}
}
synchronized (clients) {
String key = hostname + ":" + connectPort + ":" + isSecure + ":" + webForward.getResourceId()
+ Thread.currentThread().getName();
client = (HttpClient) clients.get(key);
if (client == null) {
client = new HttpClient(hostname, connectPort, isSecure);
if (!webForward.getPreferredAuthenticationScheme().equals(HttpAuthenticatorFactory.NONE)
&& !webForward.getAuthenticationUsername().equals("")
&& !webForward.getAuthenticationPassword().equals("")) {
PasswordCredentials pwd = new PasswordCredentials();
pwd.setUsername(CoreUtil.doStandardReplacements(session, webForward.getAuthenticationUsername()));
pwd.setPassword(CoreUtil.doStandardReplacements(session, webForward.getAuthenticationPassword()));
client.setCredentials(pwd);
}
// Set the preferred scheme
client.setPreferredAuthentication(webForward.getPreferredAuthenticationScheme());
// If we're using basic authentication then preempt the 401
// response
client.setPreemtiveAuthentication(webForward.getPreferredAuthenticationScheme().equalsIgnoreCase("BASIC"));
clients.put(key, client);
}
}
String header;
com.maverick.http.HttpResponse clientResponse;
ReverseProxyProxiedMethod method;
/**
* POST parameters are now not being
*/
if (!webForward.getFormType().equals("NONE") && request.getParameters().containsKey("launched")) {
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -