Skip to content
Permalink
Browse files

[FIXED JENKINS-23294] Interpret X-Forwarded-Port

- Also fixed handling of X-Forwarded-Proto and added support for X-Forwarded-Host

- Additional complexity is that there can be multiple headers with the same name (which was handled by default by accident) and
  that a header value may contain a comma separated list if there were multiple forwarding hops.
  • Loading branch information...
stephenc committed Jun 19, 2014
1 parent 1aec030 commit 5bad446dd51d31efd60538eab5c87bdde57114e9
Showing with 33 additions and 8 deletions.
  1. +33 −8 core/src/main/java/jenkins/model/Jenkins.java
@@ -1895,19 +1895,44 @@ public boolean isRootUrlSecure() {
public String getRootUrlFromRequest() {
StaplerRequest req = Stapler.getCurrentRequest();
StringBuilder buf = new StringBuilder();
String scheme = req.getScheme();
String forwardedScheme = req.getHeader("X-Forwarded-Proto");
if (forwardedScheme != null) {
scheme = forwardedScheme;
String scheme = getXForwardedHeader(req, "X-Forwarded-Proto", req.getScheme());
buf.append(scheme).append("://");
String host = getXForwardedHeader(req, "X-Forwarded-Host", req.getServerName());
buf.append(host);
int port = req.getServerPort();
String forwardedPort = getXForwardedHeader(req, "X-Forwarded-Port", null);
if (forwardedPort != null) {
try {
port = Integer.parseInt(forwardedPort);
} catch (NumberFormatException e) {
// ignore
}
}
if(("http".equals(scheme) && port != 80) || ("https".equals(scheme) && port != 443)) {
buf.append(':').append(port);
}
buf.append(scheme+"://");
buf.append(req.getServerName());
if(req.getServerPort()!=80)
buf.append(':').append(req.getServerPort());
buf.append(req.getContextPath()).append('/');
return buf.toString();
}

/**
* Gets the originating "X-Forwarded-..." header from the request. If there are multiple headers the originating
* header is the first header. If the originating header contains a comma separated list, the originating entry
* is the first one.
* @param req the request
* @param header the header name
* @param defaultValue the value to return if the header is absent.
* @return the originating entry of the header or the default value if the header was not present.
*/
private static String getXForwardedHeader(StaplerRequest req, String header, String defaultValue) {
String value = req.getHeader(header);
if (value != null) {
int index = value.indexOf(',');
return index == -1 ? value.trim() : value.substring(0,index).trim();
}
return defaultValue;
}

public File getRootDir() {
return root;
}

0 comments on commit 5bad446

Please sign in to comment.
You can’t perform that action at this time.