Skip to content

Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance

removed unused anomichttpd code after migration to jetty

Michael Peter Christen84167adb4935
diff --git a/defaults/yacy.init b/defaults/yacy.init
index f85c5f095..88ca29529 100644
--- a/defaults/yacy.init
+++ b/defaults/yacy.init
@@ -7,9 +7,6 @@
# you must delete the yacy.conf file in DATA/SETTINGS
# ----------------------------------------------------------------------------
-# the HTTP service configurations
-# choices are jetty or anomic
-defaulthttpserver=jetty
# port number where the server should bind to
port = 8090
diff --git a/htroot/AccessTracker_p.java b/htroot/AccessTracker_p.java
index cc477e615..75eea3e82 100644
--- a/htroot/AccessTracker_p.java
+++ b/htroot/AccessTracker_p.java
@@ -42,7 +42,6 @@ import net.yacy.peers.Seed;
import net.yacy.search.Switchboard;
import net.yacy.search.query.AccessTracker;
import net.yacy.search.query.QueryParams;
-import net.yacy.server.serverCore;
import net.yacy.server.serverObjects;
import net.yacy.server.serverSwitch;
import net.yacy.server.serverAccessTracker.Track;
@@ -93,16 +92,6 @@ public class AccessTracker_p {
prop.put("page_num", entCount);
entCount = 0;
- try {
- for (final Map.Entry<String, Integer> bfe: serverCore.bfHost.entrySet()) {
- prop.putHTML("page_bflist_" + entCount + "_host", bfe.getKey());
- prop.putNum("page_bflist_" + entCount + "_countSecond", bfe.getValue());
- entCount++;
- }
- } catch (final ConcurrentModificationException e) {
- // we don't want to synchronize this
- ConcurrentLog.logException(e);
- }
prop.put("page_bflist", entCount);
} else if (page == 1) {
String host = (post == null) ? "" : post.get("host", "");
diff --git a/htroot/Connections_p.java b/htroot/Connections_p.java
index 6de5b625a..99804683a 100644
--- a/htroot/Connections_p.java
+++ b/htroot/Connections_p.java
@@ -27,9 +27,6 @@
//javac -classpath .:../classes Network.java
//if the shell's current path is HTROOT
-import java.io.UnsupportedEncodingException;
-import java.net.InetAddress;
-import java.net.URLEncoder;
import java.util.Collections;
import java.util.LinkedList;
import java.util.List;
@@ -37,15 +34,10 @@ import java.util.Set;
import net.yacy.cora.protocol.ConnectionInfo;
import net.yacy.cora.protocol.RequestHeader;
-import net.yacy.cora.util.ConcurrentLog;
import net.yacy.http.YaCyHttpServer;
-import net.yacy.peers.PeerActions;
-import net.yacy.peers.Seed;
import net.yacy.search.Switchboard;
-import net.yacy.server.serverCore;
import net.yacy.server.serverObjects;
import net.yacy.server.serverSwitch;
-import net.yacy.server.serverCore.Session;
public final class Connections_p {
@@ -64,7 +56,6 @@ public final class Connections_p {
doNameLookup = post.getBoolean("nameLookup");
if (post.containsKey("closeServerSession")) {
final String sessionName = post.get("closeServerSession", null);
- sb.closeSessions(sessionName);
prop.put(serverObjects.ACTION_LOCATION,"");
return prop;
}
@@ -73,69 +64,7 @@ public final class Connections_p {
}
// waiting for all threads to finish
- int idx = 0, numActiveRunning = 0, numActivePending = 0;
- boolean dark = true;
- for (final Session s: serverCore.getJobList()) {
- if (!s.isAlive()) continue;
-
- // get the session runtime
- final long sessionTime = s.getTime();
-
- // get the request command line
- String commandLine = s.getCommandLine();
- final boolean blockingRequest = (commandLine == null);
- final int commandCount = s.getCommandCount();
-
- // get the source ip address and port
- final InetAddress userAddress = s.getUserAddress();
- final int userPort = s.getUserPort();
- if (userAddress == null) {
- continue;
- }
-
- String prot = "http"; // only httpd sessions listed
-
- // determining if the source is a yacy host
- Seed seed = null;
- if (doNameLookup) {
- seed = sb.peers.lookupByIP(userAddress, -1, true, false, false);
- if (seed != null && (seed.hash.equals(sb.peers.mySeed().hash)) &&
- (!seed.get(Seed.PORT,"").equals(Integer.toString(userPort)))) {
- seed = null;
- }
- }
-
- prop.put("list_" + idx + "_dark", dark ? "1" : "0");
- dark = !dark;
- try {
- prop.put("list_" + idx + "_serverSessionID",URLEncoder.encode(s.getName(),"UTF8"));
- } catch (final UnsupportedEncodingException e) {
- // TODO Auto-generated catch block
- ConcurrentLog.logException(e);
- }
- prop.putHTML("list_" + idx + "_sessionName", s.getName());
- prop.put("list_" + idx + "_proto", prot);
- if (sessionTime > 1000*60) {
- prop.put("list_" + idx + "_ms", "0");
- prop.put("list_" + idx + "_ms_duration",PeerActions.formatInterval(sessionTime));
- } else {
- prop.put("list_" + idx + "_ms", "1");
- prop.putNum("list_" + idx + "_ms_duration", sessionTime);
- }
- prop.putHTML("list_" + idx + "_source",(seed!=null)?seed.getName()+".yacy":userAddress.getHostAddress()+":"+userPort);
- prop.putHTML("list_" + idx + "_dest", "-");
- if (blockingRequest) {
- prop.put("list_" + idx + "_running", "0");
- prop.putNum("list_" + idx + "_running_reqNr", commandCount+1);
- numActivePending++;
- } else {
- prop.put("list_" + idx + "_running", "1");
- prop.put("list_" + idx + "_running_command", commandLine==null ? "" :commandLine);
- numActiveRunning++;
- }
- prop.putNum("list_" + idx + "_used", commandCount);
- idx++;
- }
+ int idx = 0, numActivePending = 0;
prop.put("list", idx);
prop.putNum("numMax", httpd.getMaxSessionCount());
diff --git a/htroot/yacy/hello.java b/htroot/yacy/hello.java
index 17a1f1066..6a499572a 100644
--- a/htroot/yacy/hello.java
+++ b/htroot/yacy/hello.java
@@ -52,7 +52,7 @@ public final class hello {
// example:
// http://localhost:8090/yacy/hello.html?count=1&seed=p|{Hash=sCJ6Tq8T0N9x,Port=8090,PeerType=junior}
// http://localhost:8090/yacy/hello.html?count=10&seed=z|H4sIAAAAAAAAADWQW2vDMAyF_81eJork3GyGX-YxGigly2WFvZTQijbQJsHx1pWx_z7nMj1J4ug7B_2s6-GsP5q3G-G6vBz2e0iz8t6zfuBr7-5PUNanQfulhqyzTkuUCFXvmitrBJtq4ed3tkPTtRpXhIiRDAmq0uhHFIiQMduJ-NXYU9NCbrrP1vnjIdUqgk09uIK51V6rMBRIilAo2NajwzfhGcx8QUKsEIp5iCJo-eaTVUXPfPQ4k5dm4pp8NzaESsLzS-14QVNIMlA-ka2m1JuZJJWIBRwPo0GIIiYp4zCSkC5GQSLiJIah0p6X_rvlS-MTbWdhkCSBIni9jA_rfP3-Ae1Oye9dAQAA
- public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws InterruptedException {
+ public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
final Switchboard sb = (Switchboard) env;
final serverObjects prop = new serverObjects();
final long start = System.currentTimeMillis();
@@ -146,7 +146,6 @@ public final class hello {
!clientip.equals(reportedip) &&
clientversion >= yacyVersion.YACY_SUPPORTS_PORT_FORWARDING &&
magic != 0) {
- serverCore.checkInterruption();
// try first the reportedip, since this may be a connect from a port-forwarding host
prop.put("yourip", reportedip);
@@ -171,7 +170,6 @@ public final class hello {
}
if (isNotLocal) {
- serverCore.checkInterruption();
prop.put("yourip", clientip);
remoteSeed.setIP(clientip);
@@ -221,7 +219,6 @@ public final class hello {
"' to '" + prop.get(Seed.YOURTYPE) + "'.");
}
- serverCore.checkInterruption();
final StringBuilder seeds = new StringBuilder(768);
// attach some more seeds, as requested
if (sb.peers.sizeConnected() > 0) {
diff --git a/htroot/yacy/transferRWI.java b/htroot/yacy/transferRWI.java
index 03aa000f0..904cac4a8 100644
--- a/htroot/yacy/transferRWI.java
+++ b/htroot/yacy/transferRWI.java
@@ -53,13 +53,12 @@ import net.yacy.peers.Seed;
import net.yacy.repository.Blacklist.BlacklistType;
import net.yacy.search.Switchboard;
import net.yacy.search.SwitchboardConstants;
-import net.yacy.server.serverCore;
import net.yacy.server.serverObjects;
import net.yacy.server.serverSwitch;
public final class transferRWI {
- public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) throws InterruptedException {
+ public static serverObjects respond(final RequestHeader header, final serverObjects post, final serverSwitch env) {
// return variable that accumulates replacements
final Switchboard sb = (Switchboard) env;
@@ -170,7 +169,6 @@ public final class transferRWI {
int count = 0;
Set<String> testids = new HashSet<String>();
while (it.hasNext()) {
- serverCore.checkInterruption();
estring = it.next();
count++;
if (count > 1000) break; // protection against flooding
@@ -208,7 +206,6 @@ public final class transferRWI {
} catch (final Exception e) {
ConcurrentLog.logException(e);
}
- serverCore.checkInterruption();
// check if we need to ask for the corresponding URL
testids.add(ASCII.String(urlHash));
diff --git a/htroot/yacy/transferURL.java b/htroot/yacy/transferURL.java
index 746d42c3d..0fa03f33c 100644
--- a/htroot/yacy/transferURL.java
+++ b/htroot/yacy/transferURL.java
@@ -47,13 +47,12 @@ import net.yacy.peers.Seed;
import net.yacy.repository.Blacklist.BlacklistType;
import net.yacy.search.Switchboard;
import net.yacy.search.SwitchboardConstants;
-import net.yacy.server.serverCore;
import net.yacy.server.serverObjects;
import net.yacy.server.serverSwitch;
public final class transferURL {
- public static serverObjects respond(@SuppressWarnings("unused") final RequestHeader header, final serverObjects post, final serverSwitch env) throws InterruptedException {
+ public static serverObjects respond(@SuppressWarnings("unused") final RequestHeader header, final serverObjects post, final serverSwitch env) {
final long start = System.currentTimeMillis();
long freshdate = 0;
try {freshdate = GenericFormatter.SHORT_DAY_FORMATTER.parse("20061101").getTime();} catch (final ParseException e1) {}
@@ -94,7 +93,6 @@ public final class transferURL {
URIMetadataRow lEntry;
Map<String, URIMetadataRow> lEm = new HashMap<String, URIMetadataRow>();
for (int i = 0; i < urlc; i++) {
- serverCore.checkInterruption();
// read new lurl-entry
urls = post.get("url" + i);
diff --git a/source/net/yacy/http/Jetty8YaCySecurityHandler.java b/source/net/yacy/http/Jetty8YaCySecurityHandler.java
index dc140a907..73d55a29b 100644
--- a/source/net/yacy/http/Jetty8YaCySecurityHandler.java
+++ b/source/net/yacy/http/Jetty8YaCySecurityHandler.java
@@ -26,13 +26,15 @@ package net.yacy.http;
import java.io.IOException;
import java.net.MalformedURLException;
-import net.yacy.cora.document.id.MultiProtocolURL;
+import javax.servlet.http.HttpServletResponse;
+
+import net.yacy.cora.document.id.MultiProtocolURL;
import net.yacy.cora.protocol.Domains;
import net.yacy.search.Switchboard;
+
import org.eclipse.jetty.http.HttpSchemes;
import org.eclipse.jetty.security.RoleInfo;
-
import org.eclipse.jetty.security.SecurityHandler;
import org.eclipse.jetty.security.UserDataConstraint;
import org.eclipse.jetty.server.AbstractHttpConnection;
@@ -86,7 +88,7 @@ public class Jetty8YaCySecurityHandler extends SecurityHandler {
response.sendRedirect(url);
}
else
- response.sendError(Response.SC_FORBIDDEN,"!Integral");
+ response.sendError(HttpServletResponse.SC_FORBIDDEN,"!Integral");
request.setHandled(true);
return false;
@@ -109,7 +111,7 @@ public class Jetty8YaCySecurityHandler extends SecurityHandler {
response.sendRedirect(url);
}
else
- response.sendError(Response.SC_FORBIDDEN,"!Confidential");
+ response.sendError(HttpServletResponse.SC_FORBIDDEN,"!Confidential");
request.setHandled(true);
return false;
diff --git a/source/net/yacy/http/ProxyHandler.java b/source/net/yacy/http/ProxyHandler.java
index ed33dc19f..28abb168d 100644
--- a/source/net/yacy/http/ProxyHandler.java
+++ b/source/net/yacy/http/ProxyHandler.java
@@ -61,11 +61,9 @@ public class ProxyHandler extends AbstractRemoteHandler implements Handler {
static RequestHeader convertHeaderFromJetty(HttpServletRequest request) {
RequestHeader result = new RequestHeader();
- @SuppressWarnings("unchecked")
Enumeration<String> headerNames = request.getHeaderNames();
while(headerNames.hasMoreElements()) {
String headerName = headerNames.nextElement();
- @SuppressWarnings("unchecked")
Enumeration<String> headers = request.getHeaders(headerName);
while(headers.hasMoreElements()) {
String header = headers.nextElement();
@@ -94,7 +92,7 @@ public class ProxyHandler extends AbstractRemoteHandler implements Handler {
final String httpVer = request.getHeader(HeaderFramework.CONNECTION_PROP_HTTP_VER);
setViaHeader (proxyHeaders, httpVer);
proxyHeaders.remove(RequestHeader.KEEP_ALIVE);
- proxyHeaders.remove(RequestHeader.CONTENT_LENGTH);
+ proxyHeaders.remove(HeaderFramework.CONTENT_LENGTH);
final HTTPClient client = new HTTPClient(ClientIdentification.yacyProxyAgent);
int timeout = 60000;
diff --git a/source/net/yacy/http/YaCyDefaultServlet.java b/source/net/yacy/http/YaCyDefaultServlet.java
index c3d59ad48..7403647a2 100644
--- a/source/net/yacy/http/YaCyDefaultServlet.java
+++ b/source/net/yacy/http/YaCyDefaultServlet.java
@@ -45,6 +45,7 @@ import javax.servlet.UnavailableException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
+
import net.yacy.cora.date.GenericFormatter;
import net.yacy.cora.document.analysis.Classification;
import net.yacy.cora.protocol.HeaderFramework;
@@ -65,13 +66,13 @@ import net.yacy.server.serverObjects;
import net.yacy.server.serverSwitch;
import net.yacy.server.servletProperties;
import net.yacy.visualization.RasterPlotter;
+
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.http.HttpMethods;
-
import org.eclipse.jetty.http.MimeTypes;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.WriterOutputStream;
@@ -470,7 +471,7 @@ public class YaCyDefaultServlet extends HttpServlet {
HttpServletResponse response,
boolean include,
Resource resource,
- Enumeration reqRanges)
+ Enumeration<String> reqRanges)
throws IOException {
final long content_length = resource.length();
@@ -494,7 +495,7 @@ public class YaCyDefaultServlet extends HttpServlet {
}
} else {
// Parse the satisfiable ranges
- List ranges = InclusiveByteRange.satisfiableRanges(reqRanges, content_length);
+ List<?> ranges = InclusiveByteRange.satisfiableRanges(reqRanges, content_length);
// if there are no satisfiable ranges, send 416 response
if (ranges == null || ranges.size() == 0) {
@@ -727,7 +728,6 @@ public class YaCyDefaultServlet extends HttpServlet {
if ((targetClass != null)) {
serverObjects args = new serverObjects();
- @SuppressWarnings("unchecked")
Enumeration<String> argNames = request.getParameterNames();
while (argNames.hasMoreElements()) {
String argName = argNames.nextElement();
@@ -735,7 +735,6 @@ public class YaCyDefaultServlet extends HttpServlet {
}
//TODO: for SSI request, local parameters are added as attributes, put them back as parameter for the legacy request
// likely this should be implemented via httpservletrequestwrapper to supply complete parameters
- @SuppressWarnings("unchecked")
Enumeration<String> attNames = request.getAttributeNames();
while (attNames.hasMoreElements()) {
String argName = attNames.nextElement();
@@ -900,7 +899,7 @@ public class YaCyDefaultServlet extends HttpServlet {
}
// parse SSI line and include resource
- protected void parseSSI(final net.yacy.cora.util.ByteBuffer in, final int off, HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
+ protected void parseSSI(final net.yacy.cora.util.ByteBuffer in, final int off, HttpServletRequest request, HttpServletResponse response) throws ServletException {
if (in.startsWith("<!--#include virtual=\"".getBytes(), off)) {
final int q = in.indexOf("\"".getBytes(), off + 22);
if (q > 0) {
diff --git a/source/net/yacy/http/YaCyLegacyCredential.java b/source/net/yacy/http/YaCyLegacyCredential.java
index dbd7a4abb..39d14e570 100644
--- a/source/net/yacy/http/YaCyLegacyCredential.java
+++ b/source/net/yacy/http/YaCyLegacyCredential.java
@@ -60,9 +60,8 @@ public class YaCyLegacyCredential extends Credential {
if(credentials instanceof String) {
final String pw = (String) credentials;
return calcHash(pw).equals(this.hash);
- } else {
- throw new UnsupportedOperationException();
}
+ throw new UnsupportedOperationException();
}
/**
diff --git a/source/net/yacy/http/YaCyProxyServlet.java b/source/net/yacy/http/YaCyProxyServlet.java
index c6c710b33..c2d47f49a 100644
--- a/source/net/yacy/http/YaCyProxyServlet.java
+++ b/source/net/yacy/http/YaCyProxyServlet.java
@@ -85,212 +85,211 @@ public class YaCyProxyServlet extends ProxyServlet implements Servlet {
if (!continuation.isInitial()) {
response.sendError(HttpServletResponse.SC_GATEWAY_TIMEOUT); // Need better test that isInitial
return;
- } else {
- URL proxyurl = null;
- String strARGS = request.getQueryString();
- if (strARGS == null) {
- response.sendError(HttpServletResponse.SC_NOT_FOUND,"url parameter missing");
- return;
- }
+ }
+ URL proxyurl = null;
+ String strARGS = request.getQueryString();
+ if (strARGS == null) {
+ response.sendError(HttpServletResponse.SC_NOT_FOUND,"url parameter missing");
+ return;
+ }
- if (strARGS.startsWith("action=")) {
- int detectnextargument = strARGS.indexOf("&");
- action = strARGS.substring(7, detectnextargument);
- strARGS = strARGS.substring(detectnextargument + 1);
- }
- if (strARGS.startsWith("url=")) {
- final String strUrl = strARGS.substring(4); // strip "url="
+ if (strARGS.startsWith("action=")) {
+ int detectnextargument = strARGS.indexOf("&");
+ action = strARGS.substring(7, detectnextargument);
+ strARGS = strARGS.substring(detectnextargument + 1);
+ }
+ if (strARGS.startsWith("url=")) {
+ final String strUrl = strARGS.substring(4); // strip "url="
- try {
- proxyurl = new URL(strUrl);
- } catch (final MalformedURLException e) {
- proxyurl = new URL(URLDecoder.decode(strUrl, UTF8.charset.name()));
+ try {
+ proxyurl = new URL(strUrl);
+ } catch (final MalformedURLException e) {
+ proxyurl = new URL(URLDecoder.decode(strUrl, UTF8.charset.name()));
- }
- }
- if (proxyurl == null) {
- response.sendError(HttpServletResponse.SC_NOT_FOUND,"url parameter missing");
- return;
- }
- int port = proxyurl.getPort();
- if (port < 1) {
- port = 80;
}
+ }
+ if (proxyurl == null) {
+ response.sendError(HttpServletResponse.SC_NOT_FOUND,"url parameter missing");
+ return;
+ }
+ int port = proxyurl.getPort();
+ if (port < 1) {
+ port = 80;
+ }
- String host = proxyurl.getHost();
- if (proxyurl.getPort() != -1) {
- host += ":" + proxyurl.getPort();
- }
- RequestHeader yacyRequestHeader = ProxyHandler.convertHeaderFromJetty(request);
- yacyRequestHeader.remove(RequestHeader.KEEP_ALIVE);
- yacyRequestHeader.remove(RequestHeader.CONTENT_LENGTH);
-
- final HashMap<String, Object> prop = new HashMap<String, Object>();
- prop.put(HeaderFramework.CONNECTION_PROP_HTTP_VER, HeaderFramework.HTTP_VERSION_1_1);
- prop.put(HeaderFramework.CONNECTION_PROP_HOST, proxyurl.getHost());
- prop.put(HeaderFramework.CONNECTION_PROP_PATH, proxyurl.getFile().replaceAll(" ", "%20"));
- prop.put(HeaderFramework.CONNECTION_PROP_REQUESTLINE, "PROXY");
- prop.put("CLIENTIP", "0:0:0:0:0:0:0:1");
-
- yacyRequestHeader.put(HeaderFramework.HOST, proxyurl.getHost());
- // temporarily add argument to header to pass it on to augmented browsing
- if (action != null) yacyRequestHeader.put("YACYACTION", action);
-
- final ByteArrayOutputStream tmpproxyout = new ByteArrayOutputStream();
- HTTPDProxyHandler.doGet(prop, yacyRequestHeader, tmpproxyout, ClientIdentification.yacyProxyAgent);
-
- // reparse header to extract content-length and mimetype
- final ResponseHeader outgoingHeader = new ResponseHeader(200); //
- final InputStream proxyout = new ByteArrayInputStream(tmpproxyout.toByteArray());
- String line = readLine(proxyout);
- while (line != null && !line.equals("")) {
- int p;
- if ((p = line.indexOf(':')) >= 0) {
- // store a property
- outgoingHeader.add(line.substring(0, p).trim(), line.substring(p + 1).trim());
- }
- line = readLine(proxyout);
- }
- if (line == null) {
- response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Proxy Header missing");
- return;
+ String host = proxyurl.getHost();
+ if (proxyurl.getPort() != -1) {
+ host += ":" + proxyurl.getPort();
+ }
+ RequestHeader yacyRequestHeader = ProxyHandler.convertHeaderFromJetty(request);
+ yacyRequestHeader.remove(RequestHeader.KEEP_ALIVE);
+ yacyRequestHeader.remove(HeaderFramework.CONTENT_LENGTH);
+
+ final HashMap<String, Object> prop = new HashMap<String, Object>();
+ prop.put(HeaderFramework.CONNECTION_PROP_HTTP_VER, HeaderFramework.HTTP_VERSION_1_1);
+ prop.put(HeaderFramework.CONNECTION_PROP_HOST, proxyurl.getHost());
+ prop.put(HeaderFramework.CONNECTION_PROP_PATH, proxyurl.getFile().replaceAll(" ", "%20"));
+ prop.put(HeaderFramework.CONNECTION_PROP_REQUESTLINE, "PROXY");
+ prop.put("CLIENTIP", "0:0:0:0:0:0:0:1");
+
+ yacyRequestHeader.put(HeaderFramework.HOST, proxyurl.getHost());
+ // temporarily add argument to header to pass it on to augmented browsing
+ if (action != null) yacyRequestHeader.put("YACYACTION", action);
+
+ final ByteArrayOutputStream tmpproxyout = new ByteArrayOutputStream();
+ HTTPDProxyHandler.doGet(prop, yacyRequestHeader, tmpproxyout, ClientIdentification.yacyProxyAgent);
+
+ // reparse header to extract content-length and mimetype
+ final ResponseHeader outgoingHeader = new ResponseHeader(200); //
+ final InputStream proxyout = new ByteArrayInputStream(tmpproxyout.toByteArray());
+ String line = readLine(proxyout);
+ while (line != null && !line.equals("")) {
+ int p;
+ if ((p = line.indexOf(':')) >= 0) {
+ // store a property
+ outgoingHeader.add(line.substring(0, p).trim(), line.substring(p + 1).trim());
}
+ line = readLine(proxyout);
+ }
+ if (line == null) {
+ response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR,"Proxy Header missing");
+ return;
+ }
- final int httpStatus = Integer.parseInt((String) prop.get(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_STATUS));
+ final int httpStatus = Integer.parseInt((String) prop.get(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_STATUS));
- String directory = "";
- if (proxyurl.getPath().lastIndexOf('/') > 0) {
- directory = proxyurl.getPath().substring(0, proxyurl.getPath().lastIndexOf('/'));
- }
-
- if (response.getHeader(HeaderFramework.LOCATION) != null) {
- // rewrite location header
- String location = response.getHeader(HeaderFramework.LOCATION);
- String actioncmdstr = (action != null) ? "action=" + action + "&" : "";
- if (location.startsWith("http")) {
- location = "/proxy.html?" + actioncmdstr + "url=" + location;
- } else {
- location = "/proxy.html?" + actioncmdstr + "url=http://" + proxyurl.getHost() + "/" + location;
- }
- //outgoingHeader.put(HeaderFramework.LOCATION, location);
- response.addHeader(HeaderFramework.LOCATION, location);
+ String directory = "";
+ if (proxyurl.getPath().lastIndexOf('/') > 0) {
+ directory = proxyurl.getPath().substring(0, proxyurl.getPath().lastIndexOf('/'));
+ }
+
+ if (response.getHeader(HeaderFramework.LOCATION) != null) {
+ // rewrite location header
+ String location = response.getHeader(HeaderFramework.LOCATION);
+ String actioncmdstr = (action != null) ? "action=" + action + "&" : "";
+ if (location.startsWith("http")) {
+ location = "/proxy.html?" + actioncmdstr + "url=" + location;
+ } else {
+ location = "/proxy.html?" + actioncmdstr + "url=http://" + proxyurl.getHost() + "/" + location;
}
+ //outgoingHeader.put(HeaderFramework.LOCATION, location);
+ response.addHeader(HeaderFramework.LOCATION, location);
+ }
- //final String mimeType = outgoingHeader.getContentType();
- final String mimeType = outgoingHeader.getContentType();
- if ((mimeType != null) && (mimeType.startsWith("text/html") || mimeType.startsWith("text"))) {
- final StringWriter buffer = new StringWriter();
-
- if (outgoingHeader.containsKey(HeaderFramework.TRANSFER_ENCODING)) {
- FileUtils.copy(new ChunkedInputStream(proxyout), buffer, UTF8.charset);
- } else {
- FileUtils.copy(proxyout, buffer, UTF8.charset);
- }
- final String sbuffer = buffer.toString();
-
- final Pattern p = Pattern.compile("(href=\"|src=\")([^\"]+)|(href='|src=')([^']+)|(url\\(')([^']+)|(url\\(\")([^\"]+)|(url\\()([^\\)]+)");
- final Matcher m = p.matcher(sbuffer);
- final StringBuffer result = new StringBuffer(80);
- Switchboard sb = Switchboard.getSwitchboard();
- while (m.find()) {
- String init = null;
- if (m.group(1) != null) { init = m.group(1); }
- if (m.group(3) != null) { init = m.group(3); }
- if (m.group(5) != null) { init = m.group(5); }
- if (m.group(7) != null) { init = m.group(7); }
- if (m.group(9) != null) { init = m.group(9); }
- String url = null;
- if (m.group(2) != null) { url = m.group(2); }
- if (m.group(4) != null) { url = m.group(4); }
- if (m.group(6) != null) { url = m.group(6); }
- if (m.group(8) != null) { url = m.group(8); }
- if (m.group(10) != null) { url = m.group(10); }
- if (url.startsWith("data:") || url.startsWith("#") || url.startsWith("mailto:") || url.startsWith("javascript:")) {
- String newurl = init + url;
- newurl = newurl.replaceAll("\\$", "\\\\\\$");
- m.appendReplacement(result, newurl);
+ //final String mimeType = outgoingHeader.getContentType();
+ final String mimeType = outgoingHeader.getContentType();
+ if ((mimeType != null) && (mimeType.startsWith("text/html") || mimeType.startsWith("text"))) {
+ final StringWriter buffer = new StringWriter();
- } else if (url.startsWith("http")) {
- // absoulte url of form href="http://domain.com/path"
- if (sb.getConfig("proxyURL.rewriteURLs", "all").equals("domainlist")) {
- try {
- if (sb.crawlStacker.urlInAcceptedDomain(new DigestURL(url)) != null) {
- continue;
- }
- } catch (final MalformedURLException e) {
- ConcurrentLog.fine("PROXY","ProxyServlet: malformed url for url-rewirte " + url);
+ if (outgoingHeader.containsKey(HeaderFramework.TRANSFER_ENCODING)) {
+ FileUtils.copy(new ChunkedInputStream(proxyout), buffer, UTF8.charset);
+ } else {
+ FileUtils.copy(proxyout, buffer, UTF8.charset);
+ }
+ final String sbuffer = buffer.toString();
+
+ final Pattern p = Pattern.compile("(href=\"|src=\")([^\"]+)|(href='|src=')([^']+)|(url\\(')([^']+)|(url\\(\")([^\"]+)|(url\\()([^\\)]+)");
+ final Matcher m = p.matcher(sbuffer);
+ final StringBuffer result = new StringBuffer(80);
+ Switchboard sb = Switchboard.getSwitchboard();
+ while (m.find()) {
+ String init = null;
+ if (m.group(1) != null) { init = m.group(1); }
+ if (m.group(3) != null) { init = m.group(3); }
+ if (m.group(5) != null) { init = m.group(5); }
+ if (m.group(7) != null) { init = m.group(7); }
+ if (m.group(9) != null) { init = m.group(9); }
+ String url = null;
+ if (m.group(2) != null) { url = m.group(2); }
+ if (m.group(4) != null) { url = m.group(4); }
+ if (m.group(6) != null) { url = m.group(6); }
+ if (m.group(8) != null) { url = m.group(8); }
+ if (m.group(10) != null) { url = m.group(10); }
+ if (url.startsWith("data:") || url.startsWith("#") || url.startsWith("mailto:") || url.startsWith("javascript:")) {
+ String newurl = init + url;
+ newurl = newurl.replaceAll("\\$", "\\\\\\$");
+ m.appendReplacement(result, newurl);
+
+ } else if (url.startsWith("http")) {
+ // absoulte url of form href="http://domain.com/path"
+ if (sb.getConfig("proxyURL.rewriteURLs", "all").equals("domainlist")) {
+ try {
+ if (sb.crawlStacker.urlInAcceptedDomain(new DigestURL(url)) != null) {
continue;
}
+ } catch (final MalformedURLException e) {
+ ConcurrentLog.fine("PROXY","ProxyServlet: malformed url for url-rewirte " + url);
+ continue;
}
+ }
- String newurl = init + "/proxy.html?url=" + url;
- newurl = newurl.replaceAll("\\$", "\\\\\\$");
- m.appendReplacement(result, newurl);
+ String newurl = init + "/proxy.html?url=" + url;
+ newurl = newurl.replaceAll("\\$", "\\\\\\$");
+ m.appendReplacement(result, newurl);
- } else if (url.startsWith("//")) {
- // absoulte url but same protocol of form href="//domain.com/path"
- final String complete_url = proxyurl.getProtocol() + ":" + url;
- if (sb.getConfig("proxyURL.rewriteURLs", "all").equals("domainlist")) {
- try {
- if (sb.crawlStacker.urlInAcceptedDomain(new DigestURL(complete_url)) != null) {
- continue;
- }
- } catch (MalformedURLException ex) {
- ConcurrentLog.fine("PROXY","ProxyServlet: malformed url for url-rewirte " + complete_url);
- continue;
- }
+ } else if (url.startsWith("//")) {
+ // absoulte url but same protocol of form href="//domain.com/path"
+ final String complete_url = proxyurl.getProtocol() + ":" + url;
+ if (sb.getConfig("proxyURL.rewriteURLs", "all").equals("domainlist")) {
+ try {
+ if (sb.crawlStacker.urlInAcceptedDomain(new DigestURL(complete_url)) != null) {
+ continue;
+ }
+ } catch (MalformedURLException ex) {
+ ConcurrentLog.fine("PROXY","ProxyServlet: malformed url for url-rewirte " + complete_url);
+ continue;
}
+ }
- String newurl = init + "/proxy.html?url=" + complete_url;
- newurl = newurl.replaceAll("\\$", "\\\\\\$");
- m.appendReplacement(result, newurl);
+ String newurl = init + "/proxy.html?url=" + complete_url;
+ newurl = newurl.replaceAll("\\$", "\\\\\\$");
+ m.appendReplacement(result, newurl);
+
+ } else if (url.startsWith("/")) {
+ // absolute path of form href="/absolute/path/to/linked/page"
+ String newurl = init + "/proxy.html?url=http://" + host + url;
+ newurl = newurl.replaceAll("\\$", "\\\\\\$");
+ m.appendReplacement(result, newurl);
- } else if (url.startsWith("/")) {
- // absolute path of form href="/absolute/path/to/linked/page"
- String newurl = init + "/proxy.html?url=http://" + host + url;
+ } else {
+ // relative path of form href="relative/path"
+ try {
+ MultiProtocolURL target = new MultiProtocolURL("http://" + host + directory + "/" + url);
+ String newurl = init + "/proxy.html?url=" + target.toString();
newurl = newurl.replaceAll("\\$", "\\\\\\$");
m.appendReplacement(result, newurl);
-
- } else {
- // relative path of form href="relative/path"
- try {
- MultiProtocolURL target = new MultiProtocolURL("http://" + host + directory + "/" + url);
- String newurl = init + "/proxy.html?url=" + target.toString();
- newurl = newurl.replaceAll("\\$", "\\\\\\$");
- m.appendReplacement(result, newurl);
- } catch (final MalformedURLException e) {}
- }
+ } catch (final MalformedURLException e) {}
}
- m.appendTail(result);
-
- byte[] sbb = UTF8.getBytes(result.toString());
-
- // add some proxy-headers to response header
- response.setContentType(outgoingHeader.getContentType());
- if (outgoingHeader.containsKey(HeaderFramework.SERVER)) {
- response.addHeader(HeaderFramework.SERVER, outgoingHeader.get(HeaderFramework.SERVER));
- }
- if (outgoingHeader.containsKey(HeaderFramework.DATE)) {
- response.addHeader(HeaderFramework.DATE, outgoingHeader.get(HeaderFramework.DATE));
- }
- if (outgoingHeader.containsKey(HeaderFramework.LAST_MODIFIED)) {
- response.addHeader(HeaderFramework.LAST_MODIFIED, outgoingHeader.get(HeaderFramework.LAST_MODIFIED));
- }
- if (outgoingHeader.containsKey(HeaderFramework.EXPIRES)) {
- response.addHeader(HeaderFramework.EXPIRES, outgoingHeader.get(HeaderFramework.EXPIRES));
- }
-
- response.setStatus(httpStatus);
- response.addIntHeader(HeaderFramework.CONTENT_LENGTH, sbb.length);
- response.getOutputStream().write(sbb);
-
- } else {
- if ((response.getHeader(HeaderFramework.CONTENT_LENGTH) == null) && prop.containsKey(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_SIZE)) {
- response.addHeader(HeaderFramework.CONTENT_LENGTH, (String) prop.get(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_SIZE));
- }
- response.setStatus(httpStatus);
- FileUtils.copy(proxyout, response.getOutputStream());
}
+ m.appendTail(result);
+
+ byte[] sbb = UTF8.getBytes(result.toString());
+
+ // add some proxy-headers to response header
+ response.setContentType(outgoingHeader.getContentType());
+ if (outgoingHeader.containsKey(HeaderFramework.SERVER)) {
+ response.addHeader(HeaderFramework.SERVER, outgoingHeader.get(HeaderFramework.SERVER));
+ }
+ if (outgoingHeader.containsKey(HeaderFramework.DATE)) {
+ response.addHeader(HeaderFramework.DATE, outgoingHeader.get(HeaderFramework.DATE));
+ }
+ if (outgoingHeader.containsKey(HeaderFramework.LAST_MODIFIED)) {
+ response.addHeader(HeaderFramework.LAST_MODIFIED, outgoingHeader.get(HeaderFramework.LAST_MODIFIED));
+ }
+ if (outgoingHeader.containsKey(HeaderFramework.EXPIRES)) {
+ response.addHeader(HeaderFramework.EXPIRES, outgoingHeader.get(HeaderFramework.EXPIRES));
+ }
+
+ response.setStatus(httpStatus);
+ response.addIntHeader(HeaderFramework.CONTENT_LENGTH, sbb.length);
+ response.getOutputStream().write(sbb);
+
+ } else {
+ if ((response.getHeader(HeaderFramework.CONTENT_LENGTH) == null) && prop.containsKey(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_SIZE)) {
+ response.addHeader(HeaderFramework.CONTENT_LENGTH, (String) prop.get(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_SIZE));
+ }
+ response.setStatus(httpStatus);
+ FileUtils.copy(proxyout, response.getOutputStream());
}
}
}
diff --git a/source/net/yacy/http/YacyDomainHandler.java b/source/net/yacy/http/YacyDomainHandler.java
index e9815c3e6..7041b5c35 100644
--- a/source/net/yacy/http/YacyDomainHandler.java
+++ b/source/net/yacy/http/YacyDomainHandler.java
@@ -125,7 +125,6 @@ public class YacyDomainHandler extends AbstractHandler implements Handler {
return super.getHeader(name);
}
- @SuppressWarnings("unchecked")
@Override
public Enumeration<String> getHeaders(String name) {
if (name.equals("Host")) {
diff --git a/source/net/yacy/interaction/AugmentHtmlStream.java b/source/net/yacy/interaction/AugmentHtmlStream.java
deleted file mode 100644
index eff2cd833..000000000
--- a/source/net/yacy/interaction/AugmentHtmlStream.java
+++ /dev/null
@@ -1,157 +0,0 @@
-package net.yacy.interaction;
-
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.StringReader;
-import java.net.URLEncoder;
-
-import net.yacy.cora.document.encoding.ASCII;
-import net.yacy.cora.document.id.DigestURL;
-import net.yacy.cora.protocol.ClientIdentification;
-import net.yacy.cora.protocol.Domains;
-import net.yacy.cora.protocol.RequestHeader;
-import net.yacy.cora.protocol.http.HTTPClient;
-import net.yacy.cora.util.ConcurrentLog;
-import net.yacy.search.Switchboard;
-import net.yacy.server.http.ServerSideIncludes;
-
-import org.jsoup.Jsoup;
-
-public class AugmentHtmlStream {
-
- static RequestHeader globalrequestHeader;
-
- /**
- * send web page to external REFLECT web service
- *
- * @return the web page with integrated REFLECT elements
- */
- private static String processExternal(String url, String fieldname, String data) throws IOException {
- final HTTPClient client = new HTTPClient(ClientIdentification.yacyInternetCrawlerAgent);
- try {
- StringBuilder postdata = new StringBuilder();
- postdata.append(fieldname);
- postdata.append('=');
- postdata.append(URLEncoder.encode(data, "UTF-8"));
- InputStream in = new ByteArrayInputStream(postdata.toString()
- .getBytes());
- byte[] result = client.POSTbytes(url, in, postdata.length());
- if (result != null) {
- return new String(result);
- }
- } finally {
- client.finish();
- }
- return null;
- }
-
- private static String loadInternal(String path, RequestHeader requestHeader) {
- ByteArrayOutputStream buffer = new ByteArrayOutputStream();
- String realmProp = requestHeader.get(RequestHeader.AUTHORIZATION);
- ServerSideIncludes.writeContent(path, buffer, realmProp, Domains.LOCALHOST, requestHeader); // TODO: ip
- return buffer.toString();
- }
-
- /**
- * add DOCTYPE if necessary
- *
- * @return the web page with a leading DOCTYPE definition
- */
- private static String processAddDoctype(String data) {
-
- String result = data;
-
- BufferedReader reader = new BufferedReader(new StringReader(data));
-
- try {
- String firstline = reader.readLine();
-
- if (firstline != null) {
- if (!firstline.startsWith("<!DOCTYPE")) {
- result = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\" \"http://www.w3.org/TR/html4/loose.dtd\">\n"
- + data;
- }
- }
- } catch (final IOException e1) {
-
- }
-
- return result;
-
- }
-
- public static StringBuilder process(StringBuilder data, DigestURL url, RequestHeader requestHeader) {
-
- String action = requestHeader.get("YACYACTION");
- requestHeader.remove("YACYACTION");
-
- globalrequestHeader = requestHeader;
-
- Switchboard sb = Switchboard.getSwitchboard();
-
- boolean augmented = false;
-
- try {
- ConcurrentLog.info("AUGMENTATION", url.getName());
- } catch (final IOException e1) {
- // TODO Auto-generated catch block
- e1.printStackTrace();
- }
-
- String Doc = data.toString();
-
- // Send document to REFLECT (http://www.reflect.ws/REST_API.html)
- if (sb.getConfigBool("augmentation.reflect", false) == true) {
- try {
-
- Doc = processExternal("http://reflect.ws/REST/GetHTML", "document", Doc);
- ConcurrentLog.info("AUGMENTATION", "reflected " + url);
- augmented = true;
- } catch (final Exception e) {
-
- }
- }
-
- // Add DOCTYPE if not present.
- // This is required for IE to render position:absolute correctly.
-
- if (sb.getConfigBool("augmentation.addDoctype", false) == true) {
- Doc = processAddDoctype(Doc);
- augmented = true;
- }
-
-
- if (sb.getConfigBool("augmentation.reparse", false) == true) {
-
- org.jsoup.nodes.Document d = Jsoup.parse(Doc);
-
- d.title ("yacy - "+d.title());
-
- if (sb.getConfigBool("interaction.overlayinteraction.enabled", false) == true) {
-
- d.head().append (loadInternal("env/templates/jqueryheader.template", requestHeader));
- d.head().append ("<script type='text/javascript'>"+loadInternal("interaction_elements/interaction.js", requestHeader)+"</script>");
- d.head().append ("<script type='text/javascript'>"+loadInternal("interaction_elements/interaction_metadata.js", requestHeader)+"</script>");
-
-
- d.body().append (loadInternal("interaction_elements/OverlayInteraction.html?action="+action+"&urlhash="+ ASCII.String(url.hash()) +"&url="+url.toNormalform(false), requestHeader));
- d.body().append (loadInternal("interaction_elements/Footer.html?action="+action+"&urlhash="+ ASCII.String(url.hash()) +"&url="+url.toNormalform(false), requestHeader));
-
- }
-
- Doc = d.html();
-
- augmented = true;
- }
-
-
- if (augmented) {
- return (new StringBuilder(Doc));
- }
- return (data);
- }
-
-}
\ No newline at end of file
diff --git a/source/net/yacy/server/http/AugmentedHtmlStream.java b/source/net/yacy/server/http/AugmentedHtmlStream.java
deleted file mode 100644
index 1f4308093..000000000
--- a/source/net/yacy/server/http/AugmentedHtmlStream.java
+++ /dev/null
@@ -1,64 +0,0 @@
-package net.yacy.server.http;
-
-import java.io.BufferedWriter;
-import java.io.ByteArrayOutputStream;
-import java.io.FilterOutputStream;
-import java.io.IOException;
-import java.io.OutputStream;
-import java.io.OutputStreamWriter;
-import java.io.Writer;
-import java.nio.charset.Charset;
-
-import net.yacy.cora.document.id.DigestURL;
-import net.yacy.cora.protocol.RequestHeader;
-import net.yacy.interaction.AugmentHtmlStream;
-
-public class AugmentedHtmlStream extends FilterOutputStream {
- private final Writer out;
- private final ByteArrayOutputStream buffer;
- private final Charset charset;
- private final DigestURL url;
- private final String urls;
- private final RequestHeader requestHeader;
-
- public AugmentedHtmlStream(OutputStream out, Charset charset, DigestURL url, RequestHeader requestHeader) {
- super(out);
- this.out = new BufferedWriter(new OutputStreamWriter(out, charset));
- this.buffer = new ByteArrayOutputStream();
- this.charset = charset;
- this.url = url;
- this.urls = this.url.toNormalform(false);
- this.requestHeader = requestHeader;
- }
-
- @Override
- public void write(int b) throws IOException {
- this.buffer.write(b);
- }
-
- @Override
- public void write(byte[] b, int off, int len) throws IOException {
- this.buffer.write(b, off, len);
- }
-
- @Override
- public void close() throws IOException {
- StringBuilder b = new StringBuilder(this.buffer.toString(this.charset.name()));
- b = process(b);
- this.out.write(b.toString());
- this.out.close();
- }
-
- public StringBuilder process(StringBuilder data) {
- if (this.urls.contains("StringBuilder/")) {
- return data;
- }
- return AugmentHtmlStream.process(data, this.url, this.requestHeader);
- }
-
- public static boolean supportsMime(String mime) {
-// System.out.println("mime" +mime);
- return mime.split(";")[0].equals("text/html");
- }
-
-}
diff --git a/source/net/yacy/server/http/HTTPDFileHandler.java b/source/net/yacy/server/http/HTTPDFileHandler.java
index b2d39b1e6..233a1916d 100644
--- a/source/net/yacy/server/http/HTTPDFileHandler.java
+++ b/source/net/yacy/server/http/HTTPDFileHandler.java
@@ -57,83 +57,19 @@
package net.yacy.server.http;
-import java.awt.Image;
-import java.awt.image.BufferedImage;
-import java.io.BufferedInputStream;
-import java.io.BufferedOutputStream;
-import java.io.BufferedReader;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
import java.io.File;
-import java.io.FileInputStream;
-import java.io.FileNotFoundException;
-import java.io.FileReader;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.StringWriter;
-import java.lang.ref.SoftReference;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.MalformedURLException;
-import java.net.URL;
-import java.net.URLDecoder;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Collection;
import java.util.Date;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.zip.GZIPOutputStream;
-import net.yacy.cora.date.GenericFormatter;
import net.yacy.cora.document.analysis.Classification;
-import net.yacy.cora.document.encoding.ASCII;
-import net.yacy.cora.document.encoding.UTF8;
-import net.yacy.cora.document.id.DigestURL;
-import net.yacy.cora.document.id.MultiProtocolURL;
-import net.yacy.cora.order.Digest;
-import net.yacy.cora.protocol.ClientIdentification;
-import net.yacy.cora.protocol.Domains;
-import net.yacy.cora.protocol.HeaderFramework;
-import net.yacy.cora.protocol.RequestHeader;
-import net.yacy.cora.protocol.ResponseHeader;
-import net.yacy.cora.util.ByteBuffer;
-import net.yacy.cora.util.CommonPattern;
import net.yacy.cora.util.ConcurrentLog;
-import net.yacy.cora.util.NumberTools;
-import net.yacy.data.UserDB;
-import net.yacy.document.parser.htmlParser;
-import net.yacy.document.parser.html.CharacterCoding;
-import net.yacy.document.parser.html.ContentScraper;
-import net.yacy.document.parser.html.ScraperInputStream;
-import net.yacy.kelondro.util.FileUtils;
-import net.yacy.kelondro.util.MemoryControl;
-import net.yacy.peers.Seed;
-import net.yacy.peers.graphics.EncodedImage;
-import net.yacy.peers.operation.yacyBuildProperties;
import net.yacy.search.Switchboard;
import net.yacy.search.SwitchboardConstants;
-import net.yacy.server.serverClassLoader;
-import net.yacy.server.serverCore;
-import net.yacy.server.serverObjects;
import net.yacy.server.serverSwitch;
-import net.yacy.server.servletProperties;
-import net.yacy.visualization.RasterPlotter;
public final class HTTPDFileHandler {
// create a class loader
- private static final serverClassLoader provider = new serverClassLoader(/*this.getClass().getClassLoader()*/);
private static serverSwitch switchboard = null;
- private static Switchboard sb = Switchboard.getSwitchboard();
- private final static byte[] UNRESOLVED_PATTERN = ASCII.getBytes("-UNRESOLVED_PATTERN-");
-
private static File htRootPath = null;
private static File htDocsPath = null;
@@ -146,20 +82,15 @@ public final class HTTPDFileHandler {
Date lastModified;
byte[] content;
}
- private static final ConcurrentHashMap<File, SoftReference<TemplateCacheEntry>> templateCache;
- private static final ConcurrentHashMap<File, SoftReference<Method>> templateMethodCache;
public static final boolean useTemplateCache;
//private Properties connectionProperties = null;
// creating a logger
- private static final ConcurrentLog theLogger = new ConcurrentLog("FILEHANDLER");
static {
final serverSwitch theSwitchboard = Switchboard.getSwitchboard();
useTemplateCache = theSwitchboard.getConfig("enableTemplateCache","true").equalsIgnoreCase("true");
- templateCache = (useTemplateCache)? new ConcurrentHashMap<File, SoftReference<TemplateCacheEntry>>() : new ConcurrentHashMap<File, SoftReference<TemplateCacheEntry>>(0);
- templateMethodCache = new ConcurrentHashMap<File, SoftReference<Method>>();
if (switchboard == null) {
switchboard = theSwitchboard;
@@ -194,7 +125,6 @@ public final class HTTPDFileHandler {
if (htDefaultPath == null) htDefaultPath = theSwitchboard.getAppPath("htDefaultPath", "htroot");
if (htLocalePath == null) htLocalePath = theSwitchboard.getDataPath("locale.translated_html", "DATA/LOCALE/htroot");
}
-
}
public static final void initDefaultPath() {
@@ -208,1133 +138,19 @@ public final class HTTPDFileHandler {
/** Returns a path to the localized or default file according to the locale.language (from he switchboard)
* @param path relative from htroot */
public static File getLocalizedFile(final String path){
- return getLocalizedFile(path, switchboard.getConfig("locale.language","default"));
- }
-
- /** Returns a path to the localized or default file according to the parameter localeSelection
- * @param path relative from htroot
- * @param localeSelection language of localized file; locale.language from switchboard is used if localeSelection.equals("") */
- public static File getLocalizedFile(final String path, final String localeSelection){
- //if (htDefaultPath == null) htDefaultPath = switchboard.getConfigPath("htDefaultPath", "htroot");
- //if (htLocalePath == null) htLocalePath = switchboard.getConfigPath("locale.translated_html", "DATA/LOCALE/htroot");
- //if (htDocsPath == null) htDocsPath = switchboard.getConfigPath(plasmaSwitchboardConstants.HTDOCS_PATH, plasmaSwitchboardConstants.HTDOCS_PATH_DEFAULT);
-
+ String localeSelection = switchboard.getConfig("locale.language","default");
if (path.startsWith("/repository/"))
return new File(switchboard.getConfig("repositoryPath", "DATA/HTDOCS/repository"), path.substring(11));
if (!(localeSelection.equals("default"))) {
final File localePath = new File(htLocalePath, localeSelection + '/' + path);
if (localePath.exists()) return localePath; // avoid "NoSuchFile" troubles if the "localeSelection" is misspelled
}
-
+
final File docsPath = new File(htDocsPath, path);
if (docsPath.exists()) return docsPath;
return new File(htDefaultPath, path);
}
- private static final ResponseHeader getDefaultHeaders(final String path) {
- final ResponseHeader headers = new ResponseHeader(200);
- String ext;
- int pos;
- if ((pos = path.lastIndexOf('.')) < 0) {
- ext = "";
- } else {
- ext = path.substring(pos + 1).toLowerCase();
- }
- headers.put(HeaderFramework.SERVER, "AnomicHTTPD (www.anomic.de)");
- headers.put(HeaderFramework.DATE, HeaderFramework.formatRFC1123(new Date()));
- if(!(Classification.isMediaExtension(ext))){
- headers.put(HeaderFramework.PRAGMA, "no-cache");
- }
- return headers;
- }
-
- public static void doGet(final HashMap<String, Object> conProp, final RequestHeader requestHeader, final OutputStream response) {
- doResponse(conProp, requestHeader, response, null);
- }
-
- public static void doHead(final HashMap<String, Object> conProp, final RequestHeader requestHeader, final OutputStream response) {
- doResponse(conProp, requestHeader, response, null);
- }
-
- public static void doPost(final HashMap<String, Object> conProp, final RequestHeader requestHeader, final OutputStream response, final InputStream body) {
- doResponse(conProp, requestHeader, response, body);
- }
-
- public static void doResponse(final HashMap<String, Object> conProp, final RequestHeader requestHeader, final OutputStream out, final InputStream body) {
-
- String path = null;
- try {
- // getting some connection properties
- final String method = (String) conProp.get(HeaderFramework.CONNECTION_PROP_METHOD);
- path = (String) conProp.get(HeaderFramework.CONNECTION_PROP_PATH);
- String argsString = (String) conProp.get(HeaderFramework.CONNECTION_PROP_ARGS); // is null if no args were given
- final String httpVersion = (String) conProp.get(HeaderFramework.CONNECTION_PROP_HTTP_VER);
- String clientIP = (String) conProp.get(HeaderFramework.CONNECTION_PROP_CLIENTIP); if (clientIP == null) clientIP = "unknown-host";
-
- // check hack attacks in path
- if (path.indexOf("..",0) >= 0) {
- HTTPDemon.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
- return;
- }
-
- path = UTF8.decodeURL(path);
-
- // check against hack attacks in path
- if (path.indexOf("..",0) >= 0) {
- HTTPDemon.sendRespondError(conProp,out,4,403,null,"Access not allowed",null);
- return;
- }
-
- // allow proper access to current peer via virtual directory
- if (path.startsWith("/currentyacypeer/")) {
- path = path.substring(16);
- }
-
- // cache settings
- boolean nocache = path.contains("?") || body != null;
-
- // a bad patch to map the /xml/ path to /api/
- if (path.startsWith("/xml/")) {
- path = "/api/" + path.substring(5);
- }
- // another bad patch to map the /util/ path to /api/util/ to support old yacybars
- if (path.startsWith("/util/")) {
- path = "/api/util/" + path.substring(6);
- }
- // one more for bookmarks
- if (path.startsWith("/bookmarks/")) {
- path = "/api/bookmarks/" + path.substring(11);
- }
- // another patch for the gsa interface
- if (path.startsWith("/gsa/search") && !path.startsWith("/gsa/searchresult")) {
- path = "/gsa/searchresult" + path.substring(11);
- }
-
- // these are the 5 cases where an access granted:
- // (the alternative is that we deliver a 401 to request authorization)
-
- // -1- the page is not protected; or
- final boolean protectedPage = path.indexOf("_p.",0) > 0;
- boolean accessGranted = !protectedPage;
-
- // -2- a password is not configured; or
- final String adminAccountBase64MD5 = switchboard.getConfig(SwitchboardConstants.ADMIN_ACCOUNT_B64MD5, "");
- if (!accessGranted) {
- accessGranted = adminAccountBase64MD5.isEmpty();
- }
-
- // -3- access from localhost is granted and access comes from localhost; or
- final String refererHost = requestHeader.refererHost();
- if (!accessGranted) {
- final boolean adminAccountForLocalhost = sb.getConfigBool("adminAccountForLocalhost", false);
- final boolean accessFromLocalhost = Domains.isLocalhost(clientIP) && (refererHost == null || refererHost.isEmpty() || Domains.isLocalhost(refererHost));
- accessGranted = adminAccountForLocalhost && accessFromLocalhost;
- }
-
- // -4- a password is configured and access comes from localhost
- // and the realm-value of a http-authentify String is equal to the stored base64MD5; or
- String realmProp = requestHeader.get(RequestHeader.AUTHORIZATION);
- if (realmProp != null && realmProp.isEmpty()) realmProp = null;
- final String realmValue = realmProp == null ? null : realmProp.substring(6);
- if (!accessGranted) {
- final boolean accessFromLocalhost = Domains.isLocalhost(clientIP) && (refererHost == null || refererHost.isEmpty() || Domains.isLocalhost(refererHost));
- accessGranted = accessFromLocalhost && realmValue != null && realmProp.length() > 6 && (adminAccountBase64MD5.equals(realmValue));
- //if (!accessGranted) Log.logInfo("HTTPDFileHandler", "access blocked, clientIP=" + clientIP + ", path=" + path);
- }
-
- // -5- a password is configured and access comes with matching http-authentify
- if (!accessGranted) {
- accessGranted = realmProp != null && realmValue != null && (sb.userDB.hasAdminRight(realmProp, requestHeader.getHeaderCookies()) || adminAccountBase64MD5.equals(Digest.encodeMD5Hex(realmValue)));
- }
-
- // in case that we are still not granted we ask for a password
- if (!accessGranted) {
- ConcurrentLog.info("HTTPD", "Wrong log-in for path '" + path + "' from host '" + clientIP + "'");
- final Integer attempts = serverCore.bfHost.get(clientIP);
- if (attempts == null)
- serverCore.bfHost.put(clientIP, Integer.valueOf(1));
- else
- serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
-
- final ResponseHeader responseHeader = getDefaultHeaders(path);
- responseHeader.put(RequestHeader.WWW_AUTHENTICATE, "Basic realm=\"" + serverObjects.ADMIN_AUTHENTICATE_MSG + "\"");
- final servletProperties tp=new servletProperties();
- tp.put("returnto", path);
- HTTPDemon.sendRespondError(conProp, out, 5, 401, "Wrong Authentication", "", new File("proxymsg/authfail.inc"), tp, null, responseHeader);
- return;
- }
-
- // Authentication successful. remove brute-force flag
- serverCore.bfHost.remove(conProp.get(HeaderFramework.CONNECTION_PROP_CLIENTIP));
-
- // parse arguments
- serverObjects args = new serverObjects();
- int argc = 0;
- if (argsString == null) {
- // no args here, maybe a POST with multipart extension
- final int length = requestHeader.getContentLength();
- //System.out.println("HEADER: " + requestHeader.toString()); // DEBUG
-
- /* don't parse body in case of a POST CGI call since it has to be
- * handed over to the CGI script unaltered and parsed by the script
- */
- if (method.equals(HeaderFramework.METHOD_POST) &&
- !(switchboard.getConfigBool("cgi.allow", false) &&
- matchesSuffix(path, switchboard.getConfig("cgi.suffixes", null)))
- ) {
-
- // if its a POST, it can be either multipart or as args in the body
- if ((requestHeader.containsKey(HeaderFramework.CONTENT_TYPE)) &&
- (requestHeader.get(HeaderFramework.CONTENT_TYPE).toLowerCase().startsWith("multipart"))) {
- // parse multipart
- final Map<String, byte[]> files = HTTPDemon.parseMultipart(requestHeader, args, body);
- // integrate these files into the args
- if (files != null) {
- final Iterator<Map.Entry<String, byte[]>> fit = files.entrySet().iterator();
- Map.Entry<String, byte[]> entry;
- while (fit.hasNext()) {
- entry = fit.next();
- args.add(entry.getKey() + "$file", entry.getValue());
- }
- }
- argc = Integer.parseInt(requestHeader.get("ARGC"));
- } else {
- // parse args in body
- argc = HTTPDemon.parseArgs(args, body, length);
- }
- } else {
- // no args
- argsString = null;
- args = null;
- argc = 0;
- }
- } else {
- // simple args in URL (stuff after the "?")
- argc = HTTPDemon.parseArgs(args, argsString);
- }
-
- // check for cross site scripting - attacks in request arguments
- if (args != null && argc > 0) {
- // check all values for occurrences of script values
- final Iterator<String> e = args.values().iterator(); // enumeration of values
- String val;
- while (e.hasNext()) {
- val = e.next();
- if ((val != null) && (val.indexOf("<script",0) >= 0) && !path.equals("/Crawler_p.html")) {
- // deny request
- HTTPDemon.sendRespondError(conProp,out,4,403,null,"bad post values",null);
- return;
- }
- }
- }
-
- if (args != null) nocache = true;
-
- // we are finished with parsing
- // the result of value hand-over is in args and argc
- if (path.isEmpty()) {
- HTTPDemon.sendRespondError(conProp,out,4,400,null,"Bad Request",null);
- out.flush();
- return;
- }
- File targetClass = null;
-
- // locate the file
- if (!path.isEmpty() && path.charAt(0) != '/' && path.charAt(0) != '\\') {
- path = "/" + path; // attach leading slash
- }
- if (path.endsWith("index.html")) {
- path = path.substring(0, path.length() - 10);
- }
-
- // a different language can be desired (by i.e. ConfigBasic.html) than the one stored in the locale.language
- String localeSelection = switchboard.getConfig("locale.language","default");
- if (args != null && (args.containsKey("language"))) {
- // TODO 9.11.06 Bost: a class with information about available languages is needed.
- // the indexOf(".") is just a workaround because there from ConfigLanguage.html commes "de.lng" and
- // from ConfigBasic.html comes just "de" in the "language" parameter
- localeSelection = args.get("language", localeSelection);
- if (localeSelection.indexOf('.') != -1)
- localeSelection = localeSelection.substring(0, localeSelection.indexOf('.'));
- }
-
- File targetFile = getLocalizedFile(path, localeSelection);
- String targetExt = (String) conProp.get("EXT"); if (targetExt == null) targetExt = "";
- targetClass = rewriteClassFile(new File(htDefaultPath, path));
- if (path.endsWith("/") || path.endsWith("\\")) {
- String testpath;
- // look for indexForward setting
- if (indexForward.length() > 0 && (targetFile = getOverlayedFile(path + indexForward)).exists()) {
- testpath = path + indexForward;
- targetClass = getOverlayedClass(testpath);
- path = testpath;
- } else {
- // attach default file name(s)
- for (final String defaultFile : defaultFiles) {
- testpath = path + defaultFile;
- targetFile = getOverlayedFile(testpath);
- targetClass = getOverlayedClass(testpath);
- if (targetFile.exists()) {
- path = testpath;
- break;
- }
- }
- }
- targetFile = getLocalizedFile(path, localeSelection);
-
- //no defaultfile, send a dirlisting
- if (targetFile == null || !targetFile.exists() || (targetFile.exists() && targetFile.isDirectory())) {
- final StringBuilder aBuffer = new StringBuilder();
- aBuffer.append("<html>\n<head>\n</head>\n<body>\n<h1>Index of " + CharacterCoding.unicode2html(path, true) + "</h1>\n <ul>\n");
- String[] list = targetFile.list();
- if (list == null) list = new String[0]; // should not occur!
- File f;
- String size;
- long sz;
- String headline, author, publisher;
- List<String> descriptions;
- int images, links;
- ContentScraper scraper;
- for (final String element : list) {
- f = new File(targetFile, element);
- if (f.isDirectory()) {
- aBuffer.append(" <li><a href=\"" + path + element + "/\">" + element + "/</a><br/></li>\n");
- } else {
- if (element.endsWith("html") || (element.endsWith("htm"))) {
- scraper = ContentScraper.parseResource(f, 10000);
- Collection<String> t = scraper.getTitles();
- headline = t.size() > 0 ? t.iterator().next() : "";
- author = scraper.getAuthor();
- publisher = scraper.getPublisher();
- descriptions = scraper.getDescriptions();
- images = scraper.getImages().size();
- links = scraper.getAnchors().size();
- } else {
- headline = null;
- author = null;
- publisher = null;
- descriptions = null;
- images = 0;
- links = 0;
- }
- sz = f.length();
- if (sz < 1024) {
- size = sz + " bytes";
- } else if (sz < 1024 * 1024) {
- size = (sz / 1024) + " KB";
- } else {
- size = (sz / 1024 / 1024) + " MB";
- }
- aBuffer.append(" <li>");
- if (headline != null && headline.length() > 0) aBuffer.append("<a href=\"" + element + "\"><b>" + headline + "</b></a><br/>");
- aBuffer.append("<a href=\"" + path + element + "\">" + element + "</a><br/>");
- if (author != null && author.length() > 0) aBuffer.append("Author: " + author + "<br/>");
- if (publisher != null && publisher.length() > 0) aBuffer.append("Publisher: " + publisher + "<br/>");
- if (descriptions != null && descriptions.size() > 0) {
- for (String d: descriptions) {
- aBuffer.append("Description: " + d + "<br/>");
- }
- }
- aBuffer.append(GenericFormatter.SHORT_DAY_FORMATTER.format(new Date(f.lastModified())) + ", " + size + ((images > 0) ? ", " + images + " images" : "") + ((links > 0) ? ", " + links + " links" : "") + "<br/></li>\n");
- }
- }
- aBuffer.append(" </ul>\n</body>\n</html>\n");
-
- // write the list to the client
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, 200, null, "text/html; charset=UTF-8", aBuffer.length(), new Date(targetFile.lastModified()), null, new ResponseHeader(200), null, null, true);
- if (!method.equals(HeaderFramework.METHOD_HEAD)) {
- out.write(UTF8.getBytes(aBuffer.toString()));
- }
- return;
- }
- } else {
- //XXX: you cannot share a .png/.gif file with a name like a class in htroot.
- if ( !(targetFile.exists()) &&
- !((path.endsWith("png")||path.endsWith("gif") || path.indexOf('.') < 0 ||
- matchesSuffix(path, switchboard.getConfig("cgi.suffixes", null)) ||
- path.endsWith(".stream")) &&
- targetClass!=null ) ){
- targetFile = new File(htDocsPath, path);
- targetClass = rewriteClassFile(new File(htDocsPath, path));
- }
- }
-
- // implement proxy via url (not in servlet, because we need binary access on ouputStream)
- if (path.equals("/proxy.html")) {
- final List<Pattern> urlProxyAccess = Domains.makePatterns(sb.getConfig("proxyURL.access", Domains.LOCALHOST));
- final UserDB.Entry user = sb.userDB.getUser(requestHeader);
- final boolean user_may_see_proxyurl = Domains.matchesList(clientIP, urlProxyAccess) || (user!=null && user.hasRight(UserDB.AccessRight.PROXY_RIGHT));
- if (sb.getConfigBool("proxyURL", false) && user_may_see_proxyurl) {
- doURLProxy(conProp, requestHeader, out);
- return;
- }
- HTTPDemon.sendRespondError(conProp,out,3,403,"Access denied",null,null);
- }
-
- // track all files that had been accessed so far
- if (targetFile != null && targetFile.exists()) {
- if (args != null && !args.isEmpty()) sb.setConfig("server.servlets.submitted", appendPath(sb.getConfig("server.servlets.submitted", ""), path));
- }
-
- //File targetClass = rewriteClassFile(targetFile);
- //We need tp here
- servletProperties templatePatterns = null;
- Date targetDate;
-
- if ((targetClass != null) && ((path.endsWith("png") || path.endsWith("gif")))) {
- // call an image-servlet to produce an on-the-fly - generated image
- Object img = null;
- requestHeader.put(HeaderFramework.CONNECTION_PROP_CLIENTIP, (String) conProp.get(HeaderFramework.CONNECTION_PROP_CLIENTIP));
- requestHeader.put(HeaderFramework.CONNECTION_PROP_PATH, path);
- requestHeader.put(HeaderFramework.CONNECTION_PROP_EXT, "png");
- // in case that there are no args given, args = null or empty hashmap
- img = invokeServlet(targetClass, requestHeader, args, null);
- if (img == null) {
- // error with image generation; send file-not-found
- HTTPDemon.sendRespondError(conProp, out, 3, 404, "File not Found", null, null);
- } else {
- if (img instanceof RasterPlotter) {
- final RasterPlotter yp = (RasterPlotter) img;
- // send an image to client
- targetDate = new Date(System.currentTimeMillis());
- nocache = true;
- final String mimeType = Classification.ext2mime(targetExt, "text/html");
- // write the array to the client
- if ("png".equals(targetExt)) {
- final byte[] result = ((RasterPlotter) img).pngEncode(1);
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length, targetDate, null, null, null, null, nocache);
- if (!method.equals(HeaderFramework.METHOD_HEAD)) {
- out.write(result);
- }
- } else {
- final ByteBuffer result = RasterPlotter.exportImage(yp.getImage(), targetExt);
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
- if (!method.equals(HeaderFramework.METHOD_HEAD)) {
- result.writeTo(out);
- }
- result.close();
- }
- }
- if (img instanceof EncodedImage) {
- final EncodedImage yp = (EncodedImage) img;
- // send an image to client
- targetDate = new Date(System.currentTimeMillis());
- nocache = true;
- final String mimeType = Classification.ext2mime(targetExt, "text/html");
- final ByteBuffer result = yp.getImage();
-
- // write the array to the client
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
- if (!method.equals(HeaderFramework.METHOD_HEAD)) {
- result.writeTo(out);
- }
- }
- /*
- if (img instanceof BufferedImage) {
- final BufferedImage i = (BufferedImage) img;
- // send an image to client
- targetDate = new Date(System.currentTimeMillis());
- nocache = true;
- final String mimeType = MimeTable.ext2mime(targetExt, "text/html");
-
- // generate an byte array from the generated image
- int width = i.getWidth(); if (width < 0) width = 96; // bad hack
- int height = i.getHeight(); if (height < 0) height = 96; // bad hack
- final ByteBuffer result = RasterPlotter.exportImage(i, targetExt);
-
- // write the array to the client
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
- if (!method.equals(HeaderFramework.METHOD_HEAD)) {
- result.writeTo(out);
- }
- }
- */
- if (img instanceof Image) {
- final Image i = (Image) img;
- // send an image to client
- targetDate = new Date(System.currentTimeMillis());
- nocache = true;
- final String mimeType = Classification.ext2mime(targetExt, "text/html");
-
- // generate an byte array from the generated image
- int width = i.getWidth(null); if (width < 0) width = 96; // bad hack
- int height = i.getHeight(null); if (height < 0) height = 96; // bad hack
- final BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
- bi.createGraphics().drawImage(i, 0, 0, width, height, null);
- final ByteBuffer result = RasterPlotter.exportImage(bi, targetExt);
-
- // write the array to the client
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, 200, null, mimeType, result.length(), targetDate, null, null, null, null, nocache);
- if (!method.equals(HeaderFramework.METHOD_HEAD)) {
- result.writeTo(out);
- }
- }
- }
- // old-school CGI execution
- } else if ((switchboard.getConfigBool("cgi.allow", false) // check if CGI execution is allowed in config
- && matchesSuffix(path, switchboard.getConfig("cgi.suffixes", null)) // "right" file extension?
- && path.substring(0, path.indexOf(targetFile.getName())).toUpperCase().contains("/CGI-BIN/") // file in right directory?
- && targetFile.exists())
- ) {
-
- if (!targetFile.canExecute()) {
- HTTPDemon.sendRespondError(
- conProp,
- out,
- -1,
- 403,
- null,
- HeaderFramework.http1_1.get(
- Integer.toString(403)),
- null);
- ConcurrentLog.warn(
- "HTTPD",
- "CGI script " + targetFile.getPath()
- + " could not be executed due to "
- + "insufficient access rights.");
- } else {
- String mimeType = "text/html";
- int statusCode = 200;
-
- final ProcessBuilder pb =
- new ProcessBuilder(assembleCommandFromShebang(targetFile));
- pb.directory(targetFile.getParentFile());
-
- final String fileSeparator =
- System.getProperty("file.separator", "/");
-
- // set environment variables
- final Map<String, String> env = pb.environment();
- env.put(
- "SERVER_SOFTWARE",
- getDefaultHeaders(path).get(HeaderFramework.SERVER));
- env.put("SERVER_NAME", sb.peers.mySeed().getName());
- env.put("GATEWAY_INTERFACE", "CGI/1.1");
- if (httpVersion != null) {
- env.put("SERVER_PROTOCOL", httpVersion);
- }
- env.put("SERVER_PORT", switchboard.getConfig("port", "8090"));
- env.put("REQUEST_METHOD", method);
- // env.put("PATH_INFO", ""); // TODO: implement
- // env.put("PATH_TRANSLATED", ""); // TODO: implement
- env.put("SCRIPT_NAME", path);
- if (argsString != null) {
- env.put("QUERY_STRING", argsString);
- }
- env.put("REMOTE_ADDR", clientIP);
- // env.put("AUTH_TYPE", ""); // TODO: implement
- // env.put("REMOTE_USER", ""); // TODO: implement
- // env.put("REMOTE_IDENT", ""); // I don't think we need this
- env.put(
- "DOCUMENT_ROOT",
- switchboard.getAppPath().getAbsolutePath()
- + fileSeparator + switchboard.getConfig("htDocsPath", "DATA/HTDOCS"));
- if (requestHeader.getContentType() != null) {
- env.put("CONTENT_TYPE", requestHeader.getContentType());
- }
- if (method.equalsIgnoreCase(HeaderFramework.METHOD_POST)
- && body != null) {
- env.put(
- "CONTENT_LENGTH",
- Integer.toString(requestHeader.getContentLength()));
- }
-
- /* add values from request header to environment
- * (see: http://hoohoo.ncsa.uiuc.edu/cgi/env.html#headers) */
- for (final Map.Entry<String, String> requestHeaderEntry
- : requestHeader.entrySet()) {
- env.put("HTTP_"
- + requestHeaderEntry.getKey().toUpperCase().replace("-", "_"),
- requestHeaderEntry.getValue());
- }
-
- int exitValue = 0;
- String cgiBody = null;
- final StringBuilder error = new StringBuilder(256);
-
- try {
- // start execution of script
- final Process p = pb.start();
-
- final OutputStream os =
- new BufferedOutputStream(p.getOutputStream());
-
- if (method.equalsIgnoreCase(
- HeaderFramework.METHOD_POST) && body != null) {
- final byte[] buffer = new byte[1024];
- int len = requestHeader.getContentLength();
- while (len > 0) {
- body.read(buffer);
- len = len - buffer.length;
- os.write(buffer);
- }
- }
-
- os.close();
-
- try {
- p.waitFor();
- } catch (final InterruptedException ex) {
-
- }
-
- exitValue = p.exitValue();
-
- final InputStream is =
- new BufferedInputStream(p.getInputStream());
-
- final InputStream es =
- new BufferedInputStream(p.getErrorStream());
-
- final StringBuilder processOutput =
- new StringBuilder(1024);
-
- while (is.available() > 0) {
- processOutput.append((char) is.read());
- }
-
- while (es.available() > 0) {
- error.append((char) es.read());
- }
-
- int indexOfDelimiter = processOutput.indexOf("\n\n", 0);
- final String[] cgiHeader;
- if (indexOfDelimiter > -1) {
- cgiHeader = CommonPattern.NEWLINE.split(processOutput.substring(0, indexOfDelimiter));
- } else {
- cgiHeader = new String[0];
- }
- cgiBody = processOutput.substring(indexOfDelimiter + 1);
-
- String key;
- String value;
- for (final String element : cgiHeader) {
- indexOfDelimiter = element.indexOf(':');
- key = element.substring(0, indexOfDelimiter).trim();
- value = element.substring(indexOfDelimiter + 1).trim();
- conProp.put(key, value);
- if ("Cache-Control".equals(key)
- && "no-cache".equals(value)) {
- nocache = true;
- } else if ("Content-type".equals(key)) {
- mimeType = value;
- } else if ("Status".equals(key)) {
- if (key.length() > 2) {
- try {
- statusCode =
- Integer.parseInt(
- value.substring(0, 3));
- } catch (final NumberFormatException ex) {
- ConcurrentLog.warn(
- "HTTPD",
- "CGI script " + targetFile.getPath()
- + " returned illegal status code \""
- + value + "\".");
- }
- }
- }
- }
- } catch (final IOException ex) {
- exitValue = -1;
- }
-
- /* did the script return an exit value != 0
- * and still there is supposed to be
- * everything right with the HTTP status?
- * -> change status to 500 since 200 would
- * be a lie
- */
- if (exitValue != 0 && statusCode == 200) {
- statusCode = 500;
- }
-
- targetDate = new Date(System.currentTimeMillis());
-
- if (cgiBody != null && !cgiBody.isEmpty()) {
- HTTPDemon.sendRespondHeader(
- conProp,
- out,
- httpVersion,
- statusCode,
- null,
- mimeType,
- cgiBody.length(),
- targetDate,
- null,
- null,
- null,
- null,
- nocache);
- out.write(UTF8.getBytes(cgiBody));
- } else {
- HTTPDemon.sendRespondError(
- conProp,
- out,
- exitValue,
- statusCode,
- null,
- HeaderFramework.http1_1.get(
- Integer.toString(statusCode)),
- null);
- ConcurrentLog.warn(
- "HTTPD",
- "CGI script " + targetFile.getPath()
- + " returned exit value " + exitValue
- + ", body empty: "
- + (cgiBody == null || cgiBody.isEmpty()));
- if (error.length() > 0) {
- ConcurrentLog.warn("HTTPD", "Reported error: " + error);
- }
- }
- }
- } else if (targetClass != null && (path.endsWith(".stream") || path.substring(path.length() - 8).indexOf('.') < 0)) {
- // call rewrite-class
- requestHeader.put(HeaderFramework.CONNECTION_PROP_CLIENTIP, (String) conProp.get(HeaderFramework.CONNECTION_PROP_CLIENTIP));
- requestHeader.put(HeaderFramework.CONNECTION_PROP_PATH, path);
- requestHeader.put(HeaderFramework.CONNECTION_PROP_EXT, path.endsWith(".stream") ? "stream" : "");
- //requestHeader.put(httpHeader.CONNECTION_PROP_INPUTSTREAM, body);
- //requestHeader.put(httpHeader.CONNECTION_PROP_OUTPUTSTREAM, out);
-
- // prepare response header
- ResponseHeader header = new ResponseHeader(200);
- header.put(HeaderFramework.CONTENT_TYPE, getMimeFromServlet(targetClass, requestHeader, args, "text/xml"));
- header.put(HeaderFramework.CORS_ALLOW_ORIGIN, "*"); // allow Cross-Origin Resource Sharing for all stream servlets
- conProp.remove(HeaderFramework.CONNECTION_PROP_PERSISTENT);
- final boolean zipContent = requestHeader.acceptGzip();
- if (zipContent) header.put(HeaderFramework.CONTENT_ENCODING, "gzip");
-
- // send response head
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, 200, null, header);
- forceConnectionClose(conProp);
-
- // send response content
- OutputStream o = zipContent ? new GZIPOutputStream(out) : out;
- invokeServlet(targetClass, requestHeader, args, o);
-
- // immediately close stream as this terminates the http transmission
- if (o instanceof GZIPOutputStream) ((GZIPOutputStream) o).finish();
- o.flush();
- o.close();
- out.flush();
- out.close();
- return;
- } else if (targetFile.exists() && targetFile.isFile() && targetFile.canRead()) {
- // we have found a file that can be written to the client
- // if this file uses templates, then we use the template
- // re-write - method to create an result
- String mimeType = Classification.ext2mime(targetExt, "text/html");
- String ext = (String) conProp.get("EXT"); if (ext == null) ext = "";
- final boolean zipContent = requestHeader.acceptGzip() && HTTPDemon.shallTransportZipped("." + ext);
- if (path.endsWith("html") ||
- path.endsWith("htm") ||
- path.endsWith("xml") ||
- path.endsWith("json") ||
- path.endsWith("rdf") ||
- path.endsWith("rss") ||
- path.endsWith("csv") ||
- path.endsWith("pac") ||
- path.endsWith("src") ||
- path.endsWith("vcf") ||
- path.endsWith("kml") ||
- path.endsWith("gpx") ||
- path.endsWith("css") ||
- path.endsWith("/") ||
- path.equals("/robots.txt")) {
-
- /*targetFile = getLocalizedFile(path);
- if (!(targetFile.exists())) {
- // try to find that file in the htDocsPath
- File trialFile = new File(htDocsPath, path);
- if (trialFile.exists()) targetFile = trialFile;
- }*/
-
-
- // call rewrite-class
-
- if (targetClass != null) {
- requestHeader.put(HeaderFramework.CONNECTION_PROP_CLIENTIP, (String) conProp.get(HeaderFramework.CONNECTION_PROP_CLIENTIP));
- requestHeader.put(HeaderFramework.CONNECTION_PROP_PATH, path);
- final int ep = path.lastIndexOf(".");
- requestHeader.put(HeaderFramework.CONNECTION_PROP_EXT, path.substring(ep + 1));
- // in case that there are no args given, args = null or empty hashmap
- final Object tmp = invokeServlet(targetClass, requestHeader, args, null);
- if (tmp == null) {
- // if no args given, then tp will be an empty Hashtable object (not null)
- templatePatterns = new servletProperties();
- } else if (tmp instanceof servletProperties) {
- templatePatterns = (servletProperties) tmp;
- } else {
- templatePatterns = new servletProperties((serverObjects) tmp);
- }
- // check if the servlets requests authentication
- if (templatePatterns.containsKey(serverObjects.ACTION_AUTHENTICATE)) {
- // handle brute-force protection
- if (realmProp != null) {
- ConcurrentLog.info("HTTPD", "dynamic log-in for account 'admin' in http file handler for path '" + path + "' from host '" + clientIP + "'");
- final Integer attempts = serverCore.bfHost.get(clientIP);
- if (attempts == null)
- serverCore.bfHost.put(clientIP, Integer.valueOf(1));
- else
- serverCore.bfHost.put(clientIP, Integer.valueOf(attempts.intValue() + 1));
- }
- // send authentication request to browser
- final ResponseHeader headers = getDefaultHeaders(path);
- headers.put(RequestHeader.WWW_AUTHENTICATE,"Basic realm=\"" + templatePatterns.get(serverObjects.ACTION_AUTHENTICATE, "") + "\"");
- HTTPDemon.sendRespondHeader(conProp,out,httpVersion,401,headers);
- return;
- } else if (templatePatterns.containsKey(serverObjects.ACTION_LOCATION)) {
- String location = templatePatterns.get(serverObjects.ACTION_LOCATION, "");
- if (location.isEmpty()) location = path;
-
- final ResponseHeader headers = getDefaultHeaders(path);
- headers.setAdditionalHeaderProperties(templatePatterns.getOutgoingHeader().getAdditionalHeaderProperties()); //put the cookies into the new header TODO: can we put all headerlines, without trouble?
- headers.put(HeaderFramework.LOCATION,location);
- HTTPDemon.sendRespondHeader(conProp,out,httpVersion,302,headers);
- return;
- }
- // add the application version, the uptime and the client name to every rewrite table
- templatePatterns.put(servletProperties.PEER_STAT_VERSION, yacyBuildProperties.getVersion());
- templatePatterns.put(servletProperties.PEER_STAT_UPTIME, ((System.currentTimeMillis() - serverCore.startupTime) / 1000) / 60); // uptime in minutes
- templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTNAME, sb.peers.mySeed().getName());
- templatePatterns.putHTML(servletProperties.PEER_STAT_CLIENTID, ((Switchboard) switchboard).peers.myID());
- templatePatterns.put(servletProperties.PEER_STAT_MYTIME, GenericFormatter.SHORT_SECOND_FORMATTER.format());
- final Seed myPeer = sb.peers.mySeed();
- templatePatterns.put("newpeer", myPeer.getAge() >= 1 ? 0 : 1);
- templatePatterns.putHTML("newpeer_peerhash", myPeer.hash);
- templatePatterns.put("p2p", sb.getConfigBool(SwitchboardConstants.DHT_ENABLED, true) || !sb.isRobinsonMode() ? 1 : 0);
- //System.out.println("respond props: " + ((tp == null) ? "null" : tp.toString())); // debug
- nocache = true;
- }
-
- targetDate = new Date(targetFile.lastModified());
- Date expireDate = null;
- if (templatePatterns == null) {
- // if the file will not be changed, cache it in the browser
- expireDate = new Date(new Date().getTime() + (31l * 24 * 60 * 60 * 1000));
- }
-
-
- // rewrite the file
- InputStream fis = null;
-
- // read the file/template
- TemplateCacheEntry templateCacheEntry = null;
- final long fileSize = targetFile.length();
- if (useTemplateCache && fileSize <= 512 * 1024) {
- // read from cache
- SoftReference<TemplateCacheEntry> ref = templateCache.get(targetFile);
- if (ref != null) {
- templateCacheEntry = ref.get();
- if (templateCacheEntry == null) templateCache.remove(targetFile);
- }
-
- final Date targetFileDate = new Date(targetFile.lastModified());
- if (templateCacheEntry == null || targetFileDate.after(templateCacheEntry.lastModified)) {
- // loading the content of the template file into
- // a byte array
- templateCacheEntry = new TemplateCacheEntry();
- templateCacheEntry.lastModified = targetFileDate;
- templateCacheEntry.content = FileUtils.read(targetFile);
-
- // storing the content into the cache
- ref = new SoftReference<TemplateCacheEntry>(templateCacheEntry);
- if (MemoryControl.shortStatus()) templateCache.clear();
- templateCache.put(targetFile, ref);
- if (theLogger.isFinest()) theLogger.finest("Cache MISS for file " + targetFile);
- } else {
- if (theLogger.isFinest()) theLogger.finest("Cache HIT for file " + targetFile);
- }
-
- // creating an inputstream needed by the template
- // rewrite function
- fis = new ByteArrayInputStream(templateCacheEntry.content);
- templateCacheEntry = null;
- } else if (fileSize <= Math.min(4 * 1024 * 1204, MemoryControl.available() / 100)) {
- // read file completely into ram, avoid that too many files are open at the same time
- fis = new ByteArrayInputStream(FileUtils.read(targetFile));
- } else {
- fis = new BufferedInputStream(new FileInputStream(targetFile));
- }
-
- if (mimeType.startsWith("text")) {
- // every text-file distributed by yacy is UTF-8
- if (!path.startsWith("/repository")) {
- mimeType = mimeType + "; charset=UTF-8";
- } else {
- // detect charset of html-files
- if ((path.endsWith("html") || path.endsWith("htm"))) {
- // save position
- fis.mark(1000);
- // scrape document to look up charset
- final ScraperInputStream htmlFilter = new ScraperInputStream(fis, "UTF-8", new DigestURL("http://localhost"), null, false, 10);
- final String charset = htmlParser.patchCharsetEncoding(htmlFilter.detectCharset());
- htmlFilter.close();
- if (charset != null) mimeType = mimeType + "; charset="+charset;
- // reset position
- fis.reset();
- }
- }
- }
-
- // write the array to the client
- // we can do that either in standard mode (whole thing completely) or in chunked mode
- // since yacy clients do not understand chunked mode (yet), we use this only for communication with the administrator
- final boolean yacyClient = requestHeader.userAgent().startsWith("yacy");
- final boolean chunked = !method.equals(HeaderFramework.METHOD_HEAD) && !yacyClient && httpVersion.equals(HeaderFramework.HTTP_VERSION_1_1);
- if (chunked) {
- // send page in chunks and parse SSIs
- final ByteBuffer o = new ByteBuffer();
- // apply templates
- TemplateEngine.writeTemplate(fis, o, templatePatterns, UNRESOLVED_PATTERN);
- fis.close();
- ResponseHeader rh = (templatePatterns == null) ? new ResponseHeader(200) : templatePatterns.getOutgoingHeader();
- HTTPDemon.sendRespondHeader(conProp, out,
- httpVersion, rh.getStatusCode(), null, mimeType, -1,
- targetDate, expireDate, rh,
- null, "chunked", nocache);
- // send the content in chunked parts, see RFC 2616 section 3.6.1
- final ChunkedOutputStream chos = new ChunkedOutputStream(out);
- // GZIPOutputStream does not implement flush (this is a bug IMHO)
- // so we can't compress this stuff, without loosing the cool SSI trickle feature
- ServerSideIncludes.writeSSI(o, chos, realmProp, clientIP, requestHeader);
- //chos.write(result);
- chos.finish();
- } else {
- // send page as whole thing, SSIs are not possible
- final String contentEncoding = (zipContent) ? "gzip" : null;
- // apply templates
- final ByteBuffer o1 = new ByteBuffer();
- TemplateEngine.writeTemplate(fis, o1, templatePatterns, UNRESOLVED_PATTERN);
- fis.close();
- final ByteBuffer o = new ByteBuffer();
-
- if (zipContent) {
- GZIPOutputStream zippedOut = new GZIPOutputStream(o);
- ServerSideIncludes.writeSSI(o1, zippedOut, realmProp, clientIP, requestHeader);
- //httpTemplate.writeTemplate(fis, zippedOut, tp, UNRESOLVED_PATTERN);
- zippedOut.finish();
- zippedOut.flush();
- zippedOut.close();
- zippedOut = null;
- } else {
- ServerSideIncludes.writeSSI(o1, o, realmProp, clientIP, requestHeader);
- //httpTemplate.writeTemplate(fis, o, tp, UNRESOLVED_PATTERN);
- }
- ResponseHeader rh = (templatePatterns == null) ? new ResponseHeader(200) : templatePatterns.getOutgoingHeader();
- if (method.equals(HeaderFramework.METHOD_HEAD)) {
- HTTPDemon.sendRespondHeader(conProp, out,
- httpVersion, rh.getStatusCode(), null, mimeType, o.length(),
- targetDate, expireDate, rh,
- contentEncoding, null, nocache);
- } else {
- final byte[] result = o.getBytes(); // this interrupts streaming (bad idea!)
- HTTPDemon.sendRespondHeader(conProp, out,
- httpVersion, rh.getStatusCode(), null, mimeType, result.length,
- targetDate, expireDate, rh,
- contentEncoding, null, nocache);
- FileUtils.copy(result, out);
- }
- }
- } else { // no html
-
- int statusCode = 200;
- int rangeStartOffset = 0;
- final ResponseHeader header = new ResponseHeader(statusCode);
-
- // adding the accept ranges header
- header.put(HeaderFramework.ACCEPT_RANGES, "bytes");
-
- // reading the files md5 hash if availabe and use it as ETAG of the resource
- String targetMD5 = null;
- final File targetMd5File = new File(targetFile + ".md5");
- try {
- if (targetMd5File.exists()) {
- //String description = null;
- targetMD5 = UTF8.String(FileUtils.read(targetMd5File));
- final int pos = targetMD5.indexOf('\n');
- if (pos >= 0) {
- //description = targetMD5.substring(pos + 1);
- targetMD5 = targetMD5.substring(0, pos);
- }
-
- // using the checksum as ETAG header
- header.put(HeaderFramework.ETAG, targetMD5);
- }
- } catch (final IOException e) {
- ConcurrentLog.logException(e);
- }
-
- if (requestHeader.containsKey(HeaderFramework.RANGE)) {
- final Object ifRange = requestHeader.ifRange();
- if ((ifRange == null)||
- (ifRange instanceof Date && targetFile.lastModified() == ((Date)ifRange).getTime()) ||
- (ifRange instanceof String && ifRange.equals(targetMD5))) {
- final String rangeHeaderVal = requestHeader.get(HeaderFramework.RANGE).trim();
- if (rangeHeaderVal.startsWith("bytes=")) {
- final String rangesVal = rangeHeaderVal.substring("bytes=".length());
- final String[] ranges = CommonPattern.COMMA.split(rangesVal);
- if ((ranges.length == 1)&&(ranges[0].endsWith("-"))) {
- rangeStartOffset = NumberTools.parseIntDecSubstring(ranges[0], 0, ranges[0].length() - 1);
- statusCode = 206;
- header.put(HeaderFramework.CONTENT_RANGE, "bytes " + rangeStartOffset + "-" + (targetFile.length()-1) + "/" + targetFile.length());
- }
- }
- }
- }
-
- // write the file to the client
- targetDate = new Date(targetFile.lastModified());
- // cache file for one month in browser (but most browsers won't cache for that long)
- final Date expireDate = new Date(new Date().getTime() + (31l * 24 * 60 * 60 * 1000));
- final long contentLength = (zipContent)?-1:targetFile.length()-rangeStartOffset;
- final String contentEncoding = (zipContent) ? "gzip" : null;
- final String transferEncoding = (httpVersion.equals(HeaderFramework.HTTP_VERSION_1_1) && zipContent) ? "chunked" : null;
- if (!httpVersion.equals(HeaderFramework.HTTP_VERSION_1_1) && zipContent) forceConnectionClose(conProp);
-
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, statusCode, null, mimeType, contentLength, targetDate, expireDate, header, contentEncoding, transferEncoding, nocache);
-
- if (!method.equals(HeaderFramework.METHOD_HEAD)) {
- ChunkedOutputStream chunkedOut = null;
- GZIPOutputStream zipped = null;
- OutputStream newOut = out;
-
- if (transferEncoding != null) {
- chunkedOut = new ChunkedOutputStream(newOut);
- newOut = chunkedOut;
- }
- if (contentEncoding != null) {
- zipped = new GZIPOutputStream(newOut);
- newOut = zipped;
- }
-
- FileUtils.copyRange(targetFile, newOut, rangeStartOffset);
-
- if (zipped != null) {
- zipped.flush();
- zipped.finish();
- }
- if (chunkedOut != null) {
- chunkedOut.finish();
- }
-
- // flush all
- try {newOut.flush();}catch (final Exception e) {}
- }
- }
- } else {
- if (!targetFile.exists()) ConcurrentLog.warn("HTTPDFileHandler", "target file " + targetFile.getAbsolutePath() + " does not exist");
- //if (!targetFile.isFile()) Log.logWarning("HTTPDFileHandler", "target file " + targetFile.getAbsolutePath() + " is not a file");
- //if (!targetFile.canRead()) Log.logWarning("HTTPDFileHandler", "target file " + targetFile.getAbsolutePath() + " cannot read");
- HTTPDemon.sendRespondError(conProp,out,3,404,"File not Found",null,null);
- return;
- }
- } catch (final Exception e) {
- try {
- // error handling
- if (e instanceof NullPointerException) {
- ConcurrentLog.logException(e);
- }
- int httpStatusCode = 400;
- final String httpStatusText = null;
- final StringBuilder errorMessage = new StringBuilder(2000);
- Exception errorExc = null;
-
- final String errorMsg = e.getMessage();
- if (
- (e instanceof InterruptedException) ||
- ((errorMsg != null) && (errorMsg.startsWith("Socket closed")) && (Thread.currentThread().isInterrupted()))
- ) {
- errorMessage.append("Interruption detected while processing query.");
- httpStatusCode = 503;
- } else {
- if ((errorMsg != null) &&
- (
- errorMsg.contains("Broken pipe") ||
- errorMsg.contains("Connection reset") ||
- errorMsg.contains("Read timed out") ||
- errorMsg.contains("Connection timed out") ||
- errorMsg.contains("Software caused connection abort")
- )) {
- // client closed the connection, so we just end silently
- errorMessage.append("Client unexpectedly closed connection while processing query.");
- } else {
- errorMessage.append("Unexpected error while processing query.");
- httpStatusCode = 500;
- errorExc = e;
- }
- }
-
- errorMessage.append("\nSession: ").append(Thread.currentThread().getName())
- .append("\nQuery: ").append(path)
- .append("\nClient: ").append(conProp.get(HeaderFramework.CONNECTION_PROP_CLIENTIP))
- .append("\nReason: ").append(e.getMessage());
-
- if (!conProp.containsKey(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_HEADER)) {
- // sending back an error message to the client
- // if we have not already send an http header
- HTTPDemon.sendRespondError(conProp,out, 4, httpStatusCode, httpStatusText, errorMessage.toString(), errorExc);
- } else {
- // otherwise we close the connection
- forceConnectionClose(conProp);
- }
-
- // if it is an unexpected error we log it
- if (httpStatusCode == 500) {
- theLogger.warn(errorMessage.toString(), e);
- }
-
- } catch (final Exception ee) {
- forceConnectionClose(conProp);
- }
-
- } finally {
- try {out.flush();}catch (final Exception e) {}
- }
- }
-
- /**
- * Returns a list which contains parts of command
- * which is used to start external process for
- * CGI scripts.
- * @param targetFile file to run
- * @return list of parts of command
- * @throws FileNotFoundException
- * @throws IOException if file can not be accessed
- */
- private static List<String> assembleCommandFromShebang(final File targetFile) throws FileNotFoundException {
- final List<String > ret = new ArrayList<String>();
- final BufferedReader br = new BufferedReader(new FileReader(targetFile), 512);
- String line;
- try {
- line = br.readLine();
- if (line.startsWith("#!")) {
- ret.addAll(Arrays.asList(CommonPattern.SPACE.split(line.substring(2))));
- }
- ret.add(targetFile.getAbsolutePath());
- } catch (final IOException e) {
- ConcurrentLog.logException(e);
- } finally {
- try {br.close();} catch (final IOException e) {}
- }
- return ret;
- }
-
- private static final String appendPath(final String proplist, final String path) {
- if (proplist.isEmpty()) return path;
- if (proplist.indexOf(path) >= 0) return proplist;
- return proplist + "," + path;
- }
-
- public static final File getOverlayedClass(final String path) {
- File targetClass;
- targetClass = rewriteClassFile(new File(htDefaultPath, path)); //works for default and localized files
- if (targetClass == null || !targetClass.exists()) {
- //works for htdocs
- targetClass=rewriteClassFile(new File(htDocsPath, path));
- }
- return targetClass;
- }
-
public static final File getOverlayedFile(final String path) {
File targetFile;
targetFile = getLocalizedFile(path);
@@ -1344,356 +160,4 @@ public final class HTTPDFileHandler {
return targetFile;
}
- private static final void forceConnectionClose(final HashMap<String, Object> conprop) {
- if (conprop != null) {
- conprop.put(HeaderFramework.CONNECTION_PROP_PERSISTENT, "close");
- }
- }
-
- private static final File rewriteClassFile(final File template) {
- try {
- String f = template.getCanonicalPath();
- int cp = f.length() - 8;
- if (cp < 0) {
- final int p = f.lastIndexOf('.');
- f = p < 0 ? f + ".class" : f.substring(0, p) + ".class";
- } else {
- final int p = f.substring(cp).lastIndexOf('.');
- f = p < 0 ? f + ".class" : f.substring(0, cp + p) + ".class";
- }
- final File cf = new File(f);
- if (cf.exists()) return cf;
- return null;
- } catch (final IOException e) {
- return null;
- }
- }
-
- private static final Method rewriteMethod(final File classFile, final String methodName) throws InvocationTargetException {
- Method m = null;
- // now make a class out of the stream
- try {
- if (templateMethodCache != null && "respond".equals(methodName)) {
- final SoftReference<Method> ref = templateMethodCache.get(classFile);
- if (ref != null) {
- m = ref.get();
- if (m == null) {
- templateMethodCache.remove(classFile);
- } else {
- return m;
- }
- }
- }
-
- final Class<?> c = provider.loadClass(classFile);
- Class<?>[] params = new Class[] {
- RequestHeader.class,
- serverObjects.class,
- serverSwitch.class };
- try {
- m = c.getMethod(methodName, params);
- } catch (final NoSuchMethodException e) {
- params = new Class[] {
- RequestHeader.class,
- serverObjects.class,
- serverSwitch.class,
- OutputStream.class};
- m = c.getMethod(methodName, params);
- }
-
- if (MemoryControl.shortStatus()) {
- templateMethodCache.clear();
- } else {
- // store the method into the cache
- if (templateMethodCache != null && "respond".equals(methodName)) {
- templateMethodCache.put(classFile, new SoftReference<Method>(m));
- }
- }
-
- } catch (final ClassNotFoundException e) {
- ConcurrentLog.severe("HTTPDFileHandler", "class " + classFile + " is missing:" + e.getMessage());
- throw new InvocationTargetException(e, "class " + classFile + " is missing:" + e.getMessage());
- } catch (final NoSuchMethodException e) {
- ConcurrentLog.severe("HTTPDFileHandler", "method 'respond' not found in class " + classFile + ": " + e.getMessage());
- throw new InvocationTargetException(e, "method 'respond' not found in class " + classFile + ": " + e.getMessage());
- }
- return m;
- }
-
- private static final Object invokeServlet(final File targetClass, final RequestHeader request, final serverObjects args, final OutputStream os) {
- try {
- if (os == null) {
- return rewriteMethod(targetClass, "respond").invoke(null, new Object[] {request, args, switchboard});
- }
- return rewriteMethod(targetClass, "respond").invoke(null, new Object[] {request, args, switchboard, os});
- } catch (final Throwable e) {
- theLogger.severe("INTERNAL ERROR: " + e.toString() + ":" +
- e.getMessage() +
- " target exception at " + targetClass + ": " +
- "; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'");
- ConcurrentLog.logException(e);
- ConcurrentLog.logException(e.getCause());
- if (e instanceof InvocationTargetException) ConcurrentLog.logException(((InvocationTargetException) e).getTargetException());
- return null;
- }
- }
-
- private static final String getMimeFromServlet(final File targetClass, final RequestHeader request, final serverObjects args, final String dflt) {
- try {
- return (String) rewriteMethod(targetClass, "mime").invoke(null, new Object[] {request, args, switchboard});
- } catch (final Throwable e) {
- theLogger.severe("INTERNAL ERROR: " + e.toString() + ":" +
- e.getMessage() +
- " target exception at " + targetClass + ": " +
- "; java.awt.graphicsenv='" + System.getProperty("java.awt.graphicsenv","") + "'");
- ConcurrentLog.logException(e);
- ConcurrentLog.logException(e.getCause());
- if (e instanceof InvocationTargetException) ConcurrentLog.logException(((InvocationTargetException) e).getTargetException());
- return dflt;
- }
- }
-
- /**
- * Tells if a filename ends with a suffix from a given list.
- * @param filename the filename
- * @param suffixList the list of suffixes which is a string of suffixes separated by commas
- * @return true if the filename ends with a suffix from the list, else false
- */
- private static boolean matchesSuffix(final String name, final String suffixList) {
- boolean ret = false;
-
- if (suffixList != null && name != null) {
- final String[] suffixes = CommonPattern.COMMA.split(suffixList);
- find:
- for (int i = 0; i < suffixes.length; i++) {
- if (name.endsWith("." + suffixes[i].trim())) {
- ret = true;
- break find;
- }
- }
- }
-
- return ret;
- }
-
- /**
- * do a proxy request for document
- * extracts url from GET-parameter url
- * not in separete servlet, because we need access to binary outstream
- * @throws IOException
- */
- private static void doURLProxy(final HashMap<String, Object> conProp, final RequestHeader requestHeader, final OutputStream out) throws IOException {
- final String httpVersion = (String) conProp.get(HeaderFramework.CONNECTION_PROP_HTTP_VER);
- URL proxyurl = null;
- String action = "";
-
- if(conProp != null && conProp.containsKey("ARGS")) {
- String strARGS = (String) conProp.get("ARGS");
- if(strARGS.startsWith("action=")) {
- int detectnextargument = strARGS.indexOf("&");
- action = strARGS.substring (7, detectnextargument);
- strARGS = strARGS.substring(detectnextargument+1);
- }
- if(strARGS.startsWith("url=")) {
- final String strUrl = strARGS.substring(4); // strip url=
-
- try {
- proxyurl = new URL(strUrl);
- } catch (final MalformedURLException e) {
- proxyurl = new URL (URLDecoder.decode(strUrl, UTF8.charset.name()));
-
- }
- }
- }
-
- if (proxyurl==null) {
- throw new IOException("no url as argument supplied");
- }
- String host = proxyurl.getHost();
- if (proxyurl.getPort() != -1) {
- host += ":" + proxyurl.getPort();
- }
-
- // set properties for proxy connection
- final HashMap<String, Object> prop = new HashMap<String, Object>();
- prop.put(HeaderFramework.CONNECTION_PROP_HTTP_VER, HeaderFramework.HTTP_VERSION_1_1);
- prop.put(HeaderFramework.CONNECTION_PROP_HOST, host);
- prop.put(HeaderFramework.CONNECTION_PROP_PATH, proxyurl.getFile().replaceAll(" ", "%20"));
- prop.put(HeaderFramework.CONNECTION_PROP_REQUESTLINE, "PROXY");
- prop.put("CLIENTIP", "0:0:0:0:0:0:0:1");
-
- // remove some stuff from request header, so it isn't send to the server
- requestHeader.remove("CLIENTIP");
- requestHeader.remove("EXT");
- requestHeader.remove("PATH");
- requestHeader.remove("Authorization");
- requestHeader.remove("Connection");
- requestHeader.put(HeaderFramework.HOST, proxyurl.getHost());
-
- // temporarily add argument to header to pass it on to augmented browsing
- requestHeader.put("YACYACTION", action);
-
- final ByteArrayOutputStream o = new ByteArrayOutputStream();
- HTTPDProxyHandler.doGet(prop, requestHeader, o, ClientIdentification.yacyProxyAgent);
-
- // reparse header to extract content-length and mimetype
- final ResponseHeader outgoingHeader = new ResponseHeader(200);
- final InputStream in = new ByteArrayInputStream(o.toByteArray());
- String line = readLine(in);
- while(line != null && !line.equals("")) {
- int p;
- if ((p = line.indexOf(':')) >= 0) {
- // store a property
- outgoingHeader.add(line.substring(0, p).trim(), line.substring(p + 1).trim());
- }
- line = readLine(in);
- }
- if (line==null) {
- HTTPDemon.sendRespondError(conProp,out,3,500,"null",null,null);
- return;
- }
-
- final int httpStatus = Integer.parseInt((String) prop.get(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_STATUS));
-
- String directory = "";
- if (proxyurl.getPath().lastIndexOf('/') > 0)
- directory = proxyurl.getPath().substring(0, proxyurl.getPath().lastIndexOf('/'));
-
- String location = "";
-
- if (outgoingHeader.containsKey("Location")) {
- // rewrite location header
- location = outgoingHeader.get("Location");
- if (location.startsWith("http")) {
- location = "/proxy.html?action="+action+"&url=" + location;
- } else {
- location = "/proxy.html?action="+action+"&url=http://" + proxyurl.getHost() + "/" + location;
- }
- outgoingHeader.put("Location", location);
- }
-
- final String mimeType = outgoingHeader.getContentType();
- if ((mimeType.startsWith("text/html") || mimeType.startsWith("text"))) {
- final StringWriter buffer = new StringWriter();
-
- if (outgoingHeader.containsKey(HeaderFramework.TRANSFER_ENCODING)) {
- FileUtils.copy(new ChunkedInputStream(in), buffer, UTF8.charset);
- } else {
- FileUtils.copy(in, buffer, UTF8.charset);
- }
-
- final String sbuffer = buffer.toString();
-
- final Pattern p = Pattern.compile("(href=\"|src=\")([^\"]+)|(href='|src=')([^']+)|(url\\(')([^']+)|(url\\(\")([^\"]+)|(url\\()([^\\)]+)");
- final Matcher m = p.matcher(sbuffer);
- final StringBuffer result = new StringBuffer(80);
- String init, url;
- MultiProtocolURL target;
- while (m.find()) {
- init = null;
- if(m.group(1) != null) init = m.group(1);
- if(m.group(3) != null) init = m.group(3);
- if(m.group(5) != null) init = m.group(5);
- if(m.group(7) != null) init = m.group(7);
- if(m.group(9) != null) init = m.group(9);
- url = null;
- if(m.group(2) != null) url = m.group(2);
- if(m.group(4) != null) url = m.group(4);
- if(m.group(6) != null) url = m.group(6);
- if(m.group(8) != null) url = m.group(8);
- if(m.group(10) != null) url = m.group(10);
- if (url.startsWith("data:") || url.startsWith("#") || url.startsWith("mailto:") || url.startsWith("javascript:")) {
- String newurl = init + url;
- newurl = newurl.replaceAll("\\$","\\\\\\$");
- m.appendReplacement(result, newurl);
-
- } else if (url.startsWith("http")) {
- // absoulte url of form href="http://domain.com/path"
- if (sb.getConfig("proxyURL.rewriteURLs", "all").equals("domainlist")) {
- try {
- if (sb.crawlStacker.urlInAcceptedDomain(new DigestURL(url)) != null) {
- continue;
- }
- } catch (final MalformedURLException e) {
- theLogger.fine("malformed url for url-rewirte: " + url);
- continue;
- }
- }
-
- String newurl = init + "/proxy.html?url=" + url;
- newurl = newurl.replaceAll("\\$","\\\\\\$");
- m.appendReplacement(result, newurl);
-
- } else if (url.startsWith("//")) {
- // absoulte url but same protocol of form href="//domain.com/path"
- final String complete_url = proxyurl.getProtocol() + ":" + url;
- if (sb.getConfig("proxyURL.rewriteURLs", "all").equals("domainlist")) {
- try {
- if (sb.crawlStacker.urlInAcceptedDomain(new DigestURL(complete_url)) != null) {
- continue;
- }
- } catch (final MalformedURLException e) {
- theLogger.fine("malformed url for url-rewirte: " + complete_url);
- continue;
- }
- }
-
- String newurl = init + "/proxy.html?url=" + complete_url;
- newurl = newurl.replaceAll("\\$", "\\\\\\$");
- m.appendReplacement(result, newurl);
-
- } else if (url.startsWith("/")) {
- // absolute path of form href="/absolute/path/to/linked/page"
- String newurl = init + "/proxy.html?url=http://" + host + url;
- newurl = newurl.replaceAll("\\$","\\\\\\$");
- m.appendReplacement(result, newurl);
-
- } else {
- // relative path of form href="relative/path"
- try {
- target = new MultiProtocolURL("http://" + host + directory + "/" + url);
- String newurl = init + "/proxy.html?url=" + target.toString();
- newurl = newurl.replaceAll("\\$","\\\\\\$");
- m.appendReplacement(result, newurl);
- }
- catch (final MalformedURLException e) {}
-
- }
- }
- m.appendTail(result);
-
- final byte[] sbb = UTF8.getBytes(result.toString());
-
- if (outgoingHeader.containsKey(HeaderFramework.TRANSFER_ENCODING)) {
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, httpStatus, outgoingHeader);
- final ChunkedOutputStream cos = new ChunkedOutputStream(out);
- cos.write(sbb);
- cos.finish();
- cos.close();
- } else {
- outgoingHeader.put(HeaderFramework.CONTENT_LENGTH, Integer.toString(sbb.length));
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, httpStatus, outgoingHeader);
- out.write(sbb);
- }
- } else {
- if (!outgoingHeader.containsKey(HeaderFramework.CONTENT_LENGTH))
- outgoingHeader.put(HeaderFramework.CONTENT_LENGTH, (String) prop.get(HeaderFramework.CONNECTION_PROP_PROXY_RESPOND_SIZE));
- HTTPDemon.sendRespondHeader(conProp, out, httpVersion, httpStatus, outgoingHeader);
- FileUtils.copy(in, out);
- }
- return;
- }
-
- private static String readLine(final InputStream in) throws IOException {
- final ByteArrayOutputStream buf = new ByteArrayOutputStream();
- int b;
- while ((b=in.read()) != '\r' && b != -1) {
- buf.write(b);
- }
- if (b == -1) return null;
- b = in.read(); // read \n
- if (b == -1) return null;
- return buf.toString("UTF-8");
- }
-
}
diff --git a/source/net/yacy/server/http/HTTPDProxyHandler.java b/source/net/yacy/server/http/HTTPDProxyHandler.java
index b1166527d..60a4b40d1 100644
--- a/source/net/yacy/server/http/HTTPDProxyHandler.java
+++ b/source/net/yacy/server/http/HTTPDProxyHandler.java
@@ -446,7 +446,6 @@ public final class HTTPDProxyHandler {
private static void fulfillRequestFromWeb(final HashMap<String, Object> conProp, final DigestURL url, final RequestHeader requestHeader, final ResponseHeader cachedResponseHeader, final OutputStream respond, final ClientIdentification.Agent agent) {
try {
- final boolean proxyAugmentation = sb.getConfigBool("proxyAugmentation", false);
final int reqID = requestHeader.hashCode();
String host = (String) conProp.get(HeaderFramework.CONNECTION_PROP_HOST);
@@ -504,12 +503,6 @@ public final class HTTPDProxyHandler {
throw new Exception(client.getHttpResponse().getStatusLine().toString());
}
- if (proxyAugmentation && AugmentedHtmlStream.supportsMime(responseHeader.mime())) {
- // enable chunk encoding, because we don't know the length after annotating
- responseHeader.remove(HeaderFramework.CONTENT_LENGTH);
- responseHeader.put(HeaderFramework.TRANSFER_ENCODING, "chunked");
- }
-
ChunkedOutputStream chunkedOut = setTransferEncoding(conProp, responseHeader, statusCode, respond);
// the cache does either not exist or is (supposed to be) stale
@@ -545,11 +538,6 @@ public final class HTTPDProxyHandler {
// prepareResponseHeader(responseHeader, res.getHttpVer());
prepareResponseHeader(responseHeader, client.getHttpResponse().getProtocolVersion().toString());
- if(proxyAugmentation && AugmentedHtmlStream.supportsMime(responseHeader.mime())) {
- // chunked encoding disables somewhere, add it again
- responseHeader.put(HeaderFramework.TRANSFER_ENCODING, "chunked");
- }
-
// sending the respond header back to the client
if (chunkedOut != null) {
responseHeader.put(HeaderFramework.TRANSFER_ENCODING, "chunked");
@@ -578,9 +566,6 @@ public final class HTTPDProxyHandler {
final boolean storeHTCache = response.profile().storeHTCache();
final String supportError = TextParser.supports(response.url(), response.getMimeType());
- if(proxyAugmentation && AugmentedHtmlStream.supportsMime(responseHeader.mime())) {
- outStream = new AugmentedHtmlStream(outStream, responseHeader.getCharSet(), url, requestHeader);
- }
if (
/*
* Now we store the response into the htcache directory if
@@ -737,11 +722,6 @@ public final class HTTPDProxyHandler {
HTTPDemon.sendRespondHeader(conProp,respond,httpVer,203,cachedResponseHeader);
//respondHeader(respond, "203 OK", cachedResponseHeader); // respond with 'non-authoritative'
- if(sb.getConfigBool("proxyAugmentation", false)
- && AugmentedHtmlStream.supportsMime(cachedResponseHeader.mime())) {
- respond = new AugmentedHtmlStream(respond, cachedResponseHeader.getCharSet(), url, requestHeader);
- }
-
// send also the complete body now from the cache
// simply read the file and transfer to out socket
FileUtils.copy(cacheEntry, respond);
diff --git a/source/net/yacy/server/http/HTTPDemon.java b/source/net/yacy/server/http/HTTPDemon.java
index de5274283..275849808 100644
--- a/source/net/yacy/server/http/HTTPDemon.java
+++ b/source/net/yacy/server/http/HTTPDemon.java
@@ -25,38 +25,25 @@
package net.yacy.server.http;
import java.io.ByteArrayOutputStream;
-import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.PrintStream;
-import java.io.UnsupportedEncodingException;
import java.net.InetAddress;
import java.net.MalformedURLException;
-import java.net.URLDecoder;
-import java.net.URLEncoder;
-import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
-import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
-import java.util.Set;
-import java.util.StringTokenizer;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;
import net.yacy.cora.document.encoding.ASCII;
import net.yacy.cora.document.encoding.UTF8;
import net.yacy.cora.document.id.DigestURL;
-import net.yacy.cora.order.Base64Order;
-import net.yacy.cora.protocol.ClientIdentification;
import net.yacy.cora.protocol.Domains;
import net.yacy.cora.protocol.HeaderFramework;
import net.yacy.cora.protocol.RequestHeader;
@@ -64,17 +51,11 @@ import net.yacy.cora.protocol.ResponseHeader;
import net.yacy.cora.util.ByteBuffer;
import net.yacy.cora.util.ConcurrentLog;
import net.yacy.cora.util.NumberTools;
-import net.yacy.data.UserDB;
-import net.yacy.document.parser.html.CharacterCoding;
import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.util.MemoryControl;
import net.yacy.search.Switchboard;
import net.yacy.server.serverCore;
-import net.yacy.server.serverHandler;
import net.yacy.server.serverObjects;
-import net.yacy.server.serverSwitch;
-import net.yacy.server.serverCore.Session;
-
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUpload;
@@ -92,729 +73,21 @@ import org.apache.commons.fileupload.disk.DiskFileItemFactory;
* these methods parse the command line and decide wether to call
* a proxy servlet or a file server servlet
*/
-public final class HTTPDemon implements serverHandler, Cloneable {
+public final class HTTPDemon {
- public static final int ERRORCASE_MESSAGE = 4;
- public static final int ERRORCASE_FILE = 5;
+ private static final int ERRORCASE_MESSAGE = 4;
+ private static final int ERRORCASE_FILE = 5;
private static final File TMPDIR = new File(System.getProperty("java.io.tmpdir"));
private static final int SIZE_FILE_THRESHOLD = 20 * 1024 * 1024;
private static final FileItemFactory DISK_FILE_ITEM_FACTORY = new DiskFileItemFactory(SIZE_FILE_THRESHOLD, TMPDIR);
private static AlternativeDomainNames alternativeResolver = null;
- /**
- * A Set containing extensions that indicate content that should not be transported
- * using zipped content encoding
- * @see #shallTransportZipped(String)
- */
-
- //TODO: Load this from a file
- private static final Set<String> disallowZippedContentEncoding = new HashSet<String>(Arrays.asList(new String[]{
- ".gz", ".tgz", ".jpg", ".jpeg", ".png", ".mp3", ".mov", ".avi", ".gif", ".zip", ".rar", ".bz2", ".lha", ".jar", ".rpm", ".arc", ".arj", ".wmv"
- }));
-
// static objects
- public static final String vDATE = "<<REPL>>";
- public static final String copyright = "[ HTTP SERVER: AnomicHTTPD v" + vDATE + " by Michael Christen / www.anomic.de ]";
- public static final String hline = "-------------------------------------------------------------------------------";
-
- public static final ConcurrentMap<String, String> reverseMappingCache = new ConcurrentHashMap<String, String>();
private static volatile Switchboard switchboard;
- private static String virtualHost;
public static boolean keepAliveSupport = false;
- private static ConcurrentMap<String, Long> YaCyHopAccessRequester = new ConcurrentHashMap<String, Long>();
- private static ConcurrentMap<String, Long> YaCyHopAccessTargets = new ConcurrentHashMap<String, Long>();
-
- // for authentication
- private boolean use_proxyAccounts = false;
- private boolean proxyAccounts_init = false; // is use_proxyAccounts set?
-
- private int emptyRequestCount = 0;
- private int keepAliveRequestCount = 0;
-
- // needed for logging
- private final static ConcurrentLog log = new ConcurrentLog("HTTPD");
-
- // class methods
- public HTTPDemon(final serverSwitch s) {
- // handler info
- HTTPDemon.switchboard = (Switchboard)s;
- HTTPDemon.virtualHost = switchboard.getConfig("fileHost","localhost");
-
- // authentication: by default none
- this.proxyAccounts_init = false;
-
- // configuring keep alive support
- keepAliveSupport = Boolean.parseBoolean(switchboard.getConfig("connectionKeepAliveSupport","false"));
- }
-
- /**
- * Can be used to reset this {@link serverHandler} oject so that
- * it can be reused for further connections
- * @see net.yacy.server.serverHandler#reset()
- */
- @Override
- public void reset() {
- this.proxyAccounts_init = false;
-
- this.emptyRequestCount = 0;
- this.keepAliveRequestCount = 0;
- }
-
- private static boolean allowProxy(final Session session) {
- final String proxyClient = switchboard.getConfig("proxyClient", "*");
- return (proxyClient.equals("*")) ? true : match(session.userAddress.getHostAddress(), proxyClient);
- }
-
- private static boolean allowServer(final Session session) {
- final String serverClient = switchboard.getConfig("serverClient", "*");
- return (serverClient.equals("*")) ? true : match(session.userAddress.getHostAddress(), serverClient);
- }
-
- private static boolean allowYaCyHop() {
- return switchboard.getConfigBool("YaCyHop", false);
- }
-
- private static boolean match(final String key, final String latch) {
- // the latch is a comma-separated list of patterns
- // each pattern may contain one wildcard-character '*' which matches anything
- final StringTokenizer st = new StringTokenizer(latch,",");
- String pattern;
- while (st.hasMoreTokens()) {
- pattern = st.nextToken();
- if (key.matches(pattern)) return true;
- /*
- pos = pattern.indexOf("*");
- if (pos < 0) {
- // no wild card: exact match
- if (key.equals(pattern)) return true;
- } else {
- // wild card: match left and right side of pattern
- if ((key.startsWith(pattern.substring(0, pos))) &&
- (key.endsWith(pattern.substring(pos + 1)))) return true;
- }
- */
- }
- return false;
- }
-
- @Override
- public String greeting() { // OBLIGATORIC FUNCTION
- // a response line upon connection is send to client
- // if no response line is wanted, return "" or null
- return null;
- }
-
- @Override
- public String error(final Throwable e) { // OBLIGATORIC FUNCTION
- // return string in case of any error that occurs during communication
- // is always (but not only) called if an IO-dependent exception occurrs.
- log.severe("Unexpected Error. " + e.getClass().getName(),e);
- final String message = e.getMessage();
- if (message != null && message.indexOf("heap space",0) > 0) ConcurrentLog.logException(e);
- return "501 Exception occurred: " + message;
- }
-
- /**
- * This function is used to determine if a persistent connection was requested by the client.
- * @param header the received http-headers
- * @param prop
- * @return <code>true</code> if a persistent connection was requested or <code>false</code> otherwise
- */
- private static boolean handlePersistentConnection(final RequestHeader header, final HashMap<String, Object> prop) {
-
- if (!keepAliveSupport) {
- prop.put(HeaderFramework.CONNECTION_PROP_PERSISTENT,"close");
- return false;
- }
-
- // getting the http version that is used by the client
- String httpVersion = (String) prop.get(HeaderFramework.CONNECTION_PROP_HTTP_VER); if (httpVersion == null) httpVersion = "HTTP/0.9";
-
- // managing keep-alive: in HTTP/0.9 and HTTP/1.0 every connection is closed
- // afterwards. In HTTP/1.1 (and above, in the future?) connections are
- // persistent by default, but closed with the "Connection: close"
- // property.
- boolean persistent = !(httpVersion.equals(HeaderFramework.HTTP_VERSION_0_9) || httpVersion.equals(HeaderFramework.HTTP_VERSION_1_0));
- if ((header.get(RequestHeader.CONNECTION, "keep-alive")).toLowerCase().indexOf("close",0) != -1 ||
- (header.get(RequestHeader.PROXY_CONNECTION, "keep-alive")).toLowerCase().indexOf("close",0) != -1) {
- persistent = false;
- }
-
- final String transferEncoding = header.get(HeaderFramework.TRANSFER_ENCODING, "identity");
- final boolean isPostRequest = prop.get(HeaderFramework.CONNECTION_PROP_METHOD).equals(HeaderFramework.METHOD_POST);
- final boolean hasContentLength = header.containsKey(HeaderFramework.CONTENT_LENGTH);
- final boolean hasTransferEncoding = header.containsKey(HeaderFramework.TRANSFER_ENCODING) && !transferEncoding.equalsIgnoreCase("identity");
-
- // if the request does not contain a content-length we have to close the connection
- // independently of the value of the connection header
- if (persistent && isPostRequest && !(hasContentLength || hasTransferEncoding))
- prop.put(HeaderFramework.CONNECTION_PROP_PERSISTENT,"close");
- else prop.put(HeaderFramework.CONNECTION_PROP_PERSISTENT,persistent?"keep-alive":"close");
-
- return persistent;
- }
-
- private static boolean handleYaCyHopAuthentication(final RequestHeader header, final HashMap<String, Object> prop) {
- // check if the user has allowed that his/her peer is used for hops
- if (!allowYaCyHop()) return false;
-
- // proxy hops must identify with 4 criteria:
-
- // the accessed port must not be port 80
- final String host = (String) prop.get(HeaderFramework.CONNECTION_PROP_HOST);
- if (host == null) return false;
- int pos;
- if ((pos = host.indexOf(':')) < 0) {
- // default port 80
- return false; // not allowed
- }
- if (NumberTools.parseIntDecSubstring(host, pos + 1) == 80) return false;
-
- // the access path must be into the yacy protocol path; it must start with 'yacy'
- if (!(prop.containsKey(HeaderFramework.CONNECTION_PROP_PATH) && ((String) prop.get(HeaderFramework.CONNECTION_PROP_PATH)).startsWith("/yacy/"))) return false;
-
- // the accessing client must identify with user:password, where
- // user = addressed peer name
- // pw = addressed peer hash (b64-hash)
- final String auth = header.get(RequestHeader.PROXY_AUTHORIZATION,"xxxxxx");
- if (getAlternativeResolver() != null) {
- final String test = Base64Order.standardCoder.encodeString(getAlternativeResolver().myName() + ":" + getAlternativeResolver().myID());
- if (!test.equals(auth.trim().substring(6))) return false;
- }
-
- // the accessing client must use a yacy user-agent
- if (!((header.get(HeaderFramework.USER_AGENT,"")).startsWith("yacy"))) return false;
-
- // furthermore, YaCy hops must not exceed a specific access frequency
-
- // check access requester frequency: protection against DoS against this peer
- final String requester = (String) prop.get(HeaderFramework.CONNECTION_PROP_CLIENTIP);
- if (requester == null) return false;
- if (lastAccessDelta(YaCyHopAccessRequester, requester) < 10000) return false;
- YaCyHopAccessRequester.put(requester, Long.valueOf(System.currentTimeMillis()));
-
- // check access target frequecy: protection against DoS from a single peer by several different requesters
- if (lastAccessDelta(YaCyHopAccessTargets, host) < 3000) return false;
- YaCyHopAccessTargets.put(host, Long.valueOf(System.currentTimeMillis()));
-
- // passed all tests
- return true;
- }
-
- private static long lastAccessDelta(final Map<String, Long> accessTable, final String domain) {
- final Long lastAccess = accessTable.get(domain);
- return (lastAccess == null) ? Long.MAX_VALUE : System.currentTimeMillis() - lastAccess.longValue();
- }
-
- private boolean handleProxyAuthentication(final RequestHeader header, final HashMap<String, Object> prop, final Session session) throws IOException {
- // getting the http version that is used by the client
- String httpVersion = (String) prop.get("HTTP"); if (httpVersion == null) httpVersion = "HTTP/0.9";
-
- // reading the authentication settings from switchboard
- if (!this.proxyAccounts_init) {
- this.use_proxyAccounts = switchboard.getConfigBool("use_proxyAccounts", false);
- this.proxyAccounts_init = true; // is initialised
- }
-
- if (this.use_proxyAccounts) {
- final String auth = header.get(RequestHeader.PROXY_AUTHORIZATION,"xxxxxx");
- UserDB.Entry entry = switchboard.userDB.ipAuth(session.userAddress.getHostAddress());
- if (entry == null) {
- entry = switchboard.userDB.proxyAuth(auth, session.userAddress.getHostAddress());
- }
- if (entry != null) {
- final int returncode=entry.surfRight();
- if (returncode == UserDB.Entry.PROXY_ALLOK) {
- return true;
- }
- final serverObjects tp = new serverObjects();
- if (returncode == UserDB.Entry.PROXY_TIMELIMIT_REACHED) {
- tp.put("limit", "1");//time per day
- tp.put("limit_timelimit", Long.toString(entry.getTimeLimit()));
- sendRespondError(prop, session.out, 403, "Internet-Timelimit reached", new File("proxymsg/proxylimits.inc"), tp, null);
- } else if (returncode == UserDB.Entry.PROXY_NORIGHT){
- tp.put("limit", "0");
- sendRespondError(prop, session.out, 403, "Proxy use forbidden", new File("proxymsg/proxylimits.inc"), tp, null);
- }
- return false;
- }
- // ask for authenticate
- session.out.write(UTF8.getBytes(httpVersion + " 407 Proxy Authentication Required" + serverCore.CRLF_STRING +
- RequestHeader.PROXY_AUTHENTICATE + ": Basic realm=\"log-in\"" + serverCore.CRLF_STRING));
- session.out.write(UTF8.getBytes(HeaderFramework.CONTENT_LENGTH + ": 0\r\n"));
- session.out.write(UTF8.getBytes("\r\n"));
- session.out.flush();
- return false;
- }
-
- return true;
- }
-
- @Override
- public Boolean EMPTY(final String arg, final Session session) throws IOException {
- //System.out.println("EMPTY " + arg);
- return (++this.emptyRequestCount > 10) ? serverCore.TERMINATE_CONNECTION : serverCore.RESUME_CONNECTION;
- }
-
- @Override
- public Boolean UNKNOWN(final String arg, final Session session) throws IOException {
- //System.out.println("UNKNOWN " + arg);
-
- final HashMap<String, Object> prop = parseRequestLine(HeaderFramework.METHOD_GET, arg, session);
- int pos;
- String unknownCommand = null, args = null;
- if ((pos = arg.indexOf(' ')) > 0) {
- unknownCommand = arg.substring(0,pos);
- args = arg.substring(pos+1);
- } else {
- unknownCommand = arg;
- args = "";
- }
-
- parseRequestLine(unknownCommand, args, session);
-
- sendRespondError(prop, session.out, 4, 501, null, unknownCommand + " method not implemented", null);
- return serverCore.TERMINATE_CONNECTION;
- }
-
- public Boolean GET(final String arg, final Session session) {
- //System.out.println("GET " + arg);
- try {
- // parsing the http request line
- final HashMap<String, Object> prop = parseRequestLine(HeaderFramework.METHOD_GET, arg, session);
-
- // we now know the HTTP version. depending on that, we read the header
- String httpVersion = (String) prop.get(HeaderFramework.CONNECTION_PROP_HTTP_VER); if (httpVersion == null) httpVersion = HeaderFramework.HTTP_VERSION_0_9;
- final RequestHeader header = (httpVersion.equals(HeaderFramework.HTTP_VERSION_0_9))
- ? new RequestHeader(reverseMappingCache)
- : readHeader(prop, session);
-
- // handling transparent proxy support
- handleTransparentProxySupport(header, prop, virtualHost, HTTPDProxyHandler.isTransparentProxy);
-
- // determines if the connection should be kept alive
- handlePersistentConnection(header, prop);
-
- if (prop.get(HeaderFramework.CONNECTION_PROP_HOST).equals(virtualHost)) {
- // pass to server
- if (allowServer(session)) {
- HTTPDFileHandler.doGet(prop, header, session.out);
- } else {
- // not authorized through firewall blocking (ip does not match filter)
- session.out.write(UTF8.getBytes(httpVersion + " 403 refused (IP not granted, 1)" + serverCore.CRLF_STRING + serverCore.CRLF_STRING + "you are not allowed to connect to this server, because you are using a non-granted IP (" + session.userAddress.getHostAddress() + "). allowed are only connections that match with the following filter (1): " + switchboard.getConfig("serverClient", "*") + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
- } else {
- // pass to proxy
- if (((allowYaCyHop()) && (handleYaCyHopAuthentication(header, prop))) ||
- ((allowProxy(session)) && (handleProxyAuthentication(header, prop, session)))) {
- HTTPDProxyHandler.doGet(prop, header, session.out, ClientIdentification.yacyProxyAgent);
- } else {
- // not authorized through firewall blocking (ip does not match filter)
- session.out.write(UTF8.getBytes(httpVersion + " 403 refused (IP not granted, 2)" + serverCore.CRLF_STRING + serverCore.CRLF_STRING + "you are not allowed to connect to this proxy, because you are using a non-granted IP (" + session.userAddress.getHostAddress() + "). allowed are only connections that match with the following filter (2): " + switchboard.getConfig("proxyClient", "*") + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
- }
-
- return prop.get(HeaderFramework.CONNECTION_PROP_PERSISTENT).equals("keep-alive") ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;
- } catch (final Exception e) {
- logUnexpectedError(e, session.userAddress.getHostAddress());
- return serverCore.TERMINATE_CONNECTION;
- }
- }
-
- private static void logUnexpectedError(final Exception e, final String address) {
- if (e instanceof InterruptedException) {
- log.info("Interruption detected");
- } else {
- final String errorMsg = e.getMessage();
- if (errorMsg != null) {
- if (errorMsg.startsWith("Socket closed")) {
- log.info("httpd shutdown detected ... (" + e.getMessage() + "), client = " +address);
- } else if ((errorMsg.startsWith("Broken pipe") || errorMsg.startsWith("Connection reset"))) {
- // client closed the connection, so we just end silently
- log.info("Client unexpectedly closed connection... (" + e.getMessage() + "), client = " + address);
- } else if (errorMsg.equals("400 Bad request")) {
- log.info("Bad client request ... (" + e.getMessage() + "), client = " + address);
- } else {
- log.severe("Unexpected Error ... (" + e.getMessage() + "), client = " + address,e);
- }
- } else {
- log.severe("Unexpected Error ... (" + e.getMessage() + "), client = " + address,e);
- }
- }
- }
-
- public Boolean HEAD(final String arg, final Session session) {
- //System.out.println("HEAD " + arg);
- try {
- final HashMap<String, Object> prop = parseRequestLine(HeaderFramework.METHOD_HEAD, arg, session);
-
- // we now know the HTTP version. depending on that, we read the header
- String httpVersion = (String) prop.get(HeaderFramework.CONNECTION_PROP_HTTP_VER); if (httpVersion == null) httpVersion = HeaderFramework.HTTP_VERSION_0_9;
- final RequestHeader header = (httpVersion.equals(HeaderFramework.HTTP_VERSION_0_9))
- ? new RequestHeader(reverseMappingCache)
- : readHeader(prop,session);
-
- // handle transparent proxy support
- handleTransparentProxySupport(header, prop, virtualHost, HTTPDProxyHandler.isTransparentProxy);
-
- // determines if the connection should be kept alive
- handlePersistentConnection(header, prop);
-
- // return multi-line message
- if (prop.get(HeaderFramework.CONNECTION_PROP_HOST).equals(virtualHost)) {
- // pass to server
- if (allowServer(session)) {
- HTTPDFileHandler.doHead(prop, header, session.out);
- } else {
- // not authorized through firewall blocking (ip does not match filter)
- session.out.write(UTF8.getBytes(httpVersion + " 403 refused (IP not granted)" + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
- } else {
- // pass to proxy
- if (((allowYaCyHop()) && (handleYaCyHopAuthentication(header, prop))) ||
- ((allowProxy(session)) && (handleProxyAuthentication(header, prop, session)))) {
- HTTPDProxyHandler.doHead(prop, header, session.out, ClientIdentification.yacyProxyAgent);
- } else {
- // not authorized through firewall blocking (ip does not match filter)
- session.out.write(UTF8.getBytes(httpVersion + " 403 refused (IP not granted)" + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
- }
- return prop.get(HeaderFramework.CONNECTION_PROP_PERSISTENT).equals("keep-alive") ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;
- } catch (final Exception e) {
- logUnexpectedError(e, session.userAddress.getHostAddress());
- return serverCore.TERMINATE_CONNECTION;
- }
- }
-
- public Boolean POST(final String arg, final Session session) {
- //System.out.println("POST " + arg);
- InputStream sessionIn = null;
- boolean retv;
- try {
- final HashMap<String, Object> prop = parseRequestLine(HeaderFramework.METHOD_POST, arg, session);
-
- // we now know the HTTP version. depending on that, we read the header
- String httpVersion = (String) prop.get(HeaderFramework.CONNECTION_PROP_HTTP_VER); if (httpVersion == null) httpVersion = HeaderFramework.HTTP_VERSION_0_9;
- final RequestHeader header = (httpVersion.equals(HeaderFramework.HTTP_VERSION_0_9))
- ? new RequestHeader(reverseMappingCache)
- : readHeader(prop, session);
-
- // handle transfer-coding
- final String transferEncoding = header.get(HeaderFramework.TRANSFER_ENCODING);
- if (transferEncoding != null) {
- if (!HeaderFramework.HTTP_VERSION_1_1.equals(httpVersion)) {
- log.warn("client "+ session.getName() +" uses transfer-coding with HTTP version "+ httpVersion +"!");
- }
- if("chunked".equalsIgnoreCase(header.get(HeaderFramework.TRANSFER_ENCODING))) {
- sessionIn = new ChunkedInputStream(session.in);
- } else {
- // "A server which receives an entity-body with a transfer-coding it does
- // not understand SHOULD return 501 (Unimplemented), and close the
- // connection." [RFC 2616, section 3.6]
- session.out.write(UTF8.getBytes(httpVersion + " 501 transfer-encoding not implemented" + serverCore.CRLF_STRING + serverCore.CRLF_STRING + "you send a transfer-encoding to this server, which is not supported: " + transferEncoding + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
- } else {
- sessionIn = session.in;
- }
-
- // handle transparent proxy support
- handleTransparentProxySupport(header, prop, virtualHost, HTTPDProxyHandler.isTransparentProxy);
-
- // determines if the connection should be kept alive
- handlePersistentConnection(header, prop);
-
- // return multi-line message
- if (prop.get(HeaderFramework.CONNECTION_PROP_HOST).equals(virtualHost)) {
- // pass to server
- if (allowServer(session)) {
- HTTPDFileHandler.doPost(prop, header, session.out, sessionIn);
- } else {
- // not authorized through firewall blocking (ip does not match filter)
- session.out.write(UTF8.getBytes(httpVersion + " 403 refused (IP not granted)" + serverCore.CRLF_STRING + serverCore.CRLF_STRING + "you are not allowed to connect to this server, because you are using the non-granted IP " + session.userAddress.getHostAddress() + ". allowed are only connections that match with the following filter (3): " + switchboard.getConfig("serverClient", "*") + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
- } else {
- // pass to proxy
- if (((allowYaCyHop()) && (handleYaCyHopAuthentication(header, prop))) ||
- ((allowProxy(session)) && (handleProxyAuthentication(header, prop, session)))) {
- HTTPDProxyHandler.doPost(prop, header, session.out, sessionIn, ClientIdentification.yacyProxyAgent);
- } else {
- // not authorized through firewall blocking (ip does not match filter)
- session.out.write(UTF8.getBytes(httpVersion + " 403 refused (IP not granted)" + serverCore.CRLF_STRING + serverCore.CRLF_STRING + "you are not allowed to connect to this proxy, because you are using the non-granted IP " + session.userAddress.getHostAddress() + ". allowed are only connections that match with the following filter (4): " + switchboard.getConfig("proxyClient", "*") + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
- }
- retv = prop.get(HeaderFramework.CONNECTION_PROP_PERSISTENT).equals("keep-alive") ? serverCore.RESUME_CONNECTION : serverCore.TERMINATE_CONNECTION;
- } catch (final Exception e) {
- logUnexpectedError(e, session.userAddress.getHostAddress());
- retv = serverCore.TERMINATE_CONNECTION;
- } finally {
- if (sessionIn != null && (sessionIn instanceof ChunkedInputStream)) {
- // read to end, but do not close the stream (maybe HTTP/1.1 persistent)
- try {sessionIn.close();} catch (final IOException e) {}
- }
- }
- return retv;
- }
-
- public static void handleTransparentProxySupport(final RequestHeader header, final HashMap<String, Object> prop, final String virtualHost, final boolean isTransparentProxy) {
- // transparent proxy support is only available for http 1.0 and above connections
- if (prop.containsKey(HeaderFramework.CONNECTION_PROP_HTTP_VER) && prop.get(HeaderFramework.CONNECTION_PROP_HTTP_VER).equals("HTTP/0.9")) return;
-
- // if the transparent proxy support was disabled, we have nothing todo here ...
- if (!(isTransparentProxy && header.containsKey(HeaderFramework.HOST))) return;
-
- // we only need to do the transparent proxy support if the request URL didn't contain the hostname
- // and therefor was set to virtualHost by function parseQuery()
- if (!prop.get(HeaderFramework.CONNECTION_PROP_HOST).equals(virtualHost)) return;
-
- // TODO: we could have problems with connections from extern here ...
- final String dstHostSocket = header.get(HeaderFramework.HOST);
- prop.put(HeaderFramework.CONNECTION_PROP_HOST,(HTTPDemon.isThisHostName(dstHostSocket)?virtualHost:dstHostSocket));
- }
-
- public Boolean CONNECT(String arg, final Session session) throws IOException {
- //System.out.println("CONNECT " + arg);
- // establish a ssh-tunneled http connection
- // this is to support https
-
- // parse HTTP version
- int pos = arg.indexOf(' ');
- final String httpVersion;
- if (pos >= 0) {
- httpVersion = arg.substring(pos + 1);
- arg = arg.substring(0, pos);
- } else {
- httpVersion = "HTTP/1.0";
- }
- final HashMap<String, Object> prop = new HashMap<String, Object>();
- prop.put(HeaderFramework.CONNECTION_PROP_HTTP_VER, httpVersion);
-
- // parse hostname and port
- prop.put(HeaderFramework.CONNECTION_PROP_HOST, arg);
- pos = arg.indexOf(':');
- int port = 443;
- if (pos >= 0) {
- port = NumberTools.parseIntDecSubstring(arg, pos + 1);
- //the offcut: arg = arg.substring(0, pos);
- }
-
- // setting other connection properties
- prop.put(HeaderFramework.CONNECTION_PROP_CLIENTIP, session.userAddress.isAnyLocalAddress() || session.userAddress.isLinkLocalAddress() || session.userAddress.isLoopbackAddress() ? "localhost" : session.userAddress.getHostAddress());
- prop.put(HeaderFramework.CONNECTION_PROP_METHOD, HeaderFramework.METHOD_CONNECT);
- prop.put(HeaderFramework.CONNECTION_PROP_PATH, "/");
- prop.put(HeaderFramework.CONNECTION_PROP_EXT, "");
- prop.put(HeaderFramework.CONNECTION_PROP_URL, "");
-
- // parse remaining lines
- final RequestHeader header = readHeader(prop,session);
-
- if (!(allowProxy(session))) {
- // not authorized through firewall blocking (ip does not match filter)
- session.out.write(UTF8.getBytes(httpVersion + " 403 refused (IP not granted)" + serverCore.CRLF_STRING + serverCore.CRLF_STRING + "you are not allowed to connect to this proxy, because you are using the non-granted IP " + session.userAddress.getHostAddress() + ". allowed are only connections that match with the following filter (5): " + switchboard.getConfig("proxyClient", "*") + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
-
- if (port != 443 && switchboard.getConfig("secureHttps", "true").equals("true")) {
- // security: connection only to ssl port
- // we send a 403 (forbidden) error back
- session.out.write(UTF8.getBytes(httpVersion + " 403 Connection to non-443 forbidden" +
- serverCore.CRLF_STRING + serverCore.CRLF_STRING));
- return serverCore.TERMINATE_CONNECTION;
- }
-
- // pass to proxy
- if (((allowYaCyHop()) && (handleYaCyHopAuthentication(header, prop))) ||
- ((allowProxy(session)) && (handleProxyAuthentication(header, prop, session)))) {
- HTTPDProxyHandler.doConnect(prop, header, session.in, session.out, ClientIdentification.yacyProxyAgent);
- } else {
- // not authorized through firewall blocking (ip does not match filter)
- session.out.write(UTF8.getBytes(httpVersion + " 403 refused (IP not granted)" + serverCore.CRLF_STRING + serverCore.CRLF_STRING + "you are not allowed to connect to this proxy, because you are using the non-granted IP " + session.userAddress.getHostAddress() + ". allowed are only connections that match with the following filter (6): " + switchboard.getConfig("proxyClient", "*") + serverCore.CRLF_STRING));
- }
-
- return serverCore.TERMINATE_CONNECTION;
- }
-
- private final HashMap<String, Object> parseRequestLine(final String cmd, final String s, final Session session) {
-
- // parsing the header
- final HashMap<String, Object> p = parseRequestLine(cmd, s, virtualHost);
-
- // track the request
- final String path = (String) p.get(HeaderFramework.CONNECTION_PROP_URL);
- String args = (String) p.get(HeaderFramework.CONNECTION_PROP_ARGS); if (args == null) args = "";
- switchboard.track(session.userAddress.getHostAddress(), (args.length() > 0) ? path + "?" + args : path);
-
- // reseting the empty request counter
- this.emptyRequestCount = 0;
-
- // counting the amount of received requests within this permanent connection
- p.put(HeaderFramework.CONNECTION_PROP_KEEP_ALIVE_COUNT, Integer.toString(++this.keepAliveRequestCount));
-
- // setting the client-IP
- p.put(HeaderFramework.CONNECTION_PROP_CLIENTIP, session.userAddress.getHostAddress());
-
- return p;
- }
-
- // some static methods that needs to be used from any CGI
- // and also by the httpdFileHandler
- // but this belongs to the protocol handler, this class.
-
- public static int parseArgs(final serverObjects args, final InputStream in, final int length) throws IOException {
- // this is a quick hack using a previously coded parseMultipart based on a buffer
- // should be replaced sometime by a 'right' implementation
- byte[] buffer = null;
-
- // parsing post request bodies with a given length
- if (length != -1) {
- buffer = new byte[length];
- final int bytesRead = in.read(buffer);
- assert bytesRead == buffer.length;
- // parsing post request bodies which are gzip content-encoded
- } else {
- ByteArrayOutputStream bout = new ByteArrayOutputStream(512);
- FileUtils.copy(in,bout);
- buffer = bout.toByteArray();
- bout.close(); bout = null;
- }
-
- final int argc = parseArgs(args, UTF8.String(buffer));
- buffer = null;
- return argc;
- }
-
- public static int parseArgs(final serverObjects args, String argsString) {
- // this parses a arg string that can either be attached to a URL query
- // or can be given as result of a post method
- // the String argsString is supposed to be constructed as
- // <key1>=<value1>'&'<key2>=<value2>'&'<key3>=<value3>
- // the calling function must strip off a possible leading '?' char
- if (argsString.isEmpty()) return 0;
- argsString = argsString.replaceAll("&quot;", "%22");
- argsString = argsString + "&"; // for technical reasons
- int sep;
- int eqp;
- int argc = 0;
- // Textfield1=default+value+Textfield+1&Textfield2=default+value+Textfield+2&selection1=sel1&selection2=othervalue1&selection2=sel2&selection3=sel3&Menu1=SubEnry11&radio1=button1&check1=button2&check1=button3&hidden1=&sButton1=enter+%281%29
- while (argsString.length() > 0) {
- eqp = argsString.indexOf('=');
- if (eqp <= 0) break;
- sep = argsString.indexOf("&amp;", eqp + 1);
- if (sep > 0) {
- // resulting equations are inserted into the property args with leading '&amp;'
- args.add(parseArg(argsString.substring(0, eqp)), parseArg(argsString.substring(eqp + 1, sep)));
- argsString = argsString.substring(sep + 5);
- argc++;
- continue;
- }
- sep = argsString.indexOf('&', eqp + 1);
- if (sep > 0) {
- // resulting equations are inserted into the property args with leading '&'
- args.add(parseArg(argsString.substring(0, eqp)), parseArg(argsString.substring(eqp + 1, sep)));
- argsString = argsString.substring(sep + 1);
- argc++;
- continue;
- }
- break;
- }
- // we return the number of parsed arguments
- return argc;
- }
-
- /**
- * <p>This method basically does the same as {@link URLDecoder#decode(String, String) URLDecoder.decode(s, "UTF-8")}
- * would do with the exception of more lazyness in regard to current browser implementations as they do not
- * always comply with the standards.</p>
- * <p>The following replacements are performed on the input-<code>String</code>:</p>
- * <ul>
- * <li>'<code>+</code>'-characters are replaced by space
- * <li>(supbsequent (in the case of encoded unicode-chars)) '<code>%HH</code>'-entities are replaced by their
- * respective <code>char</code>-representation</li>
- * <li>'<code>%uHHHH</code>'-entities (sent by IE although rejected by the W3C) are replaced by their respective
- * <code>char</code>-representation</li>
- * <li><strong>TODO</strong>: <code>chars</code> already encoded in UTF-8 are url-encoded and re-decoded due to internal restrictions,
- * which slows down this method unnecessarily</li>
- * </ul>
- *
- * @param s the URL-encoded <code>String</code> to decode, note that the encoding used to URL-encode the original
- * <code>String</code> has to be UTF-8 (i.e. the "<code>accept-charset</code>"-property of HTML
- * <code>&lt;form&gt;</code>-elements)
- * @return the "normal" Java-<code>String</code> (UTF-8) represented by the input or <code>null</code>
- * if the passed argument <code>encoding</code> is not supported
- */
- private static String parseArg(String s) {
- int pos = 0;
- final ByteArrayOutputStream baos = new ByteArrayOutputStream(s.length());
-
- while (pos < s.length()) {
- if (s.charAt(pos) == '+') {
- baos.write(' ');
- pos++;
- } else if (s.charAt(pos) == '%') {
- try {
- if (s.length() >= pos + 6 && (s.charAt(pos + 1) == 'u' || s.charAt(pos + 1) == 'U')) {
- // non-standard encoding of IE for unicode-chars
- final int bh = NumberTools.parseIntDecSubstring(s.substring(pos + 2, pos + 4), 16);
- final int bl = NumberTools.parseIntDecSubstring(s.substring(pos + 4, pos + 6), 16);
- // TODO: needs conversion from UTF-16 to UTF-8
- baos.write(bh);
- baos.write(bl);
- pos += 6;
- } else if (s.length() >= pos + 3) {
- baos.write(Integer.parseInt(s.substring(pos + 1, pos + 3), 16));
- pos += 3;
- } else {
- baos.write(s.charAt(pos++));
- }
- } catch (final NumberFormatException e) {
- baos.write(s.charAt(pos++));
- }
- } else if (s.charAt(pos) > 127) {
- // Unicode chars sent by client, see http://www.w3.org/International/O-URL-code.html
- try {
- // don't write anything but url-encode the unicode char
- s = s.substring(0, pos) + URLEncoder.encode(s.substring(pos, pos + 1), "UTF-8") + s.substring(pos + 1);
- } catch (final UnsupportedEncodingException e) { return null; }
- } else {
- baos.write(s.charAt(pos++));
- }
- }
-
- return UTF8.String(baos.toByteArray());
- }
-
- // 06.01.2007: decode HTML entities by [FB]
- public static String decodeHtmlEntities(String s) {
- // replace all entities defined in wikiCode.characters and htmlentities
- s = CharacterCoding.html2unicode(s);
-
- // replace all other
- final CharArrayWriter b = new CharArrayWriter(s.length());
- int end;
- for (int i = 0, len = s.length(); i < len; i++) {
- if (s.charAt(i) == '&' && (end = s.indexOf(';', i + 1)) > i) {
- if (s.charAt(i + 1) == '#') { // &#1234; symbols
- b.write(NumberTools.parseIntDecSubstring(s, i + 2, end));
- i += end - i;
- } else { // 'named' smybols
- if (log.isFine()) log.fine("discovered yet unimplemented HTML entity '" + s.substring(i, end + 1) + "'");
- b.write(s.charAt(i));
- }
- } else {
- b.write(s.charAt(i));
- }
- }
- return b.toString();
- }
/**
* parses the message accordingly to RFC 1867 using "Commons FileUpload" (http://commons.apache.org/fileupload/)
@@ -947,41 +220,6 @@ public final class HTTPDemon implements serverHandler, Cloneable {
}
- public static int indexOf(final int start, final byte[] array, final byte[] pattern) {
- // return a position of a pattern in an array
- if (start > array.length - pattern.length) return -1;
- if (pattern.length == 0) return start;
- for (int pos = start, lens = array.length - pattern.length; pos <= lens; pos++) {
- if ((array[pos] == pattern[0]) && (equals(array, pos, pattern, 0, pattern.length))) {
- return pos;
- }
- }
- return -1;
- }
-
- public static boolean equals(final byte[] a, final int aoff, final byte[] b, final int boff, final int len) {
- if ((aoff + len > a.length) || (boff + len > b.length)) return false;
- for (int i = 0; i < len; i++) {
- if (a[aoff + i] != b[boff + i]) {
- return false;
- }
- }
- return true;
- }
-
- @Override
- public HTTPDemon clone() {
- return new HTTPDemon(switchboard);
- }
-
- public static final void sendRespondBody(
- final OutputStream respond,
- final byte[] body
- ) throws IOException {
- respond.write(body);
- respond.flush();
- }
-
public static final void sendRespondError(
final HashMap<String, Object> conProp,
final OutputStream respond,
@@ -1028,7 +266,7 @@ public final class HTTPDemon implements serverHandler, Cloneable {
);
}
- public static final void sendRespondError(
+ private static final void sendRespondError(
final HashMap<String, Object> conProp,
final OutputStream respond,
final int errorcase,
@@ -1330,17 +568,7 @@ public final class HTTPDemon implements serverHandler, Cloneable {
}
}
- public static boolean shallTransportZipped(final String path) {
- if ((path == null) || (path.isEmpty())) return true;
-
- int pos;
- if ((pos = path.lastIndexOf('.')) != -1) {
- return !disallowZippedContentEncoding.contains(path.substring(pos).toLowerCase());
- }
- return true;
- }
-
- public static boolean isThisSeedIP(final String hostName) {
+ private static boolean isThisSeedIP(final String hostName) {
if ((hostName == null) || (hostName.isEmpty())) return false;
// getting ip address and port of this seed
@@ -1355,38 +583,6 @@ public final class HTTPDemon implements serverHandler, Cloneable {
return (seedInetAddress.equals(hostInetAddress));
}
- public static boolean isThisHostName(final String hostName) {
- if ((hostName == null) || (hostName.isEmpty())) return false;
-
- try {
- final int idx = hostName.indexOf(':');
- final String dstHost = (idx != -1) ? hostName.substring(0,idx).trim() : hostName.trim();
- final Integer dstPort = (idx != -1) ? Integer.valueOf(hostName.substring(idx+1).trim()) : Integer.valueOf(80);
-
- // if the hostname endswith thisPeerName.yacy ...
- final String alternativeAddress = (getAlternativeResolver() == null) ? null : getAlternativeResolver().myAlternativeAddress();
- if ((alternativeAddress != null) && (dstHost.endsWith(alternativeAddress))) {
- return true;
- /*
- * If the port number is equal to the yacy port and the IP address is an address of this host ...
- * Please note that yacy is listening to all interfaces of this host
- */
- } else if (
- // check if the destination port is equal to the port yacy is listening to
- dstPort.equals(Integer.valueOf(serverCore.getPortNr(switchboard.getConfig("port", "8090")))) &&
- (
- // check if the destination host is our local IP address
- Domains.isThisHostIP(dstHost) ||
- // check if the destination host is our seed ip address
- isThisSeedIP(dstHost)
- )
- ) {
- return true;
- }
- } catch (final Exception e) {}
- return false;
- }
-
/**
* @param alternativeResolver the alternativeResolver to set
*/
@@ -1401,160 +597,4 @@ public final class HTTPDemon implements serverHandler, Cloneable {
return alternativeResolver;
}
-
- public static RequestHeader readHeader(final HashMap<String, Object> prop, final serverCore.Session theSession) throws IOException {
-
- // reading all headers
- final RequestHeader header = new RequestHeader(HTTPDemon.reverseMappingCache);
- int p;
- String line;
- while ((line = theSession.readLineAsString()) != null) {
- if (line.isEmpty()) break; // this separates the header of the HTTP request from the body
- // parse the header line: a property separated with the ':' sign
- if ((p = line.indexOf(':')) >= 0) {
- // store a property
- header.add(line.substring(0, p).trim(), line.substring(p + 1).trim());
- }
- }
-
- /*
- * doing some header validation here ...
- */
- String httpVersion = (String) prop.get(HeaderFramework.CONNECTION_PROP_HTTP_VER); if (httpVersion == null) httpVersion = "HTTP/0.9";
- if (httpVersion.equals("HTTP/1.1") && !header.containsKey(HeaderFramework.HOST)) {
- // the HTTP/1.1 specification requires that an HTTP/1.1 server must reject any
- // HTTP/1.1 message that does not contain a Host header.
- HTTPDemon.sendRespondError(prop,theSession.out,0,400,null,null,null);
- throw new IOException("400 Bad request");
- }
-
- return header;
- }
-
- private static final Pattern P_20 = Pattern.compile(" ", Pattern.LITERAL);
- private static final Pattern P_7B = Pattern.compile("{", Pattern.LITERAL);
- private static final Pattern P_7D = Pattern.compile("}", Pattern.LITERAL);
- private static final Pattern P_7C = Pattern.compile("|", Pattern.LITERAL);
- private static final Pattern P_5C = Pattern.compile("\\", Pattern.LITERAL);
- private static final Pattern P_5E = Pattern.compile("^", Pattern.LITERAL);
- private static final Pattern P_5B = Pattern.compile("[", Pattern.LITERAL);
- private static final Pattern P_5D = Pattern.compile("]", Pattern.LITERAL);
- private static final Pattern P_60 = Pattern.compile("`", Pattern.LITERAL);
-
-
- public static HashMap<String, Object> parseRequestLine(final String cmd, String args, final String virtualHost) {
-
- final HashMap<String, Object> prop = new HashMap<String, Object>(); // we can use a non-synchronized data structure here
-
- // storing informations about the request
- prop.put(HeaderFramework.CONNECTION_PROP_METHOD, cmd);
- prop.put(HeaderFramework.CONNECTION_PROP_REQUESTLINE, cmd + " " + args);
-
- // this parses a whole URL
- if (args.isEmpty()) {
- prop.put(HeaderFramework.CONNECTION_PROP_HOST, virtualHost);
- prop.put(HeaderFramework.CONNECTION_PROP_PATH, "/");
- prop.put(HeaderFramework.CONNECTION_PROP_HTTP_VER, HeaderFramework.HTTP_VERSION_0_9);
- prop.put(HeaderFramework.CONNECTION_PROP_EXT, "");
- return prop;
- }
-
- // store the version propery "HTTP" and cut the query at both ends
- int sep = args.lastIndexOf(' ');
- if ((sep >= 0) && (args.substring(sep + 1).toLowerCase().startsWith("http/"))) {
- // HTTP version is given
- prop.put(HeaderFramework.CONNECTION_PROP_HTTP_VER, args.substring(sep + 1).trim());
- args = args.substring(0, sep).trim(); // cut off HTTP version mark
- } else {
- // HTTP version is not given, it will be treated as ver 0.9
- prop.put(HeaderFramework.CONNECTION_PROP_HTTP_VER, HeaderFramework.HTTP_VERSION_0_9);
- }
-
- // replacing spaces in the url string correctly
- args = P_20.matcher(args).replaceAll("%20");
- // replace unwise characters (see RFC 2396, 2.4.3), which may not be escaped
- args = P_7B.matcher(args).replaceAll("%7B");
- args = P_7D.matcher(args).replaceAll("%7D");
- args = P_7C.matcher(args).replaceAll("%7C");
- args = P_5C.matcher(args).replaceAll("%5C");
- args = P_5E.matcher(args).replaceAll("%5E");
- args = P_5B.matcher(args).replaceAll("%5B");
- args = P_5D.matcher(args).replaceAll("%5D");
- args = P_60.matcher(args).replaceAll("%60");
-
- // properties of the query are stored with the prefix "&"
- // additionally, the values URL and ARGC are computed
-
- final String argsString;
- sep = args.indexOf('?');
- if (sep >= 0) {
- // there are values attached to the query string
- argsString = args.substring(sep + 1); // cut head from tail of query
- args = args.substring(0, sep);
- } else {
- argsString = "";
- }
- prop.put(HeaderFramework.CONNECTION_PROP_URL, args); // store URL
- if (!argsString.isEmpty()) {
- prop.put(HeaderFramework.CONNECTION_PROP_ARGS, argsString);
- } // store arguments in original form
-
- // finally find host string
- final String path;
- if (args.toUpperCase().startsWith("HTTP://")) {
- // a host was given. extract it and set path
- args = args.substring(7);
- sep = args.indexOf('/');
- if (sep < 0) {
- // this is a malformed url, something like
- // http://index.html
- // we are lazy and guess that it means
- // /index.html
- // which is a localhost access to the file servlet
- prop.put(HeaderFramework.CONNECTION_PROP_HOST, args);
- path = "/";
- } else {
- // THIS IS THE "GOOD" CASE
- // a perfect formulated url
- final String dstHostSocket = args.substring(0, sep);
- prop.put(HeaderFramework.CONNECTION_PROP_HOST, (HTTPDemon.isThisHostName(dstHostSocket) ? virtualHost : dstHostSocket));
- path = args.substring(sep); // yes, including beginning "/"
- }
- } else {
- // no host in url. set path
- if (args.length() > 0 && args.charAt(0) == '/') {
- // thats also fine, its a perfect localhost access
- // in this case, we simulate a
- // http://localhost/s
- // access by setting a virtual host
- prop.put(HeaderFramework.CONNECTION_PROP_HOST, virtualHost);
- path = args;
- } else {
- // the client 'forgot' to set a leading '/'
- // this is the same case as above, with some lazyness
- prop.put(HeaderFramework.CONNECTION_PROP_HOST, virtualHost);
- path = "/" + args;
- }
- }
- prop.put(HeaderFramework.CONNECTION_PROP_PATH, path);
-
- // find out file extension (we already stripped ?-parameters from args)
- final String ext;
- sep = path.lastIndexOf('.');
- if (sep >= 0) {
- final int ancpos = path.indexOf("#", sep + 1);
- if (ancpos >= sep) {
- // ex: /foo/bar.html#xy => html
- ext = path.substring(sep + 1, ancpos).toLowerCase();
- } else {
- // ex: /foo/bar.php => php
- ext = path.substring(sep + 1).toLowerCase();
- }
- } else {
- ext = ""; // default when no file extension
- }
- prop.put(HeaderFramework.CONNECTION_PROP_EXT, ext);
-
- return prop;
- }
}
diff --git a/source/net/yacy/server/http/ServerSideIncludes.java b/source/net/yacy/server/http/ServerSideIncludes.java
deleted file mode 100644
index e2a848f33..000000000
--- a/source/net/yacy/server/http/ServerSideIncludes.java
+++ /dev/null
@@ -1,99 +0,0 @@
-// ServerSideIncludes.java
-// -----------------------------
-// (C) 2007 by Michael Peter Christen; [email protected], Frankfurt a. M., Germany
-// first published 26.06.2007 on http://yacy.net
-//
-// This is a part of YaCy, a peer-to-peer based web search engine
-//
-// $LastChangedDate$
-// $LastChangedRevision$
-// $LastChangedBy$
-//
-// LICENSE
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program 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 General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-package net.yacy.server.http;
-
-import java.io.IOException;
-import java.io.OutputStream;
-import java.util.HashMap;
-
-import net.yacy.cora.document.encoding.ASCII;
-import net.yacy.cora.protocol.HeaderFramework;
-import net.yacy.cora.protocol.RequestHeader;
-import net.yacy.cora.util.ByteBuffer;
-
-
-public class ServerSideIncludes {
-
- public static void writeSSI(final ByteBuffer in, final OutputStream out, final String authorization, final String requesthost, final RequestHeader requestHeader) throws IOException {
- writeSSI(in, 0, out, authorization, requesthost, requestHeader);
- }
-
- private static void writeSSI(final ByteBuffer in, int off, final OutputStream out, final String authorization, final String requesthost, final RequestHeader requestHeader) throws IOException {
- int p = in.indexOf(ASCII.getBytes("<!--#"), off);
- int q;
- while (p >= 0) {
- q = in.indexOf(ASCII.getBytes("-->"), p + 10);
- if (out instanceof ChunkedOutputStream) {
- ((ChunkedOutputStream) out).write(in, off, p - off);
- } else {
- out.write(in.getBytes(off, p - off));
- }
- parseSSI(in, p, out, authorization, requesthost, requestHeader);
- off = q + 3;
- p = in.indexOf(ASCII.getBytes("<!--#"), off);
- }
- if (out instanceof ChunkedOutputStream) {
- ((ChunkedOutputStream) out).write(in, off, in.length() - off);
- } else {
- out.write(in.getBytes(off, in.length() - off));
- }
- }
-
- private static void parseSSI(final ByteBuffer in, final int off, final OutputStream out, final String authorization, final String requesthost, final RequestHeader requestHeader) {
- if (in.startsWith(ASCII.getBytes("<!--#include virtual=\""), off)) {
- final int q = in.indexOf(ASCII.getBytes("\""), off + 22);
- if (q > 0) {
- final String path = in.toString(off + 22, q - off - 22);
- writeContent(path, out, authorization, requesthost, requestHeader);
- }
- }
- }
-
- public static void writeContent(String path, final OutputStream out, final String authorization, final String requesthost, final RequestHeader requestHeader) {
- // check if there are arguments in path string
- String args = "";
- final int argpos = path.indexOf('?');
- if (argpos > 0) {
- args = path.substring(argpos + 1);
- path = path.substring(0, argpos);
- }
-
- // set up virtual connection properties to call httpdFileHander.doGet()
- final HashMap<String, Object> conProp = new HashMap<String, Object>();
- final RequestHeader header = new RequestHeader(HTTPDemon.reverseMappingCache);
- conProp.put(HeaderFramework.CONNECTION_PROP_METHOD, HeaderFramework.METHOD_GET);
- conProp.put(HeaderFramework.CONNECTION_PROP_PATH, path);
- conProp.put(HeaderFramework.CONNECTION_PROP_ARGS, args);
- conProp.put(HeaderFramework.CONNECTION_PROP_HTTP_VER, HeaderFramework.HTTP_VERSION_0_9);
- conProp.put(HeaderFramework.CONNECTION_PROP_CLIENTIP, requesthost);
- header.put(RequestHeader.AUTHORIZATION, authorization);
- if (requestHeader.containsKey(RequestHeader.COOKIE)) header.put(RequestHeader.COOKIE, requestHeader.get(RequestHeader.COOKIE));
- header.put(RequestHeader.REFERER, requestHeader.get(RequestHeader.REFERER));
- HTTPDFileHandler.doGet(conProp, header, out);
- }
-}
diff --git a/source/net/yacy/server/serverCore.java b/source/net/yacy/server/serverCore.java
index 0342cea38..dab2d4596 100644
--- a/source/net/yacy/server/serverCore.java
+++ b/source/net/yacy/server/serverCore.java
@@ -26,221 +26,20 @@
package net.yacy.server;
-// standard server
-import java.io.FileInputStream;
-import java.io.FileOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PushbackInputStream;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.net.Inet4Address;
-import java.net.InetAddress;
-import java.net.InetSocketAddress;
-import java.net.NetworkInterface;
-import java.net.ServerSocket;
-import java.net.Socket;
-import java.net.SocketException;
-import java.nio.channels.ClosedByInterruptException;
-import java.security.KeyStore;
-import java.util.ArrayList;
-import java.util.ConcurrentModificationException;
-import java.util.Enumeration;
-import java.util.List;
-import java.util.Map;
-import java.util.concurrent.ConcurrentHashMap;
-
-import javax.net.ssl.HandshakeCompletedEvent;
-import javax.net.ssl.HandshakeCompletedListener;
-import javax.net.ssl.KeyManagerFactory;
-import javax.net.ssl.SSLContext;
-import javax.net.ssl.SSLSocket;
-import javax.net.ssl.SSLSocketFactory;
import net.yacy.cora.document.encoding.UTF8;
-import net.yacy.cora.protocol.Domains;
-import net.yacy.cora.util.ByteBuffer;
-import net.yacy.cora.util.ConcurrentLog;
-import net.yacy.http.YaCyHttpServer;
-import net.yacy.kelondro.workflow.AbstractBusyThread;
-import net.yacy.kelondro.workflow.BusyThread;
-import net.yacy.utils.PKCS12Tool;
-public final class serverCore extends AbstractBusyThread implements BusyThread, YaCyHttpServer {
+public final class serverCore {
// special ASCII codes used for protocol handling
- /**
- * Horizontal Tab
- */
- public static final byte HT = 9;
- /**
- * Line Feed
- */
- public static final byte LF = 10;
- /**
- * Carriage Return
- */
- public static final byte CR = 13;
- /**
- * Space
- */
- public static final byte SP = 32;
- /**
- * Line End of HTTP/ICAP headers
- */
- public static final byte[] CRLF = {CR, LF};
- public static final String CRLF_STRING = UTF8.String(CRLF);
- public static final String LF_STRING = UTF8.String(new byte[]{LF});
- public static final Class<?>[] sessionCallType = {String.class, Session.class}; // set up some reflection
- public static final long startupTime = System.currentTimeMillis();
- private static final ThreadGroup sessionThreadGroup = new ThreadGroup("sessionThreadGroup");
- private static final Map<String, Method> commandObjMethodCache = new ConcurrentHashMap<String, Method>(5);
-
- /**
- * will be increased with each session and is used to return a hash code
- */
- static int sessionCounter = 0;
-
- // static variables
- private static final long keepAliveTimeout = 60000; // time that a connection is kept alive if requested with a keepAlive statement
- public static final Boolean TERMINATE_CONNECTION = Boolean.FALSE;
- public static final Boolean RESUME_CONNECTION = Boolean.TRUE;
-
- /**
- * for brute-force prevention
- */
- public static final Map<String, Integer> bfHost = new ConcurrentHashMap<String, Integer>();
-
- // class variables
- /**
- * the port, which is visible from outside (in most cases bind-port)
- */
- private String extendedPort;
- /**
- * if set, yacy will bind to this port, but set extendedPort in the seed
- */
- private String bindPort;
- /**
- * specifies if the server should try to do a restart
- */
- boolean forceRestart = false;
+ private static final byte LF = 10;
+ private static final byte CR = 13;
+ public static final byte[] CRLF = {CR, LF};
+ public static final String CRLF_STRING = UTF8.String(CRLF);
+ public static final String LF_STRING = UTF8.String(new byte[]{LF});
+ public static final long startupTime = System.currentTimeMillis();
public static boolean useStaticIP = false;
- protected ConcurrentLog log;
- private SSLSocketFactory sslSocketFactory = null;
- private ServerSocket socket; // listener
- private final int timeout; // connection time-out of the socket
- serverHandler handlerPrototype; // the command class (a serverHandler)
-
- private final serverSwitch switchboard; // the command class switchboard
- private final Map<String, String> denyHost;
- int commandMaxLength;
- private int maxBusySessions;
- private long lastAutoTermination;
-
- public final void terminateOldSessions(final long minage) {
- if (System.currentTimeMillis() - this.lastAutoTermination < minage) return;
- this.lastAutoTermination = System.currentTimeMillis();
- //if (serverCore.getJobCount() < maxBusySessions - 10) return; // don't panic
-
- for (final Session s: getJobList()) {
- if (!s.isAlive()) continue;
- if (s.getTime() < minage) continue;
-
- // stop thread
- this.log.info("check for " + s.getName() + ": " + s.getTime() + " ms alive, stopping thread");
-
- // trying to stop session
- s.setStopped(true);
- try { Thread.sleep(10); } catch (final InterruptedException ex) {}
-
- // trying to interrupt session
- synchronized (s) {
- s.notify();
- }
- s.interrupt();
-
- // trying to close socket
- if (s.isAlive()) {
- s.close();
- }
- }
- }
-
- public static String clientAddress(final Socket s) {
- final InetAddress uAddr = s.getInetAddress();
- if (uAddr.isAnyLocalAddress()) return Domains.LOCALHOST;
- String cIP = uAddr.getHostAddress();
- if (Domains.isLocal(cIP, null)) cIP = Domains.LOCALHOST;
- return cIP;
- }
-
- // class initializer
- public serverCore(
- final int timeout,
- final boolean blockAttack,
- final serverHandler handlerPrototype,
- final serverSwitch switchboard,
- final int commandMaxLength
- ) {
- super(Long.MIN_VALUE, Long.MAX_VALUE, Long.MIN_VALUE, Long.MAX_VALUE);
- this.timeout = timeout;
-
- this.commandMaxLength = commandMaxLength;
- this.denyHost = (blockAttack) ? new ConcurrentHashMap<String, String>() : null;
- this.handlerPrototype = handlerPrototype;
- this.switchboard = switchboard;
-
- // initialize logger
- this.log = new ConcurrentLog("SERVER");
-
- // init the ssl socket factory
- this.sslSocketFactory = initSSLFactory();
-
- // init session parameter
- this.maxBusySessions = Math.max(1, Integer.parseInt(switchboard.getConfig("httpdMaxBusySessions","100")));
-
- this.lastAutoTermination = System.currentTimeMillis();
-
- // init servercore
- init();
- }
-
- @Override
- public boolean withSSL() {
- return this.sslSocketFactory != null && this.switchboard.getConfigBool("server.https", false);
- }
-
- public synchronized void init() {
- this.log.info("Initializing serverCore ...");
-
- // read some config values
- this.extendedPort = this.switchboard.getConfig("port", "8090").trim();
- this.bindPort = this.switchboard.getConfig("bindPort", "").trim();
-
- // Open a new server-socket channel
- try {
- // bind the ServerSocket to a specific address
- // InetSocketAddress bindAddress = null;
- this.socket = new ServerSocket();
- if (this.bindPort == null || this.bindPort.equals("")) {
- this.log.info("Trying to bind server to port " + this.extendedPort);
- this.socket.bind(/*bindAddress = */generateSocketAddress(this.extendedPort));
- } else { //bindPort set, use another port to bind than the port reachable from outside
- this.log.info("Trying to bind server to port " + this.bindPort+ " with "+ this.extendedPort + "as seedPort.");
- this.socket.bind(/*bindAddress = */generateSocketAddress(this.bindPort));
- }
- // updating the port information
- //yacyCore.seedDB.mySeed.put(yacySeed.PORT,Integer.toString(bindAddress.getPort()));
- //yacyCore.seedDB.mySeed().put(yacySeed.PORT, extendedPort);
- } catch (final Exception e) {
- final String errorMsg = "FATAL ERROR: " + e.getMessage() + " - probably root access rights needed. check port number";
- this.log.severe(errorMsg);
- System.out.println(errorMsg);
- System.exit(0);
- }
- }
public static int getPortNr(String extendedPortString) {
int pos = -1;
@@ -250,892 +49,5 @@ public final class serverCore extends AbstractBusyThread implements BusyThread,
return Integer.parseInt(extendedPortString);
}
- @Override
- public InetSocketAddress generateSocketAddress(String extendedPortString) throws SocketException {
-
- // parsing the port configuration
- String bindIP = null;
- int bindPort;
-
- int pos = -1;
- if ((pos = extendedPortString.indexOf(':'))!= -1) {
- bindIP = extendedPortString.substring(0,pos).trim();
- extendedPortString = extendedPortString.substring(pos+1);
-
- if (bindIP.length() > 0 && bindIP.charAt(0) == '#') {
- final String interfaceName = bindIP.substring(1);
- String hostName = null;
- if (this.log.isFine()) this.log.fine("Trying to determine IP address of interface '" + interfaceName + "'.");
-
- final Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
- if (interfaces != null) {
- while (interfaces.hasMoreElements()) {
- final NetworkInterface interf = interfaces.nextElement();
- if (interf.getName().equalsIgnoreCase(interfaceName)) {
- final Enumeration<InetAddress> addresses = interf.getInetAddresses();
- if (addresses != null) {
- while (addresses.hasMoreElements()) {
- final InetAddress address = addresses.nextElement();
- if (address instanceof Inet4Address) {
- hostName = address.getHostAddress();
- break;
- }
- }
- }
- }
- }
- }
- if (hostName == null) {
- this.log.warn("Unable to find interface with name '" + interfaceName + "'. Binding server to all interfaces");
- bindIP = null;
- } else {
- this.log.info("Binding server to interface '" + interfaceName + "' with IP '" + hostName + "'.");
- bindIP = hostName;
- }
- }
- }
- bindPort = Integer.parseInt(extendedPortString);
-
- return (bindIP == null)
- ? new InetSocketAddress(bindPort)
- : new InetSocketAddress(bindIP, bindPort);
- }
-
- @Override
- public void open() {
- this.log.config("* server started on " + Domains.myPublicLocalIP() + ":" + this.extendedPort);
- }
-
- @Override
- public void freemem() {
- // FIXME: can we something here to flush memory? Idea: Reduce the size of some of our various caches.
- }
-
- // class body
- @Override
- public boolean job() throws Exception {
- try {
- // prepare for new connection
- // idleThreadCheck();
- final int jobCount = getJobCount();
- this.switchboard.handleBusyState(jobCount);
- if (this.log.isFinest()) this.log.finest("* waiting for connections, " + jobCount + " sessions running");
-
- announceThreadBlockApply();
-
- // wait for new connection
- Socket controlSocket = this.socket.accept();
-
- announceThreadBlockRelease();
-
- if (jobCount >= this.maxBusySessions) {
- terminateOldSessions(3000);
- this.log.info("termination of old sessions: before = " + jobCount + ", after = " + getJobCount());
- //if (getJobCount() < this.maxBusySessions) break;
- //if (trycount++ > 5) break;
- //Thread.sleep(1000); // lets try again after a short break
- }
- /*
- if (getJobCount() >= this.maxBusySessions) {
- // immediately close connection if too much sessions are still running
- this.log.logWarning("* connections (" + getJobCount() + ") exceeding limit (" + this.maxBusySessions + ")" + ", closing new incoming connection from "+ controlSocket.getRemoteSocketAddress());
-
- controlSocket.close();
- return false;
-
- }
- */
-
- final String cIP = clientAddress(controlSocket);
- //System.out.println("server bfHosts=" + bfHost.toString());
- /*
- if (bfHost.get(cIP) != null) {
- Integer attempts = bfHost.get(cIP);
- if (attempts == null) attempts = Integer.valueOf(1); else attempts = Integer.valueOf(attempts.intValue() + 1);
- bfHost.put(cIP, attempts);
- this.log.logWarning("SLOWING DOWN ACCESS FOR BRUTE-FORCE PREVENTION FROM " + cIP + ", ATTEMPT " + attempts.intValue());
- // add a delay to make brute-force harder
- announceThreadBlockApply();
- try {Thread.sleep(attempts.intValue());} catch (final InterruptedException e) {}
- announceThreadBlockRelease();
- if ((attempts.intValue() >= 10) && (this.denyHost != null)) {
- this.denyHost.put(cIP, "deny");
- }
- }
- */
-
- if ((this.denyHost == null) || (this.denyHost.get(cIP) == null)) {
- // setting the timeout properly
- assert this.timeout >= 1000;
- controlSocket.setSoTimeout(this.timeout);
-
- // wrap this socket
- if (withSSL()) {
- controlSocket = new serverCoreSocket(controlSocket);
-
- // if the current connection is SSL we need to do a handshake
- if (((serverCoreSocket)controlSocket).isSSL()) {
- controlSocket = negotiateSSL(controlSocket);
- }
- }
- // keep-alive: if set to true, the server frequently sends keep-alive packets to the client which the client must respond to
- // we set this to false to prevent that a missing ack from the client forces the server to close the connection
- controlSocket.setKeepAlive(false);
-
- // disable Nagle's algorithm (waiting for more data until packet is full)
- // controlSocket.setTcpNoDelay(true);
-
- // set a non-zero linger, that means that a socket.close() blocks until all data is written
- controlSocket.setSoLinger(false, this.timeout);
-
- // ensure that MTU-48 is not exceeded to prevent that routers cannot handle large data packets
- // read http://www.cisco.com/warp/public/105/38.shtml for explanation
- //controlSocket.setSendBufferSize(1440);
- //controlSocket.setReceiveBufferSize(1440);
-
- // create session
- final Session connection = new Session(sessionThreadGroup, controlSocket, this.timeout);
- //terminateOldSessions(60000);
- connection.start();
- } else {
- this.log.warn("ACCESS FROM " + cIP + " DENIED");
- }
-
- return true;
- } catch (final SocketException e) {
- if (this.forceRestart) {
- // reinitialize serverCore
- init();
- this.forceRestart = false;
- return true;
- }
- throw e;
- }
- }
-
- @Override
- public synchronized void close() {
- // consuming the isInterrupted Flag. Otherwise we could not properly close the session pool
- Thread.interrupted();
-
- // shut down all busySessions
- for (final Session session: getJobList()) {
- if (session == null) continue;
- try {
- session.interrupt();
- } catch (final SecurityException e ) {
- ConcurrentLog.logException(e);
- } catch (final ConcurrentModificationException e) {
- ConcurrentLog.logException(e);
- }
- }
-
- // close the serverchannel and socket
- try {
- this.log.info("Closing server socket ...");
- this.socket.close();
- } catch (final Exception e) {
- this.log.warn("Unable to close the server socket.");
- }
-
- // close all sessions
- this.log.info("Closing server sessions ...");
- for (final Session session: getJobList()) {
- session.interrupt();
- //session.close();
- }
-
- this.log.config("* terminated");
- }
-
- public static List<Session> getJobList() {
- final Thread[] threadList = new Thread[sessionThreadGroup.activeCount()];
- serverCore.sessionThreadGroup.enumerate(threadList, false);
- final ArrayList<Session> l = new ArrayList<Session>();
- for (final Thread t: threadList) {
- if (t == null) continue;
- if (!(t instanceof Session)) {
- //log.logSevere("serverCore.getJobList - thread is not Session: " + t.getClass().getName());
- continue;
- }
- l.add((Session) t);
- }
- return l;
- }
-
- @Override
- public int getJobCount() {
- final Thread[] threadList = new Thread[sessionThreadGroup.activeCount()];
- serverCore.sessionThreadGroup.enumerate(threadList, false);
- int c = 0;
- for (final Thread t: threadList) {
- if (t == null) continue;
- if (!(t instanceof Session)) {
- //log.logSevere("serverCore.getJobList - thread is not Session: " + t.getClass().getName());
- continue;
- }
- c++;
- }
- return c;
- }
-
- // idle sensor: the thread is idle if there are no sessions running
- public static boolean idle() {
- // idleThreadCheck();
- final Thread[] threadList = new Thread[sessionThreadGroup.activeCount()];
- serverCore.sessionThreadGroup.enumerate(threadList, false);
- for (final Thread t: threadList) {
- if (t == null) continue;
- if (!(t instanceof Session)) {
- //log.logSevere("serverCore.getJobList - thread is not Session: " + t.getClass().getName());
- continue;
- }
- return false;
- }
- return true;
- //return (getJobCount() == 0);
- }
-
- @Override
- public int getMaxSessionCount() {
- return this.maxBusySessions;
- }
-
- @Override
- public void setMaxSessionCount(final int count) {
- this.maxBusySessions = count;
- }
-
- @Override
- public void startupServer() throws Exception {
- this.start();
- }
-
- @Override
- public String getVersion() {
- return "AnomicHTTPD (www.anomic.de)";
- }
-
- public final class Session extends Thread {
-
- //boolean destroyed = false;
- private boolean runningsession = false;
- private boolean stopped = false;
-
- private long start; // startup time
- private serverHandler commandObj;
-
- private String request; // current command line
- private int commandCounter; // for logging: number of commands in this session
- private String identity; // a string that identifies the client (i.e. ftp: account name)
- //private boolean promiscuous; // if true, no lines are read and streams are only passed
-
- public Socket controlSocket; // dialog socket
- public InetAddress userAddress; // the address of the client
- public int userPort; // the ip port used by the client
- public PushbackInputStream in; // on control input stream
- public OutputStream out; // on control output stream, auto-flush
- public int socketTimeout;
- public int hashIndex;
-
- public Session(final ThreadGroup theThreadGroup, final Socket controlSocket, final int socketTimeout) {
- super(theThreadGroup, controlSocket.getInetAddress().toString() + "@" + Long.toString(System.currentTimeMillis()));
- setPriority(Thread.MAX_PRIORITY);
- this.socketTimeout = socketTimeout;
- this.controlSocket = controlSocket;
- this.hashIndex = sessionCounter;
- sessionCounter++;
- }
-
- @Override
- public int hashCode() {
- // return a hash code so it is possible to store objects of httpc objects in a HashSet
- return this.hashIndex;
- }
-
- public int getCommandCount() {
- return this.commandCounter;
- }
-
- public String getCommandLine() {
- return this.request;
- }
-
- public serverHandler getCommandObj() {
- return this.commandObj;
- }
-
- public InetAddress getUserAddress() {
- return this.userAddress;
- }
-
- public int getUserPort() {
- return this.userPort;
- }
-
- public void setStopped(final boolean stopped) {
- this.stopped = stopped;
- }
-
- public boolean isStopped() {
- return this.stopped;
- }
-
- public synchronized void close() {
- // closing the socket to the client
- if (this.controlSocket != null) try {
- this.controlSocket.close();
- serverCore.this.log.info("Closing main socket of thread '" + getName() + "'");
- this.controlSocket = null;
- } catch (final Exception e) {}
- }
-
- public long getRequestStartTime() {
- return this.start;
- }
-
- public long getTime() {
- return System.currentTimeMillis() - this.start;
- }
-
- public void setIdentity(final String id) {
- this.identity = id;
- }
-
- public void log(final boolean outgoing, final String request) {
- if (serverCore.this.log.isFine()) serverCore.this.log.fine(this.userAddress.getHostAddress() + "/" + this.identity + " " +
- "[" + getJobCount() + ", " + this.commandCounter +
- ((outgoing) ? "] > " : "] < ") +
- request);
- }
-
- public void writeLine(final String messg) throws IOException {
- send(this.out, messg);
- log(true, messg);
- }
-
- public byte[] readLine() {
- return receive(this.in, serverCore.this.commandMaxLength, true);
- }
-
- /**
- * reads a line from the input socket
- * this function is provided by the server through a passed method on initialization
- * @return the next requestline as string
- */
- public String readLineAsString() {
- final byte[] l = readLine();
- return (l == null) ? null: UTF8.String(l);
- }
-
- /**
- * @return whether the {@link Thread} is currently running
- */
- public boolean isRunning() {
- return this.runningsession;
- }
-
- /**
- *
- *
- * @see java.lang.Thread#run()
- */
- @Override
- public void run() {
- this.runningsession = true;
-
- try {
- // setting the session startup time
- this.start = System.currentTimeMillis();
-
- // set the session identity
- this.identity = "-";
-
- // getting some client information
- this.userAddress = this.controlSocket.getInetAddress();
- this.userPort = this.controlSocket.getPort();
- setName("Session_" + this.userAddress.getHostAddress() + ":" + this.controlSocket.getPort());
-
- // TODO: check if we want to allow this socket to connect us
-
- // getting input and output stream for communication with client
- if (this.controlSocket.getInputStream() instanceof PushbackInputStream) {
- this.in = (PushbackInputStream) this.controlSocket.getInputStream();
- } else {
- this.in = new PushbackInputStream(this.controlSocket.getInputStream());
- }
- this.out = this.controlSocket.getOutputStream();
-
- // reseting the command counter
- this.commandCounter = 0;
-
- // listen for commands
- listen();
- } catch (final IOException e) {
- ConcurrentLog.logException(e);
- } catch (final Throwable e) {
- ConcurrentLog.logException(e);
- final Throwable targetException = (e instanceof InvocationTargetException) ? ((InvocationTargetException) e).getTargetException() : null;
- ConcurrentLog.logException(e.getCause());
- if (targetException != null) ConcurrentLog.logException(targetException);
- } finally {
- try {
- if ((this.controlSocket != null) && (! this.controlSocket.isClosed())) {
- // flush data
- this.out.flush();
-
- // maybe this doesn't work for all SSL socket implementations
- if (!(this.controlSocket instanceof SSLSocket)) {
- this.controlSocket.shutdownInput();
- this.controlSocket.shutdownOutput();
- }
-
- // close streams
- this.in.close();
- this.out.close();
-
- // close everything
- this.controlSocket.close();
- }
- } catch (final IOException e) {
- ConcurrentLog.logException(e);
- } finally {
- this.controlSocket = null;
- }
- }
-
- }
-
- private void listen() {
- try {
- // start dialog
- byte[] requestBytes = null;
- boolean terminate = false;
- String reqCmd, tmp;
- String reqProtocol = "HTTP";
- Object result;
- Object[] parameter;
- Method commandMethod;
- final long situationDependentKeepAliveTimeout = keepAliveTimeout;
- while (this.in != null &&
- this.controlSocket != null &&
- this.controlSocket.isConnected() &&
- (this.commandCounter == 0 || System.currentTimeMillis() - this.start < situationDependentKeepAliveTimeout) &&
- (requestBytes = readLine()) != null) {
- this.request = UTF8.String(requestBytes);
- setName("Session_" + this.userAddress.getHostAddress() +
- ":" + this.controlSocket.getPort() +
- "#" + this.commandCounter + "_" + this.request);
-
- //this.log.logDebug("* session " + handle + " received command '" + request + "'. time = " + (System.currentTimeMillis() - handle));
- log(false, this.request);
- try {
- // if we can not determine the proper command string we try to call function emptyRequest
- // of the commandObject
- if (this.request.trim().isEmpty()) this.request = "EMPTY";
-
- parameter = new Object[2];
-
- // get the rest of the request parameters
- final int pos = this.request.indexOf(' ');
- if (pos < 0) {
- reqCmd = this.request.trim().toUpperCase();
- parameter[0] = "";
- } else {
- reqCmd = this.request.substring(0, pos).trim().toUpperCase();
- parameter[0] = this.request.substring(pos).trim();
- }
- parameter[1] = this;
-
- // now we need to initialize the session
- if (this.commandCounter == 0) {
- // first we need to determine the proper protocol handler
- if (this.request.indexOf("HTTP",0) >= 0) reqProtocol = "HTTP";
- else reqProtocol = null;
-
- if (this.request == null) break;
- if (reqProtocol != null && reqProtocol.equals("HTTP")) {
- this.commandObj = serverCore.this.handlerPrototype.clone();
- }
- }
-
- // count the amount of requests that were processed by this session until yet
- this.commandCounter++;
-
- // setting the socket timeout for reading of the request content
- this.controlSocket.setSoTimeout(this.socketTimeout);
-
- // exec command and return value
- commandMethod = commandObjMethodCache.get(reqProtocol + "_" + reqCmd);
- if (commandMethod == null) {
- try {
- commandMethod = this.commandObj.getClass().getMethod(reqCmd, sessionCallType);
- commandObjMethodCache.put(reqProtocol + "_" + reqCmd, commandMethod);
- } catch (final NoSuchMethodException noMethod) {
- commandMethod = this.commandObj.getClass().getMethod("UNKNOWN", sessionCallType);
- parameter[0] = this.request.trim();
- }
- }
-
- result = null;
- try {
- result = commandMethod.invoke(this.commandObj, parameter);
- } catch (final OutOfMemoryError e) {
- serverCore.this.log.warn("commandMethod.invoke: OutOfMemoryError / 1 (retry1 follows)");
- // try again
- terminateOldSessions(2000);
- try {
- result = commandMethod.invoke(this.commandObj, parameter);
- } catch (final OutOfMemoryError e2) {
- serverCore.this.log.warn("commandMethod.invoke: OutOfMemoryError / 2 (retry2 follows)");
- // try again
- Thread.sleep(1000);
- result = commandMethod.invoke(this.commandObj, parameter);
- }
- }
-
- //announceMoreExecTime(commandStart - System.currentTimeMillis()); // shall be negative!
- //this.log.logDebug("* session " + handle + " completed command '" + request + "'. time = " + (System.currentTimeMillis() - handle));
- this.out.flush();
- if (result != null) {
- if (result instanceof Boolean) {
- if (((Boolean) result).equals(TERMINATE_CONNECTION)) break;
-
- /*
- * setting timeout to a very high level.
- * this is needed because of persistent connection
- * support.
- */
- if (!this.controlSocket.isClosed()) this.controlSocket.setSoTimeout(30*60*1000);
- } else if (result instanceof String) {
- if (((String) result).startsWith("!")) {
- result = ((String) result).substring(1);
- terminate = true;
- }
- writeLine((String) result);
- } else if (result instanceof InputStream) {
- tmp = send(this.out, (InputStream) result);
- if ((tmp.length() > 4) && (tmp.toUpperCase().startsWith("PASS"))) {
- log(true, "PASS ********");
- } else {
- log(true, tmp);
- }
- tmp = null;
- }
- }
- if (terminate) break;
-
-
- } catch (final InvocationTargetException e) {
- serverCore.this.log.severe("command execution, target exception " + e.getMessage() + " for client " + this.userAddress.getHostAddress(), e);
- // we extract a target exception
- writeLine(this.commandObj.error(e.getCause()));
- writeLine(this.commandObj.error(e.getTargetException()));
- break;
- } catch (final NoSuchMethodException e) {
- serverCore.this.log.severe("command execution, method exception " + e.getMessage() + " for client " + this.userAddress.getHostAddress(), e);
- if (!this.userAddress.isSiteLocalAddress()) {
- if (serverCore.this.denyHost != null) {
- serverCore.this.denyHost.put(this.userAddress.getHostAddress(), "deny"); // block client: hacker attempt
- }
- }
- break;
- } catch (final IllegalAccessException e) {
- serverCore.this.log.severe("command execution, illegal access exception " + e.getMessage() + " for client " + this.userAddress.getHostAddress(), e);
- // wrong parameters: this can only be an internal problem
- writeLine(this.commandObj.error(e));
- break;
- } catch (final ClassCastException e) {
- serverCore.this.log.severe("command execution, cast exception " + e.getMessage() + " for client " + this.userAddress.getHostAddress(), e);
- // ??
- writeLine(this.commandObj.error(e));
- break;
- } catch (final Exception e) {
- serverCore.this.log.severe("command execution, generic exception " + e.getMessage() + " for client " + this.userAddress.getHostAddress(), e);
- // whatever happens: the thread has to survive!
- writeLine("UNKNOWN REASON:" + ((this.commandObj == null) ? "no command object" : this.commandObj.error(e)));
- break;
- }
- // check if we should still keep this alive:
- break; // no more keep-alive, not needed for speed and causes only trouble
- /*
- if (getJobCount() > maxBusySessions / 2) break;
- // the more connections are alive, the shorter the keep alive timeout
- situationDependentKeepAliveTimeout = keepAliveTimeout / Math.max(1, getJobCount() - 20);
- */
- } // end of while
- } catch (final IOException e) {
- serverCore.this.log.severe("command execution, IO exception " + e.getMessage() + " for client " + this.userAddress.getHostAddress(), e);
- }
- //announceMoreExecTime(System.currentTimeMillis() - this.start);
- }
-
- public boolean isSSL() {
- return this.controlSocket != null && this.controlSocket instanceof SSLSocket;
- }
-
- }
-
- /**
- * Read a line from a protocol stream (HTTP/ICAP) and do some
- * pre-processing (check validity, strip line endings).
- * <br>
- * Illegal control characters will be stripped from the result.
- * Besides the valid line ending CRLF a single LF is treated as a
- * line ending as well to avoid errors with buggy server.
- *
- * @param pbis The stream to read from.
- * @param maxSize maximum number of bytes to read in one run.
- * @param logerr log error messages if true, be silent otherwise.
- *
- * @return A byte array representing one line of the input or
- * <code>null</null> if EOS reached.
- */
- public static byte[] receive(final PushbackInputStream pbis, final int maxSize, final boolean logerr) {
- // reuse an existing linebuffer
- final ByteBuffer readLineBuffer = new ByteBuffer(80);
-
- int bufferSize = 0, b = 0;
- try {
- // catch bytes until line end or illegal character reached or buffer full
- // resulting readLineBuffer doesn't include CRLF or illegal control chars
- while (bufferSize < maxSize) {
- b = pbis.read();
-
- if ((b > 31 && b != 127) || b == HT) {
- // add legal chars to the result
- readLineBuffer.append(b);
- bufferSize++;
- } else if (b == CR) {
- // possible beginning of CRLF, check following byte
- b = pbis.read();
- if (b == LF) {
- // line end caught: break the loop
- break;
- } else if (b >= 0) {
- // no line end: push back the byte, ignore the CR
- pbis.unread(b);
- }
- } else if (b == LF || b < 0) {
- // LF without precedent CR: treat as line end of broken servers
- // b < 0: EOS
- break;
- }
- }
-
- // EOS
- if (bufferSize == 0 && b == -1) return null;
- return readLineBuffer.getBytes();
- } catch (final ClosedByInterruptException e) {
- if (logerr) ConcurrentLog.warn("SERVER", "receive interrupted");
- return null;
- } catch (final IOException e) {
- final String message = e.getMessage();
- if (logerr && !message.equals("Socket closed") && !message.equals("Connection reset") && !message.equals("Read timed out")) ConcurrentLog.warn("SERVER", "receive closed by IOException: " + e.getMessage());
- return null;
- } finally {
- try {
- readLineBuffer.close();
- } catch (final IOException e) {
- ConcurrentLog.logException(e);
- }
- }
- }
-
- public static void send(final OutputStream os, final String buf) throws IOException {
- os.write(UTF8.getBytes(buf));
- os.write(CRLF);
- os.flush();
- }
-
- public static void send(final OutputStream os, final byte[] buf) throws IOException {
- os.write(buf);
- os.write(CRLF);
- os.flush();
- }
-
- public static String send(final OutputStream os, final InputStream is) throws IOException {
- final int bufferSize = is.available();
- final byte[] buffer = new byte[((bufferSize < 1) || (bufferSize > 4096)) ? 4096 : bufferSize];
- int l;
- while ((l = is.read(buffer)) > 0) {os.write(buffer, 0, l);}
- os.write(CRLF);
- os.flush();
- if (bufferSize > 80) return "<LONG STREAM>";
- return UTF8.String(buffer);
- }
-
- public static final void checkInterruption() throws InterruptedException {
- final Thread currentThread = Thread.currentThread();
- if (currentThread.isInterrupted()) throw new InterruptedException();
- if ((currentThread instanceof serverCore.Session) && ((serverCore.Session)currentThread).isStopped()) throw new InterruptedException();
- }
-
- @Override
- public void reconnect(final int delay) {
- final Thread restart = new Restarter(delay);
- restart.start();
- }
-
- // restarting the serverCore
- public class Restarter extends Thread {
- public serverCore theServerCore = null;
- public int delay = 5000;
- public Restarter(final int delay) {
- this.delay = delay;
- }
- @Override
- public void run() {
- // waiting for a while
- try {
- Thread.sleep(this.delay);
- } catch (final InterruptedException e) {
- ConcurrentLog.logException(e);
- } catch (final Exception e) {
- ConcurrentLog.logException(e);
- }
-
- // signaling restart
- serverCore.this.forceRestart = true;
-
- // closing socket to notify the thread
- close();
- }
- }
-
- private SSLSocketFactory initSSLFactory() {
-
- // getting the keystore file name
- String keyStoreFileName = this.switchboard.getConfig("keyStore", "").trim();
-
- // getting the keystore pwd
- String keyStorePwd = this.switchboard.getConfig("keyStorePassword", "").trim();
-
- // take a look if we have something to import
- final String pkcs12ImportFile = this.switchboard.getConfig("pkcs12ImportFile", "").trim();
-
- // if no keyStore and no import is defined, then set the default key
- if (keyStoreFileName.isEmpty() && keyStorePwd.isEmpty() && pkcs12ImportFile.isEmpty()) {
- keyStoreFileName = "defaults/freeworldKeystore";
- keyStorePwd = "freeworld";
- this.switchboard.setConfig("keyStore", keyStoreFileName);
- this.switchboard.setConfig("keyStorePassword", keyStorePwd);
- }
-
- if (pkcs12ImportFile.length() > 0) {
- this.log.info("Import certificates from import file '" + pkcs12ImportFile + "'.");
-
- try {
- // getting the password
- final String pkcs12ImportPwd = this.switchboard.getConfig("pkcs12ImportPwd", "").trim();
-
- // creating tool to import cert
- final PKCS12Tool pkcsTool = new PKCS12Tool(pkcs12ImportFile,pkcs12ImportPwd);
-
- // creating a new keystore file
- if (keyStoreFileName.isEmpty()) {
- // using the default keystore name
- keyStoreFileName = "DATA/SETTINGS/myPeerKeystore";
-
- // creating an empty java keystore
- final KeyStore ks = KeyStore.getInstance("JKS");
- ks.load(null,keyStorePwd.toCharArray());
- final FileOutputStream ksOut = new FileOutputStream(keyStoreFileName);
- ks.store(ksOut, keyStorePwd.toCharArray());
- ksOut.close();
-
- // storing path to keystore into config file
- this.switchboard.setConfig("keyStore", keyStoreFileName);
- }
-
- // importing certificate
- pkcsTool.importToJKS(keyStoreFileName, keyStorePwd);
-
- // removing entries from config file
- this.switchboard.setConfig("pkcs12ImportFile", "");
- this.switchboard.setConfig("keyStorePassword", "");
-
- // deleting original import file
- // TODO: should we do this
-
- } catch (final Exception e) {
- this.log.severe("Unable to import certificate from import file '" + pkcs12ImportFile + "'.",e);
- }
- } else if (keyStoreFileName.isEmpty()) return null;
-
-
- // get the ssl context
- try {
- this.log.info("Initializing SSL support ...");
-
- // creating a new keystore instance of type (java key store)
- if (this.log.isFine()) this.log.fine("Initializing keystore ...");
- final KeyStore ks = KeyStore.getInstance("JKS");
-
- // loading keystore data from file
- if (this.log.isFine()) this.log.fine("Loading keystore file " + keyStoreFileName);
- final FileInputStream stream = new FileInputStream(keyStoreFileName);
- ks.load(stream, keyStorePwd.toCharArray());
- stream.close();
-
- // creating a keystore factory
- if (this.log.isFine()) this.log.fine("Initializing key manager factory ...");
- final KeyManagerFactory kmf = KeyManagerFactory.getInstance(KeyManagerFactory.getDefaultAlgorithm());
- kmf.init(ks,keyStorePwd.toCharArray());
-
- // initializing the ssl context
- if (this.log.isFine()) this.log.fine("Initializing SSL context ...");
- final SSLContext sslcontext = SSLContext.getInstance("TLS");
- sslcontext.init(kmf.getKeyManagers(), null, null);
-
- final SSLSocketFactory factory = sslcontext.getSocketFactory();
- this.log.info("SSL support initialized successfully");
- return factory;
- } catch (final Exception e) {
- final String errorMsg = "FATAL ERROR: Unable to initialize the SSL Socket factory. " + e.getMessage();
- this.log.severe(errorMsg);
- System.out.println(errorMsg);
- System.exit(0);
- return null;
- }
- }
-
- public Socket negotiateSSL(final Socket sock) throws Exception {
-
- SSLSocket sslsock;
-
- try {
- sslsock=(SSLSocket)this.sslSocketFactory.createSocket(
- sock,
- sock.getInetAddress().getHostAddress(),
- sock.getPort(),
- true);
-
- sslsock.addHandshakeCompletedListener(
- new HandshakeCompletedListener() {
- @Override
- public void handshakeCompleted(
- final HandshakeCompletedEvent event) {
- //System.out.println("Handshake finished!");
- //System.out.println("\t CipherSuite:" + event.getCipherSuite());
- //System.out.println("\t SessionId " + event.getSession());
- //System.out.println("\t PeerHost " + event.getSession().getPeerHost());
- }
- }
- );
-
- sslsock.setUseClientMode(false);
- final String[] suites = sslsock.getSupportedCipherSuites();
- sslsock.setEnabledCipherSuites(suites);
-// start handshake
- sslsock.startHandshake();
-
- //String cipherSuite = sslsock.getSession().getCipherSuite();
-
- return sslsock;
- } catch (final Exception e) {
- throw e;
- }
- }
}
diff --git a/source/net/yacy/server/serverCoreSocket.java b/source/net/yacy/server/serverCoreSocket.java
deleted file mode 100644
index 680821f41..000000000
--- a/source/net/yacy/server/serverCoreSocket.java
+++ /dev/null
@@ -1,212 +0,0 @@
-//serverCoreSocket.java
-//-------------------------------------
-//part of YACY
-//
-//(C) 2006 by Martin Thelian
-//
-//last change: $LastChangedDate$ by $LastChangedBy$
-//Revision: $LastChangedRevision$
-//
-//This program is free software; you can redistribute it and/or modify
-//it under the terms of the GNU General Public License as published by
-//the Free Software Foundation; either version 2 of the License, or
-//(at your option) any later version.
-//
-//This program 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 General Public License for more details.
-//
-//You should have received a copy of the GNU General Public License
-//along with this program; if not, write to the Free Software
-//Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-package net.yacy.server;
-
-import java.io.IOException;
-import java.io.InputStream;
-import java.io.OutputStream;
-import java.io.PushbackInputStream;
-import java.net.InetAddress;
-import java.net.Socket;
-import java.net.SocketAddress;
-import java.net.SocketException;
-import java.nio.channels.SocketChannel;
-
-public class serverCoreSocket extends Socket {
-
- private PushbackInputStream input = null;
- private Socket sock = null;
- private boolean isSSL = false;
- private String sslType = null;
-
- public serverCoreSocket(final Socket sock) throws IOException {
- this.sock = sock;
-
- // determine the socket type
- detectSSL();
- }
-
- public boolean isSSL() {
- return this.isSSL;
- }
-
- public String getProtocol() {
- return this.sslType;
- }
-
- private void detectSSL() throws IOException {
- final InputStream in = getInputStream();
-
- // read the first 5 bytes to determine the protocol type
- final byte[] preRead = new byte[5];
- int read, count = 0;
- while ((count < preRead.length) && ((read = in.read()) != -1)) {
- preRead[count] = (byte) read;
- count++;
- }
- if (count < preRead.length) {
- ((PushbackInputStream) in).unread(preRead,0,count);
- return;
- }
-
- int idx = 0;
- if ((preRead[0] & 0xFF) == 22) {
- // we have detected the ContentType field.
- // 22 means "handshake"
- idx = 1;
- } else {
- // SSL messages have two preceding bytes
- // byte nr 3 specifies the handshake type
- // 3 means "ClientHello"
- final int handshakeType = preRead[2] & 0x00FF;
- if (handshakeType == 1) this.isSSL = true;
- idx = 3;
- }
-
- // determine the protocol version
- if (preRead[idx] == 3 && (preRead[idx+1] >= 0 && preRead[idx+1] <= 2)) {
- switch (preRead[idx+1]) {
- case 0:
- this.sslType = "SSL_3";
- break;
- case 1:
- this.sslType = "TLS_1";
- break;
- case 2:
- this.sslType = "TLS_1_1";
- break;
- default:
- this.sslType = "SSL_3";
- break;
- }
- this.isSSL = true;
- //} else {
- // maybe SSL_2, but we can not be sure
- }
-
- // unread pre read bytes
- ((PushbackInputStream) in).unread(preRead);
- }
-
- @Override
- public InetAddress getInetAddress() {
- return this.sock.getInetAddress();
- }
-
- @Override
- public InetAddress getLocalAddress() {
- return this.sock.getLocalAddress();
- }
-
- @Override
- public int getPort() {
- return this.sock.getPort();
- }
-
- @Override
- public int getLocalPort() {
- return this.sock.getLocalPort();
- }
-
- @Override
- public SocketAddress getRemoteSocketAddress() {
- return this.sock.getRemoteSocketAddress();
- }
-
- @Override
- public SocketAddress getLocalSocketAddress() {
- return this.sock.getLocalSocketAddress();
- }
-
- @Override
- public SocketChannel getChannel() {
- return this.sock.getChannel();
- }
-
-
- @Override
- public InputStream getInputStream() throws IOException {
- if (this.input == null) {
- this.input = new PushbackInputStream(this.sock.getInputStream(),100);
- }
- return this.input;
- }
-
- @Override
- public OutputStream getOutputStream() throws IOException {
- return this.sock.getOutputStream();
- }
-
-
- @Override
- public synchronized void close() throws IOException {
- this.sock.close();
- }
-
- @Override
- public void shutdownInput() throws IOException {
- this.sock.shutdownInput();
- }
-
- @Override
- public void shutdownOutput() throws IOException {
- this.sock.shutdownOutput();
- }
-
- @Override
- public String toString() {
- return this.sock.toString();
- }
-
- @Override
- public boolean isConnected() {
- return this.sock.isConnected();
- }
-
- @Override
- public boolean isBound() {
- return this.sock.isBound();
- }
-
- @Override
- public boolean isClosed() {
- return this.sock.isClosed();
- }
-
- @Override
- public boolean isInputShutdown() {
- return this.sock.isInputShutdown();
- }
-
- @Override
- public boolean isOutputShutdown() {
- return this.sock.isOutputShutdown();
- }
-
- @Override
- public synchronized void setSoTimeout(final int timeout) throws SocketException {
- this.sock.setSoTimeout(timeout);
- }
-
-}
diff --git a/source/net/yacy/server/serverHandler.java b/source/net/yacy/server/serverHandler.java
deleted file mode 100644
index f3a9264b4..000000000
--- a/source/net/yacy/server/serverHandler.java
+++ /dev/null
@@ -1,105 +0,0 @@
-// serverHandler.java
-// -------------------------------------------
-// (C) by Michael Peter Christen; [email protected]
-// first published on http://www.anomic.de
-// Frankfurt, Germany, 2004
-// last major change: 05.04.2004
-//
-// This program is free software; you can redistribute it and/or modify
-// it under the terms of the GNU General Public License as published by
-// the Free Software Foundation; either version 2 of the License, or
-// (at your option) any later version.
-//
-// This program 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 General Public License for more details.
-//
-// You should have received a copy of the GNU General Public License
-// along with this program; if not, write to the Free Software
-// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
-
-/*
- serverHandler:
-
- A Generic Server becomes a server for s specific protocol by impementation of
- a corresponding handler class. The handler class provides methods for each
- command of the protocol that is implemented.
- The Handler class is assigned to the serverCore by passing the handlers
- name to the serverCore upon initialization.
- Example:
- serverCore server = new serverCore(port, 1000, 0, false, "ftpdProtocol", null, 0);
- In this example the protocol handler "ftpdProtocol" is assigned. There a class
- named ftpdProtocol.java must be implemented, that implements this interface,
- a serverHandler.
- Any protocol command can be implemented in either way:
-
- public String COMMAND(String arg) throws IOException;
- public InputStream COMMAND(String arg) throws IOException;
- public void COMMAND(String arg) throws IOException;
-
- ..where COMMAND is the command that had been passed to the server
- on the terminal connection. The 'arg' argument is the remaining part of
- the command on the terminal connection.
- If the handler method returns a NULL value, which is especially
- the case if the method implements a 'void' return-value method,
- then the server disconnects the connection.
- Any other return value (String or an InputStream) is returned to
- the client on it's own line through the terminal connection.
- If it is wanted that the server terminates right after submitting
- a last line, then this can be indicated by prefixing the return
- value by a '!'-character.
-
- If one of the command methods throws a IOException, then the
- server asks the error - method for a return value on the terminal
- connection.
-
- The greeting-method is used to request a string that is transmitted
- to the client as terminal output at the beginning of a connection
- session.
-*/
-
-package net.yacy.server;
-
-import java.io.IOException;
-
-import net.yacy.server.serverCore.Session;
-
-
-
-public interface serverHandler {
-
- // a response line upon connection is send to client
- // if no response line is wanted, return "" or null
- public String greeting();
-
- // return string in case of any error that occurs during communication
- // is always (but not only) called if an IO-dependent exception occurs.
- public String error(Throwable e);
-
- // clone method for the handler prototype
- // each time a server makes a new connection it clones the hanlder prototype
- // the clone method does not need to clone every detail of a handler connection,
- // but only the necessary one for a newly initialized instance
- public serverHandler clone();
-
- /**
- * Instead of using clone this function can be used to reset an existing
- * handler prototype so that it can e reused
- */
- public void reset();
-
- /**
- * Tthis function will be called by the {@link serverCore}.listen() function
- * if the whole request line is empty and therefore no function of this
- * serverHandlerClass can be called because of the missing command name
- */
- public Boolean EMPTY(String arg, Session session) throws IOException;
-
- /**
- * This function will be called by the {@link serverCore}.listen() function
- * if no corresponding funktion of the serverHandler class can be
- * found for the received command.
- */
- public Boolean UNKNOWN(String requestLine, Session session) throws IOException;
-}
diff --git a/source/net/yacy/server/serverSwitch.java b/source/net/yacy/server/serverSwitch.java
index a4e532b50..6028bafb8 100644
--- a/source/net/yacy/server/serverSwitch.java
+++ b/source/net/yacy/server/serverSwitch.java
@@ -52,7 +52,6 @@ import net.yacy.kelondro.util.FileUtils;
import net.yacy.kelondro.workflow.BusyThread;
import net.yacy.kelondro.workflow.WorkflowThread;
import net.yacy.server.serverAccessTracker.Track;
-import net.yacy.server.serverCore.Session;
public class serverSwitch
{
@@ -442,43 +441,6 @@ public class serverSwitch
}
}
- public void closeSessions(String sessionName) {
- if ( sessionName == null ) {
- return;
- }
-
- for ( final Session s : serverCore.getJobList() ) {
- if ( (s.isAlive()) && (s.getName().equals(sessionName)) ) {
- // try to stop session
- s.setStopped(true);
- try {
- Thread.sleep(100);
- } catch (final InterruptedException ex ) {
- }
-
- // try to interrupt session
- s.interrupt();
- try {
- Thread.sleep(100);
- } catch (final InterruptedException ex ) {
- }
-
- // try to close socket
- if ( s.isAlive() ) {
- s.close();
- }
-
- // wait for session to finish
- if ( s.isAlive() ) {
- try {
- s.join(500);
- } catch (final InterruptedException ex ) {
- }
- }
- }
- }
- }
-
public Iterator<String> /*of serverThread-Names (String)*/threadNames() {
return this.workerThreads.keySet().iterator();
}
diff --git a/source/net/yacy/yacy.java b/source/net/yacy/yacy.java
index e9f7adde2..15f002521 100644
--- a/source/net/yacy/yacy.java
+++ b/source/net/yacy/yacy.java
@@ -64,8 +64,6 @@ import net.yacy.peers.operation.yacyVersion;
import net.yacy.search.Switchboard;
import net.yacy.search.SwitchboardConstants;
import net.yacy.server.serverCore;
-import net.yacy.server.http.HTTPDemon;
-
import com.google.common.io.Files;
import net.yacy.cora.document.id.DigestURL;
import net.yacy.cora.federate.yacy.CacheStrategy;
@@ -349,23 +347,7 @@ public final class yacy {
try {
// start http server
YaCyHttpServer httpServer;
- // default jetty (alternative "anomichttpd")
- if (sb.getConfig("defaulthttpserver","jetty").equalsIgnoreCase("jetty")) {
- httpServer = new Jetty8HttpServerImpl(port);
- } else {
- final HTTPDemon protocolHandler = new HTTPDemon(sb);
- httpServer = new serverCore(
- timeout /*control socket timeout in milliseconds*/,
- true /* block attacks (wrong protocol) */,
- protocolHandler /*command class*/,
- sb,
- 30000 /*command max length incl. GET args*/);
- ((serverCore) httpServer).setName("httpd:"+port);
- ((serverCore) httpServer).setPriority(Thread.MAX_PRIORITY);
- ((serverCore) httpServer).setObeyIntermission(false);
- // start the server
- //sb.deployThread("10_httpd", "HTTPD Server/Proxy", "the HTTPD, used as web server and proxy", null, server, 0, 0, 0, 0);
- }
+ httpServer = new Jetty8HttpServerImpl(port);
httpServer.startupServer();
sb.setHttpServer(httpServer);
ConcurrentLog.info("STARTUP",httpServer.getVersion());