Make ServletRequest implement the standardized HttpServletRequest interface,

to make all readily available information from the original ServletRequest
available to YaCy servlets (without converting data to internal structures).
The implementation of the common interface allows easier integration of
YaCy servlets with the servlet standard (e.g. shared login service with
the servlet container etc.)
pull/93/head
reger 8 years ago
parent 62f75417ef
commit 395f2e8946

@ -62,7 +62,7 @@ public class AccessTracker_p {
// return variable that accumulates replacements
final serverObjects prop = new serverObjects();
prop.setLocalized(!(header.get(HeaderFramework.CONNECTION_PROP_PATH)).endsWith(".xml"));
prop.setLocalized(!header.getPathInfo().endsWith(".xml"));
int page = 0;
if (post != null) {
page = post.getInt("page", 0);

@ -78,7 +78,7 @@ public class Blog {
prop.put("display", 1); // Fixed to 1
final boolean xml = (header.get(HeaderFramework.CONNECTION_PROP_PATH)).endsWith(".xml");
final boolean xml = header.getPathInfo().endsWith(".xml");
/* Peer URL base : used to generate absolute URLs in Blog.rss */
final String context = YaCyDefaultServlet.getContext(header, sb);
@ -104,7 +104,7 @@ public class Blog {
}
String pagename = post.get("page", DEFAULT_PAGE);
final String ip = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, Domains.LOCALHOST);
final String ip = header.getRemoteAddr();
String strAuthor = post.get("author", "anonymous");

@ -147,12 +147,8 @@ public class ConfigBasic {
UPnP.addPortMappings();
}
String host = null;
if (header.containsKey(HeaderFramework.HOST)) {
host = header.get(HeaderFramework.HOST);
final int idx = host.indexOf(':',0);
if (idx != -1) host = host.substring(0,idx);
} else {
String host = header.getServerName();
if (host == null) {
host = Domains.myPublicLocalIP().getHostAddress();
}

@ -258,7 +258,7 @@ public class Crawler_p {
if (crawlingStartURL != null && (crawlingStartURL.isFile() || crawlingStartURL.isSMB())) storeHTCache = false;
} catch (final MalformedURLException e) {
ConcurrentLog.warn("Crawler_p", "crawl start url invalid" + e.getMessage());
ConcurrentLog.warn("Crawler_p", "crawl start url invalid: " + e.getMessage());
}
} else {
crawlName = crawlingFile.getName();

@ -70,7 +70,7 @@ public class Network {
prop.put("menu", post == null ? 2 : (post.get("menu", "").equals("embed")) ? 0 : (post.get("menu","").equals("simple")) ? 1 : 2);
if (sb.peers.mySeed() != null) prop.put("menu_newpeer_peerhash", sb.peers.mySeed().hash);
prop.setLocalized(!(requestHeader.get(HeaderFramework.CONNECTION_PROP_PATH)).endsWith(".xml"));
prop.setLocalized(!requestHeader.getPathInfo().endsWith(".xml"));
prop.putHTML("page_networkTitle", sb.getConfig("network.unit.description", "unspecified"));
prop.putHTML("page_networkName", sb.getConfig(SwitchboardConstants.NETWORK_NAME, "unspecified"));
final boolean overview = (post == null) || (post.get("page", "0").equals("0"));
@ -530,7 +530,7 @@ public class Network {
prop.putNum("table_rt", System.currentTimeMillis() - start);
// Adding CORS Access header for Network.xml
final String path = requestHeader.get(HeaderFramework.CONNECTION_PROP_PATH);
final String path = requestHeader.getPathInfo();
if(path != null && path.endsWith(".xml")) {
final ResponseHeader outgoingHeader = new ResponseHeader(200);
outgoingHeader.put(HeaderFramework.CORS_ALLOW_ORIGIN, "*");

@ -90,7 +90,7 @@ public class PerformanceQueues_p {
String threadName;
BusyThread thread;
final boolean xml = (header.get(HeaderFramework.CONNECTION_PROP_PATH)).endsWith(".xml");
final boolean xml = header.getPathInfo().endsWith(".xml");
prop.setLocalized(!xml);
// calculate totals

@ -29,7 +29,6 @@
import net.yacy.cora.order.Base64Order;
import net.yacy.cora.order.Digest;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.protocol.ResponseHeader;
import net.yacy.cora.util.ConcurrentLog;
@ -63,7 +62,8 @@ public class User{
prop.put("logged-in_identified-by", "2");
//try via ip
if(entry == null){
entry=sb.userDB.ipAuth((requestHeader.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "xxxxxx")));
final String ip = requestHeader.getRemoteAddr();
entry = sb.userDB.ipAuth((ip != null ? ip : "xxxxxx"));
if(entry != null){
prop.put("logged-in_identified-by", "0");
}
@ -154,7 +154,8 @@ public class User{
if(post!=null && post.containsKey("logout")){
prop.put("logged-in", "0");
if(entry != null){
entry.logout((requestHeader.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "xxxxxx")), UserDB.getLoginToken(requestHeader.getHeaderCookies())); //todo: logout cookie
final String ip = requestHeader.getRemoteAddr();
entry.logout((ip != null ? ip : "xxxxxx"), UserDB.getLoginToken(requestHeader.getHeaderCookies())); //todo: logout cookie
}else{
sb.userDB.adminLogout(UserDB.getLoginToken(requestHeader.getHeaderCookies()));
}

@ -98,7 +98,7 @@ public class ViewFavicon {
pngIconCache.clear();
}
final boolean auth = Domains.isLocalhost(header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, ""))
final boolean auth = Domains.isLocalhost(header.getRemoteAddr())
|| sb.verifyAuthentication(header); // handle access rights
DigestURL url = VIEWER.parseURL(post, auth);

@ -77,7 +77,7 @@ public class ViewImage {
}
String ext = header.get(HeaderFramework.CONNECTION_PROP_EXT, null);
final boolean auth = Domains.isLocalhost(header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, ""))
final boolean auth = Domains.isLocalhost(header.getRemoteAddr())
|| sb.verifyAuthentication(header); // handle access rights
DigestURL url = VIEWER.parseURL(post, auth);

@ -27,9 +27,7 @@
//javac -classpath .:../Classes Status.java
//if the shell's current path is HTROOT
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.util.NumberTools;
import net.yacy.search.Switchboard;
import net.yacy.server.serverObjects;
import net.yacy.server.serverSwitch;
@ -46,16 +44,8 @@ public class YaCySearchPluginFF {
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
// getting the http host header
final String hostSocket = header.get(HeaderFramework.HOST);
String host = hostSocket;
int port = 80;
final int pos = hostSocket.indexOf(':',0);
if (pos != -1) {
port = NumberTools.parseIntDecSubstring(hostSocket, pos + 1);
host = hostSocket.substring(0, pos);
}
String host = header.getServerName();
int port = header.getServerPort();
prop.put("host", host);
prop.put("port", port);

@ -27,9 +27,7 @@
//javac -classpath .:../Classes Status.java
//if the shell's current path is HTROOT
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.util.NumberTools;
import net.yacy.search.SwitchboardConstants;
import net.yacy.server.serverObjects;
import net.yacy.server.serverSwitch;
@ -51,16 +49,8 @@ public class autoconfig {
final boolean yacyonly = env.getConfigBool(SwitchboardConstants.PROXY_YACY_ONLY, false);
// get the http host header
final String hostSocket = header.get(HeaderFramework.HOST);
String host = hostSocket;
int port = 80;
final int pos = hostSocket.indexOf(':',0);
if (pos != -1) {
port = NumberTools.parseIntDecSubstring(hostSocket, pos + 1);
host = hostSocket.substring(0, pos);
}
String host = header.getServerName();
int port = header.getServerPort();
prop.put("yacy", yacyonly ? "0" : "1");
prop.put("yacy_host", host);

@ -31,7 +31,6 @@ import java.io.IOException;
import net.yacy.cora.date.GenericFormatter;
import net.yacy.cora.document.id.MultiProtocolURL;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.document.ImageParser;
import net.yacy.document.parser.html.CharacterCoding;
@ -56,7 +55,8 @@ public class cytag {
appendJSON(connect, "nick", (post == null) ? "" : post.get("nick", ""));
appendJSON(connect, "tag", (post == null) ? "" : post.get("tag", ""));
appendJSON(connect, "icon", (post == null) ? "" : post.get("icon", ""));
appendJSON(connect, "ip", header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, ""));
final String ip = header.getRemoteAddr();
appendJSON(connect, "ip", (ip == null) ? "" : ip);
appendJSON(connect, "agent", header.get("User-Agent", ""));
connect.append('}');

@ -57,7 +57,7 @@ public final class hello {
final serverObjects prop = new serverObjects();
final long start = System.currentTimeMillis();
prop.put("message", "none");
String clientip = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP); // read an artificial header addendum
String clientip = header.getRemoteAddr();
//ConcurrentLog.info("**hello-DEBUG**", "client request from = " + clientip);
final InetAddress ias = Domains.dnsResolve(clientip);
long time = System.currentTimeMillis();

@ -28,7 +28,6 @@
import java.io.File;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
import net.yacy.cora.util.CommonPattern;
import net.yacy.kelondro.util.FileUtils;
@ -63,7 +62,7 @@ public final class list {
final Seed bla = sb.peers.get(post.get("iam", ""));
if (bla != null) otherPeerName = bla.getName();
}
if (otherPeerName == null) otherPeerName = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP);
if (otherPeerName == null) otherPeerName = header.getRemoteAddr();
if ((sb.isRobinsonMode()) && (!sb.isInMyCluster(otherPeerName))) {
// if we are a robinson cluster, answer only if this client is known by our network definition

@ -71,7 +71,7 @@ public final class message {
if (!Protocol.authentifyRequest(post, env)) return prop;
final String process = post.get("process", "permission");
final String clientip = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP); // read an artificial header addendum
final String clientip = header.getRemoteAddr();
final InetAddress ias = clientip != null ? Domains.dnsResolve(clientip) : null;
final int messagesize = 10240;
@ -90,7 +90,7 @@ public final class message {
if ((sb.isRobinsonMode()) &&
(!((sb.isPublicRobinson()) ||
(sb.isInMyCluster(header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP)))))) {
(sb.isInMyCluster(header.getRemoteAddr()))))) {
// if we are a robinson cluster, answer only if this client is known by our network definition
prop.put("response", "-1"); // request rejected
return prop;

@ -53,7 +53,7 @@ public final class profile {
if ((sb.isRobinsonMode()) &&
(!sb.isPublicRobinson()) &&
(!sb.isInMyCluster(header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP)))) {
(!sb.isInMyCluster(header.getRemoteAddr()))) {
// if we are a robinson cluster, answer only if this client is known by our network definition
prop.put("list", "0");
return prop;

@ -51,9 +51,9 @@ public final class query {
final Switchboard sb = (Switchboard) ss;
// remember the peer contact for peer statistics
final String clientip = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "<unknown>"); // read an artificial header addendum
final String clientip = header.getRemoteAddr();
final String userAgent = header.get(HeaderFramework.USER_AGENT, "<unknown>");
sb.peers.peerActions.setUserAgent(clientip, userAgent);
if (clientip != null) sb.peers.peerActions.setUserAgent(clientip, userAgent);
final serverObjects prop = new serverObjects();
prop.put("magic", Network.magic);
@ -65,7 +65,7 @@ public final class query {
if ((sb.isRobinsonMode()) &&
(!sb.isPublicRobinson()) &&
(!sb.isInMyCluster(header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP)))) {
(!sb.isInMyCluster(clientip))) {
// if we are a robinson cluster, answer only if we are public robinson peers,
// or we are a private cluster and the requester is in our cluster.
// if we don't answer, the remote peer will recognize us as junior peer,

@ -101,7 +101,7 @@ public final class search {
if (post == null || env == null) return prop;
if (!Protocol.authentifyRequest(post, env)) return prop;
final String client = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP);
final String client = header.getRemoteAddr();
//System.out.println("yacy: search received request = " + post.toString());

@ -66,9 +66,9 @@ public final class transferRWI {
final Switchboard sb = (Switchboard) env;
// remember the peer contact for peer statistics
final String clientip = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "<unknown>"); // read an artificial header addendum
final String clientip = header.getRemoteAddr();
final String userAgent = header.get(HeaderFramework.USER_AGENT, "<unknown>");
sb.peers.peerActions.setUserAgent(clientip, userAgent);
if (clientip != null) sb.peers.peerActions.setUserAgent(clientip, userAgent);
final serverObjects prop = new serverObjects();
final String contentType = header.getContentType();

@ -114,7 +114,7 @@ public class yacysearch {
(env.getConfigBool(SwitchboardConstants.GREETING_NETWORK_NAME, false)) ? env.getConfig(
"network.unit.description",
"") : env.getConfig(SwitchboardConstants.GREETING, "");
final String client = header.get(HeaderFramework.CONNECTION_PROP_CLIENTIP); // the search client who initiated the search
final String client = header.getRemoteAddr(); // the search client who initiated the search
// in case that the crawler is running and the search user is the peer admin, we expect that the user wants to check recently crawled document
// to ensure that recent crawl results are inside the search results, we do a soft commit here. This is also important for live demos!

@ -91,7 +91,7 @@ public class HeaderFramework extends TreeMap<String, String> implements Map<Stri
public static final String PRAGMA = "Pragma";
public static final String CACHE_CONTROL = "Cache-Control";
public static final String DATE = "Date";
public static final String DATE = "Date"; // time message/response was created, https://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html#sec14.18
public static final String LAST_MODIFIED = "Last-Modified";
public static final String SERVER = "Server";
@ -114,7 +114,7 @@ public class HeaderFramework extends TreeMap<String, String> implements Map<Stri
public static final String X_YACY_MEDIA_TITLE = "X-YaCy-Media-Title"; // can be attached to media files which do not have metadata; this will be used as title
public static final String X_YACY_MEDIA_KEYWORDS = "X-YaCy-Media-Keywords"; // can be attached to media files which do not have metadata; this will be used as keywords (space-separared list of words)
/** Added when generating legacy request header to allow template servlets to know the original request scheme : "http" or "https" */
public static final String X_YACY_REQUEST_SCHEME = "X-YaCy-Request-Scheme";
public static final String X_YACY_REQUEST_SCHEME = "X-YaCy-Request-Scheme"; // TODO: after completing implementation of HttpServletRequest getScheme() should be used and this can be removed
public static final String SET_COOKIE = "Set-Cookie";
public static final String SET_COOKIE2 = "Set-Cookie2";
@ -424,7 +424,7 @@ public class HeaderFramework extends TreeMap<String, String> implements Map<Stri
* @return mime or on missing header field "application/octet-stream"
*/
public String mime() {
final String tmpstr = get(CONTENT_TYPE, "application/octet-stream");
final String tmpstr = this.get(CONTENT_TYPE, "application/octet-stream");
final int pos = tmpstr.indexOf(';');
if (pos > 0) {
return tmpstr.substring(0, pos).trim();
@ -500,7 +500,7 @@ public class HeaderFramework extends TreeMap<String, String> implements Map<Stri
* @see org.apache.commons.fileupload.RequestContext#getContentType()
*/
public String getContentType() {
return get(CONTENT_TYPE);
return this.get(CONTENT_TYPE);
}
protected Date headerDate(final String kind) {
@ -768,18 +768,10 @@ public class HeaderFramework extends TreeMap<String, String> implements Map<Stri
return "";
}
public void addHeader(final String key, final String value) {
this.headerProps.add(new Entry(key, value));
}
public Vector<Entry> getAdditionalHeaderProperties() {
return this.headerProps;
}
public void setAdditionalHeaderProperties(final Vector<Entry> mycookies){
this.headerProps=mycookies;
}
/*
* Patch END:
* Name: Header Property Patch

@ -20,14 +20,43 @@
package net.yacy.cora.protocol;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.security.Principal;
import java.util.Collection;
import java.util.Date;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.AsyncContext;
import javax.servlet.DispatcherType;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpUpgradeHandler;
import javax.servlet.http.Part;
import net.yacy.cora.document.id.DigestURL;
import net.yacy.cora.document.id.MultiProtocolURL;
import net.yacy.cora.util.NumberTools;
public class RequestHeader extends HeaderFramework {
/**
* YaCy servlet request header.
* YaCy runs in a servlet container (Jetty), starting 2016 this implements the
* widely used HttpServletRequest for tighter and further standardization and
* adherence to common standards, to make the use of HttpServletRequest parameters
* available to YaCy servlets.
*/
public class RequestHeader extends HeaderFramework implements HttpServletRequest {
// request header properties
@ -58,22 +87,21 @@ public class RequestHeader extends HeaderFramework {
HTML, JSON, XML
}
private final HttpServletRequest _request; // reference to the original request
private Date date_cache_IfModifiedSince = null;
public RequestHeader() {
super();
this._request = null;
}
public RequestHeader(final Map<String, String> reverseMappingCache) {
super(reverseMappingCache);
}
public RequestHeader(final Map<String, String> reverseMappingCache, final Map<String, String> othermap) {
super(reverseMappingCache, othermap);
public RequestHeader(HttpServletRequest request) {
super();
this._request = request;
}
public DigestURL referer() {
final String referer = get(REFERER, null);
final String referer = get(REFERER);
if (referer == null) return null;
try {
return new DigestURL(referer);
@ -91,32 +119,13 @@ public class RequestHeader extends HeaderFramework {
public Date ifModifiedSince() {
if (this.date_cache_IfModifiedSince != null) return date_cache_IfModifiedSince;
this.date_cache_IfModifiedSince = headerDate(RequestHeader.IF_MODIFIED_SINCE);
long time = this.getDateHeader(RequestHeader.IF_MODIFIED_SINCE);
if (time > 0) this.date_cache_IfModifiedSince = new Date(time);
return this.date_cache_IfModifiedSince;
}
public Object ifRange() {
if (containsKey(IF_RANGE)) {
final Date rangeDate = parseHTTPDate(get(IF_RANGE));
if (rangeDate != null)
return rangeDate;
return get(IF_RANGE);
}
return null;
}
public String userAgent() {
return get(USER_AGENT, "");
}
public boolean acceptGzip() {
return ((containsKey(ACCEPT_ENCODING)) &&
((get(ACCEPT_ENCODING)).toUpperCase().indexOf("GZIP",0)) != -1);
}
public FileType fileType() {
String path = get(HeaderFramework.CONNECTION_PROP_PATH);
String path = this.getPathInfo();
if (path == null) return FileType.HTML;
path = path.toLowerCase();
if (path.endsWith(".json")) return FileType.JSON;
@ -126,10 +135,9 @@ public class RequestHeader extends HeaderFramework {
return FileType.HTML;
}
public boolean accessFromLocalhost() {
// authorization for localhost, only if flag is set to grant localhost access as admin
final String clientIP = this.get(HeaderFramework.CONNECTION_PROP_CLIENTIP, "");
final String clientIP = this.getRemoteAddr();
if ( !Domains.isLocalhost(clientIP) ) {
return false;
}
@ -137,4 +145,692 @@ public class RequestHeader extends HeaderFramework {
if (refererHost == null || refererHost.isEmpty() || Domains.isLocalhost(refererHost)) return true;
return false;
}
// implementation of HttpServletRequest procedures
// the general approach is to prefer values in the YaCy legacy RequestHeader.map and if no value exists
// to use the httpservletrequest. This approach is used, because legacy requestheader allows to add or
// change header values. This makes sure a modified or added value is used.
// At this point of implementation a original request is not required, so test for _request != null is needed.
/**
* This overrides the legacy get() to make sure the original _request values
* are considered
* @param key header name
* @return value
*/
@Override
public String get(Object key) {
String value = super.get(key); // important to use super.get
if (value == null && _request != null) {
return _request.getHeader((String)key);
}
return value;
}
/**
* Override legacy containsKey to be sure original request headers are incl.
* in the check.
* Use of this legacy methode is discouraged
* @param key headername
* @return
*/
@Override
public boolean containsKey(Object key) {
boolean val = super.containsKey(key);
if (val) {
return val;
} else if (_request != null) {
return _request.getHeader((String) key) != null;
}
return val;
}
/**
* Override legacy mime()
* @return mime string or "application/octet-stream" if content type missing
* @see getContentType()
*/
@Override
public String mime() {
if (super.containsKey(HeaderFramework.CONTENT_TYPE)) {
return super.mime();
} else {
if (_request != null) {
return _request.getContentType();
}
}
return "application/octet-stream";
}
@Override
public String getAuthType() {
if (_request != null) {
return _request.getAuthType();
} else if (super.containsKey(RequestHeader.AUTHORIZATION)) {
return HttpServletRequest.BASIC_AUTH; // legacy supported only BASIC
}
return null;
}
@Override
public Cookie[] getCookies() {
if (_request != null) {
return _request.getCookies();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public long getDateHeader(String name) {
Date d = super.headerDate(name);
if (d != null) {
return d.getTime();
} else {
if (_request != null) {
return _request.getDateHeader(name);
}
return -1;
}
}
@Override
public String getHeader(String name) {
return this.get(name);
}
@Override
public Enumeration<String> getHeaders(String name) {
if (_request != null) {
return _request.getHeaders(name);
}
return null;
}
@Override
public Enumeration<String> getHeaderNames() {
if (_request != null) {
return _request.getHeaderNames();
}
return null; // not supported in legacy RequestHeader, safe to return null
}
@Override
public int getIntHeader(String name) {
if (super.containsKey(name)) {
String val = super.get(name);
if (val != null) {
try {
return Integer.parseInt(val);
} catch (NumberFormatException ex) {}
}
} else if(_request != null) {
return _request.getIntHeader(name);
}
return -1;
}
@Override
public String getMethod() {
if (_request != null) {
return _request.getMethod();
} else {
return HeaderFramework.METHOD_POST;
}
}
@Override
public String getPathInfo() {
if (super.containsKey(HeaderFramework.CONNECTION_PROP_PATH)) {
return super.get(HeaderFramework.CONNECTION_PROP_PATH);
} else if (_request != null) {
return _request.getPathInfo();
}
return ""; // TODO: in difference to standard return empty string (instead null) as we not always check for null
}
@Override
public String getPathTranslated() {
if (_request != null) {
return _request.getPathTranslated();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public String getContextPath() {
if (_request != null) {
return _request.getContextPath();
} else {
return "";
}
}
@Override
public String getQueryString() {
if (_request != null) {
return _request.getQueryString();
} else {
// in case of discoraged use of arbitrary header prop
return super.get(HeaderFramework.CONNECTION_PROP_ARGS);
}
}
@Override
public String getRemoteUser() {
if (_request != null)
return _request.getRemoteUser();
else
return null;
}
@Override
public boolean isUserInRole(String role) {
if (_request != null) {
return _request.isUserInRole(role);
} else {
return false;
}
}
@Override
public Principal getUserPrincipal() {
if (_request != null) {
return _request.getUserPrincipal();
} else {
return null;
}
}
@Override
public String getRequestedSessionId() {
if (_request != null) {
return _request.getRequestedSessionId();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public String getRequestURI() {
if (_request != null) {
return _request.getRequestURI();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public StringBuffer getRequestURL() {
if (_request != null) {
return _request.getRequestURL();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public String getServletPath() {
if (_request != null) {
return _request.getServletPath();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public HttpSession getSession(boolean create) {
if (_request != null) {
return _request.getSession(create);
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public HttpSession getSession() {
if (_request != null) {
return _request.getSession();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public String changeSessionId() {
if (_request != null) {
return _request.changeSessionId();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public boolean isRequestedSessionIdValid() {
if (_request != null) {
return _request.isRequestedSessionIdValid();
} else {
return false;
}
}
@Override
public boolean isRequestedSessionIdFromCookie() {
if (_request != null) {
return _request.isRequestedSessionIdFromCookie();
} else {
return false;
}
}
@Override
public boolean isRequestedSessionIdFromURL() {
if (_request != null) {
return _request.isRequestedSessionIdFromURL();
} else {
return false;
}
}
@Override
public boolean isRequestedSessionIdFromUrl() {
if (_request != null) {
return _request.isRequestedSessionIdFromUrl();
} else {
return false;
}
}
@Override
public boolean authenticate(HttpServletResponse response) throws IOException, ServletException {
if (_request != null) {
return _request.authenticate(response);
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public void login(String username, String password) throws ServletException {
if (_request != null) {
_request.login(username, password);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void logout() throws ServletException {
if (_request != null) {
_request.logout();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Collection<Part> getParts() throws IOException, ServletException {
if (_request != null) {
return _request.getParts();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Part getPart(String name) throws IOException, ServletException {
if (_request != null) {
return _request.getPart(name);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public <T extends HttpUpgradeHandler> T upgrade(Class<T> handlerClass) throws IOException, ServletException {
if (_request != null) {
return _request.upgrade(handlerClass);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Object getAttribute(String name) {
if (_request != null) {
return _request.getAttribute(name);
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public Enumeration<String> getAttributeNames() {
if (_request != null) {
return _request.getAttributeNames();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public String getCharacterEncoding() {
String enc = super.getCharacterEncoding();
if (enc == null && _request != null) return _request.getCharacterEncoding();
return enc;
}
@Override
public void setCharacterEncoding(String env) throws UnsupportedEncodingException {
if (_request != null) {
_request.setCharacterEncoding(env);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getContentLength() {
int len = super.getContentLength();
if (len < 0 && _request != null) return _request.getContentLength();
return len;
}
@Override
public long getContentLengthLong() {
long len = super.getContentLengthLong();
if (len < 0 && _request != null) return _request.getContentLengthLong();
return len;
}
@Override
public String getContentType() {
if (super.containsKey(HeaderFramework.CONTENT_TYPE)) {
return super.mime();
} else {
if (_request != null) {
return _request.getContentType();
}
}
return null;
}
@Override
public ServletInputStream getInputStream() throws IOException {
if (_request != null) {
return _request.getInputStream();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public String getParameter(String name) {
if (_request != null) {
return _request.getParameter(name);
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public Enumeration<String> getParameterNames() {
if (_request != null) {
return _request.getParameterNames();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public String[] getParameterValues(String name) {
if (_request != null) {
return _request.getParameterValues(name);
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public Map<String, String[]> getParameterMap() {
if (_request != null) {
return _request.getParameterMap();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public String getProtocol() {
// here we can directly check original request, as protocol is not expected to be modified
if (_request != null) {
return _request.getProtocol();
} else {
return this.get(HeaderFramework.CONNECTION_PROP_HTTP_VER);
}
}
@Override
public String getScheme() {
// here we can directly check original request first, as scheme is not expected to be changed
if (_request != null) {
return _request.getScheme();
} else {
if (super.containsKey(HeaderFramework.X_YACY_REQUEST_SCHEME)) {
return super.get(HeaderFramework.X_YACY_REQUEST_SCHEME);
} else {
return "http";
}
}
}
@Override
public String getServerName() {
if (super.containsKey(HeaderFramework.HOST)) {
final String hostport = super.get(HeaderFramework.HOST);
if (hostport.contains("[")) { // handle ipv6
final int pos = hostport.lastIndexOf(']');
if (pos > 0) {
return hostport.substring(0, pos + 1);
}
} else if (hostport.contains(":")) {
final int pos = hostport.indexOf(':');
if (pos > 0) {
return hostport.substring(0, pos);
}
}
return hostport;
} else if (_request != null) {
return _request.getServerName();
} else {
return Domains.LOCALHOST;
}
}
@Override
public int getServerPort() {
if (super.containsKey(HeaderFramework.HOST)) {
final String hostport = super.get(HeaderFramework.HOST);
int port = getScheme().equals("https") ? 443 : 80; // init with default ports
final int pos = hostport.lastIndexOf(':');
if (pos > 0 && hostport.lastIndexOf(']') < pos) { // check for ipv6
port = NumberTools.parseIntDecSubstring(hostport, pos + 1);
}
return port;
} else if (_request != null) {
return _request.getServerPort();
} else {
return 80;
}
}
@Override
public BufferedReader getReader() throws IOException {
if (_request != null) {
return _request.getReader();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getRemoteAddr() {
if (this._request != null) {
return _request.getRemoteAddr();
} else {
return super.get(HeaderFramework.CONNECTION_PROP_CLIENTIP);
}
}
@Override
public String getRemoteHost() {
if (_request != null) {
return _request.getRemoteHost();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void setAttribute(String name, Object o) {
if (_request != null) {
_request.setAttribute(name, o);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public void removeAttribute(String name) {
if (_request != null) {
_request.removeAttribute(name);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public Locale getLocale() {
if (this._request != null) {
return _request.getLocale();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public Enumeration<Locale> getLocales() {
if (this._request != null) {
return _request.getLocales();
} else {
throw new UnsupportedOperationException("Not supported yet.");
}
}
@Override
public boolean isSecure() {
if (_request != null) {
return _request.isSecure();
}
return false;
}
@Override
public RequestDispatcher getRequestDispatcher(String path) {
if (_request != null) {
return _request.getRequestDispatcher(path);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
@Deprecated // Deprecated. As of Version 2.1 of the Java Servlet API, use ServletContext.getRealPath(java.lang.String) instead.
public String getRealPath(String path) {
if (_request != null) {
return _request.getRealPath(path);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getRemotePort() {
if (_request != null) {
return _request.getRemotePort();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getLocalName() {
if (_request != null) {
return _request.getLocalName();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public String getLocalAddr() {
if (_request != null) {
return _request.getLocalAddr();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public int getLocalPort() {
if (_request != null) {
return _request.getLocalPort();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public ServletContext getServletContext() {
if (_request != null) {
return _request.getServletContext();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public AsyncContext startAsync() throws IllegalStateException {
if (_request != null) {
return _request.startAsync();
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public AsyncContext startAsync(ServletRequest servletRequest, ServletResponse servletResponse) throws IllegalStateException {
if (_request != null) {
startAsync(servletRequest, servletResponse);
}
throw new UnsupportedOperationException("Not supported yet.");
}
@Override
public boolean isAsyncStarted() {
if (_request != null) {
return _request.isAsyncStarted();
}
return false;
}
@Override
public boolean isAsyncSupported() {
if (_request != null) {
return _request.isAsyncStarted();
}
return false;
}
@Override
public AsyncContext getAsyncContext() {
if (_request != null) {
return _request.getAsyncContext();
}
return null;
}
@Override
public DispatcherType getDispatcherType() {
if (_request != null) {
return _request.getDispatcherType();
}
return null;
}
}

@ -680,7 +680,9 @@ public class YaCyDefaultServlet extends HttpServlet {
* Convert ServletRequest header to YaCy RequestHeader
* @param request ServletRequest
* @return RequestHeader created from ServletRequest
* @deprecated use RequestHeader(HttpServletRequest); but .remove(key) can't be used after switch to new instance
*/
@Deprecated // TODO: only used for proxy, should be handled there
public static RequestHeader convertHeaderFromJetty(HttpServletRequest request) {
RequestHeader result = new RequestHeader();
Enumeration<String> headerNames = request.getHeaderNames();
@ -736,14 +738,12 @@ public class YaCyDefaultServlet extends HttpServlet {
}
if(header != null) {
/* YaCyDefaultServelt should have filled this custom header, making sure we know here whether original request is http or https
* (when default ports (80 and 443) are used, there is no way to distinguish the two schemes relying only on the Host header) */
String protocolHeader = header.get(HeaderFramework.X_YACY_REQUEST_SCHEME, "").toLowerCase();
String protocolHeader = header.getScheme();
/* Let's check this custom header has a valid value */
/* Let's check this header has a valid value */
if("http".equals(protocolHeader) || "https".equals(protocolHeader)) {
protocol = protocolHeader.toLowerCase();
} else if(!protocolHeader.isEmpty()) {
} else if(protocolHeader != null && !protocolHeader.isEmpty()) {
ConcurrentLog.warn("FILEHANDLER","YaCyDefaultServlet: illegal " + HeaderFramework.X_YACY_REQUEST_SCHEME + " header value : " + protocolHeader);
}
@ -763,15 +763,11 @@ public class YaCyDefaultServlet extends HttpServlet {
return protocol + "://" + hostAndPort;
}
protected RequestHeader generateLegacyRequestHeader(HttpServletRequest request, String target, String targetExt) {
RequestHeader legacyRequestHeader = convertHeaderFromJetty(request);
private RequestHeader generateLegacyRequestHeader(HttpServletRequest request, String target, String targetExt) {
RequestHeader legacyRequestHeader = new RequestHeader(request);
legacyRequestHeader.put(HeaderFramework.CONNECTION_PROP_CLIENTIP, request.getRemoteAddr());
legacyRequestHeader.put(HeaderFramework.CONNECTION_PROP_PATH, target);
legacyRequestHeader.put(HeaderFramework.CONNECTION_PROP_PATH, target); // target may contain a server side include (SSI)
legacyRequestHeader.put(HeaderFramework.CONNECTION_PROP_EXT, targetExt);
/* Add request scheme (http or https) to allow templates to know wether original request is http or https
* (when default ports (80 and 443) are used, there is no way to distinguish the two schemes relying only on the Host header) */
legacyRequestHeader.put(HeaderFramework.X_YACY_REQUEST_SCHEME, request.getScheme());
Switchboard sb = Switchboard.getSwitchboard();
if (legacyRequestHeader.containsKey(RequestHeader.AUTHORIZATION)) {
if (HttpServletRequest.BASIC_AUTH.equalsIgnoreCase(request.getAuthType())) {
@ -879,6 +875,17 @@ public class YaCyDefaultServlet extends HttpServlet {
return m;
}
/**
* Handles a YaCy servlet template, reads the template and replaces the template
* items with actual values. Because of supported server side includes target
* might not be the same as request.getPathInfo
*
* @param target the path to the template
* @param request the remote servlet request
* @param response
* @throws IOException
* @throws ServletException
*/
protected void handleTemplate(String target, HttpServletRequest request, HttpServletResponse response) throws IOException, ServletException {
Switchboard sb = Switchboard.getSwitchboard();

@ -37,7 +37,7 @@ public final class BlacklistHelper {
}
if (newEntry == null || newEntry.isEmpty()) {
return header.get(HeaderFramework.CONNECTION_PROP_PATH) + "?selectList=&selectedListName=" + blacklistToUse;
return header.getPathInfo() + "?selectList=&selectedListName=" + blacklistToUse;
}
// ignore empty entries
@ -104,7 +104,7 @@ public final class BlacklistHelper {
}
if (oldEntry == null || oldEntry.isEmpty()) {
return header.get(HeaderFramework.CONNECTION_PROP_PATH) + "?selectList=&selectedListName=" + blacklistToUse;
return header.getPathInfo() + "?selectList=&selectedListName=" + blacklistToUse;
}

@ -156,8 +156,6 @@ public final class HTTPDemon {
// set rewrite values
final serverObjects tp = new serverObjects();
String clientIP = (String) conProp.get(HeaderFramework.CONNECTION_PROP_CLIENTIP); if (clientIP == null) clientIP = Domains.LOCALHOST;
tp.put("peerName", (switchboard.peers == null) ? "" : switchboard.peers.myName());
tp.put("errorMessageType", Integer.toString(errorcase));
tp.put("httpStatus", Integer.toString(httpStatusCode) + " " + httpStatusText);

@ -0,0 +1,67 @@
/**
* RequestHeaderTest
* part of YaCy
* Copyright 2016 by reger24; https://github.com/reger24
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program in the file lgpl21.txt
* If not, see <http://www.gnu.org/licenses/>.
*/
package net.yacy.cora.protocol;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* Unit tests for RequestHeader class.
*
* @author reger24
*/
public class RequestHeaderTest {
/**
* Test of getServerPort method, of class RequestHeader.
*/
@Test
public void testGetServerPort() {
int portresult;
RequestHeader hdr = new RequestHeader();
// test host with port
hdr.put(HeaderFramework.HOST, "[:1]:8090");
portresult = hdr.getServerPort();
assertEquals (8090, portresult);
hdr.put(HeaderFramework.HOST, "127.0.0.1:8090");
portresult = hdr.getServerPort();
assertEquals (8090, portresult);
hdr.put(HeaderFramework.HOST, "localhost:8090");
portresult = hdr.getServerPort();
assertEquals (8090, portresult);
// test default port
hdr.put(HeaderFramework.HOST, "[:1]");
portresult = hdr.getServerPort();
assertEquals (80, portresult);
hdr.put(HeaderFramework.HOST, "127.0.0.1");
portresult = hdr.getServerPort();
assertEquals (80, portresult);
hdr.put(HeaderFramework.HOST, "localhost");
portresult = hdr.getServerPort();
assertEquals (80, portresult);
}
}
Loading…
Cancel
Save