Distributed Peer-to-Peer Web Search Engine and Intranet Search Appliance
Java decentralizedintranet-searchintranet-search-enginep2pp2p-networkprivacyprivacy-protectionsearch-enginesearchenginewebweb-search-enginewebsearchwebseearch-engine
*) First trial implementation of robots.txt support
thelif8ad65eae1f6
diff --git a/source/de/anomic/data/robotsParser.java b/source/de/anomic/data/robotsParser.javaindex e457e723d..dcfeff2a8 100644--- a/source/de/anomic/data/robotsParser.java+++ b/source/de/anomic/data/robotsParser.java@@ -6,7 +6,8 @@// Frankfurt, Germany, 2004//// This file ist contributed by Alexander Schier-// last major change: 05.09.2005+// last major 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@@ -44,100 +45,227 @@package de.anomic.data;import java.lang.String;-import java.util.Vector;-import java.util.Iterator;-import java.io.IOException;+import java.net.MalformedURLException;+import java.net.URL;+import java.util.ArrayList;+import java.util.Date;+import java.util.HashSet;+import java.io.ByteArrayInputStream;+import java.io.ByteArrayOutputStream;import java.io.File;import java.io.BufferedReader;+import java.io.FileNotFoundException;import java.io.FileReader;-import java.net.URL;+import java.io.IOException;+import java.io.InputStreamReader;++import de.anomic.http.httpHeader;+import de.anomic.http.httpc;+import de.anomic.plasma.plasmaCrawlRobotsTxt;+import de.anomic.plasma.plasmaParser;+import de.anomic.plasma.plasmaSwitchboard;+import de.anomic.plasma.plasmaURL;+import de.anomic.server.logging.serverLog;+import de.anomic.tools.bitfield;+import de.anomic.yacy.yacyCore;/** A class for Parsing robots.txt files.* It only parses the Deny Part, yet.* TODO: Allow, Do not deny if User-Agent: != yacy*+ * http://www.robotstxt.org/wc/norobots-rfc.html+ ** Use:* robotsParser rp=new Robotsparser(robotsfile);* if(rp.isAllowedRobots("/test")){* System.out.println("/test is allowed");* }*/-public class robotsParser{- String robotstxt="";- Vector deny;- /*- * constructor with a robots.txt as string- */- public robotsParser(String robots){- robotstxt=robots;- parse();- }- /*- * constructor with a robots.txt as Filehandle- */- public robotsParser(File robotsFile){- String robots="";- String line="";- try{- BufferedReader br=new BufferedReader(new FileReader(robotsFile));- while( (line=br.readLine()) != null){- robots+=line+"\n";- }- }catch(IOException e){- System.out.println("File Error");- }- robotstxt=robots;- parse();- }+public final class robotsParser{+/*public robotsParser(URL robotsUrl){}*//** this parses the robots.txt.* at the Moment it only creates a list of Deny Paths*/- private void parse(){- deny=new Vector();- String[] lines = robotstxt.split("\n");- String line;- for(int i=0;i<lines.length;i++){- line=lines[i];- if(line.startsWith("Disallow:")){- line=line.substring(9);- line=line.trim();- deny.add(line);- }- }- }- /*- * Check if a url is allowed.- */- public boolean isAllowedRobots(String url){- boolean allowed=false;- if(deny !=null){- Iterator it=deny.iterator();- allowed=true;- while(it.hasNext()){- if(url.startsWith((String)it.next())){- allowed=false;- break;- }- }- }- return allowed;++ public static ArrayList parse(File robotsFile) throws IOException {+ BufferedReader reader = new BufferedReader(new FileReader(robotsFile));+ return parse(reader);+ }++ public static ArrayList parse(byte[] robotsTxt) throws IOException {+ if ((robotsTxt == null)||(robotsTxt.length == 0)) return new ArrayList(0);+ ByteArrayInputStream bin = new ByteArrayInputStream(robotsTxt);+ BufferedReader reader = new BufferedReader(new InputStreamReader(bin));+ return parse(reader);+ }++ public static ArrayList parse(BufferedReader reader) throws IOException{+ ArrayList deny = new ArrayList();++ int pos;+ String line = null;+ boolean rule4Yacy = false;+ while ((line = reader.readLine()) != null) {+ line = line.trim();+ if (line.length() == 0) {+ // we have reached the end of the rule block+ rule4Yacy = false;+ } else if (line.startsWith("#")) {+ // we can ignore this. Just a comment line+ } else if ((!rule4Yacy) && (line.startsWith("User-agent:"))) {+ pos = line.indexOf(" ");+ if (pos != -1) {+ String userAgent = line.substring(pos).trim();+ rule4Yacy = (userAgent.equals("*") || (userAgent.toLowerCase().indexOf("yacy") >=0));+ }+ } else if (line.startsWith("Disallow:") && rule4Yacy) {+ pos = line.indexOf(" ");+ if (pos != -1) {+ // getting the path+ String path = line.substring(pos).trim();++ // escaping all occurences of ; because this char is used as special char in the Robots DB+ path = path.replaceAll(";","%3B");++ // adding it to the pathlist+ deny.add(path);+ }+ }+ }++ return deny;}- /*- * Test the class with a file robots.txt in the workdir and a testpath as argument.- */- public static void main(String[] args){- robotsParser rp=new robotsParser(new File("robots.txt"));- for(int i=0;i<args.length;i++){- if(rp.isAllowedRobots(args[i])){- System.out.println(args[i]+" is allowed.");- }else{- System.out.println(args[i]+" is NOT allowed.");- }- }- }+ public static boolean isDisallowed(URL nexturl) {+ if (nexturl == null) throw new IllegalArgumentException();++ // generating the hostname:poart string needed to do a DB lookup+ String urlHostPort = nexturl.getHost() + ":" + ((nexturl.getPort()==-1)?80:nexturl.getPort());++ // doing a DB lookup to determine if the robots data is already available+ plasmaCrawlRobotsTxt.Entry robotsTxt4Host = plasmaSwitchboard.robots.getEntry(urlHostPort);++ // if we have not found any data or the data is older than 7 days, we need to load it from the remote server+ if ((robotsTxt4Host == null) ||+ (System.currentTimeMillis() - robotsTxt4Host.getLoadedDate().getTime() > 7*24*60*60*1000)) {+ URL robotsURL = null;+ // generating the proper url to download the robots txt+ try {+ robotsURL = new URL(nexturl.getProtocol(),nexturl.getHost(),(nexturl.getPort()==-1)?80:nexturl.getPort(),"/robots.txt");+ } catch (MalformedURLException e) {+ serverLog.logSevere("ROBOTS","Unable to generate robots.txt URL for URL '" + nexturl.toString() + "'.");+ return false;+ }++ boolean accessCompletelyRestricted = false;+ byte[] robotsTxt = null;+ try {+ Object[] result = downloadRobotsTxt(robotsURL,5);+ accessCompletelyRestricted = ((Boolean)result[0]).booleanValue();+ robotsTxt = (byte[])result[1];++ } catch (Exception e) {+ serverLog.logSevere("ROBOTS","Unable to download the robots.txt file from URL '" + robotsURL + "'. " + e.getMessage());+ }++ ArrayList denyPath = null;+ if (accessCompletelyRestricted) {+ denyPath = new ArrayList();+ denyPath.add("/");+ } else {+ // parsing the robots.txt Data and converting it into an arraylist+ try {+ denyPath = robotsParser.parse(robotsTxt);+ } catch (IOException e) {+ serverLog.logSevere("ROBOTS","Unable to parse the robots.txt file from URL '" + robotsURL + "'.");+ }+ }++ // storing the data into the robots DB+ robotsTxt4Host = plasmaSwitchboard.robots.addEntry(urlHostPort,denyPath,new Date());+ }++ if (robotsTxt4Host.isDisallowed(nexturl.getPath())) {+ return true;+ }+ return false;+ }++ private static Object[] downloadRobotsTxt(URL robotsURL, int redirectionCount) throws Exception {++ if (redirectionCount < 0) return new Object[]{Boolean.FALSE,null};+ redirectionCount--;++ boolean accessCompletelyRestricted = false;+ byte[] robotsTxt = null;+ httpc con = null;+ try {+ plasmaSwitchboard sb = plasmaSwitchboard.getSwitchboard();+ if (!sb.remoteProxyUse) {+ con = httpc.getInstance(robotsURL.getHost(), robotsURL.getPort(), 10000, false);+ } else {+ con = httpc.getInstance(robotsURL.getHost(), robotsURL.getPort(), 10000, false, sb.remoteProxyHost, sb.remoteProxyPort);+ }++ httpc.response res = con.GET(robotsURL.getPath(), null);+ if (res.status.startsWith("2")) {+ if (!res.responseHeader.mime().startsWith("text/plain")) {+ robotsTxt = null;+ serverLog.logFinest("ROBOTS","Robots.txt from URL '" + robotsURL + "' has wrong mimetype '" + res.responseHeader.mime() + "'.");+ } else {+ ByteArrayOutputStream bos = new ByteArrayOutputStream();+ res.writeContent(bos, null);+ con.close();+ robotsTxt = bos.toByteArray();+ serverLog.logFinest("ROBOTS","Robots.txt successfully loaded from URL '" + robotsURL + "'.");+ }+ } else if (res.status.startsWith("3")) {+ // getting redirection URL+ String redirectionUrlString = (String) res.responseHeader.get(httpHeader.LOCATION);+ redirectionUrlString = redirectionUrlString.trim();++ // generating the new URL object+ URL redirectionUrl = new URL(robotsURL, redirectionUrlString);++ // returning the used httpc+ httpc.returnInstance(con);+ con = null;++ // following the redirection+ serverLog.logFinest("ROBOTS","Redirection detected for Robots.txt with URL '" + robotsURL + "'." ++ "\nRedirecting request to: " + redirectionUrl);+ return downloadRobotsTxt(redirectionUrl,redirectionCount);++ } else if (res.status.startsWith("401") || res.status.startsWith("403")) {+ accessCompletelyRestricted = true;+ serverLog.logFinest("ROBOTS","Access to Robots.txt not allowed on URL '" + robotsURL + "'.");+ } else {+ serverLog.logFinest("ROBOTS","Robots.txt could not be downloaded from URL '" + robotsURL + "'. [" + res.status + "].");+ robotsTxt = null;+ }+ } catch (Exception e) {+ throw e;+ } finally {+ if (con != null) httpc.returnInstance(con);+ }+ return new Object[]{new Boolean(accessCompletelyRestricted),robotsTxt};+ }++// /*+// * Test the class with a file robots.txt in the workdir and a testpath as argument.+// */+// public static void main(String[] args){+// robotsParser rp=new robotsParser(new File("robots.txt"));+// for(int i=0;i<args.length;i++){+// if(rp.isAllowedRobots(args[i])){+// System.out.println(args[i]+" is allowed.");+// }else{+// System.out.println(args[i]+" is NOT allowed.");+// }+// }+// }}diff --git a/source/de/anomic/http/httpdProxyHandler.java b/source/de/anomic/http/httpdProxyHandler.javaindex 48ff788fa..b653525bf 100644--- a/source/de/anomic/http/httpdProxyHandler.java+++ b/source/de/anomic/http/httpdProxyHandler.java@@ -1019,6 +1019,19 @@ public final class httpdProxyHandler extends httpdAbstractHandler implements httString httpVersion = conProp.getProperty("HTTP");int timeout = Integer.parseInt(switchboard.getConfig("clientTimeout", "10000"));++ // check the blacklist+ // blacklist idea inspired by [AS]:+ // respond a 404 for all AGIS ("all you get is shit") servers+ String hostlow = host.toLowerCase();+ if (plasmaSwitchboard.urlBlacklist.isListed(hostlow, "/")) {+ httpd.sendRespondError(conProp,clientOut,4,403,null,+ "URL '" + hostlow + "' blocked by yacy proxy (blacklisted)",null);+ this.theLogger.logInfo("AGIS blocking of host '" + hostlow + "'");+ forceConnectionClose();+ return;+ }+// possibly branch into PROXY-PROXY connectionif (remoteProxyUse) {httpc remoteProxy = null;@@ -1035,6 +1048,7 @@ public final class httpdProxyHandler extends httpdAbstractHandler implements htt// pass error response back to clienthttpd.sendRespondHeader(conProp,clientOut,httpVersion,response.statusCode,response.statusText,response.responseHeader);//respondHeader(clientOut, response.status, response.responseHeader);+ forceConnectionClose();return;}} catch (Exception e) {diff --git a/source/de/anomic/plasma/plasmaCrawlRobotsTxt.java b/source/de/anomic/plasma/plasmaCrawlRobotsTxt.javanew file mode 100644index 000000000..1cad929d7--- /dev/null+++ b/source/de/anomic/plasma/plasmaCrawlRobotsTxt.java@@ -0,0 +1,213 @@+//plasmaCrawlRobotsTxt.java+//-------------------------------------+//part of YACY+//(C) by Michael Peter Christen; [email protected]+//first published on http://www.anomic.de+//Frankfurt, Germany, 2004+//+//This file ist contributed by Martin Thelian+//last major 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+//+//Using this software in any meaning (reading, learning, copying, compiling,+//running) means that you agree that the Author(s) is (are) not responsible+//for cost, loss of data or any harm that may be caused directly or indirectly+//by usage of this softare or this documentation. The usage of this software+//is on your own risk. The installation and usage (starting/running) of this+//software may allow other people or application to access your computer and+//any attached devices and is highly dependent on the configuration of the+//software which must be done by the user of the software; the author(s) is+//(are) also not responsible for proper configuration and usage of the+//software, even if provoked by documentation provided together with+//the software.+//+//Any changes to this file according to the GPL as documented in the file+//gpl.txt aside this file in the shipment you received can be done to the+//lines that follows this copyright notice here, but changes must not be+//done inside the copyright notive above. A re-distribution must contain+//the intact and unchanged copyright notice.+//Contributions and changes to the program code must be marked as such.+++package de.anomic.plasma;++import java.io.File;+import java.io.IOException;+import java.util.ArrayList;+import java.util.Arrays;+import java.util.Date;+import java.util.HashMap;+import java.util.Iterator;+import java.util.LinkedList;+import java.util.Map;+import de.anomic.kelondro.kelondroDyn;+import de.anomic.kelondro.kelondroMap;+import de.anomic.server.logging.serverLog;++public class plasmaCrawlRobotsTxt {+ private kelondroMap robotsTable;+ private File robotsTableFile;++ public plasmaCrawlRobotsTxt(File robotsTableFile) throws IOException {+ this.robotsTableFile = robotsTableFile;+ if (robotsTableFile.exists()) {+ robotsTable = new kelondroMap(new kelondroDyn(robotsTableFile, 32000));+ } else {+ robotsTableFile.getParentFile().mkdirs();+ robotsTable = new kelondroMap(new kelondroDyn(robotsTableFile, 32000, 256, 512));+ }+ }++ private void resetDatabase() {+ // deletes the robots.txt database and creates a new one+ if (robotsTable != null) try {+ robotsTable.close();+ } catch (IOException e) {}+ if (!(robotsTableFile.delete())) throw new RuntimeException("cannot delete robots.txt database");+ try {+ robotsTableFile.getParentFile().mkdirs();+ robotsTable = new kelondroMap(new kelondroDyn(robotsTableFile, 32000, 256, 512));+ } catch (IOException e){+ serverLog.logSevere("PLASMA", "robotsTxt.resetDatabase", e);+ }+ }++ public void close() {+ try {+ robotsTable.close();+ } catch (IOException e) {}+ }++ public int size() {+ return robotsTable.size();+ }++ public void removeEntry(String hostName) {+ try {+ robotsTable.remove(hostName.toLowerCase());+ } catch (IOException e) {}+ }++ public Entry getEntry(String hostName) {+ try {+ Map record = robotsTable.get(hostName);+ if (record == null) return null;+ return new Entry(hostName, record);+ } catch (IOException e) {+ return null;+ }+ }++ public Entry addEntry(String hostName, ArrayList disallowPathList, Date loadedDate) {+ Entry entry = new Entry(hostName,disallowPathList,loadedDate);+ addEntry(entry);+ return entry;+ }++ public String addEntry(Entry entry) {+ // writes a new page and returns key+ try {+ robotsTable.set(entry.hostName,entry.mem);+ return entry.hostName;+ } catch (IOException e) {+ return null;+ }+ }++ public class Entry {+ public static final String DISALLOW_PATH_LIST = "disallow";+ public static final String LOADED_DATE = "date";++ // this is a simple record structure that hold all properties of a single crawl start+ private Map mem;+ private LinkedList disallowPathList;+ private String hostName;++ public Entry(String hostName, Map mem) {+ this.hostName = hostName;+ this.mem = mem;++ if (this.mem.containsKey(DISALLOW_PATH_LIST)) {+ this.disallowPathList = new LinkedList();+ String csPl = (String) this.mem.get(DISALLOW_PATH_LIST);+ if (csPl.length() > 0){+ String[] pathArray = csPl.split(";");+ if ((pathArray != null)&&(pathArray.length > 0)) {+ this.disallowPathList.addAll(Arrays.asList(pathArray));+ }+ }+ } else {+ this.disallowPathList = new LinkedList();+ }+ }++ public Entry(String hostName, ArrayList disallowPathList, Date loadedDate) {+ if ((hostName == null) || (hostName.length() == 0)) throw new IllegalArgumentException();++ this.hostName = hostName.trim().toLowerCase();+ this.disallowPathList = new LinkedList();++ this.mem = new HashMap();+ if (loadedDate != null) this.mem.put(LOADED_DATE,Long.toString(loadedDate.getTime()));++ if ((disallowPathList != null)&&(disallowPathList.size()>0)) {+ this.disallowPathList.addAll(disallowPathList);++ StringBuffer pathListStr = new StringBuffer();+ for (int i=0; i<disallowPathList.size();i++) {+ pathListStr.append(disallowPathList.get(i))+ .append(";");+ }+ this.mem.put(DISALLOW_PATH_LIST,pathListStr.substring(0,pathListStr.length()-1));+ }+ }++ public String toString() {+ StringBuffer str = new StringBuffer();+ str.append((this.hostName==null)?"null":this.hostName)+ .append(": ");++ if (this.mem != null) {+ str.append(this.mem.toString());+ }++ return str.toString();+ }++ public Date getLoadedDate() {+ if (this.mem.containsKey(LOADED_DATE)) {+ return new Date(Long.valueOf((String) this.mem.get(LOADED_DATE)).longValue());+ }+ return null;+ }++ public boolean isDisallowed(String path) {+ if ((path == null) || (path.length() == 0)) return false;+ if ((this.mem == null) || (this.disallowPathList.size() == 0)) return false;++ Iterator pathIter = this.disallowPathList.iterator();+ while (pathIter.hasNext()) {+ String nextPath = (String) pathIter.next();+ if (path.startsWith(nextPath)) return true;+ }+ return false;+ }++ }+++}diff --git a/source/de/anomic/plasma/plasmaSwitchboard.java b/source/de/anomic/plasma/plasmaSwitchboard.javaindex 84a2a1a34..b4c60c6c3 100644--- a/source/de/anomic/plasma/plasmaSwitchboard.java+++ b/source/de/anomic/plasma/plasmaSwitchboard.java@@ -4,7 +4,9 @@// (C) by Michael Peter Christen; [email protected]// first published on http://www.anomic.de// Frankfurt, Germany, 2004, 2005-// last major change: 24.03.2005+//+// last major 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@@ -106,6 +108,7 @@ import java.io.IOException;import java.net.MalformedURLException;import java.net.URL;import java.text.SimpleDateFormat;+import java.util.ArrayList;import java.util.Date;import java.util.HashMap;import java.util.HashSet;@@ -114,6 +117,7 @@ import java.util.Map;import java.util.Set;import java.util.TreeSet;import de.anomic.data.messageBoard;+import de.anomic.data.robotsParser;import de.anomic.data.wikiBoard;import de.anomic.htmlFilter.htmlFilterContentScraper;import de.anomic.http.httpHeader;@@ -163,6 +167,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements serpublic String remoteProxyHost;public int remoteProxyPort;public boolean remoteProxyUse;+ public static plasmaCrawlRobotsTxt robots;public plasmaCrawlProfile profiles;public plasmaCrawlProfile.entry defaultProxyProfile;public plasmaCrawlProfile.entry defaultRemoteProfile;@@ -259,10 +264,16 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements ser// make crawl profiles database and default profilesthis.log.logConfig("Initializing Crawl Profiles");File profilesFile = new File(this.plasmaPath, "crawlProfiles0.db");- this.profiles = new plasmaCrawlProfile(new File(this.plasmaPath, "crawlProfiles0.db"));+ this.profiles = new plasmaCrawlProfile(profilesFile);initProfiles();log.logConfig("Loaded profiles from file " + profilesFile + ", " + this.profiles.size() + " entries");+ // loading the robots.txt db+ this.log.logConfig("Initializing robots.txt DB");+ File robotsDBFile = new File(this.plasmaPath, "crawlRobotsTxt.db");+ this.robots = new plasmaCrawlRobotsTxt(robotsDBFile);+ this.log.logConfig("Loaded robots.txt DB from file " + robotsDBFile + ", " + this.robots.size() + " entries");+// start indexing managementlog.logConfig("Starting Indexing Management");urlPool = new plasmaURLPool(plasmaPath, ramLURL, ramNURL, ramEURL);@@ -572,6 +583,7 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements serif (facilityDB != null) facilityDB.close();urlPool.close();profiles.close();+ robots.close();parser.close();cacheManager.close();sbQueue.close();@@ -1148,6 +1160,16 @@ public final class plasmaSwitchboard extends serverAbstractSwitch implements serlog.logFine("URL '" + nexturlString + "' is post URL.");return reason;}++ // checking robots.txt+ if (robotsParser.isDisallowed(nexturl)) {+ reason = "denied_(robots.txt)";+ urlPool.errorURL.newEntry(nexturl, referrerHash, initiatorHash, yacyCore.seedDB.mySeed.hash,+ name, reason, new bitfield(plasmaURL.urlFlagLength), false);+ log.logFine("Crawling of URL '" + nexturlString + "' disallowed by robots.txt.");+ return reason;+ }+String nexturlhash = plasmaURL.urlHash(nexturl);String dbocc = "";