Compare commits

...

32 Commits

Author SHA1 Message Date
jrandom
265d5e306e * 2005-02-23 0.5.0.1 released 2005-02-23 05:00:52 +00:00
jrandom
10ed058c2e 2005-02-22 jrandom
* Reworked the tunnel (re)building process to remove the tokens and
      provide cleaner controls on the tunnels built.
    * Fixed situations where the timestamper wanted to test more servers than
      were provided (thanks Tracker!)
    * Get rid of the dead SAM sessions by using the streaming lib's callbacks
      (thanks Tracker!)
2005-02-23 04:20:28 +00:00
jrandom
8a21f0efec 2005-02-22 jrandom
* Temporary workaround for the I2CP disconnect bug (have the streaminglib
      try to automatically reconnect on accept()/connect(..)).
    * Loop check for expired lease republishing (just in case)
2005-02-22 23:13:00 +00:00
jrandom
b8291ac5a4 2005-02-22 jrandom
* Temporary workaround for the I2CP disconnect bug (have the streaminglib
      try to automatically reconnect on accept()/connect(..)).
    * Loop check for expired lease republishing (just in case)
2005-02-22 22:58:21 +00:00
jrandom
c17433cb93 2005-02-22 jrandom
* Adjusted (and fixed...) the timestamper change detection
    * Deal with a rare reordering bug at the beginning of a stream (so we
      don't drop it unnecessarily)
    * Cleaned up some dropped message handling in the router
    * Reduced job queue churn when dealing with a large number of tunnels by
      sharing an expiration job
    * Keep a separate list of the most recent CRIT messages (shown on the
      logs.jsp).  This way they don't get buried among any other messages.
    * For clarity, display the tunnel variance config as "Randomization" on
      the web console.
    * If lease republishing fails (boo! hiss!) try it again
    * Actually fix the negative jobLag in the right place (this time)
    * Allow reseeding when there are less than 10 known peer references
    * Lots of logging updates.
2005-02-22 07:07:29 +00:00
jrandom
35fe7f8203 2005-02-20 jrandom
* Allow the streaming lib resend frequency to drop down to 20s as the
      minimum, so that up to 2 retries can get sent on an http request.
    * Add further limits to failsafe tunnels.
    * Keep exploratory and client tunnel testing and building stats separate.
    * Only use the 60s period for throttling tunnel requests due to transient
      network overload.
    * Rebuild tunnels earlier (1-3m before expiration, by default)
    * Cache the next hop's routerInfo for participating tunnels so that the
      tunnel participation doesn't depend on the netDb.
    * Fixed a long standing bug in the streaming lib where we wouldn't always
      unchoke messages when the window size grows.
    * Make sure the window size never reaches 0 (duh)
2005-02-21 19:08:01 +00:00
jrandom
21f13dba43 2005-02-20 jrandom
* Allow the streaming lib resend frequency to drop down to 20s as the
      minimum, so that up to 2 retries can get sent on an http request.
    * Add further limits to failsafe tunnels.
    * Keep exploratory and client tunnel testing and building stats separate.
    * Only use the 60s period for throttling tunnel requests due to transient
      network overload.
    * Rebuild tunnels earlier (1-3m before expiration, by default)
    * Cache the next hop's routerInfo for participating tunnels so that the
      tunnel participation doesn't depend on the netDb.
    * Fixed a long standing bug in the streaming lib where we wouldn't always
      unchoke messages when the window size grows.
    * Make sure the window size never reaches 0 (duh)
2005-02-21 18:02:14 +00:00
duck
0db239a3fe added irc.postman.i2p 2005-02-21 03:13:40 +00:00
jrandom
4745d61f9b added subrosa.i2p 2005-02-21 02:55:12 +00:00
jrandom
b9a4c3ba52 *cough* 2005-02-20 11:09:05 +00:00
jrandom
cbf6a70a1a 2005-02-20 jrandom
* Only build failsafe tunnels if we need them
    * Properly implement the selectNotFailingPeers so that we get a random
      selection of peers, rather than using the strictOrdering (thanks dm!)
    * Don't include too many "don't tell me about" peer references in the
      lookup message - only send the 10 peer references closest to the target.
2005-02-20 09:12:43 +00:00
jrandom
7d4e093b58 2005-02-19 jrandom
* Only build new extra tunnels on failure if we don't have enough
    * Fix a fencepost in the tunnel building so that e.g. a variance of
      2 means +/- 2, not +/- 1 (thanks dm!)
    * Avoid an NPE on client disconnect
    * Never select a shitlisted peer to participate in a tunnel
    * Have netDb store messages timeout after 10s, not the full 60s (duh)
    * Keep session tags around for a little longer, just in case (grr)
    * Cleaned up some closing event issues on the streaming lib
    * Stop bundling the jetty 5.1.2 and updated wrapper.config in the update
      so that 0.4.* users will need to do a clean install, but we don't need
      to shove an additional 2MB in each update to those already on 0.5.
    * Imported the susimail css (oops, thanks susi!)
2005-02-19 23:20:56 +00:00
jrandom
d27feabcb3 clear the old precompiled .java files (thanks duck!) 2005-02-18 16:56:46 +00:00
jrandom
0d9efa17de bah, fuck it. we can deal with a little shitlisting 2005-02-18 16:04:51 +00:00
jrandom
b125b04c8d 0.5 released 2005-02-18 15:58:20 +00:00
jrandom
0539f1d794 updated for the new props 2005-02-18 15:35:02 +00:00
jrandom
a4b6709f02 added moxonom.i2p 2005-02-18 15:27:46 +00:00
jrandom
f2db143a6f Refuse to load 0.4 routerInfo (to help weed out the old ones) 2005-02-18 15:25:25 +00:00
jrandom
b615f54d41 *cough* 2005-02-18 08:28:56 +00:00
jrandom
db2328e03e * actually reseed properly
* hide the susimail deprecation warnings
* dont push hosts.txt in the update (people can subscribe if they want to)
2005-02-18 08:12:40 +00:00
jrandom
e2071935ad added sex0r.i2p flock.i2p cneal.i2p www.nntp.i2p wallsgetbombed.i2p
thedarkside.i2p legion.i2p manveru.i2p books.manveru.i2p bt.i2p
2005-02-18 06:23:29 +00:00
jrandom
1c40ff773f fproxy.i2p and www1.squid.i2p are back (yay!) 2005-02-18 00:52:26 +00:00
ragnarok
37a3645663 Default subscriptions shouldn't rely on a pre-existing hosts.txt. 2005-02-18 00:50:18 +00:00
jrandom
eb8accd1e0 damn those copyright laws 2005-02-17 23:59:52 +00:00
jrandom
3af97894b4 tyop 2005-02-17 23:45:50 +00:00
jrandom
15a0dcf4d8 (not yet tagging this 0.5, but I don't think there's anytihng left)
2005-02-17  jrandom
    * If the clock is adjusted during a job run, don't act as if the job took
      negative time.
2005-02-17 22:57:53 +00:00
jrandom
aa3a44c42a 2005-02-17 jrandom
* Included the GPL'ed susimail 0.13 by default (thanks susi23!)
2005-02-17 20:55:07 +00:00
jrandom
40f4b47b87 initial vanilla import of susimail 0.13 (no build script yet) 2005-02-17 20:08:53 +00:00
jrandom
dca09d96b3 logging 2005-02-17 19:49:16 +00:00
jrandom
dd10747460 2005-02-17 jrandom
* Fixed the braindead tunnel testing logic
    * If a large number of tunnels are failing (within the last 5-10 minutes)
      and the current tunnel pool's configuration allows it, randomly build a
      zero hop tunnel to replace failed tunnels.
    * Enable postman's POP3 and SMTP tunnels by default
2005-02-17 17:59:27 +00:00
jrandom
77176162af 2005-02-16 jrandom
* Added some error handling when the number of session tags exceeds the
      realistic capacity, dropping a random chunk of received tag sets and
      conducting some minor analysis of the remaining ones.  This is a part
      of a pretty serious error condition, and logs as CRIT (if/when people
      see "TOO MANY SESSION TAGS!", please let me know the full log line it
      puts in the wrapper.log or /logs.jsp)
    * Update the addressbook to only write to the published hosts location
      if the addressbook's config contains "should_publish=true" (by default,
      it contains "should_publish=false")
2005-02-17 04:08:34 +00:00
jrandom
8b9ee4dfd7 updated to reflect what was implemented 2005-02-17 00:48:18 +00:00
109 changed files with 7038 additions and 416 deletions

View File

@@ -65,7 +65,8 @@ public class Daemon {
master.merge((AddressBook) iter.next(), log);
}
master.write(new File(routerLocation));
master.write(published);
if (published != null)
master.write(published);
subscriptions.write();
}
@@ -82,7 +83,9 @@ public class Daemon {
.get("master_addressbook"));
File routerFile = new File(home, (String) settings
.get("router_addressbook"));
File published = new File(home, (String) settings
File published = null;
if ("true".equals(settings.get("should_publish")))
published = new File(home, (String) settings
.get("published_addressbook"));
File subscriptionFile = new File(home, (String) settings
.get("subscriptions"));
@@ -95,8 +98,7 @@ public class Daemon {
AddressBook router = new AddressBook(routerFile);
List defaultSubs = new LinkedList();
defaultSubs.add("http://dev.i2p/i2p/hosts.txt");
defaultSubs.add("http://duck.i2p/hosts.txt");
defaultSubs.add("http://i2p/NF2RLVUxVulR3IqK0sGJR0dHQcGXAzwa6rEO4WAWYXOHw-DoZhKnlbf1nzHXwMEJoex5nFTyiNMqxJMWlY54cvU~UenZdkyQQeUSBZXyuSweflUXFqKN-y8xIoK2w9Ylq1k8IcrAFDsITyOzjUKoOPfVq34rKNDo7fYyis4kT5bAHy~2N1EVMs34pi2RFabATIOBk38Qhab57Umpa6yEoE~rbyR~suDRvD7gjBvBiIKFqhFueXsR2uSrPB-yzwAGofTXuklofK3DdKspciclTVzqbDjsk5UXfu2nTrC1agkhLyqlOfjhyqC~t1IXm-Vs2o7911k7KKLGjB4lmH508YJ7G9fLAUyjuB-wwwhejoWqvg7oWvqo4oIok8LG6ECR71C3dzCvIjY2QcrhoaazA9G4zcGMm6NKND-H4XY6tUWhpB~5GefB3YczOqMbHq4wi0O9MzBFrOJEOs3X4hwboKWANf7DT5PZKJZ5KorQPsYRSq0E3wSOsFCSsdVCKUGsAAAA/i2p/hosts.txt");
SubscriptionList subscriptions = new SubscriptionList(subscriptionFile,
etagsFile, lastModifiedFile, defaultSubs);
@@ -131,6 +133,7 @@ public class Daemon {
defaultSettings.put("master_addressbook", "../userhosts.txt");
defaultSettings.put("router_addressbook", "../hosts.txt");
defaultSettings.put("published_addressbook", "../eepsite/docroot/hosts.txt");
defaultSettings.put("should_publish", "false");
defaultSettings.put("log", "log.txt");
defaultSettings.put("subscriptions", "subscriptions.txt");
defaultSettings.put("etags", "etags");

View File

@@ -31,6 +31,9 @@
</war>
</target>
<target name="precompilejsp">
<delete dir="../jsp/WEB-INF/" />
<delete file="../jsp/web-fragment.xml" />
<delete file="../jsp/web-out.xml" />
<mkdir dir="../jsp/WEB-INF/" />
<mkdir dir="../jsp/WEB-INF/classes" />
<!-- there are various jspc ant tasks, but they all seem a bit flakey -->

View File

@@ -216,7 +216,7 @@ public class I2PTunnelRunner extends I2PThread implements I2PSocket.SocketErrorL
this.out = out;
_toI2P = toI2P;
direction = (toI2P ? "toI2P" : "fromI2P");
_cache = ByteCache.getInstance(256, NETWORK_BUFFER_SIZE);
_cache = ByteCache.getInstance(16, NETWORK_BUFFER_SIZE);
setName("StreamForwarder " + _runnerId + "." + (++__forwarderId));
start();
}

View File

@@ -49,9 +49,11 @@ public class ConfigTunnelsHelper {
TunnelPoolSettings in = _context.tunnelManager().getInboundSettings(dest.calculateHash());
TunnelPoolSettings out = _context.tunnelManager().getOutboundSettings(dest.calculateHash());
String name = (in != null ? in.getDestinationNickname() : null);
if ( (in == null) || (out == null) ) continue;
String name = in.getDestinationNickname();
if (name == null)
name = (out != null ? out.getDestinationNickname() : null);
name = out.getDestinationNickname();
if (name == null)
name = dest.calculateHash().toBase64().substring(0,6);
@@ -110,7 +112,7 @@ public class ConfigTunnelsHelper {
buf.append("</tr>\n");
// tunnel depth variance
buf.append("<tr><td>Variance</td>\n");
buf.append("<tr><td>Randomization</td>\n");
buf.append("<td><select name=\"").append(index).append(".varianceInbound\">\n");
buf.append("<option value=\"0\" ");
if (in.getLengthVariance() == 0) buf.append(" selected=\"true\" ");

View File

@@ -41,6 +41,22 @@ public class LogsHelper {
return buf.toString();
}
public String getCriticalLogs() {
List msgs = _context.logManager().getBuffer().getMostRecentCriticalMessages();
StringBuffer buf = new StringBuffer(16*1024);
buf.append("<ul>");
buf.append("<code>\n");
for (int i = msgs.size(); i > 0; i--) {
String msg = (String)msgs.get(i - 1);
buf.append("<li>");
buf.append(msg);
buf.append("</li>\n");
}
buf.append("</code></ul>\n");
return buf.toString();
}
public String getServiceLogs() {
String str = FileUtil.readTextFile("wrapper.log", 500, false);
if (str == null)

View File

@@ -100,11 +100,12 @@ public class ReseedHandler {
URL url = new URL(seedURL + (seedURL.endsWith("/") ? "" : "/") + "routerInfo-" + peer + ".dat");
byte data[] = readURL(url);
//System.out.println("read: " + (data != null ? data.length : -1));
writeSeed(peer, data);
}
private static byte[] readURL(URL url) throws Exception {
ByteArrayOutputStream baos = new ByteArrayOutputStream(1024);
ByteArrayOutputStream baos = new ByteArrayOutputStream(4*1024);
String hostname = url.getHost();
int port = url.getPort();
if (port < 0)
@@ -113,9 +114,28 @@ public class ReseedHandler {
OutputStream out = s.getOutputStream();
InputStream in = s.getInputStream();
String request = getRequest(url);
System.out.println("Sending to " + hostname +":"+ port + ": " + request);
//System.out.println("Sending to " + hostname +":"+ port + ": " + request);
out.write(request.getBytes());
out.flush();
// skip the HTTP response headers
// (if we were smart, we'd check for HTTP 200, content-length, etc)
int consecutiveNL = 0;
while (true) {
int cur = in.read();
switch (cur) {
case -1:
return null;
case '\n':
case '\r':
consecutiveNL++;
break;
default:
consecutiveNL = 0;
}
if (consecutiveNL == 4)
break;
}
// ok, past the headers, grab the goods
byte buf[] = new byte[1024];
while (true) {
int read = in.read(buf);
@@ -155,6 +175,6 @@ public class ReseedHandler {
public static void main(String args[]) {
reseed();
System.out.println("Done reseeding");
//System.out.println("Done reseeding");
}
}

View File

@@ -3,8 +3,12 @@ package net.i2p.router.web;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import java.util.Set;
import net.i2p.data.DataHelper;
@@ -70,7 +74,32 @@ public class SummaryHelper {
else
return DataHelper.formatDuration(router.getUptime());
}
private static final DateFormat _fmt = new java.text.SimpleDateFormat("HH:mm:ss", Locale.UK);
public String getTime() {
if (_context == null) return "";
String now = null;
synchronized (_fmt) {
now = _fmt.format(new Date(_context.clock().now()));
}
long ms = _context.clock().getOffset();
if (ms < 60 * 1000) {
return now + " (" + (ms / 1000) + "s)";
} else if (ms < 60 * 1000) {
return now + " (" + (ms / (60 * 1000)) + "m)";
} else if (ms < 24 * 60 * 60 * 1000) {
return now + " (" + (ms / (60 * 60 * 1000)) + "h)";
} else {
return now + " (" + (ms / (24 * 60 * 60 * 1000)) + "d)";
}
}
public boolean allowReseed() {
return (_context.netDb().getKnownRouters() < 10);
}
/**
* Retrieve amount of used memory.

View File

@@ -34,7 +34,11 @@ by their binary code license. This product includes software developed by the A
<p>Another application you can see on this webpage is <a href="http://www.i2p.net/i2ptunnel">I2PTunnel</a>
(your <a href="i2ptunnel/" target="_blank">web interface</a>) - a GPL'ed application written by mihi that
lets you tunnel normal TCP/IP traffic over I2P (such as the eepproxy and the irc proxy).</p>
lets you tunnel normal TCP/IP traffic over I2P (such as the eepproxy and the irc proxy). There is also a
<a href="http://susi.i2p/">susimail</a> web based mail client <a href="susimail/susimail">available</a> on
the console, which is a GPL'ed application written by susi23. The addressbook application, written by
<a href="http://ragnarok.i2p/">Ragnarok</a> helps maintain your hosts.txt files (see ./addressbook/ for
more information).</p>
<p>The router by default also includes human's public domain <a href="http://www.i2p.net/sam">SAM</a> bridge,
which other client applications (such the <a href="http://duck.i2p/i2p-bt/">bittorrent port</a>) can use.

View File

@@ -19,6 +19,9 @@
<h4>Connection logs:</h4><a name="connectionlogs"> </a>
<jsp:getProperty name="logsHelper" property="connectionLogs" />
<hr />
<h4>Critical logs:</h4><a name="criticallogs"> </a>
<jsp:getProperty name="logsHelper" property="criticalLogs" />
<hr />
<h4>Service logs:</h4><a name="servicelogs"> </a>
<jsp:getProperty name="logsHelper" property="serviceLogs" />
</div>

View File

@@ -17,11 +17,12 @@
<h4>
<a href="tunnels.jsp">Tunnels</a> |
<a href="profiles.jsp">Profiles</a> |
<a href="netdb.jsp">Network Database</a> |
<a href="netdb.jsp">NetDB</a> |
<a href="logs.jsp">Logs</a> |
<a href="oldconsole.jsp">Old console</a> |
<a href="oldconsole.jsp">Internals</a> |
<a href="oldstats.jsp">Stats</a> |
<a href="i2ptunnel/" target="_blank">I2PTunnel</a>
<a href="i2ptunnel/" target="_blank">I2PTunnel</a> |
<a href="susimail/susimail" target="_blank">Susimail</a>
<jsp:useBean class="net.i2p.router.web.NavHelper" id="navhelper" scope="request" />
<jsp:setProperty name="navhelper" property="contextId" value="<%=(String)session.getAttribute("i2p.contextId")%>" />
<jsp:getProperty name="navhelper" property="clientAppLinks" />

View File

@@ -10,6 +10,7 @@
<b>Ident:</b> <jsp:getProperty name="helper" property="ident" /><br />
<b>Version:</b> <jsp:getProperty name="helper" property="version" /><br />
<b>Uptime:</b> <jsp:getProperty name="helper" property="uptime" /><br />
<b>Now:</b> <jsp:getProperty name="helper" property="time" /><br />
<b>Memory:</b> <jsp:getProperty name="helper" property="memory" /><br />
<hr />
@@ -23,7 +24,7 @@
if (helper.getActivePeers() <= 0) {
%><b><a href="config.jsp">check your NAT/firewall</a></b><br /><%
}
if (helper.getActiveProfiles() <= 10) { // 10 is the min fallback
if (helper.allowReseed()) {
if ("true".equals(System.getProperty("net.i2p.router.web.ReseedHandler.reseedInProgress", "false"))) {
out.print(" <i>reseeding</i>");
} else {

View File

@@ -132,6 +132,8 @@ public class SAMStreamSession {
if (socketMgr == null) {
throw new SAMException("Error creating I2PSocketManager");
}
socketMgr.addDisconnectListener(new DisconnectListener());
forceFlush = Boolean.valueOf(allprops.getProperty(PROP_FORCE_FLUSH, DEFAULT_FORCE_FLUSH)).booleanValue();
@@ -156,6 +158,12 @@ public class SAMStreamSession {
t.start();
}
}
private class DisconnectListener implements I2PSocketManager.DisconnectListener {
public void sessionDisconnected() {
close();
}
}
/**
* Get the SAM STREAM session Destination.

View File

@@ -57,7 +57,7 @@ public class Connection {
private I2PSocketFull _socket;
/** set to an error cause if the connection could not be established */
private String _connectionError;
private boolean _disconnectScheduled;
private long _disconnectScheduledOn;
private long _lastReceivedOn;
private ActivityTimer _activityTimer;
/** window size when we last saw congestion */
@@ -76,7 +76,7 @@ public class Connection {
private long _lifetimeDupMessageReceived;
public static final long MAX_RESEND_DELAY = 60*1000;
public static final long MIN_RESEND_DELAY = 30*1000;
public static final long MIN_RESEND_DELAY = 20*1000;
/** wait up to 5 minutes after disconnection so we can ack/close packets */
public static int DISCONNECT_TIMEOUT = 5*60*1000;
@@ -113,7 +113,7 @@ public class Connection {
_connectionManager = manager;
_resetReceived = false;
_connected = true;
_disconnectScheduled = false;
_disconnectScheduledOn = -1;
_lastReceivedOn = -1;
_activityTimer = new ActivityTimer();
_ackSinceCongestion = true;
@@ -181,6 +181,11 @@ public class Connection {
}
}
}
void windowAdjusted() {
synchronized (_outboundPackets) {
_outboundPackets.notifyAll();
}
}
void ackImmediately() {
_receiver.send(null, 0, 0);
@@ -191,6 +196,10 @@ public class Connection {
*
*/
void sendReset() {
if (_disconnectScheduledOn < 0) {
_disconnectScheduledOn = _context.clock().now();
SimpleTimer.getInstance().addEvent(new DisconnectEvent(), DISCONNECT_TIMEOUT);
}
_resetSent = true;
if (_resetSentOn <= 0)
_resetSentOn = _context.clock().now();
@@ -382,6 +391,10 @@ public class Connection {
}
void resetReceived() {
if (_disconnectScheduledOn < 0) {
_disconnectScheduledOn = _context.clock().now();
SimpleTimer.getInstance().addEvent(new DisconnectEvent(), DISCONNECT_TIMEOUT);
}
_resetReceived = true;
MessageOutputStream mos = _outputStream;
MessageInputStream mis = _inputStream;
@@ -398,6 +411,7 @@ public class Connection {
public boolean getHardDisconnected() { return _hardDisconnected; }
public boolean getResetSent() { return _resetSent; }
public long getResetSentOn() { return _resetSentOn; }
public long getDisconnectScheduledOn() { return _disconnectScheduledOn; }
void disconnect(boolean cleanDisconnect) {
disconnect(cleanDisconnect, true);
@@ -424,8 +438,8 @@ public class Connection {
killOutstandingPackets();
}
if (removeFromConMgr) {
if (!_disconnectScheduled) {
_disconnectScheduled = true;
if (_disconnectScheduledOn < 0) {
_disconnectScheduledOn = _context.clock().now();
SimpleTimer.getInstance().addEvent(new DisconnectEvent(), DISCONNECT_TIMEOUT);
}
}
@@ -445,8 +459,8 @@ public class Connection {
SimpleTimer.getInstance().removeEvent(_activityTimer);
_activityTimer = null;
if (!_disconnectScheduled) {
_disconnectScheduled = true;
if (_disconnectScheduledOn < 0) {
_disconnectScheduledOn = _context.clock().now();
if (_log.shouldLog(Log.INFO))
_log.info("Connection disconnect complete from dead, drop the con "
@@ -576,7 +590,13 @@ public class Connection {
public long getAckedPackets() { return _ackedPackets; }
public long getCreatedOn() { return _createdOn; }
public long getCloseSentOn() { return _closeSentOn; }
public void setCloseSentOn(long when) { _closeSentOn = when; }
public void setCloseSentOn(long when) {
_closeSentOn = when;
if (_disconnectScheduledOn < 0) {
_disconnectScheduledOn = _context.clock().now();
SimpleTimer.getInstance().addEvent(new DisconnectEvent(), DISCONNECT_TIMEOUT);
}
}
public long getCloseReceivedOn() { return _closeReceivedOn; }
public void setCloseReceivedOn(long when) { _closeReceivedOn = when; }
@@ -851,6 +871,7 @@ public class Connection {
+ ") for " + Connection.this.toString());
getOptions().setWindowSize(newWindowSize);
windowAdjusted();
}
}

View File

@@ -160,6 +160,8 @@ public class ConnectionOptions extends I2PSocketOptionsImpl {
public void setWindowSize(int numMsgs) {
if (numMsgs > _maxWindowSize)
numMsgs = _maxWindowSize;
else if (numMsgs <= 0)
numMsgs = 1;
_windowSize = numMsgs;
}

View File

@@ -224,6 +224,9 @@ public class ConnectionPacketHandler {
newWindowSize += 1;
}
}
if (newWindowSize <= 0)
newWindowSize = 1;
if (_log.shouldLog(Log.DEBUG))
_log.debug("New window size " + newWindowSize + "/" + oldWindow + " congestionSeenAt: "
@@ -233,6 +236,7 @@ public class ConnectionPacketHandler {
con.setCongestionWindowEnd(newWindowSize + lowest);
}
con.windowAdjusted();
return congested;
}
@@ -255,11 +259,15 @@ public class ConnectionPacketHandler {
con.setRemotePeer(packet.getOptionalFrom());
return true;
} else {
// neither RST nor SYN and we dont have the stream id yet? nuh uh
if (_log.shouldLog(Log.WARN))
_log.warn("Packet without RST or SYN where we dont know stream ID: "
+ packet);
return false;
// neither RST nor SYN and we dont have the stream id yet?
if (packet.getSequenceNum() <= 2) {
return true;
} else {
if (_log.shouldLog(Log.WARN))
_log.warn("Packet without RST or SYN where we dont know stream ID: "
+ packet);
return false;
}
}
} else {
if (!DataHelper.eq(con.getSendStreamId(), packet.getReceiveStreamId())) {

View File

@@ -105,7 +105,7 @@ public class I2PSocketManagerFull implements I2PSocketManager {
}
public I2PSocket receiveSocket() throws I2PException {
if (_session.isClosed()) throw new I2PException("Session closed");
verifySession();
Connection con = _connectionManager.getConnectionHandler().accept(-1);
if (_log.shouldLog(Log.DEBUG))
_log.debug("receiveSocket() called: " + con);
@@ -149,6 +149,12 @@ public class I2PSocketManagerFull implements I2PSocketManager {
return _serverSocket;
}
private void verifySession() throws I2PException {
if (!_connectionManager.getSession().isClosed())
return;
_connectionManager.getSession().connect();
}
/**
* Create a new connected socket (block until the socket is created)
*
@@ -160,8 +166,7 @@ public class I2PSocketManagerFull implements I2PSocketManager {
*/
public I2PSocket connect(Destination peer, I2PSocketOptions options)
throws I2PException, NoRouteToHostException {
if (_connectionManager.getSession().isClosed())
throw new I2PException("Session is closed");
verifySession();
if (options == null)
options = _defaultOptions;
ConnectionOptions opts = null;

View File

@@ -92,7 +92,9 @@ public class MessageHandler implements I2PSessionListener {
*/
public void errorOccurred(I2PSession session, String message, Throwable error) {
if (_log.shouldLog(Log.ERROR))
_log.error("error occurred: " + message, error);
_log.error("error occurred: " + message + "- " + error.getMessage());
if (_log.shouldLog(Log.WARN))
_log.warn("cause", error);
//_manager.disconnectAllHard();
}

View File

@@ -137,28 +137,31 @@ public class PacketHandler {
if (_log.shouldLog(Log.WARN))
_log.warn("Received forged reset for " + con, ie);
}
} else if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) {
} else {
if ( (con.getSendStreamId() == null) ||
(DataHelper.eq(con.getSendStreamId(), packet.getReceiveStreamId())) ) {
byte oldId[] =con.getSendStreamId();
// con fully established, w00t
con.setSendStreamId(packet.getReceiveStreamId());
if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) // con fully established, w00t
con.setSendStreamId(packet.getReceiveStreamId());
try {
con.getPacketHandler().receivePacket(packet, con);
} catch (I2PException ie) {
if (_log.shouldLog(Log.WARN))
_log.warn("Received forged syn for " + con, ie);
_log.warn("Received forged packet for " + con + ": " + packet, ie);
con.setSendStreamId(oldId);
}
} else {
} else if (packet.isFlagSet(Packet.FLAG_SYNCHRONIZE)) {
if (_log.shouldLog(Log.WARN))
_log.warn("Receive a syn packet with the wrong IDs, sending reset: " + packet);
sendReset(packet);
} else {
if (!con.getResetSent()) {
// someone is sending us a packet on the wrong stream
if (_log.shouldLog(Log.WARN))
_log.warn("Received a packet on the wrong stream: " + packet + " connection: " + con);
}
}
} else {
// someone is sending us a packet on the wrong stream
if (_log.shouldLog(Log.WARN))
_log.warn("Received a packet on the wrong stream: " + packet + " connection: " + con);
}
}
}

View File

@@ -38,7 +38,7 @@ class SchedulerConnectedBulk extends SchedulerImpl {
public boolean accept(Connection con) {
boolean ok = (con != null) &&
(con.getAckedPackets() > 0) &&
(con.getHighestAckedThrough() >= 0) &&
(con.getOptions().getProfile() == ConnectionOptions.PROFILE_BULK) &&
(!con.getResetReceived()) &&
( (con.getCloseSentOn() <= 0) || (con.getCloseReceivedOn() <= 0) );

View File

@@ -39,7 +39,7 @@ class SchedulerConnecting extends SchedulerImpl {
boolean notYetConnected = (con.getIsConnected()) &&
//(con.getSendStreamId() == null) && // not null on recv
(con.getLastSendId() >= 0) &&
(con.getAckedPackets() <= 0) &&
(con.getHighestAckedThrough() < 0) &&
(!con.getResetReceived());
return notYetConnected;
}

View File

@@ -32,19 +32,13 @@ class SchedulerDead extends SchedulerImpl {
public boolean accept(Connection con) {
if (con == null) return false;
long timeSinceClose = _context.clock().now() - con.getCloseSentOn();
if (con.getResetSent())
timeSinceClose = _context.clock().now() - con.getResetSentOn();
boolean nothingLeftToDo = (con.getCloseSentOn() > 0) &&
(con.getCloseReceivedOn() > 0) &&
(con.getUnackedPacketsReceived() <= 0) &&
(con.getUnackedPacketsSent() <= 0) &&
(con.getResetSent()) &&
long timeSinceClose = _context.clock().now() - con.getDisconnectScheduledOn();
boolean nothingLeftToDo = (con.getDisconnectScheduledOn() > 0) &&
(timeSinceClose >= Connection.DISCONNECT_TIMEOUT);
boolean timedOut = (con.getOptions().getConnectTimeout() < con.getLifetime()) &&
con.getSendStreamId() == null &&
con.getLifetime() >= Connection.DISCONNECT_TIMEOUT;
return con.getResetReceived() || nothingLeftToDo || timedOut;
return nothingLeftToDo || timedOut;
}
public void eventOccurred(Connection con) {

View File

@@ -38,7 +38,7 @@ class SchedulerHardDisconnected extends SchedulerImpl {
timeSinceClose = _context.clock().now() - con.getResetSentOn();
boolean ok = (con.getHardDisconnected() || con.getResetSent()) &&
(timeSinceClose < Connection.DISCONNECT_TIMEOUT);
return ok;
return ok || con.getResetReceived();
}
public void eventOccurred(Connection con) {

42
apps/susimail/build.xml Normal file
View File

@@ -0,0 +1,42 @@
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="all" name="susimail">
<target name="all" depends="clean, build" />
<target name="build" depends="builddep, jar" />
<target name="builddep">
<ant dir="../jetty/" target="build" />
</target>
<target name="compile" depends="clean">
<javac
srcdir="./src/src"
debug="true" deprecation="off" source="1.3" target="1.3"
destdir="./src/WEB-INF/classes">
<classpath>
<pathelement location="../jetty/jettylib/javax.servlet.jar" />
<pathelement location="../jetty/jettylib/org.mortbay.jetty.jar" />
</classpath>
</javac>
</target>
<target name="jar" depends="compile, war" />
<target name="war" depends="compile">
<war destfile="susimail.war" webxml="src/WEB-INF/web.xml"
basedir="src/" excludes="WEB-INF/web.xml">
</war>
</target>
<target name="javadoc">
<mkdir dir="./build" />
<mkdir dir="./build/javadoc" />
<javadoc
sourcepath="./src/src/" destdir="./build/javadoc"
packagenames="*"
use="true"
splitindex="true"
windowtitle="susimail" />
</target>
<target name="clean">
<delete>
<fileset dir="src/WEB-INF/classes/" includes="**/*.class, susimail.war" />
</delete>
</target>
<target name="cleandep" depends="clean" />
<target name="distclean" depends="clean" />
</project>

2
apps/susimail/readme.txt Normal file
View File

@@ -0,0 +1,2 @@
The src/ dir contains susimail 0.13 retrieved from http://susi.i2p/ on 2005/02/17
The contents are released under GPL. Please see http://susi.i2p/ for more info

BIN
apps/susimail/src/3down.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 415 B

BIN
apps/susimail/src/3up.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 406 B

340
apps/susimail/src/LICENSE Normal file
View File

@@ -0,0 +1,340 @@
GNU GENERAL PUBLIC LICENSE
Version 2, June 1991
Copyright (C) 1989, 1991 Free Software Foundation, Inc.
59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
Everyone is permitted to copy and distribute verbatim copies
of this license document, but changing it is not allowed.
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
License is intended to guarantee your freedom to share and change free
software--to make sure the software is free for all its users. This
General Public License applies to most of the Free Software
Foundation's software and to any other program whose authors commit to
using it. (Some other Free Software Foundation software is covered by
the GNU Library General Public License instead.) You can apply it to
your programs, too.
When we speak of free software, we are referring to freedom, not
price. Our General Public Licenses are designed to make sure that you
have the freedom to distribute copies of free software (and charge for
this service if you wish), that you receive source code or can get it
if you want it, that you can change the software or use pieces of it
in new free programs; and that you know you can do these things.
To protect your rights, we need to make restrictions that forbid
anyone to deny you these rights or to ask you to surrender the rights.
These restrictions translate to certain responsibilities for you if you
distribute copies of the software, or if you modify it.
For example, if you distribute copies of such a program, whether
gratis or for a fee, you must give the recipients all the rights that
you have. You must make sure that they, too, receive or can get the
source code. And you must show them these terms so they know their
rights.
We protect your rights with two steps: (1) copyright the software, and
(2) offer you this license which gives you legal permission to copy,
distribute and/or modify the software.
Also, for each author's protection and ours, we want to make certain
that everyone understands that there is no warranty for this free
software. If the software is modified by someone else and passed on, we
want its recipients to know that what they have is not the original, so
that any problems introduced by others will not reflect on the original
authors' reputations.
Finally, any free program is threatened constantly by software
patents. We wish to avoid the danger that redistributors of a free
program will individually obtain patent licenses, in effect making the
program proprietary. To prevent this, we have made it clear that any
patent must be licensed for everyone's free use or not licensed at all.
The precise terms and conditions for copying, distribution and
modification follow.
GNU GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License applies to any program or other work which contains
a notice placed by the copyright holder saying it may be distributed
under the terms of this General Public License. The "Program", below,
refers to any such program or work, and a "work based on the Program"
means either the Program or any derivative work under copyright law:
that is to say, a work containing the Program or a portion of it,
either verbatim or with modifications and/or translated into another
language. (Hereinafter, translation is included without limitation in
the term "modification".) Each licensee is addressed as "you".
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running the Program is not restricted, and the output from the Program
is covered only if its contents constitute a work based on the
Program (independent of having been made by running the Program).
Whether that is true depends on what the Program does.
1. You may copy and distribute verbatim copies of the Program's
source code as you receive it, in any medium, provided that you
conspicuously and appropriately publish on each copy an appropriate
copyright notice and disclaimer of warranty; keep intact all the
notices that refer to this License and to the absence of any warranty;
and give any other recipients of the Program a copy of this License
along with the Program.
You may charge a fee for the physical act of transferring a copy, and
you may at your option offer warranty protection in exchange for a fee.
2. You may modify your copy or copies of the Program or any portion
of it, thus forming a work based on the Program, and copy and
distribute such modifications or work under the terms of Section 1
above, provided that you also meet all of these conditions:
a) You must cause the modified files to carry prominent notices
stating that you changed the files and the date of any change.
b) You must cause any work that you distribute or publish, that in
whole or in part contains or is derived from the Program or any
part thereof, to be licensed as a whole at no charge to all third
parties under the terms of this License.
c) If the modified program normally reads commands interactively
when run, you must cause it, when started running for such
interactive use in the most ordinary way, to print or display an
announcement including an appropriate copyright notice and a
notice that there is no warranty (or else, saying that you provide
a warranty) and that users may redistribute the program under
these conditions, and telling the user how to view a copy of this
License. (Exception: if the Program itself is interactive but
does not normally print such an announcement, your work based on
the Program is not required to print an announcement.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Program,
and can be reasonably considered independent and separate works in
themselves, then this License, and its terms, do not apply to those
sections when you distribute them as separate works. But when you
distribute the same sections as part of a whole which is a work based
on the Program, the distribution of the whole must be on the terms of
this License, whose permissions for other licensees extend to the
entire whole, and thus to each and every part regardless of who wrote it.
Thus, it is not the intent of this section to claim rights or contest
your rights to work written entirely by you; rather, the intent is to
exercise the right to control the distribution of derivative or
collective works based on the Program.
In addition, mere aggregation of another work not based on the Program
with the Program (or with a work based on the Program) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may copy and distribute the Program (or a work based on it,
under Section 2) in object code or executable form under the terms of
Sections 1 and 2 above provided that you also do one of the following:
a) Accompany it with the complete corresponding machine-readable
source code, which must be distributed under the terms of Sections
1 and 2 above on a medium customarily used for software interchange; or,
b) Accompany it with a written offer, valid for at least three
years, to give any third party, for a charge no more than your
cost of physically performing source distribution, a complete
machine-readable copy of the corresponding source code, to be
distributed under the terms of Sections 1 and 2 above on a medium
customarily used for software interchange; or,
c) Accompany it with the information you received as to the offer
to distribute corresponding source code. (This alternative is
allowed only for noncommercial distribution and only if you
received the program in object code or executable form with such
an offer, in accord with Subsection b above.)
The source code for a work means the preferred form of the work for
making modifications to it. For an executable work, complete source
code means all the source code for all modules it contains, plus any
associated interface definition files, plus the scripts used to
control compilation and installation of the executable. However, as a
special exception, the source code distributed need not include
anything that is normally distributed (in either source or binary
form) with the major components (compiler, kernel, and so on) of the
operating system on which the executable runs, unless that component
itself accompanies the executable.
If distribution of executable or object code is made by offering
access to copy from a designated place, then offering equivalent
access to copy the source code from the same place counts as
distribution of the source code, even though third parties are not
compelled to copy the source along with the object code.
4. You may not copy, modify, sublicense, or distribute the Program
except as expressly provided under this License. Any attempt
otherwise to copy, modify, sublicense or distribute the Program is
void, and will automatically terminate your rights under this License.
However, parties who have received copies, or rights, from you under
this License will not have their licenses terminated so long as such
parties remain in full compliance.
5. You are not required to accept this License, since you have not
signed it. However, nothing else grants you permission to modify or
distribute the Program or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Program (or any work based on the
Program), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Program or works based on it.
6. Each time you redistribute the Program (or any work based on the
Program), the recipient automatically receives a license from the
original licensor to copy, distribute or modify the Program subject to
these terms and conditions. You may not impose any further
restrictions on the recipients' exercise of the rights granted herein.
You are not responsible for enforcing compliance by third parties to
this License.
7. If, as a consequence of a court judgment or allegation of patent
infringement or for any other reason (not limited to patent issues),
conditions are imposed on you (whether by court order, agreement or
otherwise) that contradict the conditions of this License, they do not
excuse you from the conditions of this License. If you cannot
distribute so as to satisfy simultaneously your obligations under this
License and any other pertinent obligations, then as a consequence you
may not distribute the Program at all. For example, if a patent
license would not permit royalty-free redistribution of the Program by
all those who receive copies directly or indirectly through you, then
the only way you could satisfy both it and this License would be to
refrain entirely from distribution of the Program.
If any portion of this section is held invalid or unenforceable under
any particular circumstance, the balance of the section is intended to
apply and the section as a whole is intended to apply in other
circumstances.
It is not the purpose of this section to induce you to infringe any
patents or other property right claims or to contest validity of any
such claims; this section has the sole purpose of protecting the
integrity of the free software distribution system, which is
implemented by public license practices. Many people have made
generous contributions to the wide range of software distributed
through that system in reliance on consistent application of that
system; it is up to the author/donor to decide if he or she is willing
to distribute software through any other system and a licensee cannot
impose that choice.
This section is intended to make thoroughly clear what is believed to
be a consequence of the rest of this License.
8. If the distribution and/or use of the Program is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Program under this License
may add an explicit geographical distribution limitation excluding
those countries, so that distribution is permitted only in or among
countries not thus excluded. In such case, this License incorporates
the limitation as if written in the body of this License.
9. The Free Software Foundation may publish revised and/or new versions
of the General Public License from time to time. Such new versions will
be similar in spirit to the present version, but may differ in detail to
address new problems or concerns.
Each version is given a distinguishing version number. If the Program
specifies a version number of this License which applies to it and "any
later version", you have the option of following the terms and conditions
either of that version or of any later version published by the Free
Software Foundation. If the Program does not specify a version number of
this License, you may choose any version ever published by the Free Software
Foundation.
10. If you wish to incorporate parts of the Program into other free
programs whose distribution conditions are different, write to the author
to ask for permission. For software which is copyrighted by the Free
Software Foundation, write to the Free Software Foundation; we sometimes
make exceptions for this. Our decision will be guided by the two goals
of preserving the free status of all derivatives of our free software and
of promoting the sharing and reuse of software generally.
NO WARRANTY
11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY
FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN
OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES
PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED
OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS
TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE
PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING,
REPAIR OR CORRECTION.
12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR
REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES,
INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING
OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED
TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY
YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER
PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE
POSSIBILITY OF SUCH DAMAGES.
END OF TERMS AND CONDITIONS
How to Apply These Terms to Your New Programs
If you develop a new program, and you want it to be of the greatest
possible use to the public, the best way to achieve this is to make it
free software which everyone can redistribute and change under these terms.
To do so, attach the following notices to the program. It is safest
to attach them to the start of each source file to most effectively
convey the exclusion of warranty; and each file should have at least
the "copyright" line and a pointer to where the full notice is found.
<one line to give the program's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
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
Also add information on how to contact you by electronic and paper mail.
If the program is interactive, make it output a short notice like this
when it starts in an interactive mode:
Gnomovision version 69, Copyright (C) year name of author
Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
This is free software, and you are welcome to redistribute it
under certain conditions; type `show c' for details.
The hypothetical commands `show w' and `show c' should show the appropriate
parts of the General Public License. Of course, the commands you use may
be called something other than `show w' and `show c'; they could even be
mouse-clicks or menu items--whatever suits your program.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the program, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the program
`Gnomovision' (which makes passes at compilers) written by James Hacker.
<signature of Ty Coon>, 1 April 1989
Ty Coon, President of Vice
This General Public License does not permit incorporating your program into
proprietary programs. If your program is a subroutine library, you may
consider it more useful to permit linking proprietary applications with the
library. If this is what you want to do, use the GNU Library General
Public License instead of this License.

View File

@@ -0,0 +1,20 @@
susimail.encodings=i2p.susi.webmail.encoding.HeaderLine;i2p.susi.webmail.encoding.QuotedPrintable;i2p.susi.webmail.encoding.Base64;i2p.susi.webmail.encoding.SevenBit;i2p.susi.webmail.encoding.EightBit;i2p.susi.webmail.encoding.HTML
susimail.host=localhost
susimail.ports.fixed=true
susimail.ports.pop3=7660
susimail.ports.smtp=7659
susimail.fast.start=true
susimail.sender.fixed=true
susimail.sender.domain=mail.i2p
susimail.pager.pagesize=10
susimail.composer.cols=80
susimail.composer.rows=15
susimail.composer.bcc.to.self=true
susimail.date.format=MM/dd/yyyy HH:mm:ss

View File

@@ -0,0 +1,18 @@
<?xml version="1.0" encoding="ISO-8859-1"?>
<!DOCTYPE web-app
PUBLIC "-//Sun Microsystems, Inc.//DTD Web Application 2.2//EN"
"http://java.sun.com/j2ee/dtds/web-app_2.2.dtd">
<web-app>
<display-name>susimail</display-name>
<servlet>
<servlet-name>SusiMail</servlet-name>
<servlet-class>i2p.susi.webmail.WebMail</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SusiMail</servlet-name>
<url-pattern>/susimail</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>15</session-timeout>
</session-config>
</web-app>

96
apps/susimail/src/css.css Normal file
View File

@@ -0,0 +1,96 @@
body {
background-color:white;
}
li {
font-family:Verdana,Tahoma,Arial,Helvetica;
color:black;
line-height:12pt;
font-size:10pt;
margin-left:5mm;
margin-right:5mm;
}
p {
font-family:Verdana,Tahoma,Arial,Helvetica;
color:black;
line-height:12pt;
margin-left:5mm;
margin-right:5mm;
font-size:10pt;
}
p.hl {
font-size:12pt;
letter-spacing:2pt;
line-height:18pt;
font-weight:bold;
}
p.text {
margin-left:10mm;
margin-right:10mm;
}
p.error {
color:#ff0000;
}
p.info {
color:#327BBF;
}
span.coloured {
color:#327BBF;
}
p.footer {
margin-left:10mm;
margin-right:10mm;
font-size:8pt;
line-height:10pt;
}
p.mailbody {
font-family:Courier-Fixed;
margin-left:1cm;
margin-right:1cm;
}
a {
color:#327BBF;
text-decoration:none;
}
a:hover {
text-decoration:underline;
}
td {
font-family:Verdana,Tahoma,Arial,Helvetica;
color:black;
line-height:12pt;
margin-left:5mm;
margin-right:5mm;
font-size:10pt;
}
tr.list0 {
background-color:#e0e0e0;
}
tr.list1 {
background-color:#ffffff;
}
table.noborder {
margin-left:0mm;
margin-top:0mm;
margin-right:0mm;
}
pre {
font-family:Courier-Fixed;
margin-left:1cm;
margin-right:1cm;
}

View File

@@ -0,0 +1,10 @@
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="refresh" content="0;url=susimail" />
<title>Susimail</title>
</head>
<body>
<a href="susimail">Enter</a>
</body>
</html>

View File

@@ -0,0 +1,43 @@
/*
* Created on Nov 4, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.2 $
*/
package i2p.susi.debug;
/**
* @author susi23
*/
public class Debug {
public static final int ERROR = 1;
public static final int DEBUG = 2;
private static int level = ERROR;
public static void setLevel( int newLevel )
{
level = newLevel;
}
public static void debug( int msgLevel, String msg )
{
if( msgLevel <= level )
System.err.println( msg );
}
}

View File

@@ -0,0 +1,128 @@
/*
* Created on Nov 15, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.4 $
*/
package i2p.susi.util;
import i2p.susi.debug.Debug;
import java.io.FileInputStream;
import java.util.Properties;
/**
* @author susi
*/
public class Config {
private static Properties properties = null, config = null;
private static String configPrefix = null;
/**
*
* @param name
* @return
*/
public static String getProperty( String name )
{
if( configPrefix != null )
name = configPrefix + name;
String result = null;
if( properties == null ) {
reloadConfiguration();
}
result = System.getProperty( name );
if( result != null )
return result;
result = config.getProperty( name );
if( result != null )
return result;
result = properties.getProperty( name );
return result;
}
/**
*
*
*/
public static void reloadConfiguration()
{
properties = new Properties();
config = new Properties();
try {
properties.load( Config.class.getResourceAsStream( "/susimail.properties" ) );
} catch (Exception e) {
Debug.debug( Debug.DEBUG, "Could not open WEB-INF/classes/susimail.properties (possibly in jar), reason: " + e.getMessage() );
}
try {
config.load( new FileInputStream( "susimail.config" ) );
} catch (Exception e) {
Debug.debug( Debug.DEBUG, "Could not open susimail.config, reason: " + e.getMessage() );
}
}
/**
*
* @param name
* @param defaultValue
* @return
*/
public static String getProperty( String name, String defaultValue )
{
String result = getProperty( name );
return result != null ? result : defaultValue;
}
/**
*
* @param name
* @param defaultValue
* @return
*/
public static int getProperty( String name, int defaultValue )
{
int result = defaultValue;
String str = getProperty( name );
if( str != null ) {
try {
result = Integer.parseInt( str );
}
catch( NumberFormatException nfe ) {
result = defaultValue;
}
}
return result;
}
/**
*
* @param prefix
*/
public static void setPrefix( String prefix )
{
configPrefix = prefix.endsWith( "." ) ? prefix : prefix + ".";
}
}

View File

@@ -0,0 +1,452 @@
/*
* Created on Nov 23, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.2 $
*/
package i2p.susi.util;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
/**
* Folder object manages a array Object[] to support
* paging and sorting.
*
* You create a folder object, set the contents with setElements(),
* add Comparators with addSorter(), choose one with sortBy() and
* and then fetch the content of the current page with
* currentPageIterator().
*
* @author susi
*/
public class Folder {
public static final String PAGESIZE = "pager.pagesize";
public static final int DEFAULT_PAGESIZE = 10;
public static final boolean DOWN = false;
public static final boolean UP = true;
private int pages, pageSize, currentPage;
private Object[] unsortedElements, elements;
private Hashtable sorter;
private boolean sortingDirection;
Comparator currentSorter;
public Folder()
{
pages = 1;
pageSize = 0;
currentPage = 1;
unsortedElements = null;
sorter = new Hashtable();
sortingDirection = UP;
currentSorter = null;
}
/**
* Returns the current page.
*
* @return Returns the current page.
*/
public int getCurrentPage() {
return currentPage;
}
/**
* Sets the current page to the given parameter.
*
* @param currentPage The current page to set.
*/
public void setCurrentPage(int currentPage) {
if( currentPage >= 1 && currentPage <= pages )
this.currentPage = currentPage;
}
/**
* Returns the size of the folder.
*
* @return Returns the size of the folder.
*/
public int getSize() {
return elements != null ? elements.length : 0;
}
/**
* Returns the number of pages in the folder.
* @return Returns the number of pages.
*/
public int getPages() {
return pages;
}
/**
* Returns page size. If no page size has been set, it returns property @link PAGESIZE.
* If no property is set @link DEFAULT_PAGESIZE is returned.
*
* @return Returns the pageSize.
*/
public int getPageSize() {
return pageSize > 0 ? pageSize : Config.getProperty( PAGESIZE, DEFAULT_PAGESIZE );
}
/**
* Set page size.
*
* @param pageSize The page size to set.
*/
public void setPageSize(int pageSize) {
if( pageSize > 0 )
this.pageSize = pageSize;
update();
}
/**
* Creates a copy of an array by copying its elements.
*
* @param source Array to copy.
* @return Copy of source.
*/
private Object[] copyArray( Object[] source )
{
Object[] destination = new Object[source.length];
for( int i = 0; i < source.length; i++ )
destination[i] = source[i];
return destination;
}
/**
* Recalculates variables.
*/
private void update() {
if( elements != null ) {
pages = elements.length / getPageSize();
if( pages * getPageSize() < elements.length )
pages++;
if( currentPage > pages )
currentPage = pages;
}
else {
pages = 1;
currentPage = 1;
}
}
/**
* Sorts the elements according the order given by @link addSorter()
* and @link sortBy().
*/
private void sort()
{
if( currentSorter != null ) {
elements = copyArray( unsortedElements );
Arrays.sort( elements, currentSorter );
}
else {
elements = unsortedElements;
}
}
/**
* Set the array of objects the folder should manage.
*
* @param elements Array of Objects.
*/
public void setElements( Object[] elements )
{
this.unsortedElements = elements;
if( currentSorter != null )
sort();
else
this.elements = elements;
update();
}
/**
* Returns an iterator containing the elements on the current page.
* @return Iterator containing the elements on the current page.
*/
public Iterator currentPageIterator()
{
ArrayList list = new ArrayList();
if( elements != null ) {
int pageSize = getPageSize();
int offset = ( currentPage - 1 ) * pageSize;
int step = 1;
if( sortingDirection == DOWN ) {
offset = elements.length - offset - 1;
step = -1;
}
for( int i = 0; i < pageSize && offset >= 0 && offset < elements.length; i++ ) {
list.add( elements[offset] );
offset += step;
}
}
return list.iterator();
}
/**
* Turns folder to next page.
*/
public void nextPage()
{
currentPage++;
if( currentPage > pages )
currentPage = pages;
}
/**
* Turns folder to previous page.
*/
public void previousPage()
{
currentPage--;
if( currentPage < 1 )
currentPage = 1;
}
/**
* Sets folder to display first page.
*/
public void firstPage()
{
currentPage = 1;
}
/**
* Sets folder to display last page.
*/
public void lastPage()
{
currentPage = pages;
}
/**
* Adds a new sorter to the folder. You can sort the folder by
* calling sortBy() and choose the given id there.
*
* @param id ID to identify the Comparator with @link sortBy()
* @param sorter a Comparator to sort the Array given by @link setElements()
*/
public void addSorter( String id, Comparator sorter )
{
this.sorter.put( id, sorter );
}
/**
* Activates sorting by the choosen Comparator. The id must
* match the one, which the Comparator has been stored in the
* folder with @link addSorter().
*
* @param id ID to identify the Comparator stored with @link addSorter()
*/
public void sortBy( String id )
{
currentSorter = (Comparator)sorter.get( id );
sort();
}
/**
* Returns the element on the current page on the given position.
*
* @param Position of the element on the current page.
* @return Element on the current page on the given position.
*/
public Object getElementAtPosXonCurrentPage( int x )
{
Object result = null;
if( elements != null ) {
int pageSize = getPageSize();
int offset = ( currentPage - 1 ) * pageSize;
int step = 1;
if( sortingDirection == DOWN ) {
offset = elements.length - offset - 1;
step = -1;
}
offset += x * step;
if( offset >= 0 && offset < elements.length )
result = elements[offset];
}
return result;
}
/**
* Sets the sorting direction of the folder.
*
* @param direction @link UP or @link DOWN
*/
public void setSortingDirection( boolean direction )
{
sortingDirection = direction;
}
/**
* Returns the first element of the sorted folder.
*
* @return First element.
*/
public Object getFirstElement()
{
/*
* sorting direction is taken into account from getElement
*/
return elements == null ? null : getElement( 0 );
}
/**
* Returns the last element of the sorted folder.
*
* @return Last element.
*/
public Object getLastElement()
{
/*
* sorting direction is taken into account from getElement
*/
return elements == null ? null : getElement( elements.length - 1 );
}
/**
* Gets index of an element in the array regardless of sorting direction.
*
* @param element
* @return
*/
private int getIndexOf( Object element )
{
if( elements != null ) {
for( int i = 0; i < elements.length; i++ )
if( elements[i].equals( element ) )
return i;
}
return -1;
}
/**
* Retrieves the next element in the sorted array.
* Sorting direction is taken into account.
*
* @param element
* @return
*/
public Object getNextElement( Object element )
{
Object result = null;
int i = getIndexOf( element );
if( i != -1 && elements != null ) {
i += sortingDirection == UP ? 1 : -1;
if( i >= 0 && i < elements.length )
result = elements[i];
}
return result;
}
/**
* Retrieves the previous element in the sorted array.
* Sorting direction is taken into account.
*
* @param element
* @return
*/
public Object getPreviousElement( Object element )
{
Object result = null;
int i = getIndexOf( element );
if( i != -1 && elements != null ) {
i += sortingDirection == DOWN ? 1 : -1;
if( i >= 0 && i < elements.length )
result = elements[i];
}
return result;
}
/**
* Retrieves element at index i. Depends on sorting direction.
*
* @param i
* @return
*/
private Object getElement( int i )
{
Object result = null;
if( elements != null ) {
if( sortingDirection == DOWN )
i = elements.length - i - 1;
result = elements[i];
}
return result;
}
/**
* Returns true, if folder shows points to the last page.
*
* @return
*/
public boolean isLastPage()
{
return currentPage == pages;
}
/**
* Returns true, if folder shows points to the first page.
*
* @return
*/
public boolean isFirstPage()
{
return currentPage == 1;
}
/**
* Returns true, if elements.equals( lastElementOfTheSortedArray ).
* The sorting direction influences which element is taken for comparison.
*
* @param element
* @return
*/
public boolean isLastElement( Object element )
{
if( elements == null )
return false;
return elements[ sortingDirection == DOWN ? 0 : elements.length - 1 ].equals( element );
}
/**
* Returns true, if elements.equals( firstElementOfTheSortedArray ).
* The sorting direction influences which element is taken for comparison.
*
* @param element
* @return
*/
public boolean isFirstElement( Object element )
{
if( elements == null )
return false;
return elements[ sortingDirection == UP ? 0 : elements.length - 1 ].equals( element );
}
}

View File

@@ -0,0 +1,60 @@
/*
* Created on Nov 12, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.2 $
*/
package i2p.susi.util;
/**
* @author susi
*/
public class HexTable {
public static String[] table = null;
static {
table = new String[256];
for( int i = 0; i < 256; i++ ) {
String str = intToHex( i );
if( str.length() == 1 )
str = "0" + str;
table[i] = "=" + str;
}
}
private static String intToHex( int b )
{
if( b == 0 )
return "0";
else {
String str = "";
while( b > 0 ) {
byte c = (byte)(b % 16);
if( c < 10 )
c += '0';
else
c += 'A' - 10;
str = "" + (char)c + str;
b = (byte)(b / 16);
}
return str;
}
}
}

View File

@@ -0,0 +1,38 @@
/*
* Created on Nov 15, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.2 $
*/
package i2p.susi.util;
/**
* @author susi
*/
public class ReadBuffer {
public byte content[];
public int length, offset;
public String toString()
{
return content != null ? new String( content, offset, length ) : "";
}
}

View File

@@ -0,0 +1,97 @@
/*
* Created on 01.12.2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.4 $
*/
package i2p.susi.webmail;
import i2p.susi.util.ReadBuffer;
/**
* @author user
*/
public class Attachment {
private String fileName, contentType, transferEncoding;
private ReadBuffer buffer;
private String data;
/**
* @return Returns the fileName.
*/
public String getFileName() {
return fileName;
}
/**
* @param fileName The fileName to set.
*/
public void setFileName(String fileName) {
this.fileName = fileName;
}
/**
* @return Returns the buffer.
*/
public ReadBuffer getBuffer() {
return buffer;
}
/**
* @param buffer The buffer to set.
*/
public void setBuffer(ReadBuffer buffer) {
this.buffer = buffer;
}
/**
* @return
*/
public String getTransferEncoding() {
// TODO Auto-generated method stub
return transferEncoding;
}
/**
* @return
*/
public String getContentType() {
// TODO Auto-generated method stub
return contentType;
}
/**
* @param contentType The contentType to set.
*/
public void setContentType(String contentType) {
this.contentType = contentType;
}
/**
* @param transferEncoding The transferEncoding to set.
*/
public void setTransferEncoding(String transferEncoding) {
this.transferEncoding = transferEncoding;
}
/**
* @param string
*/
public void setData(String data ) {
this.data = data;
}
/**
* @return Returns the data.
*/
public String getData() {
return data;
}
}

View File

@@ -0,0 +1,240 @@
/*
* Created on Nov 9, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.5 $
*/
package i2p.susi.webmail;
import i2p.susi.debug.Debug;
import i2p.susi.util.Config;
import i2p.susi.util.ReadBuffer;
import i2p.susi.webmail.encoding.Encoding;
import i2p.susi.webmail.encoding.EncodingFactory;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStreamReader;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
/**
* data structure to hold a single message, mostly used with folder view and sorting
*
* @author susi
*/
public class Mail {
public static final String DATEFORMAT = "date.format";
public static final String unknown = "unknown";
public int id, size;
public String sender, reply, subject, dateString,
formattedSender, formattedSubject, formattedDate,
shortSender, shortSubject, quotedDate, uidl;
public Date date;
public ReadBuffer header, body;
public MailPart part;
Object[] to, cc;
public String error;
public boolean markForDeletion;
public boolean deleted;
public Mail() {
id = 0;
size = 0;
formattedSender = unknown;
formattedSubject = unknown;
formattedDate = unknown;
shortSender = unknown;
shortSubject = unknown;
quotedDate = unknown;
error = "";
}
/**
*
* @param address
* @return
*/
public static boolean validateAddress( String address )
{
if( address == null || address.length() == 0 )
return false;
address = address.trim();
if( address.indexOf( "\n" ) != -1 ||
address.indexOf( "\r" ) != -1 )
return false;
String[] tokens = address.split( "[ \t]+" );
int addresses = 0;
for( int i = 0; i < tokens.length; i++ ) {
if( tokens[i].matches( "^[^@< \t]+@[^> \t]+$" ) ||
tokens[i].matches( "^<[^@< \t]+@[^> \t]+>$" ) )
addresses++;
}
return addresses == 1;
}
/**
* @param address
* @return
*/
public static String getAddress(String address )
{
String[] tokens = address.split( "[ \t]+" );
for( int i = 0; i < tokens.length; i++ ) {
if( tokens[i].matches( "^[^@< \t]+@[^> \t]+$" ) )
return "<" + tokens[i] + ">";
if( tokens[i].matches( "^<[^@< \t]+@[^> \t]+>$" ) )
return tokens[i];
}
return null;
}
public static boolean getRecipientsFromList( ArrayList recipients, String text, boolean ok )
{
if( text != null && text.length() > 0 ) {
String[] ccs = text.split( "," );
for( int i = 0; i < ccs.length; i++ ) {
String recipient = ccs[i].trim();
if( validateAddress( recipient ) ) {
String str = getAddress( recipient );
if( str != null && str.length() > 0 ) {
recipients.add( str );
}
else {
ok = false;
}
}
else {
ok = false;
}
}
}
return ok;
}
public static void appendRecipients( StringBuffer buf, ArrayList recipients, String prefix )
{
for( Iterator it = recipients.iterator(); it.hasNext(); ) {
buf.append( prefix );
prefix ="\t";
buf.append( (String)it.next() );
buf.append( "\r\n" );
}
}
public void parseHeaders()
{
DateFormat dateFormatter = new SimpleDateFormat( Config.getProperty( DATEFORMAT, "mm/dd/yyyy HH:mm:ss" ) );
DateFormat mailDateFormatter = new SimpleDateFormat("EEE, d MMM yyyy HH:mm:ss Z", Locale.ENGLISH );
error = "";
if( header != null ) {
boolean ok = true;
Encoding html = EncodingFactory.getEncoding( "HTML" );
if( html == null ) {
error += "HTML encoder not found.<br>";
ok = false;
}
Encoding hl = EncodingFactory.getEncoding( "HEADERLINE" );
if( hl == null ) {
error += "Header line encoder not found.<br>";
ok = false;
}
if( ok ) {
try {
ReadBuffer decoded = hl.decode( header );
BufferedReader reader = new BufferedReader( new InputStreamReader( new ByteArrayInputStream( decoded.content, decoded.offset, decoded.length ), "ISO-8859-1" ) );
String line;
while( ( line = reader.readLine() ) != null ) {
if( line.length() == 0 )
break;
if( line.startsWith( "From:" ) ) {
sender = line.substring( 5 ).trim();
formattedSender = getAddress( sender );
shortSender = formattedSender.trim();
if( shortSender.length() > 40 ) {
shortSender = shortSender.substring( 0, 37 ).trim() + "...";
}
shortSender = html.encode( shortSender );
}
else if( line.startsWith( "Date:" ) ) {
dateString = line.substring( 5 ).trim();
try {
date = mailDateFormatter.parse( dateString );
formattedDate = dateFormatter.format( date );
quotedDate = html.encode( dateString );
}
catch (ParseException e) {
date = null;
e.printStackTrace();
}
}
else if( line.startsWith( "Subject:" ) ) {
subject = line.substring( 8 ).trim();
formattedSubject = subject;
shortSubject = formattedSubject;
if( formattedSubject.length() > 60 )
shortSubject = formattedSubject.substring( 0, 57 ).trim() + "...";
shortSubject = html.encode( shortSubject );
}
else if( line.toLowerCase().startsWith( "Reply-To:" ) ) {
reply = Mail.getAddress( line.substring( 9 ).trim() );
}
else if( line.startsWith( "To:" ) ) {
ArrayList list = new ArrayList();
Mail.getRecipientsFromList( list, line.substring( 3 ).trim(), true );
to = list.toArray();
}
else if( line.startsWith( "Cc:" ) ) {
ArrayList list = new ArrayList();
Mail.getRecipientsFromList( list, line.substring( 3 ).trim(), true );
cc = list.toArray();
}
}
}
catch( Exception e ) {
error += "Error parsing mail header: " + e.getClass().getName() + "<br>";
}
}
}
}
}

View File

@@ -0,0 +1,103 @@
/*
* Created on Nov 23, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail;
import java.util.Hashtable;
import i2p.susi.debug.Debug;
import i2p.susi.webmail.pop3.POP3MailBox;
/**
* @author user
*/
public class MailCache {
public static final boolean FETCH_HEADER = true;
public static final boolean FETCH_ALL = false;
private POP3MailBox mailbox;
private String error;
private Hashtable mails;
private Object synchronizer;
MailCache( POP3MailBox mailbox ) {
this.mailbox = mailbox;
mails = new Hashtable();
synchronizer = new Object();
}
/**
* Fetch any needed data from pop3 server.
*
* @param id message id to get
* @param headerOnly fetch only header lines?
* @return
*/
public Mail getMail( String uidl, boolean headerOnly ) {
Mail mail = null, newMail = null;
if( mailbox != null ) {
/*
* synchronize update to hashtable
*/
synchronized( synchronizer ) {
mail = (Mail)mails.get( uidl );
if( mail == null ) {
newMail = new Mail();
mails.put( uidl, newMail );
}
}
if( mail == null ) {
mail = newMail;
mail.uidl = uidl;
mail.size = mailbox.getSize( uidl );
}
if( mail.size < 1024 )
headerOnly = false;
boolean parseHeaders = mail.header == null;
if( headerOnly ) {
if( mail.header == null )
mail.header = mailbox.getHeader( uidl );
}
else {
if( mail.body == null ) {
mail.body = mailbox.getBody( uidl );
if( mail.body != null ) {
mail.header = mail.body;
MailPart.parse( mail );
}
}
}
if( parseHeaders && mail.header != null )
mail.parseHeaders();
}
if( mail != null && mail.deleted )
mail = null;
return mail;
}
}

View File

@@ -0,0 +1,260 @@
/*
* Created on 07.11.2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.4 $
*/
package i2p.susi.webmail;
import i2p.susi.util.ReadBuffer;
import i2p.susi.webmail.encoding.EncodingFactory;
import java.util.ArrayList;
/**
* @author susi23
*/
public class MailPart {
public String headerLines[], type, boundary, encoding, name,
filename, description, disposition, charset, version;
public int beginBody, begin, end;
public ArrayList parts = null;
public boolean multipart = false, message = false;
public ReadBuffer buffer = null;
public void parse( ReadBuffer readBuffer )
{
parse( readBuffer, readBuffer.offset, readBuffer.length );
}
public void parse( ReadBuffer readBuffer, int offset, int length )
{
begin = offset;
end = offset + length;
buffer = readBuffer;
if( parts == null )
parts = new ArrayList();
else
parts.clear();
/*
* parse header lines
*/
beginBody = end;
for( int i = begin; i < end - 4; i++ )
if( buffer.content[i] == '\r' &&
buffer.content[i+1] == '\n' &&
buffer.content[i+2] == '\r' &&
buffer.content[i+3] == '\n' ) {
beginBody = i + 2;
break;
}
ReadBuffer decodedHeaders = null;
try {
decodedHeaders = EncodingFactory.getEncoding( "HEADERLINE" ).decode( buffer.content, begin, beginBody - begin );
}
catch (Exception e) {
e.printStackTrace();
}
headerLines = new String( decodedHeaders.content, decodedHeaders.offset, decodedHeaders.length ).split( "\r\n" );
for( int i = 0; i < headerLines.length; i++ )
{
if( headerLines[i].toLowerCase().startsWith( "content-transfer-encoding: " ) ) {
encoding = getFirstAttribute( headerLines[i] ).toLowerCase();
}
else if( headerLines[i].toLowerCase().startsWith( "content-disposition: " ) ) {
disposition = getFirstAttribute( headerLines[i] ).toLowerCase();
String str;
str = getHeaderLineAttribute( headerLines[i], "filename" );
if( str != null )
name = str;
}
else if( headerLines[i].toLowerCase().startsWith( "content-type: " ) ) {
type = getFirstAttribute( headerLines[i] ).toLowerCase();
/*
* extract boundary, name and charset from content type
*/
String str;
str = getHeaderLineAttribute( headerLines[i], "boundary" );
if( str != null )
boundary = str;
if( type != null && type.startsWith( "multipart" ) && boundary != null )
multipart = true;
if( type != null && type.startsWith( "message" ) )
message = true;
str = getHeaderLineAttribute( headerLines[i], "name" );
if( str != null )
name = str;
str = getHeaderLineAttribute( headerLines[i], "charset" );
if( str != null )
charset = str.toUpperCase();
}
else if( headerLines[i].toLowerCase().startsWith( "content-description: " ) ) {
description = getFirstAttribute( headerLines[i] );
}
else if( headerLines[i].toLowerCase().startsWith( "mime-version: " ) ) {
version = getFirstAttribute( headerLines[i] );
}
}
/*
* parse body
*/
int beginLastPart = -1;
if( multipart ) {
byte boundaryArray[] = boundary.getBytes();
for( int i = beginBody; i < end - 4; i++ ) {
if( buffer.content[i] == '\r' &&
buffer.content[i+1] == '\n' &&
buffer.content[i+2] == '-' &&
buffer.content[i+3] == '-' ) {
/*
* begin of possible boundary line
*/
int j = 0;
for( ; j < boundaryArray.length && i + 4 + j < end; j++ )
if( buffer.content[ i + 4 + j ] != boundaryArray[j] )
break;
if( j == boundaryArray.length ) {
int k = i + 4 + j;
if( k < end - 2 &&
buffer.content[k] == '-' &&
buffer.content[k+1] == '-' )
k += 2;
if( k < end - 2 &&
buffer.content[k] == '\r' &&
buffer.content[k+1] == '\n' ) {
k += 2;
int endLastPart = i + 2;
if( beginLastPart != -1 ) {
MailPart newPart = new MailPart();
newPart.parse( buffer, beginLastPart, endLastPart - beginLastPart );
parts.add( newPart );
}
beginLastPart = k;
}
i = k;
}
}
}
}
else if( message ) {
MailPart newPart = new MailPart();
newPart.parse( buffer, beginBody, end );
parts.add( newPart );
}
}
public static String getFirstAttribute( String line )
{
String result = null;
int i = line.indexOf( ": " );
if( i != - 1 ) {
int j = line.indexOf( ";", i + 2 );
if( j == -1 )
result = line.substring( i + 2 );
else
result = line.substring( i + 2, j );
result = result.trim();
}
return result;
}
public static String getHeaderLineAttribute( String line, String attributeName )
{
String result = null;
int h = 0;
int l = attributeName.length();
while( true ) {
int i = line.indexOf( attributeName, h );
// System.err.println( "i=" + i );
if( i == -1 )
break;
h = i + l;
int j = line.indexOf( "=", i + l );
// System.err.println( "j=" + j );
if( j != -1 ) {
int k = line.indexOf( "\"", j + 1 );
int m = line.indexOf( ";", j + 1 );
// System.err.println( "k=" + k );
if( k != -1 && ( m == -1 || k < m ) ) {
/*
* we found a " before a possible ;
*
* now we look for the 2nd (not quoted) "
*/
m = -1;
int k2 = k + 1;
while( true ) {
m = line.indexOf( "\"", k2 );
// System.err.println( "m=" + m + " '" + line.substring( m ) + "'" );
if( m == -1 ) {
break;
}
else {
/*
* found one
*/
if( line.charAt( m - 1 ) != '\\' ) {
/*
* its not quoted, so it is the one we look for
*/
result = line.substring( k + 1, m );
break;
}
else {
/*
* this is quoted, so we extract the quote and continue the search
*/
line = line.substring( 0, m - 1 ) + line.substring( m );
// System.err.println( "quoting found, line='" + line + "'" );
k2 = m;
}
}
}
}
else if( m != -1 ) {
/*
* no " found, but a ;
*/
result = line.substring( j + 1, m ).trim();
}
else {
/*
* no " found and no ;
*/
result = line.substring( j + 1 );
}
}
}
return result;
}
/**
* @param mail
*/
public static void parse(Mail mail) {
// TODO Auto-generated method stub
}
}

View File

@@ -0,0 +1,214 @@
/*
* Created on Dec 8, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail;
import java.io.IOException;
import java.io.InputStream;
import java.util.Enumeration;
import java.util.Hashtable;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.mortbay.servlet.MultiPartRequest;
/**
* @author user
*/
public class RequestWrapper {
private HttpServletRequest httpRequest = null;
private MultiPartRequest multiPartRequest = null;
private Hashtable cache;
private Hashtable cachedParameterNames;
/**
* do not call
*/
private RequestWrapper()
{
}
/**
* @param httpRequest
*/
public RequestWrapper(HttpServletRequest httpRequest) {
cache = new Hashtable();
this.httpRequest = httpRequest;
String contentType = httpRequest.getContentType();
if( contentType != null && contentType.toLowerCase().startsWith( "multipart/form-data" ) ) {
try {
multiPartRequest = new MultiPartRequest( httpRequest );
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
/**
* @param b
* @return
*/
public HttpSession getSession(boolean b) {
return httpRequest.getSession( b );
}
/**
* @param key
* @return
*/
public String getParameter(String name ) {
return getParameter( name, null );
}
/**
* @return
*/
public HttpSession getSession() {
return httpRequest.getSession();
}
/**
* @return
*/
public Enumeration getParameterNames() {
if( multiPartRequest != null ) {
if( cachedParameterNames == null ) {
cachedParameterNames = new Hashtable();
String[] partNames = multiPartRequest.getPartNames();
for( int i = 0; i < partNames.length; i++ )
cachedParameterNames.put( partNames[i], new Integer( i ) );
}
return cachedParameterNames.keys();
}
else
return httpRequest.getParameterNames();
}
/**
* @return
*/
public int getContentLength() {
return httpRequest.getContentLength();
}
/**
* @return
*/
public String getContentType() {
return httpRequest.getContentType();
}
/**
*
* @param partName
* @return
*/
public String getContentType( String partName )
{
String result = null;
if( multiPartRequest != null ) {
Hashtable params = multiPartRequest.getParams( partName );
for( Enumeration e = params.keys(); e.hasMoreElements(); ) {
String key = (String)e.nextElement();
if( key.toLowerCase().compareToIgnoreCase( "content-type") == 0 ) {
String value = (String)params.get( key );
int i = value.indexOf( ";" );
if( i != -1 )
result = value.substring( 0, i );
else
result = value;
}
}
}
return result;
}
/**
* @param string
* @return
*/
public Object getAttribute(String string) {
return httpRequest.getAttribute( string );
}
/**
* @param new_subject
* @param string
* @return
*/
public String getParameter( String name, String defaultValue )
{
String result = defaultValue;
if( multiPartRequest != null ) {
String str = (String)cache.get( name );
if( str != null ) {
result = str;
}
else {
String[] partNames = multiPartRequest.getPartNames();
for( int i = 0; i < partNames.length; i++ )
if( partNames[i].compareToIgnoreCase( name ) == 0 ) {
str = multiPartRequest.getString( partNames[i] );
if( str != null ) {
result = str;
cache.put( name, result );
break;
}
}
}
}
else {
String str = httpRequest.getParameter( name );
if( str != null )
result = str;
}
return result;
}
/**
* @param new_filename
* @return
*/
public String getFilename(String partName )
{
String result = null;
if( multiPartRequest != null ) {
String str = multiPartRequest.getFilename( partName );
if( str != null )
result = str;
}
return result;
}
/**
* @param new_filename
* @return
*/
public InputStream getInputStream(String partName )
{
InputStream result = null;
if( multiPartRequest != null ) {
result = multiPartRequest.getInputStream( partName );
}
return result;
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,237 @@
/*
* Created on 09.11.2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.6 $
*/
package i2p.susi.webmail.encoding;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import i2p.susi.util.ReadBuffer;
/**
* @author susi
*/
public class Base64 implements Encoding {
/* (non-Javadoc)
* @see i2p.susi23.util.Encoding#getName()
*/
public String getName() {
return "base64";
}
/**
* @param string
* @return
*/
public String encode( byte in[] ) throws EncodingException
{
try {
return encode( new ByteArrayInputStream( in ) );
}catch (IOException e) {
throw new EncodingException( e.getMessage() );
}
}
/* (non-Javadoc)
* @see i2p.susi23.util.Encoding#encode(java.lang.String)
*/
public String encode(String str) throws EncodingException {
try {
return encode( new StringBufferInputStream( str ) );
}catch (IOException e) {
throw new EncodingException( e.getMessage() );
}
}
/**
*
* @param in
* @return
*/
private String encode( InputStream in ) throws IOException, EncodingException
{
StringBuffer strBuf = new StringBuffer();
int buf[] = new int[3];
int out[] = new int[4];
int l = 0;
while( true ) {
int read = in.available();
if( read == 0 )
break;
int i = 0;
buf[0] = buf[1] = buf[2] = 0;
while( read > 0 && i < 3 ) {
buf[i] = in.read();
if( buf[i] < 0 || buf[i] > 255 )
throw new EncodingException( "Encoding supports only values 0..255 (" + buf[i] + ")" );
i++;
read--;
}
out[0] = encodeByte( ( buf[0] >> 2 ) & 63 );
out[1] = encodeByte( ( ( buf[0] & 3 ) << 4 ) | ( ( buf[1] >> 4 ) & 15 ) );
out[2] = encodeByte( ( ( buf[1] & 15 ) << 2 ) | ( ( buf[2] >> 6 ) & 3 ) );
out[3] = encodeByte( buf[2] & 63 );
strBuf.append( (char)out[0] );
strBuf.append( (char)out[1] );
if( i > 1 ) {
strBuf.append( (char)out[2] );
}
else
strBuf.append( "=" );
if( i > 2 )
strBuf.append( (char)out[3] );
else
strBuf.append( "=" );
i += 3;
l += 4;
if( l >= 76 ) {
strBuf.append( "\r\n" );
l -= 76;
}
}
return strBuf.toString();
}
/**
* @param b
* @return
*/
private static int encodeByte(int b) {
/*
0 A 17 R 34 i 51 z
1 B 18 S 35 j 52 0
2 C 19 T 36 k 53 1
3 D 20 U 37 l 54 2
4 E 21 V 38 m 55 3
5 F 22 W 39 n 56 4
6 G 23 X 40 o 57 5
7 H 24 Y 41 p 58 6
8 I 25 Z 42 q 59 7
9 J 26 a 43 r 60 8
10 K 27 b 44 s 61 9
11 L 28 c 45 t 62 +
12 M 29 d 46 u 63 /
13 N 30 e 47 v
14 O 31 f 48 w (pad) =
15 P 32 g 49 x
16 Q 33 h 50 y
*/
if( b < 26 )
b += 'A';
else if( b < 52 )
b += 'a' - 26;
else if( b < 62 )
b += '0' - 52;
else if( b == 62 )
b = '+';
else
b = '/';
return b;
}
private static byte decodeByte( byte b ) throws DecodingException {
byte a = b;
if( b >= 'A' && b <= 'Z' )
b -= 'A';
else if( b >= 'a' && b <= 'z' )
b = (byte) (b - 'a' + 26);
else if( b >= '0' && b <= '9' )
b = (byte) (b - '0' + 52);
else if( b == '+' )
b = 62;
else if( b == '/' )
b = 63;
else if( b == '=' )
b = 0;
else
throw new DecodingException( "Decoding base64 failed (invalid data)." );
// System.err.println( "decoded " + (char)a + " to " + b );
return b;
}
/**
* @param str
* @return
*/
public ReadBuffer decode(String text) throws DecodingException {
return text != null ? decode( text.getBytes() ) : null;
}
/* (non-Javadoc)
* @see i2p.susi23.util.Encoding#decode(byte[])
*/
public ReadBuffer decode(byte[] in) throws DecodingException {
return decode( in, 0, in.length );
}
/* (non-Javadoc)
* @see i2p.susi23.util.Encoding#decode(byte[], int, int)
*/
public ReadBuffer decode(byte[] in, int offset, int length) throws DecodingException {
byte out[] = new byte[length * 3 / 4 + 1 ];
int written = 0;
while( length > 0 ) {
if( in[offset] == '\r' || in[offset] == '\n' ||
in[offset] == ' ' || in[offset] == '\t' ) {
offset++;
length--;
continue;
}
if( length >= 4 ) {
// System.out.println( "decode: " + (char)in[offset] + (char)in[offset+1]+ (char)in[offset+2]+ (char)in[offset+3] );
byte b1 = decodeByte( in[offset++] );
byte b2 = decodeByte( in[offset++] );
out[written++] = (byte) (( b1 << 2 ) | ( ( b2 >> 4 ) & 3 ) );
byte b3 = in[offset++];
if( b3 != '=' ) {
b3 = decodeByte( b3 );
out[written++] = (byte)( ( ( b2 & 15 ) << 4 ) | ( ( b3 >> 2 ) & 15 ) );
}
byte b4 = in[offset++];
if( b4 != '=' ) {
b4 = decodeByte( b4 );
out[written++] = (byte)( ( ( b3 & 3 ) << 6 ) | b4 & 63 );
}
length -= 4;
}
else {
System.err.println( "" );
throw new DecodingException( "Decoding base64 failed (trailing garbage)." );
}
}
ReadBuffer readBuffer = new ReadBuffer();
readBuffer.content = out;
readBuffer.offset = 0;
readBuffer.length = written;
return readBuffer;
}
/* (non-Javadoc)
* @see i2p.susi23.util.Encoding#decode(i2p.susi23.util.ReadBuffer)
*/
public ReadBuffer decode(ReadBuffer in) throws DecodingException {
return decode( in.content, in.offset, in.length );
}
}

View File

@@ -0,0 +1,36 @@
/*
* Created on Nov 15, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.2 $
*/
package i2p.susi.webmail.encoding;
/**
* @author susi
*/
public class DecodingException extends Exception {
private static final long serialVersionUID = 1L;
DecodingException( String msg ) {
super( msg );
}
}

View File

@@ -0,0 +1,89 @@
/*
* Created on Nov 16, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail.encoding;
import i2p.susi.util.ReadBuffer;
/**
* @author susi
*/
public class EightBit implements Encoding {
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#getName()
*/
public String getName() {
return "8bit";
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#encode(byte[])
*/
public String encode(byte[] in) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#encode(java.lang.String)
*/
public String encode(String str) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(byte[])
*/
public ReadBuffer decode(byte[] in) throws DecodingException {
return decode( in, 0, in.length );
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(byte[], int, int)
*/
public ReadBuffer decode(byte[] in, int offset, int length)
throws DecodingException {
ReadBuffer readBuffer = new ReadBuffer();
readBuffer.content = in;
readBuffer.offset = offset;
readBuffer.length = length;
return readBuffer;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(java.lang.String)
*/
public ReadBuffer decode(String str) throws DecodingException {
return decode( str.getBytes() );
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(i2p.susi.webmail.util.ReadBuffer)
*/
public ReadBuffer decode(ReadBuffer in) throws DecodingException {
return in;
}
}

View File

@@ -0,0 +1,72 @@
/*
* Created on Nov 12, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail.encoding;
import i2p.susi.util.ReadBuffer;
/**
* Interface to encode/decode content transfer encodings like quoted-printable, base64 etc.
*
* @author susi
*/
public interface Encoding {
public String getName();
/**
*
* @param in
* @return
*/
public String encode( byte in[] ) throws EncodingException;
/**
*
* @param str
* @return
*/
public String encode( String str ) throws EncodingException;
/**
*
* @param in
* @return
*/
public ReadBuffer decode( byte in[] ) throws DecodingException;
/**
*
* @param in
* @param size
* @return
*/
public ReadBuffer decode( byte in[], int offset, int length ) throws DecodingException;
/**
*
* @param str
* @return
*/
public ReadBuffer decode( String str ) throws DecodingException;
/**
*
* @param in
* @return
*/
public ReadBuffer decode( ReadBuffer in ) throws DecodingException;
}

View File

@@ -0,0 +1,40 @@
/*
* Created on Nov 17, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.2 $
*/
package i2p.susi.webmail.encoding;
/**
* @author susi
*/
public class EncodingException extends Exception {
/**
* Comment for <code>serialVersionUID</code>
*/
private static final long serialVersionUID = 1L;
EncodingException( String msg )
{
super( msg );
}
}

View File

@@ -0,0 +1,80 @@
/*
* Created on Nov 12, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.4 $
*/
package i2p.susi.webmail.encoding;
import i2p.susi.debug.Debug;
import i2p.susi.util.Config;
import java.util.Hashtable;
import java.util.Set;
/**
* Manager class to handle content transfer encodings.
* @author susi
*/
public class EncodingFactory {
public static String CONFIG_ENCODING = "encodings";
private static Hashtable encodings = null;
static {
encodings = new Hashtable();
String list = Config.getProperty( CONFIG_ENCODING );
if( list != null ) {
String[] classNames = list.split( ";" );
for( int i = 0; i < classNames.length; i++ ) {
try {
Class c = Class.forName( classNames[i] );
Encoding e = (Encoding)c.newInstance();
encodings.put( e.getName(), e );
Debug.debug( Debug.DEBUG, "Registered " + e.getClass().getName() );
}
catch (Exception e) {
Debug.debug( Debug.ERROR, "Error loading class '" + classNames[i] + "', reason: " + e.getClass().getName() );
}
}
}
}
/**
* Retrieve instance of an encoder for a supported encoding (or null).
*
* @param name name of encoding (e.g. quoted-printable)
*
* @return
*/
public static Encoding getEncoding( String name )
{
return name != null && name.length() > 0 ? (Encoding)encodings.get( name ) : null;
}
/**
* Returns list of available encodings;
*
* @return
*/
public static Set availableEncodings()
{
return encodings.keySet();
}
}

View File

@@ -0,0 +1,89 @@
/*
* Created on Nov 23, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail.encoding;
import i2p.susi.util.ReadBuffer;
/**
* @author user
*/
public class HTML implements Encoding {
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#getName()
*/
public String getName() {
return "HTML";
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#encode(byte[])
*/
public String encode(byte[] in) throws EncodingException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#encode(java.lang.String)
*/
public String encode(String str) throws EncodingException
{
return str.replaceAll( "<", "&lt;" ).replaceAll( ">", "&gt;" ).replaceAll( "\r{0,1}\n", "<br>\r\n" );
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(byte[])
*/
public ReadBuffer decode(byte[] in) throws DecodingException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(byte[], int, int)
*/
public ReadBuffer decode(byte[] in, int offset, int length)
throws DecodingException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(java.lang.String)
*/
public ReadBuffer decode(String str) throws DecodingException {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(i2p.susi.webmail.util.ReadBuffer)
*/
public ReadBuffer decode(ReadBuffer in) throws DecodingException {
// TODO Auto-generated method stub
return null;
}
}

View File

@@ -0,0 +1,303 @@
/*
* Created on Nov 12, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail.encoding;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import i2p.susi.util.HexTable;
import i2p.susi.util.ReadBuffer;
/**
* @author susi
*/
public class HeaderLine implements Encoding {
public static final String NAME = "HEADERLINE";
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#getName()
*/
public String getName() {
return NAME;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#encode(java.lang.String)
*/
public String encode(String text) throws EncodingException {
try {
return encode( new StringBufferInputStream( text ) );
} catch (IOException e) {
throw new EncodingException( "IOException occured." );
}
}
private static final int BUFSIZE = 2;
private String encode(InputStream in) throws IOException
{
StringBuffer out = new StringBuffer();
int l = 0, buffered = 0, tmp[] = new int[BUFSIZE];
boolean quoting = false;
boolean quote = false;
boolean linebreak = false;
String quotedSequence = null;
int rest = 0;
while( true ) {
rest = in.available();
while( rest > 0 && buffered < BUFSIZE ) {
tmp[buffered++] = in.read();
rest--;
}
if( rest == 0 && buffered == 0 )
break;
int c = tmp[0];
buffered--;
for( int j = 1; j < BUFSIZE; j++ )
tmp[j-1] = tmp[j];
quote = true;
if( c > 32 && c < 127 && c != 61 ) {
quote = false;
}
else if( ( c == 32 || c == 9 ) ) {
quote = false;
if( rest == 0 && buffered == 1 )
quote = true;
if( buffered > 0 && ( tmp[0] == '\r' || tmp[0] == '\n' ) )
quote = true;
}
else if( c == 13 && buffered > 0 && tmp[0] == 10 ) {
quote = false;
linebreak = true;
buffered--;
for( int j = 1; j < BUFSIZE; j++ )
tmp[j-1] = tmp[j];
}
if( quote ) {
if( ! quoting ) {
quotedSequence = "=?iso-8859-1?Q?";
quoting = true;
}
quotedSequence += HexTable.table[ c ];
}
else {
if( quoting ) {
quotedSequence += "?=";
int sl = quotedSequence.length();
if( l + sl > 76 ) {
/*
* wrap line
*/
out.append( "\r\n\t" );
l = 0;
}
out.append( quotedSequence );
l += sl;
quoting = false;
}
if( linebreak ) {
out.append( "\r\n" );
linebreak = false;
l = 0;
}
else {
if( l > 76 ) {
out.append( "\r\n\t" );
l = 0;
}
out.append( (char)c );
l++;
}
}
}
if( quoting ) {
quotedSequence += "?=";
int sl = quotedSequence.length();
if( l + sl > 76 ) {
/*
* wrap line
*/
out.append( "\r\n\t" );
l = 0;
}
out.append( quotedSequence );
}
return out.toString();
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(java.lang.String)
*/
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#encode(java.lang.String)
*/
public String encode( byte in[] ) throws EncodingException {
try {
return encode( new ByteArrayInputStream( in ) );
} catch (IOException e) {
throw new EncodingException( "IOException occured." );
}
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(java.lang.String)
*/
public ReadBuffer decode( byte in[] ) throws DecodingException {
return decode( in, 0, in.length );
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(java.lang.String)
*/
public ReadBuffer decode( byte in[], int offset, int length ) throws DecodingException {
byte[] out = new byte[length];
int written = 0;
int end = offset + length;
if( end > in.length )
throw new DecodingException( "Index out of bound." );
boolean linebreak = false;
boolean lastCharWasQuoted = false;
while( length-- > 0 ) {
byte c = in[offset++];
if( c == '=' ) {
if( length > 0 ) {
if( in[offset] == '?' ) {
// System.err.println( "=? found at " + ( offset -1 ) );
int f2 = offset + 1;
for( ; f2 < end && in[f2] != '?'; f2++ );
if( f2 < end ) {
/*
* 2nd question mark found
*/
// System.err.println( "2nd ? found at " + f2 );
int f3 = f2 + 1;
for( ; f3 < end && in[f3] != '?'; f3++ );
if( f3 < end ) {
/*
* 3rd question mark found
*/
// System.err.println( "3rd ? found at " + f3 );
int f4 = f3 + 1;
for( ; f4 < end && in[f4] != '?'; f4++ );
if( f4 < end - 1 && in[f4+1] == '=' ) {
/*
* 4th question mark found, we are complete, so lets start
*/
String enc = ( in[f2+1] == 'Q' || in[f2+1] == 'q' ) ? "quoted-printable" : ( ( in[f2+1] == 'B' || in[f2+1] == 'b' ) ? "base64" : null );
// System.err.println( "4th ? found at " + f4 + ", encoding=" + enc );
if( enc != null ) {
Encoding e = EncodingFactory.getEncoding( enc );
if( e != null ) {
// System.err.println( "encoder found" );
ReadBuffer tmp = null;
try {
// System.err.println( "decode(" + (f3 + 1) + "," + ( f4 - f3 - 1 ) + ")" );
tmp = e.decode( in, f3 + 1, f4 - f3 - 1 );
for( int j = 0; j < tmp.length; j++ ) {
byte d = tmp.content[ tmp.offset + j ];
out[written++] = ( d == '_' ? 32 : d );
}
int distance = f4 + 2 - offset;
offset += distance;
length -= distance;
lastCharWasQuoted = true;
continue;
}
catch (Exception e1) {
}
}
}
}
}
}
}
}
}
else if( c == '\r' ) {
if( length > 0 && in[offset] == '\n' ) {
/*
* delay linebreak in case of long line
*/
linebreak = true;
length--;
offset++;
continue;
}
}
if( linebreak ) {
linebreak = false;
if( c != ' ' && c != '\t' ) {
/*
* new line does not start with whitespace, so its not a new part of a
* long line
*/
out[written++] = '\r';
out[written++] = '\n';
}
else {
if( !lastCharWasQuoted )
out[written++] = ' ';
/*
* skip whitespace
*/
while( length > 0 && ( in[offset] == ' ' || in[offset] == '\t' ) ) {
offset++;
length--;
}
continue;
}
}
/*
* print out everything else literally
*/
out[written++] = c;
lastCharWasQuoted = false;
}
if( linebreak ) {
out[written++] = '\r';
out[written++] = '\n';
}
ReadBuffer readBuffer = new ReadBuffer();
readBuffer.content = out;
readBuffer.offset = 0;
readBuffer.length = written;
return readBuffer;
}
public ReadBuffer decode(String text) throws DecodingException {
return text != null ? decode( text.getBytes() ) : null;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(i2p.susi.webmail.util.ReadBuffer)
*/
public ReadBuffer decode(ReadBuffer in) throws DecodingException {
return decode( in.content, in.offset, in.length );
}
public static void main( String[] args ) throws EncodingException {
String text = "Subject: test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test test \r\n" +
"From: Sm<53>rebr<62>d <smoerebroed@mail.i2p>\r\n" +
"To: <20><><EFBFBD><EFBFBD> <lalala@mail.i2p>\r\n";
HeaderLine hl = new HeaderLine();
System.out.println( hl.encode( text ) );
System.out.println( hl.encode( "test <20><><EFBFBD>" ) );
}
}

View File

@@ -0,0 +1,203 @@
/*
* Created on Nov 12, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail.encoding;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.StringBufferInputStream;
import i2p.susi.util.HexTable;
import i2p.susi.util.ReadBuffer;
/**
* @author susi
*/
public class QuotedPrintable implements Encoding {
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#getName()
*/
public String getName() {
return "quoted-printable";
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#encode(java.lang.String)
*/
public String encode( byte in[] ) throws EncodingException {
try {
return encode( new ByteArrayInputStream( in ) );
}catch (IOException e) {
throw new EncodingException( "IOException occured." );
}
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#encode(java.lang.String)
*/
public String encode(String text) throws EncodingException {
try {
return encode( new StringBufferInputStream( text ) );
}catch (IOException e) {
throw new EncodingException( "IOException occured." );
}
}
/**
*
* @param in
* @return
*/
private static int BUFSIZE = 2;
private String encode( InputStream in ) throws EncodingException, IOException {
StringBuffer out = new StringBuffer();
int l = 0;
int read = 0, buffered = 0, tmp[] = new int[BUFSIZE];
while( true ) {
read = in.available();
while( read > 0 && buffered < BUFSIZE ) {
tmp[buffered++] = in.read();
read--;
}
if( read == 0 && buffered == 0 )
break;
int c = tmp[0];
buffered--;
for( int j = 1; j < BUFSIZE; j++ )
tmp[j-1] = tmp[j];
if( c > 32 && c < 127 && c != 61 ) {
out.append( (char)c );
l++;
}
else if( ( c == 32 || c == 9 ) ) {
if( buffered > 0 && ( tmp[0] == 10 || tmp[0] == 13 ) ) {
/*
* whitespace at end of line
*/
out.append( c == 32 ? "=20" : "=09" );
l += 3;
}
else {
out.append( (char)c );
l++;
}
}
else if( c == 13 && buffered > 0 && tmp[0] == 10 ) {
out.append( "\r\n" );
buffered--;
for( int j = 1; j < BUFSIZE; j++ )
tmp[j-1] = tmp[j];
l = 0;
}
else {
if( c < 0 || c > 255 ) {
throw new EncodingException( "Encoding supports only values of 0..255." );
}
out.append( HexTable.table[ c ] );
l += 3;
}
}
return out.toString();
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(java.lang.String)
*/
public ReadBuffer decode( byte in[] ) {
return decode( in, 0, in.length );
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(java.lang.String)
*/
public ReadBuffer decode(String text) {
return text != null ? decode( text.getBytes() ) : null;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(byte[], int, int)
*/
public ReadBuffer decode(byte[] in, int offset, int length) {
byte[] out = new byte[length];
int written = 0;
while( length-- > 0 ) {
byte c = in[offset++];
if( c == '=' ) {
if( length >= 2 ) {
byte a = in[offset];
byte b = in[offset + 1];
if( ( ( a >= '0' && a <= '9' ) || ( a >= 'A' && a <= 'F' ) ) &&
( ( b >= '0' && b <= '9' ) || ( b >= 'A' && b <= 'F' ) ) ) {
/*
* decode sequence
*/
// System.err.println( "decoding 0x" + (char)a + "" + (char)b );
length -= 2 ;
offset += 2;
if( a >= '0' && a <= '9' )
a -= '0';
else if( a >= 'A' && a <= 'F' )
a = (byte) (a - 'A' + 10);
if( b >= '0' && b <= '9' )
b -= '0';
else if( b >= 'A' && b <= 'F' )
b = (byte) (b - 'A' + 10);
out[written++]=(byte) (a*16 + b);
continue;
}
else if( a == '\r' && b == '\n' ) {
/*
* softbreak, simply ignore it
*/
length -= 2;
offset += 2;
continue;
}
/*
* no correct encoded sequence found, ignore it and print it literally
*/
}
}
/*
* print out everything else literally
*/
out[written++] = c;
}
ReadBuffer readBuffer = new ReadBuffer();
readBuffer.content = out;
readBuffer.offset = 0;
readBuffer.length = written;
return readBuffer;
}
/* (non-Javadoc)
* @see i2p.susi.webmail.encoding.Encoding#decode(i2p.susi.webmail.util.ReadBuffer)
*/
public ReadBuffer decode(ReadBuffer in) {
return decode( in.content, in.offset, in.length );
}
}

View File

@@ -0,0 +1,101 @@
/*
* Created on 15.11.2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail.encoding;
import i2p.susi.util.ReadBuffer;
/**
* @author susi
*/
public class SevenBit implements Encoding {
/* (non-Javadoc)
* @see i2p.susi23.mail.encoding.Encoding#getName()
*/
public String getName() {
return "7bit";
}
/* (non-Javadoc)
* @see i2p.susi23.mail.encoding.Encoding#encode(byte[])
*/
public String encode(byte[] in) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see i2p.susi23.mail.encoding.Encoding#encode(java.lang.String)
*/
public String encode(String str) {
// TODO Auto-generated method stub
return null;
}
/* (non-Javadoc)
* @see i2p.susi23.mail.encoding.Encoding#decode(byte[])
*/
public ReadBuffer decode(byte[] in) throws DecodingException {
return decode( in, 0, in.length );
}
/* (non-Javadoc)
* @see i2p.susi23.mail.encoding.Encoding#decode(byte[], int, int)
*/
public ReadBuffer decode(byte[] in, int offset, int length)
throws DecodingException {
int backupLength = length;
int backupOffset = offset;
while( length-- > 0 ) {
byte b = in[offset++];
if( b > 32 && b < 127 )
continue;
if( b == ' ' || b == '\t' )
continue;
if( b == '\r' || b == '\n' )
continue;
throw new DecodingException( "No 8bit Data allowed (" + b + ")" );
}
ReadBuffer readBuffer = new ReadBuffer();
readBuffer.content = in;
readBuffer.offset = backupOffset;
readBuffer.length = backupLength;
return readBuffer;
}
/* (non-Javadoc)
* @see i2p.susi23.mail.encoding.Encoding#decode(java.lang.String)
*/
public ReadBuffer decode(String str) throws DecodingException {
return decode( str.getBytes() );
}
/* (non-Javadoc)
* @see i2p.susi23.mail.encoding.Encoding#decode(i2p.susi.webmail.util.ReadBuffer)
*/
public ReadBuffer decode(ReadBuffer in) throws DecodingException {
return decode( in.content, in.offset, in.length );
}
}

View File

@@ -0,0 +1,725 @@
/*
* Created on Nov 4, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.8 $
*/
package i2p.susi.webmail.pop3;
import java.io.IOException;
import java.io.InputStream;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Hashtable;
import i2p.susi.debug.Debug;
import i2p.susi.util.*;
/**
* @author susi23
*/
public class POP3MailBox {
private static final int DEFAULT_BUFSIZE = 4096;
private String host = null, user = null, pass = null;
private String lastLine = "-ERR", lastError = null;
private int port = 0, mails = 0, read = 0;
private boolean connected = false;
private Hashtable headerList = null, bodyList = null, sizes = null, uidlToID = null;
private ArrayList uidlList = null;
private Socket socket = null;
private byte[] buffer = new byte[DEFAULT_BUFSIZE];
private Object synchronizer = null;
private Object[] uidls = null;
/**
* @param host
* @param port
* @param user
* @param pass
*/
public POP3MailBox(String host, int port, String user, String pass) {
Debug.debug(
Debug.DEBUG,
"Mailbox(" + host + "," + port + "," + user + ",password)");
this.host = host;
this.port = port;
this.user = user;
this.pass = pass;
headerList = new Hashtable();
bodyList = new Hashtable();
uidlList = new ArrayList();
uidlToID = new Hashtable();
sizes = new Hashtable();
synchronizer = new Object();
connect();
}
/**
*
* @param uidl
* @return
*/
public ReadBuffer getHeader( String uidl ) {
synchronized( synchronizer ) {
return getHeader( getIDfromUIDL( uidl ) );
}
}
/**
* retrieves header from pop3 server (with TOP command and RETR as fallback)
*
* @param id message id
* @return byte buffer containing data
*/
private ReadBuffer getHeader( int id ) {
synchronized( synchronizer ) {
Debug.debug(Debug.DEBUG, "getHeader(" + id + ")");
Integer idObj = new Integer(id);
ReadBuffer header = null;
if (id >= 1 && id <= mails) {
/*
* is data already cached?
*/
header = (ReadBuffer)headerList.get(idObj);
if (header == null) {
/*
* try 'TOP n 0' command
*/
header = sendCmdN("TOP " + id + " 0" );
}
if( header == null) {
/*
* try 'RETR n' command
*/
header = sendCmdN("RETR " + id );
}
if( header != null ) {
/*
* store result in hashtable
*/
headerList.put(idObj, header);
}
}
else {
lastError = "Message id out of range.";
}
return header;
}
}
/**
*
* @param uidl
* @return
*/
public ReadBuffer getBody( String uidl ) {
synchronized( synchronizer ) {
return getBody( getIDfromUIDL( uidl ) );
}
}
/**
* retrieve message body from pop3 server (via RETR command)
*
* @param id message id
* @return byte buffer containing data
*/
private ReadBuffer getBody(int id) {
synchronized( synchronizer ) {
Debug.debug(Debug.DEBUG, "getBody(" + id + ")");
Integer idObj = new Integer(id);
ReadBuffer body = null;
if (id >= 1 && id <= mails) {
body = (ReadBuffer)bodyList.get(idObj);
if( body == null ) {
body = sendCmdN( "RETR " + id );
if (body != null) {
bodyList.put(idObj, body);
}
else {
Debug.debug( Debug.DEBUG, "sendCmdN returned null" );
}
}
}
else {
lastError = "Message id out of range.";
}
return body;
}
}
/**
*
* @param uidl
* @return
*/
public boolean delete( String uidl )
{
Debug.debug(Debug.DEBUG, "delete(" + uidl + ")");
synchronized( synchronizer ) {
return delete( getIDfromUIDL( uidl ) );
}
}
/**
* delete message on pop3 server
*
* @param id message id
* @return true if successful
*/
private boolean delete(int id)
{
Debug.debug(Debug.DEBUG, "delete(" + id + ")");
boolean result = false;
synchronized( synchronizer ) {
try {
result = sendCmd1a( "DELE " + id );
}
catch (IOException e) {
}
}
return result;
}
/**
*
* @param uidl
* @return
*/
public int getSize( String uidl ) {
synchronized( synchronizer ) {
return getSize( getIDfromUIDL( uidl ) );
}
}
/**
* get size of a message (via LIST command)
*
* @param id message id
* @return message size in bytes
*/
private int getSize(int id) {
synchronized( synchronizer ) {
Debug.debug(Debug.DEBUG, "getSize(" + id + ")");
int result = 0;
/*
* find value in hashtable
*/
Integer resultObj = (Integer) sizes.get(new Integer(id));
if (resultObj != null)
result = resultObj.intValue();
return result;
}
}
/**
* check whether connection is still alive
*
* @return true or false
*/
public boolean isConnected() {
Debug.debug(Debug.DEBUG, "isConnected()");
if (socket == null
|| !socket.isConnected()
|| socket.isInputShutdown()
|| socket.isOutputShutdown()
|| socket.isClosed()) {
connected = false;
}
return connected;
}
/**
*
* @throws IOException
*/
private void updateUIDLs() throws IOException
{
synchronized (synchronizer) {
ReadBuffer readBuffer = null;
uidlToID.clear();
uidlList.clear();
uidls = null;
readBuffer = sendCmdNa( "UIDL", DEFAULT_BUFSIZE );
if( readBuffer != null ) {
String[] lines = new String( readBuffer.toString() ).split( "\r\n" );
for( int i = 0; i < lines.length; i++ ) {
int j = lines[i].indexOf( " " );
if( j != -1 ) {
try {
int n = Integer.parseInt( lines[i].substring( 0, j ) );
String uidl = lines[i].substring( j+1 );
uidlToID.put( uidl, new Integer( n ) );
uidlList.add( n-1, uidl );
}
catch( NumberFormatException nfe ) {
}
}
}
uidls = uidlList.toArray();
}
else {
System.err.println( "Error getting UIDL list from pop3 server.");
}
}
}
/**
*
* @throws IOException
*/
private void updateSizes() throws IOException {
/*
* try LIST
*/
sizes.clear();
ReadBuffer readBuffer = sendCmdNa("LIST", DEFAULT_BUFSIZE );
if(readBuffer != null) {
String[] lines = new String( readBuffer.content, 0, readBuffer.length ).split( "\r\n" );
if (lines != null) {
sizes = new Hashtable();
for (int i = 0; i < lines.length; i++) {
int j = lines[i].indexOf(" ");
if (j != -1) {
int key = Integer.parseInt(lines[i].substring(0, j));
int value = Integer.parseInt(lines[i].substring(j + 1));
sizes.put(new Integer(key), new Integer(value));
}
}
}
}
else {
System.err.println( "Error getting size LIST from pop3 server.");
}
}
/**
*
*
*/
public void refresh() {
synchronized( synchronizer ) {
close();
connect();
}
}
/**
*
*
*/
private void clear()
{
uidlList.clear();
uidlToID.clear();
sizes.clear();
uidls = null;
mails = 0;
}
/**
* connect to pop3 server, login with USER and PASS and try STAT then
*/
private void connect() {
Debug.debug(Debug.DEBUG, "connect()");
clear();
if (socket != null && socket.isConnected())
close();
try {
socket = new Socket(host, port);
} catch (UnknownHostException e) {
lastError = e.getMessage();
return;
} catch (IOException e) {
lastError = e.getMessage();
return;
}
if (socket != null) {
try {
if (sendCmd1a("")
&& sendCmd1a("USER " + user)
&& sendCmd1a("PASS " + pass)
&& sendCmd1a("STAT") ) {
int i = lastLine.indexOf(" ", 5);
mails =
Integer.parseInt(
i != -1
? lastLine.substring(4, i)
: lastLine.substring(4));
connected = true;
updateUIDLs();
updateSizes();
}
else {
lastError = new String( lastLine );
close();
}
}
catch (NumberFormatException e1) {
lastError = "Error getting number of messages: " + e1.getCause();
}
catch (IOException e1) {
lastError = "Error while opening mailbox: " + e1.getCause();
}
}
}
/**
* send command to pop3 server (and expect single line answer), if any
* exception occurs, reconnect and try again
*
* @param cmd command to send
* @return true if command was successful (+OK)
*/
private boolean sendCmd1(String cmd) {
boolean result = false;
synchronized (synchronizer) {
if (!isConnected())
connect();
try {
result = sendCmd1a(cmd);
}
catch (Exception e) {
Debug.debug(Debug.ERROR, "Exception: " + e.getCause());
Debug.debug(Debug.ERROR, "trying to reconnect" );
connect();
try {
result = sendCmd1a(cmd);
} catch (IOException e2) {
Debug.debug(Debug.ERROR, "reconnect failed: " + e2.getCause());
}
}
}
return result;
}
/**
* send command to pop3 server (and expect single line answer)
*
* @param cmd command to send
* @return true if command was successful (+OK)
* @throws IOException
*/
private boolean sendCmd1a(String cmd) throws IOException {
/*
* dont log password
*/
boolean result = false;
String msg = cmd;
if (msg.startsWith("PASS"))
msg = "PASS provided";
Debug.debug(Debug.DEBUG, "sendCmd1a(" + msg + ")");
cmd += "\r\n";
socket.getOutputStream().write(cmd.getBytes());
read = socket.getInputStream().read(buffer);
// Debug.debug(Debug.DEBUG, "sendCmd1a: read " + read + " bytes");
if (read > 0) {
lastLine = new String(buffer, 0, read);
// Debug.debug( Debug.DEBUG, "sendCmd1a: READBUFFER: '" + lastLine + "'" );
if (lastLine.startsWith("+OK")) {
result = true;
}
else {
lastError = lastLine;
}
}
return result;
}
/**
*
* @param cmd
* @return
*/
private ReadBuffer sendCmdN(String cmd )
{
return sendCmdN( cmd, DEFAULT_BUFSIZE );
}
/**
* @param cmd
* @return
*/
private ReadBuffer sendCmdN(String cmd, int bufSize )
{
ReadBuffer result = null;
synchronized (synchronizer) {
if (!isConnected())
connect();
try {
result = sendCmdNa(cmd, bufSize);
}
catch (IOException e) {
lastError = e.getMessage();
Debug.debug( Debug.DEBUG, "sendCmdNa throws IOException: " + lastError );
result = null;
}
if( result == null ) {
connect();
if (connected) {
try {
result = sendCmdNa(cmd, bufSize);
}
catch (IOException e2) {
lastError = e2.getMessage();
Debug.debug( Debug.DEBUG, "2nd sendCmdNa throws IOException: " + lastError );
result = null;
}
}
else {
Debug.debug( Debug.DEBUG, "not connected after reconnect" );
}
}
}
return result;
}
/**
*
* @param src
* @param newSize
* @return
*/
private byte[] resizeArray( byte src[], int newSize )
{
byte dest[] = new byte[newSize];
for( int i = 0; i < src.length; i++ )
dest[i] = src[i];
return dest;
}
/**
*
* @param src
* @param srcOffset
* @param len
* @param dest
* @param destOffset
*/
private void copy( byte[] src, int srcOffset, int len, byte[] dest, int destOffset )
{
while( len-- > 0 ) {
dest[destOffset++] = src[srcOffset++];
}
}
/**
* @param id
* @return @throws
* IOException
*/
private ReadBuffer sendCmdNa(String cmd, int bufSize ) throws IOException
{
Debug.debug(Debug.DEBUG, "sendCmdNa(" + cmd + ")");
ReadBuffer readBuffer = null;
long timeOut = 60000;
byte result[] = new byte[bufSize];
int written = 0;
if (sendCmd1a(cmd)) {
int offset = 0;
while( offset < read - 1 && buffer[offset] != '\r' && buffer[offset+1] != '\n' )
offset++;
offset += 2;
if( read - offset > result.length )
result = resizeArray( result, result.length + result.length );
if( read - offset > 0 )
copy( buffer, offset, read - offset, result, 0 );
written = read - offset;
boolean doRead = true;
// Debug.debug( Debug.DEBUG, "READBUFFER: '" + new String( result, 0, written ) + "'" );
if( written >= 5 && result[ written - 5 ] == '\r' &&
result[ written - 4 ] == '\n' &&
result[ written - 3 ] == '.' &&
result[ written - 2 ] == '\r' &&
result[ written - 1 ] == '\n' ) {
written -= 3;
doRead = false;
}
InputStream input = socket.getInputStream();
long startTime = System.currentTimeMillis();
while (doRead) {
int len = input.available();
if( len == 0 ) {
if( System.currentTimeMillis() - startTime > timeOut )
throw new IOException( "Timeout while waiting on server response." );
try {
Thread.sleep( 500 );
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
else {
while (len > 0) {
read = socket.getInputStream().read(buffer, 0, len > buffer.length ? buffer.length : len );
// Debug.debug(Debug.DEBUG, "read " + read + " bytes");
if( written + read > result.length )
result = resizeArray( result, result.length + result.length );
copy( buffer, 0, read, result, written );
written += read;
// Debug.debug( Debug.DEBUG, "READBUFFER: '" + new String( result, 0, written ) + "'" );
if( result[ written - 5 ] == '\r' &&
result[ written - 4 ] == '\n' &&
result[ written - 3 ] == '.' &&
result[ written - 2 ] == '\r' &&
result[ written - 1 ] == '\n' ) {
written -= 3;
doRead = false;
}
len -= read;
}
}
}
readBuffer = new ReadBuffer();
readBuffer.content = result;
readBuffer.offset = 0;
readBuffer.length = written;
}
else {
Debug.debug( Debug.DEBUG, "sendCmd1a returned false" );
}
return readBuffer;
}
/**
* @return
*/
public int getNumMails() {
synchronized( synchronizer ) {
Debug.debug(Debug.DEBUG, "getNumMails()");
if (!isConnected())
connect();
return connected ? mails : 0;
}
}
/**
* @return
*/
public String lastError() {
Debug.debug(Debug.DEBUG, "lastError()");
return this.lastError;
}
/**
*
*
*/
public void close() {
synchronized( synchronizer ) {
Debug.debug(Debug.DEBUG, "close()");
if (socket != null && socket.isConnected()) {
try {
sendCmd1a("QUIT");
socket.close();
} catch (IOException e) {
System.err.println(
"Error while closing connection: " + e.getCause());
}
}
socket = null;
connected = false;
}
}
/**
* returns number of message with given UIDL
*
* @param uidl
* @return
*/
private int getIDfromUIDL( String uidl )
{
int result = -1;
Integer intObject = (Integer)uidlToID.get( uidl );
if( intObject != null ) {
result = intObject.intValue();
}
return result;
}
/**
*
* @param id
* @return
*/
public String getUIDLfromID( int id )
{
return (String)uidlList.get( id );
}
/**
*
* @return
*/
public Object[] getUIDLs()
{
return uidls;
}
/**
*
* @param args
*/
public static void main( String[] args )
{
Debug.setLevel( Debug.DEBUG );
POP3MailBox mailbox = new POP3MailBox( "localhost", 7660 , "test", "test");
ReadBuffer readBuffer = mailbox.sendCmdN( "LIST" );
System.out.println( "list='" + readBuffer + "'" );
}
/**
*
*/
public void performDelete()
{
close();
connect();
}
}

View File

@@ -0,0 +1,176 @@
/*
* Created on Nov 9, 2004
*
* This file is part of susimail project, see http://susi.i2p/
*
* Copyright (C) 2004-2005 <susi23@mail.i2p>
*
* 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
*
* $Revision: 1.3 $
*/
package i2p.susi.webmail.smtp;
import i2p.susi.debug.Debug;
import i2p.susi.webmail.encoding.Encoding;
import i2p.susi.webmail.encoding.EncodingException;
import i2p.susi.webmail.encoding.EncodingFactory;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.Socket;
/**
* @author susi
*/
public class SMTPClient {
Socket socket;
byte buffer[];
public String error;
String lastResponse;
private static Encoding base64 = null;
static {
base64 = EncodingFactory.getEncoding( "base64" );
}
public SMTPClient()
{
socket = null;
buffer = new byte[10240];
error = "";
lastResponse = "";
}
public int sendCmd( String cmd )
{
Debug.debug( Debug.DEBUG, "sendCmd(" + cmd +")" );
if( socket == null )
return 0;
int result = 0;
lastResponse = "";
try {
InputStream in = socket.getInputStream();
OutputStream out = socket.getOutputStream();
if( cmd != null ) {
cmd += "\r\n";
out.write( cmd.getBytes() );
}
String str = "";
boolean doContinue = true;
while( doContinue ) {
if( in.available() > 0 ) {
int read = in.read( buffer );
str += new String( buffer, 0, read );
lastResponse += str;
while( true ) {
int i = str.indexOf( "\r\n" );
if( i == -1 )
break;
if( result == 0 ) {
try {
result = Integer.parseInt( str.substring( 0, 3 ) );
}
catch( NumberFormatException nfe ) {
result = 0;
doContinue = false;
break;
}
}
if( str.substring( 3, 4 ).compareTo( " " ) == 0 ) {
doContinue = false;
break;
}
str = str.substring( i + 2 );
}
}
}
}
catch (IOException e) {
error += "IOException occured.<br>";
result = 0;
}
return result;
}
public boolean sendMail( String host, int port, String user, String pass, String sender, Object[] recipients, String body )
{
boolean mailSent = false;
boolean ok = true;
try {
socket = new Socket( host, port );
}
catch (Exception e) {
error += "Cannot connect: " + e.getMessage() + "<br>";
ok = false;
}
try {
if( ok && sendCmd( null ) == 220 &&
sendCmd( "EHLO localhost" ) == 250 &&
sendCmd( "AUTH LOGIN" ) == 334 &&
sendCmd( base64.encode( user ) ) == 334 &&
sendCmd( base64.encode( pass ) ) == 235 &&
sendCmd( "MAIL FROM: " + sender ) == 250 ) {
for( int i = 0; i < recipients.length; i++ ) {
if( sendCmd( "RCPT TO: " + recipients[i] ) != 250 ) {
ok = false;
}
}
if( ok ) {
if( sendCmd( "DATA" ) == 354 ) {
if( body.indexOf( "\r\n.\r\n" ) != -1 )
body = body.replaceAll( "\r\n.\r\n", "\r\n..\r\n" );
body += "\r\n.\r\n";
try {
socket.getOutputStream().write( body.getBytes() );
if( sendCmd( null ) == 250 ) {
mailSent = true;
}
}
catch (Exception e) {
ok = false;
error += "Error while sending mail: " + e.getMessage() + "<br>";
}
}
}
}
} catch (EncodingException e) {
ok = false;
error += e.getMessage();
}
if( !mailSent && lastResponse.length() > 0 ) {
String[] lines = lastResponse.split( "\r\n" );
for( int i = 0; i < lines.length; i++ )
error += lines[i] + "<br>";
}
sendCmd( "QUIT" );
if( socket != null ) {
try {
socket.close();
}
catch (IOException e1) {
// ignore
}
}
return mailSent;
}
}

Binary file not shown.

After

Width:  |  Height:  |  Size: 7.4 KiB

View File

@@ -0,0 +1,20 @@
susimail.encodings=i2p.susi.webmail.encoding.HeaderLine;i2p.susi.webmail.encoding.QuotedPrintable;i2p.susi.webmail.encoding.Base64;i2p.susi.webmail.encoding.SevenBit;i2p.susi.webmail.encoding.EightBit;i2p.susi.webmail.encoding.HTML
susimail.host=localhost
susimail.ports.fixed=true
susimail.ports.pop3=7660
susimail.ports.smtp=7659
susimail.fast.start=true
susimail.sender.fixed=true
susimail.sender.domain=mail.i2p
susimail.pager.pagesize=20
susimail.composer.cols=80
susimail.composer.rows=15
susimail.composer.bcc.to.self=true
susimail.date.format=MM/dd/yyyy HH:mm:ss

View File

@@ -27,6 +27,7 @@
<ant dir="apps/systray/java/" target="jar" />
<ant dir="apps/routerconsole/java/" target="jar" />
<ant dir="apps/addressbook/" target="war" />
<ant dir="apps/susimail/" target="war" />
</target>
<target name="buildWEB">
<ant dir="apps/jetty" target="fetchJettylib" />
@@ -56,6 +57,7 @@
<copy file="apps/systray/java/build/systray.jar" todir="build/" />
<copy file="installer/lib/jbigi/jbigi.jar" todir="build" />
<copy file="apps/addressbook/dist/addressbook.war" todir="build/" />
<copy file="apps/susimail/susimail.war" todir="build/" />
</target>
<target name="javadoc">
<mkdir dir="./build" />
@@ -104,6 +106,7 @@
<ant dir="apps/netmonitor/java/" target="distclean" />
<ant dir="apps/routerconsole/java/" target="distclean" />
<ant dir="apps/addressbook/" target="distclean" />
<ant dir="apps/susimail/" target="distclean" />
<ant dir="apps/systray/java/" target="distclean" />
<ant dir="installer/java/" target="distclean" />
<delete>
@@ -180,6 +183,7 @@
<copy file="build/i2ptunnel.war" todir="pkg-temp/webapps/" />
<copy file="build/routerconsole.war" todir="pkg-temp/webapps/" />
<copy file="build/addressbook.war" todir="pkg-temp/webapps/" />
<copy file="build/susimail.war" todir="pkg-temp/webapps/" />
<copy file="installer/resources/clients.config" todir="pkg-temp/" />
<copy file="installer/resources/i2prouter" todir="pkg-temp/" />
<copy file="installer/resources/i2prouter.bat" todir="pkg-temp/" />
@@ -246,21 +250,27 @@
<copy file="build/routerconsole.jar" todir="pkg-temp/lib/" />
<!-- for the i2p 0.5 release, push jetty 5.2.1 -->
<!--
<copy file="build/jasper-compiler.jar" todir="pkg-temp/lib/" />
<copy file="build/jasper-runtime.jar" todir="pkg-temp/lib/" />
<copy file="build/commons-logging.jar" todir="pkg-temp/lib/" />
<copy file="build/commons-el.jar" todir="pkg-temp/lib/" />
<copy file="build/org.mortbay.jetty.jar" todir="pkg-temp/lib/" />
<copy file="build/javax.servlet.jar" todir="pkg-temp/lib/" />
-->
<!-- requires commons-* to be added to the classpath (boo, hiss) -->
<!--
<copy file="installer/resources/wrapper.config" todir="pkg-temp/" />
<touch file="pkg-temp/wrapper.config.updated" />
-->
<copy file="build/i2ptunnel.war" todir="pkg-temp/webapps/" />
<copy file="build/routerconsole.war" todir="pkg-temp/webapps/" />
<copy file="build/addressbook.war" todir="pkg-temp/webapps/" />
<copy file="build/susimail.war" todir="pkg-temp/webapps/" />
<copy file="history.txt" todir="pkg-temp/" />
<copy file="hosts.txt" todir="pkg-temp/" />
<!-- the addressbook handles this for updates -->
<!-- <copy file="hosts.txt" todir="pkg-temp/" /> -->
<mkdir dir="pkg-temp/eepsite" />
<mkdir dir="pkg-temp/eepsite/webapps" />
<mkdir dir="pkg-temp/eepsite/cgi-bin" />

View File

@@ -14,8 +14,8 @@ package net.i2p;
*
*/
public class CoreVersion {
public final static String ID = "$Revision: 1.26.2.1 $ $Date: 2005/02/09 13:46:58 $";
public final static String VERSION = "0.5-pre";
public final static String ID = "$Revision: 1.28 $ $Date: 2005/02/17 17:57:53 $";
public final static String VERSION = "0.5.0.1";
public static void main(String args[]) {
System.out.println("I2P Core version: " + VERSION);

View File

@@ -225,6 +225,7 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
*/
public void connect() throws I2PSessionException {
_closed = false;
_availabilityNotifier.stopNotifying();
I2PThread notifier = new I2PThread(_availabilityNotifier);
notifier.setName("Notifier " + _myDestination.calculateHash().toBase64().substring(0,4));
notifier.setDaemon(true);
@@ -504,7 +505,11 @@ abstract class I2PSessionImpl implements I2PSession, I2CPMessageReader.I2CPMessa
* Pass off the error to the listener
*/
void propogateError(String msg, Throwable error) {
if (_log.shouldLog(Log.ERROR)) _log.error(getPrefix() + "Error occurred: " + msg, error);
if (_log.shouldLog(Log.ERROR))
_log.error(getPrefix() + "Error occurred: " + msg + " - " + error.getMessage());
if (_log.shouldLog(Log.WARN))
_log.warn(getPrefix() + " cause", error);
if (_sessionListener != null) _sessionListener.errorOccurred(this, msg, error);
}

View File

@@ -57,8 +57,8 @@ class MessagePayloadMessageHandler extends HandlerImpl {
Payload payload = msg.getPayload();
byte[] data = _context.elGamalAESEngine().decrypt(payload.getEncryptedData(), session.getDecryptionKey());
if (data == null) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error decrypting the payload");
if (_log.shouldLog(Log.WARN))
_log.warn("Error decrypting the payload");
throw new DataFormatException("Unable to decrypt the payload");
}
payload.setUnencryptedData(data);

View File

@@ -34,8 +34,10 @@ import net.i2p.util.Log;
*/
class TransientSessionKeyManager extends SessionKeyManager {
private Log _log;
private Map _outboundSessions; // PublicKey --> OutboundSession
private Map _inboundTagSets; // SessionTag --> TagSet
/** Map allowing us to go from the targeted PublicKey to the OutboundSession used */
private Map _outboundSessions;
/** Map allowing us to go from a SessionTag to the containing TagSet */
private Map _inboundTagSets;
protected I2PAppContext _context;
/**
@@ -46,12 +48,12 @@ class TransientSessionKeyManager extends SessionKeyManager {
*/
public final static long SESSION_TAG_DURATION_MS = 10 * 60 * 1000;
/**
* Keep unused inbound session tags around for up to 15 minutes (5 minutes longer than
* Keep unused inbound session tags around for up to 12 minutes (2 minutes longer than
* session tags are used on the outbound side so that no reasonable network lag
* can cause failed decrypts)
*
*/
public final static long SESSION_LIFETIME_MAX_MS = SESSION_TAG_DURATION_MS + 2 * 60 * 1000;
public final static long SESSION_LIFETIME_MAX_MS = SESSION_TAG_DURATION_MS + 5 * 60 * 1000;
public final static int MAX_INBOUND_SESSION_TAGS = 500 * 1000; // this will consume at most a few MB
/**
@@ -213,10 +215,11 @@ class TransientSessionKeyManager extends SessionKeyManager {
sess.setCurrentKey(key);
TagSet set = new TagSet(sessionTags, key, _context.clock().now());
sess.addTags(set);
if (_log.shouldLog(Log.DEBUG))
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Tags delivered to set " + set + " on session " + sess);
if (sessionTags.size() > 0)
_log.debug("Tags delivered: " + sessionTags.size() + " total = " + sess.availableTags());
if (sessionTags.size() > 0)
_log.debug("Tags delivered: " + sessionTags.size() + " total = " + sess.availableTags());
}
}
/**
@@ -234,6 +237,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
*
*/
public void tagsReceived(SessionKey key, Set sessionTags) {
int overage = 0;
TagSet tagSet = new TagSet(sessionTags, key, _context.clock().now());
for (Iterator iter = sessionTags.iterator(); iter.hasNext();) {
SessionTag tag = (SessionTag) iter.next();
@@ -241,18 +245,66 @@ class TransientSessionKeyManager extends SessionKeyManager {
_log.debug("Receiving tag " + tag + " for key " + key);
synchronized (_inboundTagSets) {
_inboundTagSets.put(tag, tagSet);
overage = _inboundTagSets.size() - MAX_INBOUND_SESSION_TAGS;
}
}
synchronized (_inboundTagSets) {
// todo: make this limit the tags by sessionKey and actually enforce the limit!
int overage = _inboundTagSets.size() - MAX_INBOUND_SESSION_TAGS;
if (overage > 0) {
if (_log.shouldLog(Log.ERROR))
_log.error("TOO MANY SESSION TAGS! " + (_inboundTagSets.size()));
}
}
if (overage > 0)
clearExcess(overage);
if (sessionTags.size() <= 0) _log.debug("Received 0 tags for key " + key);
if ( (sessionTags.size() <= 0) && (_log.shouldLog(Log.DEBUG)) )
_log.debug("Received 0 tags for key " + key);
}
/**
* remove a bunch of arbitrarily selected tags, then drop all of
* the associated tag sets. this is very time consuming - iterating
* across the entire _inboundTagSets map, but it should be very rare,
* and the stats we can gather can hopefully reduce the frequency of
* using too many session tags in the future
*
*/
private void clearExcess(int overage) {
long now = _context.clock().now();
int old = 0;
int large = 0;
int absurd = 0;
int recent = 0;
int tags = 0;
int toRemove = overage * 2;
List removed = new ArrayList(toRemove);
synchronized (_inboundTagSets) {
for (Iterator iter = _inboundTagSets.values().iterator(); iter.hasNext(); ) {
TagSet set = (TagSet)iter.next();
int size = set.getTags().size();
if (size > 1000)
absurd++;
if (size > 100)
large++;
if (now - set.getDate() > SESSION_LIFETIME_MAX_MS)
old++;
else if (now - set.getDate() < 1*60*1000)
recent++;
if ((removed.size() < (toRemove)) || (now - set.getDate() > SESSION_LIFETIME_MAX_MS))
removed.add(set);
}
for (int i = 0; i < removed.size(); i++) {
TagSet cur = (TagSet)removed.get(i);
for (Iterator iter = cur.getTags().iterator(); iter.hasNext(); ) {
SessionTag tag = (SessionTag)iter.next();
_inboundTagSets.remove(tag);
tags++;
}
}
}
if (_log.shouldLog(Log.CRIT))
_log.log(Log.CRIT, "TOO MANY SESSION TAGS! removing " + removed
+ " tag sets arbitrarily, with " + tags + " tags,"
+ "where there are " + old + " long lasting sessions, "
+ recent + " ones created in the last minute, and "
+ large + " sessions with more than 100 tags (and "
+ absurd + " with more than 1000!), leaving a total of "
+ _inboundTagSets.size() + " tags behind");
}
/**
@@ -562,6 +614,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
_date = date;
}
/** when the tag set was created */
public long getDate() {
return _date;
}
@@ -570,6 +623,7 @@ class TransientSessionKeyManager extends SessionKeyManager {
_date = when;
}
/** tags still available */
public Set getTags() {
return _sessionTags;
}

View File

@@ -758,7 +758,7 @@ public class DataHelper {
int rv = 0;
if (b != null) {
for (int i = 0; i < b.length && i < 8; i++)
rv += b[i];
rv += (b[i] << i);
}
return rv;
}

View File

@@ -99,7 +99,7 @@ public class BufferedStatLog implements StatLog {
if (_out != null) try { _out.close(); } catch (IOException ioe) {}
_outFile = filename;
try {
_out = new BufferedWriter(new FileWriter(_outFile, true));
_out = new BufferedWriter(new FileWriter(_outFile, true), 32*1024);
} catch (IOException ioe) { ioe.printStackTrace(); }
}
}
@@ -147,12 +147,16 @@ public class BufferedStatLog implements StatLog {
_out.write(when);
_out.write(" ");
if (_events[cur].getScope() == null)
_out.write("noScope ");
_out.write("noScope");
else
_out.write(_events[cur].getScope() + " ");
_out.write(_events[cur].getStat()+" ");
_out.write(_events[cur].getValue()+" ");
_out.write(_events[cur].getDuration()+"\n");
_out.write(_events[cur].getScope());
_out.write(" ");
_out.write(_events[cur].getStat());
_out.write(" ");
_out.write(Long.toString(_events[cur].getValue()));
_out.write(" ");
_out.write(Long.toString(_events[cur].getDuration()));
_out.write("\n");
}
cur = (cur + 1) % _events.length;
}

View File

@@ -26,10 +26,10 @@ public class Timestamper implements Runnable {
private boolean _initialized;
private static final int DEFAULT_QUERY_FREQUENCY = 5*60*1000;
private static final String DEFAULT_SERVER_LIST = "pool.ntp.org, pool.ntp.org";
private static final String DEFAULT_SERVER_LIST = "pool.ntp.org, pool.ntp.org, pool.ntp.org";
private static final boolean DEFAULT_DISABLED = true;
/** how many times do we have to query if we are changing the clock? */
private static final int DEFAULT_CONCURRING_SERVERS = 2;
private static final int DEFAULT_CONCURRING_SERVERS = 3;
public static final String PROP_QUERY_FREQUENCY = "time.queryFrequencyMs";
public static final String PROP_SERVER_LIST = "time.sntpServerList";
@@ -109,7 +109,7 @@ public class Timestamper implements Runnable {
if (_log.shouldLog(Log.INFO))
_log.info("Starting up timestamper");
boolean alreadyBitched = false;
boolean lastFailed = false;
try {
while (true) {
updateConfig();
@@ -123,14 +123,16 @@ public class Timestamper implements Runnable {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Querying servers " + _servers);
try {
queryTime(serverList);
lastFailed = !queryTime(serverList);
} catch (IllegalArgumentException iae) {
if (!alreadyBitched)
if (!lastFailed)
_log.log(Log.CRIT, "Unable to reach any of the NTP servers - network disconnected?");
alreadyBitched = true;
lastFailed = true;
}
}
long sleepTime = _context.random().nextInt(_queryFrequency) + _queryFrequency;
if (lastFailed)
sleepTime = 30*1000;
try { Thread.sleep(sleepTime); } catch (InterruptedException ie) {}
}
} catch (Throwable t) {
@@ -138,39 +140,64 @@ public class Timestamper implements Runnable {
}
}
private void queryTime(String serverList[]) throws IllegalArgumentException {
/**
* True if the time was queried successfully, false if it couldn't be
*/
private boolean queryTime(String serverList[]) throws IllegalArgumentException {
long found[] = new long[_concurringServers];
long localTime = -1;
long now = -1;
long expectedDelta = 0;
for (int i = 0; i < _concurringServers; i++) {
try { Thread.sleep(10*1000); } catch (InterruptedException ie) {}
localTime = _context.clock().now();
now = NtpClient.currentTime(serverList);
long delta = now - localTime;
found[i] = delta;
if (i == 0) {
if (Math.abs(delta) < MAX_VARIANCE) {
if (_log.shouldLog(Log.INFO))
_log.info("a single SNTP query was within the tolerance (" + delta + "ms)");
return;
return true;
} else {
// outside the tolerance, lets iterate across the concurring queries
expectedDelta = delta;
}
} else {
if (Math.abs(delta - expectedDelta) > MAX_VARIANCE) {
if (_log.shouldLog(Log.ERROR))
_log.error("SNTP client variance exceeded at query " + i + ". expected = " + expectedDelta + ", found = " + delta);
return;
if (_log.shouldLog(Log.ERROR)) {
StringBuffer err = new StringBuffer(96);
err.append("SNTP client variance exceeded at query ").append(i);
err.append(". expected = ");
err.append(expectedDelta);
err.append(", found = ");
err.append(delta);
err.append(" all deltas: ");
for (int j = 0; j < found.length; j++)
err.append(found[j]).append(' ');
_log.error(err.toString());
}
return false;
}
}
}
stampTime(now);
if (_log.shouldLog(Log.DEBUG)) {
StringBuffer buf = new StringBuffer(64);
buf.append("Deltas: ");
for (int i = 0; i < found.length; i++)
buf.append(found[i]).append(' ');
_log.debug(buf.toString());
}
return true;
}
/**
* Send an HTTP request to a given URL specifying the current time
*/
private void stampTime(long now) {
long before = _context.clock().now();
synchronized (_listeners) {
for (int i = 0; i < _listeners.size(); i++) {
UpdateListener lsnr = (UpdateListener)_listeners.get(i);
@@ -178,7 +205,7 @@ public class Timestamper implements Runnable {
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Stamped the time as " + now);
_log.debug("Stamped the time as " + now + " (delta=" + (now-before) + ")");
}
/**

View File

@@ -12,10 +12,12 @@ import net.i2p.I2PAppContext;
public class LogConsoleBuffer {
private I2PAppContext _context;
private List _buffer;
private List _critBuffer;
public LogConsoleBuffer(I2PAppContext context) {
_context = context;
_buffer = new ArrayList();
_critBuffer = new ArrayList();
}
void add(String msg) {
@@ -26,6 +28,14 @@ public class LogConsoleBuffer {
_buffer.add(msg);
}
}
void addCritical(String msg) {
int lim = _context.logManager().getConsoleBufferSize();
synchronized (_critBuffer) {
while (_critBuffer.size() >= lim)
_critBuffer.remove(0);
_critBuffer.add(msg);
}
}
/**
* Retrieve the currently bufferd messages, earlier values were generated...
@@ -38,4 +48,15 @@ public class LogConsoleBuffer {
return new ArrayList(_buffer);
}
}
/**
* Retrieve the currently bufferd crutucak messages, earlier values were generated...
* earlier. All values are strings with no formatting (as they are written
* in the logs)
*
*/
public List getMostRecentCriticalMessages() {
synchronized (_critBuffer) {
return new ArrayList(_critBuffer);
}
}
}

View File

@@ -101,6 +101,8 @@ class LogWriter implements Runnable {
// we always add to the console buffer, but only sometimes write to stdout
_manager.getBuffer().add(val);
if (rec.getPriority() >= Log.CRIT)
_manager.getBuffer().addCritical(val);
if (_manager.getDisplayOnScreenLevel() <= rec.getPriority()) {
if (_manager.displayOnScreen()) {
System.out.print(val);

View File

@@ -1,4 +1,97 @@
$Id: history.txt,v 1.141 2005/02/10 21:44:49 smeghead Exp $
$Id: history.txt,v 1.153 2005/02/22 23:20:29 jrandom Exp $
* 2005-02-23 0.5.0.1 released
2005-02-22 jrandom
* Reworked the tunnel (re)building process to remove the tokens and
provide cleaner controls on the tunnels built.
* Fixed situations where the timestamper wanted to test more servers than
were provided (thanks Tracker!)
* Get rid of the dead SAM sessions by using the streaming lib's callbacks
(thanks Tracker!)
2005-02-22 jrandom
* Temporary workaround for the I2CP disconnect bug (have the streaminglib
try to automatically reconnect on accept()/connect(..)).
* Loop check for expired lease republishing (just in case)
2005-02-22 jrandom
* Adjusted (and fixed...) the timestamper change detection
* Deal with a rare reordering bug at the beginning of a stream (so we
don't drop it unnecessarily)
* Cleaned up some dropped message handling in the router
* Reduced job queue churn when dealing with a large number of tunnels by
sharing an expiration job
* Keep a separate list of the most recent CRIT messages (shown on the
logs.jsp). This way they don't get buried among any other messages.
* For clarity, display the tunnel variance config as "Randomization" on
the web console.
* If lease republishing fails (boo! hiss!) try it again
* Actually fix the negative jobLag in the right place (this time)
* Allow reseeding when there are less than 10 known peer references
* Lots of logging updates.
2005-02-20 jrandom
* Allow the streaming lib resend frequency to drop down to 20s as the
minimum, so that up to 2 retries can get sent on an http request.
* Add further limits to failsafe tunnels.
* Keep exploratory and client tunnel testing and building stats separate.
* Only use the 60s period for throttling tunnel requests due to transient
network overload.
* Rebuild tunnels earlier (1-3m before expiration, by default)
* Cache the next hop's routerInfo for participating tunnels so that the
tunnel participation doesn't depend on the netDb.
* Fixed a long standing bug in the streaming lib where we wouldn't always
unchoke messages when the window size grows.
* Make sure the window size never reaches 0 (duh)
2005-02-20 jrandom
* Only build failsafe tunnels if we need them
* Properly implement the selectNotFailingPeers so that we get a random
selection of peers, rather than using the strictOrdering (thanks dm!)
* Don't include too many "don't tell me about" peer references in the
lookup message - only send the 10 peer references closest to the target.
2005-02-19 jrandom
* Only build new extra tunnels on failure if we don't have enough
* Fix a fencepost in the tunnel building so that e.g. a variance of
2 means +/- 2, not +/- 1 (thanks dm!)
* Avoid an NPE on client disconnect
* Never select a shitlisted peer to participate in a tunnel
* Have netDb store messages timeout after 10s, not the full 60s (duh)
* Keep session tags around for a little longer, just in case (grr)
* Cleaned up some closing event issues on the streaming lib
* Stop bundling the jetty 5.1.2 and updated wrapper.config in the update
so that 0.4.* users will need to do a clean install, but we don't need
to shove an additional 2MB in each update to those already on 0.5.
* Imported the susimail css (oops, thanks susi!)
* 2005-02-18 0.5 released
2005-02-17 jrandom
* If the clock is adjusted during a job run, don't act as if the job took
negative time.
2005-02-17 jrandom
* Included the GPL'ed susimail 0.13 by default (thanks susi23!)
2005-02-17 jrandom
* Fixed the braindead tunnel testing logic
* If a large number of tunnels are failing (within the last 5-10 minutes)
and the current tunnel pool's configuration allows it, randomly build a
zero hop tunnel to replace failed tunnels.
* Enable postman's POP3 and SMTP tunnels by default
2005-02-16 jrandom
* Added some error handling when the number of session tags exceeds the
realistic capacity, dropping a random chunk of received tag sets and
conducting some minor analysis of the remaining ones. This is a part
of a pretty serious error condition, and logs as CRIT (if/when people
see "TOO MANY SESSION TAGS!", please let me know the full log line it
puts in the wrapper.log or /logs.jsp)
* Update the addressbook to only write to the published hosts location
if the addressbook's config contains "should_publish=true" (by default,
it contains "should_publish=false")
2005-02-16 jrandom
* (Merged the 0.5-pre branch back into CVS HEAD)
@@ -47,7 +140,7 @@ $Id: history.txt,v 1.141 2005/02/10 21:44:49 smeghead Exp $
* Substantial memory optimizations within the router and the SDK to reduce
GC churn. Client apps and the streaming libs have not been tuned,
however.
* More bugfixes thank you can shake a stick at.
* More bugfixes than you can shake a stick at.
2005-02-13 jrandom
* Updated jbigi source to handle 64bit CPUs. The bundled jbigi.jar still

View File

@@ -1,6 +1,11 @@
; TC's hosts.txt guaranteed freshness
; $Id: hosts.txt,v 1.122 2005/02/14 22:08:45 jrandom Exp $
; $Id: hosts.txt,v 1.126 2005/02/20 21:55:12 jrandom Exp $
; changelog:
; (1.148) added irc.postman.i2p
; (1.147) added subrosa.i2p
; (1.146) added moxonom.i2p
; (1.145) added sex0r.i2p flock.i2p cneal.i2p www.nntp.i2p wallsgetbombed.i2p
; thedarkside.i2p legion.i2p manveru.i2p books.manveru.i2p bt.i2p
; (1.144) added riaa.i2p
; (1.143) added mpaa.i2p
; (1.142) added pants.i2p
@@ -318,4 +323,16 @@ irc.carambar.i2p=xfMseaHQgLA-MjJTKZoe8fL8cfjOhJBe1ii23jfdInJoioDTNRLJE4EnMxdda4Z
pants.i2p=Nawyl6EPP30naqz3VwiLiThON4i78Peras6RCtMMUdt62vAND1mQGejJaO--eJfICziDMVhGbrtvAOZzlPBxVhswxENkFFawNf6yDVsdJgJgdtg9i7KUU120IgGS5wABdv5w0sAIn19lu7oZT~Yl-MI6um~Wvg6Dc3SPbHSCgNBMXzuUN1yNGkYdM6xOOkqCEl3H~NujG1gqac8EY5Q9edh0DSMpGXP6vCqVbw6C6uO5InfL5G3BCB4mgq-MooflyN5RL3qELIUnwN76QcOIcHhWbNhbMUzFnwra9g7044GnFGgZZHgkd8iQ25d-en87UHnwLVAxzg7nVj7XTEM-l1CoeQCbPtqZNjn--PMPlLL8b4r0eR6SMV63EhZQzm6Z35C3nhKZOKoeCPPrObi6dgQWk1qnisOUu5isXYA4X~e2xhSrDEXw3UTK71Tpxc6VIw5nBCAD~HLGlOCZGWIKsmUvsgjFBsKNwfl5dhnDCXFWqKaw8ZKo7zpAyXfc4A1EAAAA
mpaa.i2p=99SlYfaoMM9xHU8Pl9Pdi77YxuPfULgOoNED86rEH~JxLpsLB8g6stATdoGZye3fTVxnuFIrnPBLR6UBPyFS-FSGr2ZfXcknOdNyk~tes5AxaRvSzuqFsJiOpLvsnOLAN~D0Mu7ZmZJybBRSQhqZiVVczQBM6kgh73EyX6WYwLL3RtWu6zoggVuYZbqPhVpGxun22zI1ZGhTaLZtI8XqgHeeQbSv1dYjAxJxGlWzFb88mVvvOt-X-QjT0G1jNa-wjRutRHja-bIXDRpc1-4cffmbXw2IksSpwZ7BPfLrMKrlvzZxnjjAqiatyPGHR5tkczaD~HCI3p5p8JzIMAgfVpfx6NSHLX5n6Ymm~hQCnT60iwjFAP8AB1LXrLeLaIR~V3ryCs14f9psjleTMCrwPn34h38QWWnxX85cQ5n~P-vvz-wu8uksKvCN2fvHDNEhnIFdy~AYAywVn-UjzLwR1~SHemmxhQoGpwm4YWxnAgrHRHtYX3wzx8aNBMogs5EsAAAA
riaa.i2p=cpnfxy9veluR3ZnwYeprHrJt7B359PymL0OEUonqKOTVvemHU9h-WBObN0xgfOajDTWhOskbZ~danOnSJGXmsRI1VrxhjCpJ4ruNcKwILjLv9s7Xa7aWp9MeTNdLJTtTIH9n84HMPd3pG6zHncwI54DUwZTqPkvg4k1u~ZU7fmyT0e5xmog1KBnRoE-ZYSkIAM~H-O-hKtrozkC~FHnMsxq14U6YSwL6e6dQmAXHjcF7u75bYNRbCQJfl1k1XWLVtTimbL3TuNR-6vDX0CyRxt~ma~kKBX4qYLX3SZk7uoX9LX0rFTIAk~1zhGm4yvr~YvXKm6dCJeIgaV1hfQyzqU6iuvgx-Pw9bU5SZiY97JezC0Uj6D5r0~nR1zfD4ULy7slfQsI9NipPtdpHIitcbzXjdwmAfSADNt-dy2MFn-6WqxHG9YUaN4cVUp-tquEqf3ppQ9ynbDABDhcu3ZJ85NccpTCcNRkCUobj9fUWls0tw20dxRLkHmXY-U7r64TfAAAA
sex0r.i2p=FXBJquP-C0O1YWyd3wa0FiUgFRn3qN4jADGRTlplVD0LPHepWTPZQB~q29Oj30Q439Vd~KBMVTBp64OI04arwH~xbWPPpKRHhWtqtNfYbSk8UQ2JO~eoKuUlkCvF2H7sqLjZuRbzXz9M4hmUbTEnYzbi6udR56OoI4HVe86ixD9of6PuXGli2OnEKCjXgqX6tp9O0gLrEjeqepvyHHwDhyTYmmSaAXaZsjNgRHtKxnSimnYHij5zXcwiGcSmwZpG3~%20CJiiETf59tA32Mcf5TcRztPRHZNfYfTWN~1DdlU1Nv5x3RJptecJFgkWRIuRXd7DDNCxyibIx9kGBExs11wJl1XOWUtVh5PYVcYV5KSy1~Zz-B5Hovb8AFBjam0r2P0zoKB0-7mDhjhHloeOOyV2txVoZQbgpGNXPlFmrsxtpbDaCB0FBqGw2tPLksgqKJpDmNxE3usNMMy8gv2NtZ92fuHcwr95YwwgoDrePB6-AqywWjYlffyQvEdw0zqLs8AAAA
flock.i2p=W0fudCJgidi6SxrdX0YrV7k1~5fKiQsopQdSNa-2D-P7wmJE3nipFnlGY9QEiIRMOBf3K48Q406Glf2zuQLjtrmO8li8SGu9iHOAai--aidcRjVS6n2L70iYnYMK5godipzbAROt-pyHroYq1JnDptqPZGHBovDiwJcPWUIY7Qizl9AWkj3FSXvXCRnb8aeLOVFUiKKPKw~mQ7BPUFWKjmVUuJFON2kxzEBm4p~V4EUR4KGijb3-8JYnMVC4PRk5KNGGxaQ6vO2mnW2Ix0I4JRhG-KL59Tbn6reQBSCL~jiZg9~v7NJHMNZJI8Yqv-76Z1sC1Y0b0fm58J-yO-gQxBlA9CPRpA9uVsckD6wMww1B0ssYjV8oMRtljEpWvJAH3WCTZuT9~i1rbj2dG46hWvMVI9-vQviEDTGjeMagjUWxNkjxU-2LgHUCrfUKfVwqfzUFV1oDVi3MgvWasIK6zUY4LWFz0e4F8QNllJgSdMoZ6PaLZGbi4s8zaoktITA4AAAA
cneal.i2p=rOcHhSaRh8VHx-oViRwBBZM49AM3OykwAyBBMkjSlUluFtUFvVbeQDpmMk7CjqwWYFil-wrGOsQBNZw7tLz1cUlvGvAcs-Ji3W9djNPwlYxiY8OwghAFaWoiIWT3cbDuPnugNp9S5sIIvhCUwtALNDjgxSgR3wFvM3FE-Ye9dZpSophLZbUUIZtaholSjZW5yCC8rGftNr3I06Ax1B52jRm0c-niq6AWLb0wYSc3fUcZsIAeWWFfXNGcHL2X8qcslu~hfklQfL36mWgDySd3sjblt7Xg4DbvYkj5ZejnVJIGqY1ZvbOrZkO8kMEUIyqW8Tk5x8aawlfMDj2Cy2RUa1rOKhJHsTfTMB74SHnsGrYk9Cf~G-~6erIns3S085KK-oS1U9MWP9zOVtTzdtlWGjKktWu49e-xzoNbsH9flDZ6d385On~V2fl~zNqQRs-91pv9MDE63bhxroUI4NWst4mfV9zHjgk7Izt4pO5jmzh3KAF2DgCb2~BcMC-x3CM0AAAA
www.nntp.i2p=H63RoPaxWD5GTW0HoceyM0vihVal3vpfPyBbC~9yI0~i0WrCs9twJa6oP7RlhT~AIfFKiWaaZLxsKOODuvSwmuM0K4mFSAVYeCWzYeNnbLFrNn85u7cO~w03Rp5UyrxAFMNVE2Hxrgjw9ZPQGRZ8eE6GGEyx8etzkkXoknS4uDhN-qhfTEuYPiVh0Lel4H~VkdiCwepK0tBbxKeKQYtokoFnosrlGo49krkoXD2hLfxPSc-dFHqaQgQqV3XLzKAsb0NUxNMHA18Vr-WBOcB-OubqONpbWAejcB-X6rcZ9rc1b4mAtU~YeV64WESGf9GLadAKb1Z6bfy2qA~-twMMzQzNHmU5b3F0hcA2LD7kZSljZynoss6M2oWAsifewsQ8lKkgXhoyOHjU4sWRUZSxsObcLuI~HM2eWEOkIsBH3MSInC7BSRKKg7GUK3zj4M7f8muHiozOTWCvw5vevV9ay274N~JRrZVKb83oqC3hGoh8OlInMq5RgyyEmuuqcT-RAAAA
wallsgetbombed.i2p=Y6tf8FnxhUTUQgOwTSNthnvcLTQVm1QT7dKFe5iqMaE2d-65y1T4BHj8nF69ncy5MwrpHOLuuXDD-BI~Bwufh19FomEYC~NZdzBwK6580qg-VMfDxEkLVV7olqOWPlWoWIAumVwy6cDtly5NlSJ-JoHhSCgQzgO--0HKmPQbWnJlxAogHYyWNgaFldpY2BbGWSStMbe4MaI6KLl3jNfGvIsYgHyD4enptuREA4ex30SCdH0Wkci1DwQeG2EbP9GeK~k5JRTFAgnrOmUjrF7EzMXYA-Yw-zboiw4dRFIj~LJCtEHdSMH3NYZpNOOm56ySB4bGKKrnZCFnSYIOjNSNF3Ff~JYPvDRokL2Fn1AZqNKuVCvMSMqrBOBVzeUq4MXcNKWnRAZi3pF0eSwu2X8rS49PBZh0mcexcasUhM16yBARxXsADDT~fmty5xhzIntbaGIPX0H1HQ4XssvQ-Yfj9uW2NGQT-3o-Ffy0czdmSyP6~RoyI~yLqDmXqgAzcPvEAAAA
thedarkside.i2p=4cqv-FeJohpA3ht3YUoHFTC9PJTaECIsWH706AaKLNubWzfNNA3PcUQQW-rpU1-81cGwL1xw9b24~GWjmHgoAU4hvBuwMLf7OKy4Qj0uPxkI2HLg65JBkyskVqKWiutq~u57JUv0UHbDuugcOQOnFRLPoaJsEzftqUTvZUlRrr57K7ysCXEYiGceOO7iIxIWZD1vo7Kh8Yr8oWpSv4SEzPRTZA4TVsOs3ACYlPFB24FEu5~f9YXAhwkKEkE2iw8~Z40oOV6vTsFRBrxYDS0qEUayt11nAbAbqSTpMBembm0cFU5Daxf3VGOlv0LSfXfBGZTLDjS7q3ZW-Q0GRgwhj4uZZSZOuo1rU-6GhXBwxkAb9hHwAGU31~-uLErYEJv~zn~Jq-LN0UiTlHDp3-dG3Eq3wxPcyhHSES2zeBa8bm37~au441ZBJHhUHNgg5wPiIKH3rO~-Rt~dPMLu09dcLr~JJjdNPLm4B0dLfN3~OUxvF4-N~kQ7bcOa1rhh3KIuAAAA
legion.i2p=vKmi5he9RE0tpUdkopYiEksZ1oZyd6WWZAMTIUS2u-PgPiz204echSPyyhnMDCged~e0udhOqKebYEANyq9WfAnVCXJwqVybo1TbGXLo28ZGw5DoqYmJQ1W5KP999-Mn7khlEthbB8X24vzEkvWeAxIyXT8zqb-fqM2ty1tr7Y06TJEeXMrQ9Jkc18lJsIqbhijzttAJxHfCdn8vgj0yVwl7FEUxPXxOU0ESdn5rmdRIZL5mweSQVDsa~xzQfvmOUUJqZ7agSrRpdb6x4UmMfnGCaFJJn2EM20eyfx6nYQ9YNfEdok1buw8XAFjVpaKAbpFTLikvQ5t3GrWEyTf5yiJPfT3MBt2j6PXRVtdrWwohVq3dlrQo3KF4svzFehaU8Sz0Cn7U4pDxwfSYJfAtr-tvgXfCcqtJ21wBUZYQpudbaqPfdMP1ZtDrAY8cPqXHmeDIt6TfFGBssMRVsKrCPThba0~gyloq-G6FHmnXQchaiPNCZ-J6T2nCcSzk0BjaAAAA
manveru.i2p=JqF1WsB~pgmGgXWuAL~yuTRrQYK8WpemusXASZ5RJuXbxtr0eV-GENTNnhQSRsgFx~CviqgYAsSY8Ff~jPuU24DQaKR3okOYS~HTXj3NO0VTDLCOUxMJqUhjhHzJgWDkikYiOClBo19yWbR56e6W6JiRKhnrM1ifW0X~WqOc0KUaEKg7vSKoZJyqaSiu2xGnJ1UATvJm9Muu5hpdg~O8jqivuKWKSZyyO4jlyfOXE8khtaylt6UJC6gegYOr0c9fMq65Pz8NgiekvK42hxac5krPWsNthF7qZzact0sJ6514cHekZ0LqVquJaA40A6yU9vMr-EH-Y868Ta0KJkey9GL5~Ws~DhJfjUW5Cn7swqCgJ98fxkIbmPwF-nAod5gqNzS-0KJM0g2TUAuACViIFfvyiO-4IOk7u~1mDbJJ13IGglns74cEhRo2icit3--O9ZNJsUJ-QCHHNX8tqaTulOTpR2~DVf86ODSEeXhI6~IhSo~VcFoqhnbQSEqzlIEPAAAA
books.manveru.i2p=qJpeR~kf1GVSlXtkm8BUnUIThLlmK5XsInMf4Zs9kOSebJs53tu8JOztk5WRCOExZ0MDojJUuWcMuC1~9zSvIMMokEILOM91D53og9hY2zLSFD4wqEjzHFvsmr7Vwp8EYTkab9AziqV5Pe5-rycf1BXTeTKyDjc5KSGJu23DHHXuaHrEZbJ9gKmyloe5mKUYRH~zJ7zGreL5isTWBNj596NWlXJA6XSrhP2HWX7HfMgzv-3sO0hZcfWVTb1NDhBdjIaJbsBdo2LCVaMlxqdLkAKMFnoAlN1YMwejvCab5nFFIqtecdTsXIbnKV0eo4t3F61cKaJur~tINRCVT8iek1aTTddR1rsPYdEHOiAG87qdQh0ny8la3m55ThD0Bf0aNqzyIytJnP9JHmU320FtrpZNKJ7-BMvtkOwBGcjUBdpVzcQGHo5cNkszahMm4NPbuQn3XtTZZYIVe52LLHi9oJC3mwGl8-FiRfXt3brvmkH6vZc~Z~vWUV0w1SmyFUGuAAAA
bt.i2p=Ei0~5AINGp-RegMS79AWJOgPRi2hCBAml92pFZTVTEZxOaaEHyOA0Ef6d43e1p0-Fx0ERR--YLdUBdTxAR1P3BYqZnDNDpegm5ywwp6mq27D~m5HWFljGAn33tqq6XUMO2e3iem5lPcY4RQ~-bILo9NHPLDFgd-i0ng9p11efyHeTN4uEIOKIj4esL0l-3CoNmODCM2Cw4VsTeNOvWnUAY7cOQg4OWQeKWcSV~K2YNn5~le6WGLTGwMsxKlXJRbnoSdGjEyD2tErtBNMzDGUYuYT9570oB0zuBskW8-3RBA8y5WT0tM3YshLpA9vSSgJT4k1S~mJGQdqQ3LNKA3F-n~F6mQ-l8y6yX5z9GNql505-aHs35WGBgN9xdAFDMZrb-dYtytGWHDblQGexuHy7zdbs8Pf0GOE1Mm1oKLm7iLZZEcJV4eh0dwsTMwPjKADbJVQCwn1YIIWJ-jUyACWrKyDEqR8rdGco2qX~PMi5CRW66sJyVrgcoHAz92d58FmAAAA
moxonom.i2p=hJU2KuBAv8QJh3jgoigFHE89h-FgTVQ1aHwRND2lqpkeLkVkC9A~7hCpYz2KAbWfKANImDzWMZ4jQvL80yfd~ZD7buqEZ60qA85l16YRZ-3JdWIiyQmyS5mNPxhCD3QZRyqoz56XJm0IyLc4PYcVdBAByRu19zjVZQeC-e4fMNRCNparVAm0lsdkNuLI3vwbrcxGNYoS1KQRJxGJAylngmL1DO7gu1FIBkxv~Ge1Q7m1pPgVluksmwxEaQDtbnZWS1nlcApEZuI0hXSfpmr1pTjS8oLSk3~j1G9q-TZ0PCSH5j8bofs5vWBOrdYw3-V3JfuZvrQkLWjlcCM6uHQ8VpAeAlDBpqLBZ5ixOquaO7bPqyjxD9oV4mYxcQusYPrHsbO15XQep9Y77r1aKYSo1SWnxGBtQqDtAorMHC8gBnLQwQeLT3Sk0mryp1PCxydR~m7xB2GWHxeIUQLNUOAf0LXnaOswVeZPImK0M04a87IGcd5yfJiKwJRO4rSdh4v~AAAA
subrosa.i2p=ndXKjhUrTaZYPX6EFeUsM~grnrsH-sFqFA74fe6qP-kTnpwxh29Vx6UPbxy~kTnhFEOmrJ7I1btDs8L4FgXhFgMCSVp2EcyoloLJJWUGaUrrBNEcvmCZOjtzS6X3KA7I~ZKfNY~Edumdp~FQoiRTl6gbuScdk2EwEYalUOGHGHTp74hF5ktHlt3HTkQCZVfA8avbkti0JHeWEy5bwQIW3hrfAFb6tRXFtkmCnK6xqFT~~qMw9vaaXDCqp5O1fUIY-8L4B2Bz52EK~tRrb1yTIQzAhYy0lT2RjmA0dH9mfywaEikOdyNBttf1xo0g7bTw4k44KTLaEVj4WakHMvsSWw~HH7vNDlLFvbWY-Fd3TJEuQSrAt43cXYTMM7x8ZkmXTNP3Z-bH6o-NuizpLPue0uWYTvVym66VWXysF6BrB~BV1lQ~U~PzNlvqxQ9GvAAc5LS7iSw-tuAleP151sS7GmFW~BF~SOYKQVR0nXKRBmIpkGvFCBMqVKXFJ2OWTW2-AAAA
irc.postman.i2p=d38SuD-ayF9gprdrl2uJM-FfFBor8qmBVQDxZt8SL7VZPUukrkzvxeaCE8riF5~2g1EgOA1nSfrQ4mt5NhuyL8MxGf6xByDng2lVCZ5Ks2InFVdaCEVg0BCfzdpztUGfO81oT7902zoE260P-qDuiSih5KMEouSWr7RPfP75ivoKfnRhVFcZiI36mRUfgOjKSGloeVLdkGIYh3AVYZ4MqQSWP-MXcY0xr1cD~G1ars2vfTNUjwErPirsyktbES0xXDtgr-Q7EF1vYo3cbPttFTyG6LUSEHvcHErfov5hAy~3lYkhgqMqVFyeKDEyb4ZkoSse1q2TpKxzmDAC95H4DQoxB6onvGjpgYQgwK3ZREf-0UVYY8eVHbnN~jTWLnIOdHfEbSMqN5OMYMeLvLc~SX-qKGNExTaA6Zl80QOkTF~Hh3lAONXUhJgPtzuV2igtXyV~BuhFuA8M2nu~HwLsgv5qPN8wInudXpzhhp~hG36tZ90OGDMSA-XXRMzwhHgCAAAA

View File

@@ -4,7 +4,7 @@
<info>
<appname>i2p</appname>
<appversion>0.4.2.6</appversion>
<appversion>0.5</appversion>
<authors>
<author name="I2P" email="support@i2p.net"/>
</authors>

View File

@@ -4,11 +4,11 @@ tunnel.0.description=HTTP proxy for browsing eepsites and the web
tunnel.0.type=httpclient
tunnel.0.interface=127.0.0.1
tunnel.0.listenPort=4444
tunnel.0.proxyList=squid.i2p
tunnel.0.proxyList=squid.i2p,www1.squid.i2p
tunnel.0.i2cpHost=127.0.0.1
tunnel.0.i2cpPort=7654
tunnel.0.option.tunnels.depthInbound=2
tunnel.0.option.tunnels.numInbound=2
tunnel.0.option.inbound.nickname=eepProxy
tunnel.0.option.outbound.nickname=eepProxy
tunnel.0.option.i2p.streaming.connectDelay=1000
tunnel.0.startOnLoad=true
@@ -21,8 +21,8 @@ tunnel.1.listenPort=6668
tunnel.1.targetDestination=irc.duck.i2p,irc.baffled.i2p
tunnel.1.i2cpHost=127.0.0.1
tunnel.1.i2cpPort=7654
tunnel.1.option.tunnels.depthInbound=2
tunnel.1.option.tunnels.numInbound=2
tunnel.1.option.inbound.nickname=ircProxy
tunnel.1.option.outbound.nickname=ircProxy
tunnel.1.option.i2p.streaming.connectDelay=1000
tunnel.1.option.i2p.maxWindowSize=1
tunnel.1.startOnLoad=true
@@ -36,8 +36,8 @@ tunnel.2.listenPort=2401
tunnel.2.targetDestination=cvs.i2p
tunnel.2.i2cpHost=127.0.0.1
tunnel.2.i2cpPort=7654
tunnel.2.option.tunnels.depthInbound=2
tunnel.2.option.tunnels.numInbound=2
tunnel.2.option.inbound.nickname=cvsProxy
tunnel.2.option.outbound.nickname=cvsProxy
tunnel.2.startOnLoad=false
# local eepserver
@@ -50,8 +50,8 @@ tunnel.3.spoofedHost=mysite.i2p
tunnel.3.privKeyFile=eepsite/eepPriv.dat
tunnel.3.i2cpHost=127.0.0.1
tunnel.3.i2cpPort=7654
tunnel.3.option.tunnels.depthInbound=2
tunnel.3.option.tunnels.numInbound=2
tunnel.3.option.inbound.nickname=eepsite
tunnel.3.option.outbound.nickname=eepsite
tunnel.3.startOnLoad=true
# postman's SMTP server - see www.postman.i2p
@@ -61,10 +61,10 @@ tunnel.4.i2cpPort=7654
tunnel.4.interface=127.0.0.1
tunnel.4.listenPort=7659
tunnel.4.name=smtp.postman.i2p
tunnel.4.option.tunnels.depthInbound=2
tunnel.4.option.tunnels.numInbound=2
tunnel.4.option.inbound.nickname=smtp
tunnel.4.option.outbound.nickname=smtp
tunnel.4.option.i2p.streaming.connectDelay=1000
tunnel.4.startOnLoad=false
tunnel.4.startOnLoad=true
tunnel.4.targetDestination=smtp.postman.i2p
tunnel.4.type=client
@@ -75,9 +75,9 @@ tunnel.5.i2cpHost=127.0.0.1
tunnel.5.i2cpPort=7654
tunnel.5.interface=127.0.0.1
tunnel.5.listenPort=7660
tunnel.5.option.tunnels.depthInbound=2
tunnel.5.option.tunnels.numInbound=2
tunnel.5.option.inbound.nickname=pop3
tunnel.5.option.outbound.nickname=pop3
tunnel.5.option.i2p.streaming.connectDelay=1000
tunnel.5.startOnLoad=false
tunnel.5.startOnLoad=true
tunnel.5.targetDestination=pop.postman.i2p
tunnel.5.type=client

View File

@@ -21,7 +21,7 @@ listed (if not, <a href="#trouble">see below</a>). Once those are up, you can:<
<li><a href="http://forum.i2p/">forum.i2p</a>: a secure and anonymous connection to <a href="http://forum.i2p.net/">forum.i2p.net</a></li>
<li><a href="http://www.i2p/">www.i2p</a>: a secure and anonymous connection to <a href="http://www.i2p.net/">www.i2p.net</a></li>
<li><a href="http://dev.i2p/">dev.i2p</a>: a secure and anonymous connection to <a href="http://dev.i2p.net/">dev.i2p.net</a></li>
<li><a href="http://fproxy.i2p/">fproxy.i2p</a>: a secure and anonymous connection to a freenet node</li>
<li>Freenet proxies: <a href="http://fproxy.i2p/">fproxy.i2p</a> and <a href="http://freenet.eco.i2p/">freenet.eco.i2p</a></li>
</ul>
There are many more eepsites - just follow the links from the ones you see,
bookmark your favorites, and visit them often!</li>
@@ -33,7 +33,9 @@ listed (if not, <a href="#trouble">see below</a>). Once those are up, you can:<
of the <a href="http://www.bittorrent.com/">BitTorrent</a> application available.</li>
<li><b>use anonymous email</b> - postman has created a mail system compatible with normal mail
clients (POP3 / SMTP) that allows email within I2P as well as mail from and to the normal
internet! get your account at <a href="http://www.postman.i2p/">www.postman.i2p</a>.</li>
internet! get your account at <a href="http://www.postman.i2p/">www.postman.i2p</a>.
We bundle <a href="http://susi.i2p/">susimail</a>, a web based anonymity-oriented pop3/smtp client
configured to access postman's mail services.</li>
<li>and lots more</li>
</ul>
@@ -42,13 +44,14 @@ listed (if not, <a href="#trouble">see below</a>). Once those are up, you can:<
<p>We've bundled some software to let you run your own eepsite - a
<a href="http://jetty.mortbay.org/">Jetty</a> instance listening on
<a href="http://localhost:7658/">http://localhost:7658/</a>. Simply place your files in
the <code>eepsite/docroot/</code> directory (or any standard JSP/Servlet <code>.war</code>
files under <code>eepsite/webapps</code>) and they'll show up. Your eepsite's
the <code>eepsite/docroot/</code> directory (or place any standard JSP/Servlet <code>.war</code>
files under <code>eepsite/webapps</code>, or standard CGI script under <code>eepsite/cgi-bin</code>)
and they'll show up. Your eepsite's
<i>destination</i> (which uniquely and securely identifies it) is shown on the I2PTunnel
<a href="/i2ptunnel/">configuration page</a> - if you want other people to see your eepsite,
you need to give them that really huge string. Just paste it into the
<a href="http://forum.i2p/viewforum.php?f=16">Eepsite announce</a> forum, add it to
ugha's <a href="http://ugha.i2p/I2pLinks">wiki</a>, or paste it in the #i2p or #i2p-chat channels on
ugha's <a href="http://ugha.i2p/I2pLinks">wiki</a>, <a href="http://orion.i2p/">orion's list</a>, or paste it in the #i2p or #i2p-chat channels on
IRC (be sure to split it into two lines, as its too long for one).</p>
<h2><a name="trouble">Troubleshooting</a></h2>

View File

@@ -1,4 +1,4 @@
<code>$Id: tunnel-alt.html,v 1.5 2005/01/19 18:13:10 jrandom Exp $</code>
<code>$Id: tunnel-alt.html,v 1.6 2005/01/25 00:46:22 jrandom Exp $</code>
<pre>
1) <a href="#tunnel.overview">Tunnel overview</a>
2) <a href="#tunnel.operation">Tunnel operation</a>
@@ -91,8 +91,8 @@ requested.</p>
tunnel ID to listen for messages with and what tunnel ID they should be forwarded
on as to the next hop, and each hop chooses the tunnel ID which they receive messages
on. Tunnels themselves are short lived (10 minutes at the
moment), but depending upon the tunnel's purpose, and though subsequent tunnels
may be built using the same sequence of peers, each hop's tunnel ID will change.</p>
moment), and even if subsequent tunnels are built using the same sequence of
peers, each hop's tunnel ID will change.</p>
<h3>2.1) <a name="tunnel.preprocessing">Message preprocessing</a></h3>
@@ -103,9 +103,9 @@ each I2NP message should be handled by the tunnel endpoint, encoding that
data into the raw tunnel payload:</p>
<ul>
<li>the first 4 bytes of the SHA256 of the remaining preprocessed data concatenated
with the preIV, using the preIV as will be seen on the tunnel endpoint (for
outbound tunnels) or the preIV as was seen on the tunnel gateway (for inbound
tunnels) (see below for preIV processing).</li>
with the IV, using the IV as will be seen on the tunnel endpoint (for
outbound tunnels) or the IV as was seen on the tunnel gateway (for inbound
tunnels) (see below for IV processing).</li>
<li>0 or more bytes containing random nonzero integers</li>
<li>1 byte containing 0x00</li>
<li>a series of zero or more { instructions, message } pairs</li>
@@ -114,7 +114,7 @@ data into the raw tunnel payload:</p>
<p>The instructions are encoded with a single control byte, followed by any
necessary additional information. The first bit in that control byte determines
how the remainder of the header is interpreted - if it is not set, the message
is eithernot fragmented or this is the first fragment in the message. If it is
is either not fragmented or this is the first fragment in the message. If it is
set, this is a follow on fragment.</p>
<p>With the first bit being 0, the instructions are:</p>
@@ -155,35 +155,34 @@ preprocessed payload must be padded to a multiple of 16 bytes.</p>
<h3>2.2) <a name="tunnel.gateway">Gateway processing</a></h3>
<p>After the preprocessing of messages into a padded payload, the gateway builds
a random 16 byte preIV value, iteratively encrypting it and the tunnel message as
necessary, and forwards the tuple {tunnelID, preIV, encrypted tunnel message} to the next hop.</p>
a random 16 byte IV value, iteratively encrypting it and the tunnel message as
necessary, and forwards the tuple {tunnelID, IV, encrypted tunnel message} to the next hop.</p>
<p>How encryption at the gateway is done depends on whether the tunnel is an
inbound or an outbound tunnel. For inbound tunnels, they simply select a random
preIV, postprocessing and updating it to generate the IV for the gateway and using
IV, postprocessing and updating it to generate the IV for the gateway and using
that IV along side their own layer key to encrypt the preprocessed data. For outbound
tunnels they must iteratively decrypt the (unencrypted) preIV and preprocessed
data with the layer keys for all hops in the tunnel. The result of the outbound
tunnels they must iteratively decrypt the (unencrypted) IV and preprocessed
data with the IV and layer keys for all hops in the tunnel. The result of the outbound
tunnel encryption is that when each peer encrypts it, the endpoint will recover
the initial preprocessed data.</p>
<p>The preIV postprocessing should be a secure invertible transform of the received value
capable of providing the full 16 byte IV necessary for AES256. At the moment, the
plan is to use AES256 against the received preIV using that layer's IV key (a seperate
session key delivered to the tunnel participant by the creator).</p>
<h3>2.3) <a name="tunnel.participant">Participant processing</a></h3>
<p>When a peer receives a tunnel message, it checks that the message came from
the same previous hop as before (initialized when the first message comes through
the tunnel). If the previous peer is a different router, the message is dropped.
The participant then postprocesses
and updates the preIV received to determine the current hop's IV, using that
with the layer key to encrypt the tunnel message. The IV is added to a bloom
filter maintained for that tunnel - if it is a duplicate, it is dropped
<i>The details of the hash functions used in the bloom filter
are not yet worked out. Suggestions?</i>. They then forwarding the tuple
{nextTunnelID, nextPreIV, encrypted tunnel message} to the next hop.</p>
the tunnel). If the previous peer is a different router, or if the message has
already been seen, the message is dropped. The participant then encrypts the
data with AES256/CBC using the participant's layer key and the received IV,
updates the IV by encrypting it with AES256/ECB using the participant's IV key,
then forwards the tuple {nextTunnelId, nextIV, encryptedData} to the next hop.</p>
<p>Duplicate message detection is handled by a decaying Bloom filter on message
IVs. Each router maintains a single Bloom filter to contain all of the IVs for
all of the tunnels it is participating in, modified to drop seen entries after
10-20 minutes (when the tunnels will have expired). The size of the bloom
filter and the parameters used are sufficient to more than saturate the router's
network connection with a negligible chance of false positive.</p>
<h3>2.4) <a name="tunnel.endpoint">Endpoint processing</a></h3>
@@ -192,8 +191,8 @@ how the endpoint recovers the data encoded by the gateway depends upon whether
the tunnel is an inbound or an outbound tunnel. For outbound tunnels, the
endpoint encrypts the message with its layer key just like any other participant,
exposing the preprocessed data. For inbound tunnels, the endpoint is also the
tunnel creator so they can merely iteratively decrypt the preIV and message, using the
layer keys (both message and IV keys) of each step in reverse order.</p>
tunnel creator so they can merely iteratively decrypt the IV and message, using the
layer and IV keys of each step in reverse order.</p>
<p>At this point, the tunnel endpoint has the preprocessed data sent by the gateway,
which it may then parse out into the included I2NP messages and forwards them as
@@ -211,24 +210,28 @@ requested in their delivery instructions.</p>
<li>Padding to the closest exponential size (2^n bytes)</li>
</ul>
<p><i>Which to use? no padding is most efficient, random padding is what
we have now, fixed size would either be an extreme waste or force us to
implement fragmentation. Padding to the closest exponential size (ala freenet)
seems promising. Perhaps we should gather some stats on the net as to what size
messages are, then see what costs and benefits would arise from different
strategies? <b>See <a href="http://dev.i2p.net/~jrandom/messageSizes/">gathered
stats</a></b>. The current plan is to pad to a fixed 1024 byte message size with
fragmentation.</i></p>
<p>These padding strategies can be used on a variety of levels, addressing the
exposure of message size information to different adversaries. After gathering
and reviewing some <a href="http://dev.i2p.net/~jrandom/messageSizes/">statistics</a>
from the 0.4 network, as well as exploring the anonymity tradeoffs, we're starting
with a fixed tunnel message size of 1024 bytes. Within this however, the fragmented
messages themselves are not padded by the tunnel at all (though for end to end
messages, they may be padded as part of the garlic wrapping).</p>
<h3>2.6) <a name="tunnel.fragmentation">Tunnel fragmentation</a></h3>
<p>To prevent adversaries from tagging the messages along the path by adjusting
the message size, all tunnel messages are a fixed 1KB in size. To accommodate
the message size, all tunnel messages are a fixed 1024 bytes in size. To accommodate
larger I2NP messages as well as to support smaller ones more efficiently, the
gateway splits up the larger I2NP messages into fragments contained within each
tunnel message. The endpoint will attempt to rebuild the I2NP message from the
fragments for a short period of time, but will discard them as necessary.</p>
<p>Routers have a lot of leeway as to how the fragments are arranged, whether
they are stuffed inefficiently as discrete units, batched for a brief period to
fit more payload into the 1024 byte tunnel messages, or opportunistically padded
with other messages that the gateway wanted to send out.</p>
<h3>2.7) <a name="tunnel.alternatives">Alternatives</a></h3>
<h4>2.7.1) <a name="tunnel.reroute">Adjust tunnel processing midstream</a></h4>
@@ -268,17 +271,17 @@ along the same peers.</p>
<h4>2.7.3) <a name="tunnel.backchannel">Backchannel communication</a></h4>
<p>At the moment, the preIV values used are random values. However, it is
<p>At the moment, the IV values used are random values. However, it is
possible for that 16 byte value to be used to send control messages from the
gateway to the endpoint, or on outbound tunnels, from the gateway to any of the
peers. The inbound gateway could encode certain values in the preIV once, which
peers. The inbound gateway could encode certain values in the IV once, which
the endpoint would be able to recover (since it knows the endpoint is also the
creator). For outbound tunnels, the creator could deliver certain values to the
participants during the tunnel creation (e.g. "if you see 0x0 as the preIV, that
participants during the tunnel creation (e.g. "if you see 0x0 as the IV, that
means X", "0x1 means Y", etc). Since the gateway on the outbound tunnel is also
the creator, they can build a preIV so that any of the peers will receive the
the creator, they can build a IV so that any of the peers will receive the
correct value. The tunnel creator could even give the inbound tunnel gateway
a series of preIV values which that gateway could use to communicate with
a series of IV values which that gateway could use to communicate with
individual participants exactly one time (though this would have issues regarding
collusion detection)</p>
@@ -308,17 +311,14 @@ still exists as peers could use the frequency of each size as the carrier (e.g.
two 1024 byte messages followed by an 8192). Smaller messages do incur the
overhead of the headers (IV, tunnel ID, hash portion, etc), but larger fixed size
messages either increase latency (due to batching) or dramatically increase
overhead (due to padding).</p>
overhead (due to padding). Fragmentation helps ammortize the overhead, at the
cost of potential message loss due to lost fragments.</p>
<p><i>Perhaps we should have I2CP use small fixed size messages which are
individually garlic wrapped so that the resulting size fits into a single tunnel
message so that not even the tunnel endpoint and gateway can see the size. We'll
then need to optimize the streaming lib to adjust to the smaller messages, but
should be able to squeeze sufficient performance out of it. However, if the
performance is unsatisfactory, we could explore the tradeoff of speed (and hence
userbase) vs. further exposure of the message size to the gateways and endpoints.
If even that is too slow, we could then review the tunnel size limitations vs.
exposure to participating peers.</i></p>
<p>Timing attacks are also relevent when reviewing the effectiveness of fixed
size messages, though they require a substantial view of network activity
patterns to be effective. Excessive artificial delays in the tunnel will be
detected by the tunnel's creator, due to periodic testing, causing that entire
tunnel to be scrapped and the profiles for peers within it to be adjusted.</p>
<h2>3) <a name="tunnel.building">Tunnel building</a></h2>
@@ -364,6 +364,10 @@ the hop after A may be B, B may never be before A. Other configuration options
include the ability for just the inbound tunnel gateways and outbound tunnel
endpoints to be fixed, or rotated on an MTBF rate.</p>
<p>In the initial implementation, only random ordering has been implemented,
though more strict ordering will be developed and deployed over time, as well
as controls for the user to select which strategy to use for individual clients.</p>
<h3>3.2) <a name="tunnel.request">Request delivery</a></h3>
<p>As mentioned above, once the tunnel creator knows what peers should go into
@@ -372,11 +376,11 @@ messages, each containing the necessary information for that peer. For instance
participating tunnels will be given the 4 byte nonce with which to reply with,
the 4 byte tunnel ID on which they are to send out the messages,
the 32 byte hash of the next hop's identity, the 32 byte layer key used to
remove a layer from the tunnel, and a 32 byte layer IV key used to transform the
preIV into the IV. Of course, outbound tunnel endpoints are not
remove a layer from the tunnel, and a 32 byte IV key used to encrypt the IV.
Of course, outbound tunnel endpoints are not
given any "next hop" or "next tunnel ID" information. To allow
replies, the request contains a random session tag and a random session key with
which the peer may garlic encrypt their decision, as well as the tunnel to which
which the peer should garlic encrypt their decision, as well as the tunnel to which
that garlic should be sent. In addition to the above information, various client
specific options may be included, such as what throttling to place on the tunnel,
what padding or batch strategies to use, etc.</p>
@@ -391,6 +395,13 @@ router on which that tunnel listens). Upon receipt of the reply at the tunnel
creator, the tunnel is considered valid on that hop (if accepted). Once all
peers have accepted, the tunnel is active.</p>
<p>Peers may reject tunnel creation requests for a variety of reasons, though
a series of four increasingly severe rejections are known: probabalistic rejection
(due to approaching the router's capacity, or in response to a flood of requests),
transient overload, bandwidth overload, and critical failure. When received,
those four are interpreted by the tunnel creator to help adjust their profile of
the router in question.</p>
<h3>3.3) <a name="tunnel.pooling">Pooling</a></h3>
<p>To allow efficient operation, the router maintains a series of tunnel pools,

View File

@@ -243,7 +243,9 @@ public class DatabaseLookupMessage extends I2NPMessageImpl {
buf.append("\n\tSearch Key: ").append(getSearchKey());
buf.append("\n\tFrom: ").append(getFrom());
buf.append("\n\tReply Tunnel: ").append(getReplyTunnel());
buf.append("\n\tDont Include Peers: ").append(getDontIncludePeers());
buf.append("\n\tDont Include Peers: ");
if (_dontIncludePeers != null)
buf.append(_dontIncludePeers.size());
buf.append("]");
return buf.toString();
}

View File

@@ -20,6 +20,7 @@ import net.i2p.data.RouterIdentity;
import net.i2p.data.i2np.DeliveryStatusMessage;
import net.i2p.data.i2np.I2NPMessage;
import net.i2p.data.i2np.DatabaseSearchReplyMessage;
import net.i2p.data.i2np.DatabaseLookupMessage;
import net.i2p.data.i2np.TunnelCreateStatusMessage;
import net.i2p.data.i2np.TunnelDataMessage;
import net.i2p.data.i2np.TunnelGatewayMessage;
@@ -35,7 +36,7 @@ import net.i2p.util.Log;
public class InNetMessagePool implements Service {
private Log _log;
private RouterContext _context;
private Map _handlerJobBuilders;
private HandlerJobBuilder _handlerJobBuilders[];
private List _pendingDataMessages;
private List _pendingDataMessagesFrom;
private List _pendingGatewayMessages;
@@ -57,7 +58,7 @@ public class InNetMessagePool implements Service {
public InNetMessagePool(RouterContext context) {
_context = context;
_handlerJobBuilders = new HashMap();
_handlerJobBuilders = new HandlerJobBuilder[20];
_pendingDataMessages = new ArrayList(16);
_pendingDataMessagesFrom = new ArrayList(16);
_pendingGatewayMessages = new ArrayList(16);
@@ -75,11 +76,15 @@ public class InNetMessagePool implements Service {
}
public HandlerJobBuilder registerHandlerJobBuilder(int i2npMessageType, HandlerJobBuilder builder) {
return (HandlerJobBuilder)_handlerJobBuilders.put(new Integer(i2npMessageType), builder);
HandlerJobBuilder old = _handlerJobBuilders[i2npMessageType];
_handlerJobBuilders[i2npMessageType] = builder;
return old;
}
public HandlerJobBuilder unregisterHandlerJobBuilder(int i2npMessageType) {
return (HandlerJobBuilder)_handlerJobBuilders.remove(new Integer(i2npMessageType));
HandlerJobBuilder old = _handlerJobBuilders[i2npMessageType];
_handlerJobBuilders[i2npMessageType] = null;
return old;
}
/**
@@ -132,7 +137,7 @@ public class InNetMessagePool implements Service {
shortCircuitTunnelData(messageBody, fromRouterHash);
allowMatches = false;
} else {
HandlerJobBuilder builder = (HandlerJobBuilder)_handlerJobBuilders.get(new Integer(type));
HandlerJobBuilder builder = _handlerJobBuilders[type];
if (_log.shouldLog(Log.DEBUG))
_log.debug("Add message to the inNetMessage pool - builder: " + builder
@@ -190,12 +195,14 @@ public class InNetMessagePool implements Service {
if (_log.shouldLog(Log.INFO))
_log.info("Dropping slow db lookup response: " + messageBody);
_context.statManager().addRateData("inNetPool.droppedDbLookupResponseMessage", 1, 0);
} else if (type == DatabaseLookupMessage.MESSAGE_TYPE) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Dropping netDb lookup due to throttling");
} else {
if (_log.shouldLog(Log.ERROR))
_log.error("Message " + messageBody + " expiring on "
+ (messageBody != null ? (messageBody.getMessageExpiration()+"") : " [unknown]")
+ " was not handled by a HandlerJobBuilder - DROPPING: "
+ messageBody, new Exception("DROPPED MESSAGE"));
if (_log.shouldLog(Log.WARN))
_log.warn("Message expiring on "
+ (messageBody != null ? (messageBody.getMessageExpiration()+"") : " [unknown]")
+ " was not handled by a HandlerJobBuilder - DROPPING: " + messageBody);
_context.statManager().addRateData("inNetPool.dropped", 1, 0);
}
} else {

View File

@@ -499,6 +499,9 @@ public class JobQueue {
MessageHistory hist = _context.messageHistory();
long uptime = _context.router().getUptime();
if (lag < 0) lag = 0;
if (duration < 0) duration = 0;
JobStats stats = null;
if (!_jobStats.containsKey(key)) {
_jobStats.put(key, new JobStats(key));

View File

@@ -92,9 +92,12 @@ class JobQueueRunner implements Runnable {
_state = 13;
long diff = _context.clock().now() - beforeUpdate;
long lag = doStart - origStartAfter;
if (lag < 0) lag = 0;
_context.statManager().addRateData("jobQueue.jobRunnerInactive", betweenJobs, betweenJobs);
_context.statManager().addRateData("jobQueue.jobRun", duration, duration);
_context.statManager().addRateData("jobQueue.jobLag", doStart - origStartAfter, 0);
_context.statManager().addRateData("jobQueue.jobLag", lag, 0);
_context.statManager().addRateData("jobQueue.jobWait", enqueuedTime, enqueuedTime);
if (duration > 1000) {

View File

@@ -57,6 +57,8 @@ public abstract class NetworkDatabaseFacade implements Service {
public abstract void publish(LeaseSet localLeaseSet);
public abstract void unpublish(LeaseSet localLeaseSet);
public abstract void fail(Hash dbEntry);
public int getKnownRouters() { return 0; }
}

View File

@@ -24,11 +24,11 @@ class RouterThrottleImpl implements RouterThrottle {
private static int JOB_LAG_LIMIT = 2000;
/**
* Arbitrary hard limit - if we throttle our network connection this many
* times in the previous 10-20 minute period, don't accept requests to
* times in the previous 2 minute period, don't accept requests to
* participate in tunnels.
*
*/
private static int THROTTLE_EVENT_LIMIT = 300;
private static int THROTTLE_EVENT_LIMIT = 30;
private static final String PROP_MAX_TUNNELS = "router.maxParticipatingTunnels";
private static final String PROP_DEFAULT_KBPS_THROTTLE = "router.defaultKBpsThrottle";
@@ -81,7 +81,7 @@ class RouterThrottleImpl implements RouterThrottle {
RateStat rs = _context.statManager().getRate("router.throttleNetworkCause");
Rate r = null;
if (rs != null)
r = rs.getRate(10*60*1000);
r = rs.getRate(60*1000);
long throttleEvents = (r != null ? r.getCurrentEventCount() + r.getLastEventCount() : 0);
if (throttleEvents > THROTTLE_EVENT_LIMIT) {
if (_log.shouldLog(Log.DEBUG))

View File

@@ -15,9 +15,9 @@ import net.i2p.CoreVersion;
*
*/
public class RouterVersion {
public final static String ID = "$Revision: 1.137.2.12 $ $Date: 2005/02/16 13:59:59 $";
public final static String VERSION = "0.5-pre";
public final static long BUILD = 12;
public final static String ID = "$Revision: 1.148 $ $Date: 2005/02/22 23:20:29 $";
public final static String VERSION = "0.5.0.1";
public final static long BUILD = 0;
public static void main(String args[]) {
System.out.println("I2P Router version: " + VERSION);
System.out.println("Router ID: " + RouterVersion.ID);

View File

@@ -227,7 +227,10 @@ public class ClientConnectionRunner {
}
void disconnectClient(String reason) {
_log.error("Disconnecting the client: " + reason);
if (_log.shouldLog(Log.CRIT))
_log.log(Log.CRIT, "Disconnecting the client ("
+ _config.getDestination().calculateHash().toBase64().substring(0,4)
+ ": " + reason);
DisconnectMessage msg = new DisconnectMessage();
msg.setReason(reason);
try {

View File

@@ -223,7 +223,7 @@ public class ClientManager {
}
}
private static final int REQUEST_LEASESET_TIMEOUT = 20*1000;
private static final int REQUEST_LEASESET_TIMEOUT = 120*1000;
public void requestLeaseSet(Hash dest, LeaseSet ls) {
ClientConnectionRunner runner = getRunner(dest);
if (runner != null) {

View File

@@ -41,6 +41,9 @@ class RequestLeaseSetJob extends JobImpl {
_expiration = expiration;
_onCreate = onCreate;
_onFail = onFail;
ctx.statManager().createRateStat("client.requestLeaseSetSuccess", "How frequently the router requests successfully a new leaseSet?", "ClientMessages", new long[] { 10*60*1000, 60*60*1000, 24*60*60*1000 });
ctx.statManager().createRateStat("client.requestLeaseSetTimeout", "How frequently the router requests a new leaseSet but gets no reply?", "ClientMessages", new long[] { 10*60*1000, 60*60*1000, 24*60*60*1000 });
ctx.statManager().createRateStat("client.requestLeaseSetDropped", "How frequently the router requests a new leaseSet but the client drops?", "ClientMessages", new long[] { 10*60*1000, 60*60*1000, 24*60*60*1000 });
}
public String getName() { return "Request Lease Set"; }
@@ -80,6 +83,7 @@ class RequestLeaseSetJob extends JobImpl {
getContext().jobQueue().addJob(new CheckLeaseRequestStatus(getContext(), state));
return;
} catch (I2CPMessageException ime) {
getContext().statManager().addRateData("client.requestLeaseSetDropped", 1, 0);
_log.error("Error sending I2CP message requesting the lease set", ime);
state.setIsSuccessful(false);
_runner.setLeaseRequest(null);
@@ -107,9 +111,13 @@ class RequestLeaseSetJob extends JobImpl {
if (_runner.isDead()) return;
if (_req.getIsSuccessful()) {
// we didn't fail
RequestLeaseSetJob.CheckLeaseRequestStatus.this.getContext().statManager().addRateData("client.requestLeaseSetSuccess", 1, 0);
return;
} else {
_log.error("Failed to receive a leaseSet in the time allotted (" + new Date(_req.getExpiration()) + ")");
RequestLeaseSetJob.CheckLeaseRequestStatus.this.getContext().statManager().addRateData("client.requestLeaseSetTimeout", 1, 0);
if (_log.shouldLog(Log.CRIT))
_log.log(Log.CRIT, "Failed to receive a leaseSet in the time allotted (" + new Date(_req.getExpiration()) + ") for "
+ _runner.getConfig().getDestination().calculateHash().toBase64());
_runner.disconnectClient("Took too long to request leaseSet");
if (_req.getOnFailed() != null)
RequestLeaseSetJob.this.getContext().jobQueue().addJob(_req.getOnFailed());

View File

@@ -76,6 +76,9 @@ public class GarlicMessageReceiver {
} else {
if (_log.shouldLog(Log.ERROR))
_log.error("CloveMessageParser failed to decrypt the message [" + message.getUniqueId()
+ "]");
if (_log.shouldLog(Log.WARN))
_log.warn("CloveMessageParser failed to decrypt the message [" + message.getUniqueId()
+ "]", new Exception("Decrypt garlic failed"));
_context.statManager().addRateData("crypto.garlic.decryptFail", 1, 0);
_context.messageHistory().messageProcessingError(message.getUniqueId(),
@@ -105,6 +108,9 @@ public class GarlicMessageReceiver {
String howLongAgo = DataHelper.formatDuration(_context.clock().now()-clove.getExpiration().getTime());
if (_log.shouldLog(Log.ERROR))
_log.error("Clove is NOT valid: id=" + clove.getCloveId()
+ " expiration " + howLongAgo + " ago");
if (_log.shouldLog(Log.WARN))
_log.warn("Clove is NOT valid: id=" + clove.getCloveId()
+ " expiration " + howLongAgo + " ago", new Exception("Invalid within..."));
_context.messageHistory().messageProcessingError(clove.getCloveId(),
clove.getData().getClass().getName(),

View File

@@ -71,19 +71,18 @@ class ExploreJob extends SearchJob {
DatabaseLookupMessage msg = new DatabaseLookupMessage(getContext(), true);
msg.setSearchKey(getState().getTarget());
msg.setFrom(replyGateway.getIdentity().getHash());
msg.setDontIncludePeers(getState().getAttempted());
msg.setDontIncludePeers(getState().getClosestAttempted(MAX_CLOSEST));
msg.setMessageExpiration(expiration);
msg.setReplyTunnel(replyTunnelId);
Set attempted = getState().getAttempted();
List peers = _peerSelector.selectNearestExplicit(getState().getTarget(), NUM_CLOSEST_TO_IGNORE, attempted, getFacade().getKBuckets());
Set toSkip = new HashSet(64);
toSkip.addAll(attempted);
toSkip.addAll(peers);
msg.setDontIncludePeers(toSkip);
int available = MAX_CLOSEST - msg.getDontIncludePeers().size();
if (available > 0) {
List peers = _peerSelector.selectNearestExplicit(getState().getTarget(), available, msg.getDontIncludePeers(), getFacade().getKBuckets());
msg.getDontIncludePeers().addAll(peers);
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Peers we don't want to hear about: " + toSkip);
_log.debug("Peers we don't want to hear about: " + msg.getDontIncludePeers());
return msg;
}

View File

@@ -60,6 +60,7 @@ public class KademliaNetworkDatabaseFacade extends NetworkDatabaseFacade {
private boolean _initialized;
/** Clock independent time of when we started up */
private long _started;
private int _knownRouters;
private StartExplorersJob _exploreJob;
private HarvesterJob _harvestJob;
/** when was the last time an exploration found something new? */
@@ -130,6 +131,7 @@ public class KademliaNetworkDatabaseFacade extends NetworkDatabaseFacade {
_peerSelector = new PeerSelector(_context);
_publishingLeaseSets = new HashSet(8);
_lastExploreNew = 0;
_knownRouters = 0;
_activeRequests = new HashMap(8);
_enforceNetId = DEFAULT_ENFORCE_NETID;
}
@@ -359,6 +361,8 @@ public class KademliaNetworkDatabaseFacade extends NetworkDatabaseFacade {
return rv;
}
public int getKnownRouters() { return _knownRouters; }
public void lookupLeaseSet(Hash key, Job onFindJob, Job onFailedLookupJob, long timeoutMs) {
if (!_initialized) return;
LeaseSet ls = lookupLeaseSetLocally(key);
@@ -639,6 +643,7 @@ public class KademliaNetworkDatabaseFacade extends NetworkDatabaseFacade {
+ routerInfo.getOptions().size() + " options on "
+ new Date(routerInfo.getPublished()));
_knownRouters++;
_ds.put(key, routerInfo);
synchronized (_lastSent) {
if (!_lastSent.containsKey(key))
@@ -699,6 +704,8 @@ public class KademliaNetworkDatabaseFacade extends NetworkDatabaseFacade {
synchronized (_passiveSendKeys) {
_passiveSendKeys.remove(dbEntry);
}
if (isRouterInfo)
_knownRouters--;
}
public void unpublish(LeaseSet localLeaseSet) {

View File

@@ -22,7 +22,8 @@ import net.i2p.util.Log;
*/
public class RepublishLeaseSetJob extends JobImpl {
private Log _log;
private final static long REPUBLISH_LEASESET_DELAY = 60*1000; // 5 mins
private final static long REPUBLISH_LEASESET_DELAY = 5*60*1000; // 5 mins
private final static long REPUBLISH_LEASESET_TIMEOUT = 60*1000;
private Hash _dest;
private KademliaNetworkDatabaseFacade _facade;
@@ -43,7 +44,7 @@ public class RepublishLeaseSetJob extends JobImpl {
if (!ls.isCurrent(Router.CLOCK_FUDGE_FACTOR)) {
_log.warn("Not publishing a LOCAL lease that isn't current - " + _dest, new Exception("Publish expired LOCAL lease?"));
} else {
getContext().jobQueue().addJob(new StoreJob(getContext(), _facade, _dest, ls, new OnSuccess(getContext()), new OnFailure(getContext()), REPUBLISH_LEASESET_DELAY));
getContext().jobQueue().addJob(new StoreJob(getContext(), _facade, _dest, ls, new OnSuccess(getContext()), new OnFailure(getContext()), REPUBLISH_LEASESET_TIMEOUT));
}
} else {
_log.warn("Client " + _dest + " is local, but we can't find a valid LeaseSet? perhaps its being rebuilt?");
@@ -73,8 +74,11 @@ public class RepublishLeaseSetJob extends JobImpl {
public OnFailure(RouterContext ctx) { super(ctx); }
public String getName() { return "Publish leaseSet failed"; }
public void runJob() {
if (_log.shouldLog(Log.ERROR))
_log.error("FAILED publishing of the leaseSet for " + _dest.toBase64());
if (_log.shouldLog(Log.WARN))
_log.warn("FAILED publishing of the leaseSet for " + _dest.toBase64());
LeaseSet ls = _facade.lookupLeaseSetLocally(_dest);
if ( (ls != null) && (ls.isCurrent(0)) )
getContext().jobQueue().addJob(new RepublishLeaseSetJob(getContext(), _facade, _dest));
}
}
}

View File

@@ -53,6 +53,8 @@ class SearchJob extends JobImpl {
private static final int SEARCH_BREDTH = 3; // 3 peers at a time
private static final int SEARCH_PRIORITY = 400; // large because the search is probably for a real search
/** only send the 10 closest "dont tell me about" refs */
static final int MAX_CLOSEST = 10;
/**
* How long will we give each peer to reply to our search?
@@ -371,7 +373,7 @@ class SearchJob extends JobImpl {
DatabaseLookupMessage msg = new DatabaseLookupMessage(getContext(), true);
msg.setSearchKey(_state.getTarget());
msg.setFrom(replyGateway.getIdentity().getHash());
msg.setDontIncludePeers(_state.getAttempted());
msg.setDontIncludePeers(_state.getClosestAttempted(MAX_CLOSEST));
msg.setMessageExpiration(expiration);
msg.setReplyTunnel(replyTunnelId);
return msg;
@@ -386,7 +388,7 @@ class SearchJob extends JobImpl {
DatabaseLookupMessage msg = new DatabaseLookupMessage(getContext(), true);
msg.setSearchKey(_state.getTarget());
msg.setFrom(getContext().routerHash());
msg.setDontIncludePeers(_state.getAttempted());
msg.setDontIncludePeers(_state.getClosestAttempted(MAX_CLOSEST));
msg.setMessageExpiration(expiration);
msg.setReplyTunnel(null);
return msg;

View File

@@ -6,7 +6,9 @@ import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
import net.i2p.router.RouterContext;
@@ -48,6 +50,25 @@ class SearchState {
return (Set)_attemptedPeers.clone();
}
}
public Set getClosestAttempted(int max) {
synchronized (_attemptedPeers) {
return locked_getClosest(_attemptedPeers, max, _searchKey);
}
}
private Set locked_getClosest(Set peers, int max, Hash target) {
if (_attemptedPeers.size() <= max)
return new HashSet(_attemptedPeers);
TreeSet closest = new TreeSet(new XORComparator(target));
closest.addAll(_attemptedPeers);
HashSet rv = new HashSet(max);
int i = 0;
for (Iterator iter = closest.iterator(); iter.hasNext() && i < max; i++) {
rv.add(iter.next());
}
return rv;
}
public boolean wasAttempted(Hash peer) {
synchronized (_attemptedPeers) {
return _attemptedPeers.contains(peer);

View File

@@ -37,14 +37,15 @@ class SearchUpdateReplyFoundJob extends JobImpl implements ReplyJob {
public String getName() { return "Update Reply Found for Kademlia Search"; }
public void runJob() {
I2NPMessage message = _message;
if (_log.shouldLog(Log.INFO))
_log.info(getJobId() + ": Reply from " + _peer.toBase64()
+ " with message " + _message.getClass().getName());
+ " with message " + message.getClass().getName());
if (_message instanceof DatabaseStoreMessage) {
if (message instanceof DatabaseStoreMessage) {
long timeToReply = _state.dataFound(_peer);
DatabaseStoreMessage msg = (DatabaseStoreMessage)_message;
DatabaseStoreMessage msg = (DatabaseStoreMessage)message;
if (msg.getValueType() == DatabaseStoreMessage.KEY_TYPE_LEASESET) {
try {
_facade.store(msg.getKey(), msg.getLeaseSet());
@@ -71,11 +72,11 @@ class SearchUpdateReplyFoundJob extends JobImpl implements ReplyJob {
if (_log.shouldLog(Log.ERROR))
_log.error(getJobId() + ": Unknown db store type?!@ " + msg.getValueType());
}
} else if (_message instanceof DatabaseSearchReplyMessage) {
_job.replyFound((DatabaseSearchReplyMessage)_message, _peer);
} else if (message instanceof DatabaseSearchReplyMessage) {
_job.replyFound((DatabaseSearchReplyMessage)message, _peer);
} else {
if (_log.shouldLog(Log.ERROR))
_log.error(getJobId() + ": WTF, reply job matched a strange message: " + _message);
_log.error(getJobId() + ": WTF, reply job matched a strange message: " + message);
return;
}

View File

@@ -199,7 +199,7 @@ class StoreJob extends JobImpl {
// _log.debug(getJobId() + ": Send store to " + router.getIdentity().getHash().toBase64());
}
sendStore(msg, router, _expiration);
sendStore(msg, router, getContext().clock().now() + STORE_TIMEOUT_MS);
}
private void sendStore(DatabaseStoreMessage msg, RouterInfo peer, long expiration) {
@@ -315,7 +315,7 @@ class StoreJob extends JobImpl {
sendNext();
}
public String getName() { return "Kademlia Store Failed"; }
public String getName() { return "Kademlia Store Peer Failed"; }
}
/**

View File

@@ -54,5 +54,12 @@ class StoreMessageSelector implements MessageSelector {
return false;
}
}
public String toString() {
StringBuffer rv = new StringBuffer(64);
rv.append("Waiting for netDb confirm from ").append(_peer.toBase64()).append(", found? ");
rv.append(_found).append(" waiting for ").append(_waitingForId);
return rv.toString();
}
}

View File

@@ -0,0 +1,30 @@
package net.i2p.router.networkdb.kademlia;
import java.util.Comparator;
import net.i2p.data.DataHelper;
import net.i2p.data.Hash;
/**
* Help sort Hashes in relation to a base key using the XOR metric
*
*/
class XORComparator implements Comparator {
private Hash _base;
/**
* @param target key to compare distances with
*/
public XORComparator(Hash target) {
_base = target;
}
public int compare(Object lhs, Object rhs) {
if (lhs == null) throw new NullPointerException("LHS is null");
if (rhs == null) throw new NullPointerException("RHS is null");
if ( (lhs instanceof Hash) && (rhs instanceof Hash) ) {
byte lhsDelta[] = DataHelper.xor(((Hash)lhs).getData(), _base.getData());
byte rhsDelta[] = DataHelper.xor(((Hash)rhs).getData(), _base.getData());
return DataHelper.compareTo(lhsDelta, rhsDelta);
} else {
throw new ClassCastException(lhs.getClass().getName() + " / " + rhs.getClass().getName());
}
}
}

View File

@@ -44,6 +44,8 @@ public class ProfileOrganizer {
private Map _wellIntegratedPeers;
/** H(routerIdentity) to PeerProfile for all peers that are not failing horribly */
private Map _notFailingPeers;
/** H(routerIdnetity), containing elements in _notFailingPeers */
private List _notFailingPeersList;
/** H(routerIdentity) to PeerProfile for all peers that ARE failing horribly (but that we haven't dropped reference to yet) */
private Map _failingPeers;
/** who are we? */
@@ -91,7 +93,8 @@ public class ProfileOrganizer {
_fastPeers = new HashMap(16);
_highCapacityPeers = new HashMap(16);
_wellIntegratedPeers = new HashMap(16);
_notFailingPeers = new HashMap(16);
_notFailingPeers = new HashMap(64);
_notFailingPeersList = new ArrayList(64);
_failingPeers = new HashMap(16);
_strictCapacityOrder = new TreeSet(_comp);
_thresholdSpeedValue = 0.0d;
@@ -285,8 +288,20 @@ public class ProfileOrganizer {
*
*/
public void selectNotFailingPeers(int howMany, Set exclude, Set matches) {
selectNotFailingPeers(howMany, exclude, matches, false);
}
/**
* Return a set of Hashes for peers that are not failing, preferring ones that
* we are already talking with
*
* @param howMany how many peers to find
* @param exclude what peers to skip (may be null)
* @param matches set to store the matches in
* @param onlyNotFailing if true, don't include any high capacity peers
*/
public void selectNotFailingPeers(int howMany, Set exclude, Set matches, boolean onlyNotFailing) {
if (matches.size() < howMany)
selectActiveNotFailingPeers(howMany, exclude, matches);
selectAllNotFailingPeers(howMany, exclude, matches, onlyNotFailing);
return;
}
/**
@@ -294,6 +309,7 @@ public class ProfileOrganizer {
* talking with.
*
*/
/*
private void selectActiveNotFailingPeers(int howMany, Set exclude, Set matches) {
if (true) {
selectAllNotFailingPeers(howMany, exclude, matches);
@@ -319,30 +335,39 @@ public class ProfileOrganizer {
selectAllNotFailingPeers(howMany, exclude, matches);
return;
}
*/
/**
* Return a set of Hashes for peers that are not failing.
*
*/
private void selectAllNotFailingPeers(int howMany, Set exclude, Set matches) {
private void selectAllNotFailingPeers(int howMany, Set exclude, Set matches, boolean onlyNotFailing) {
if (matches.size() < howMany) {
int orig = matches.size();
int needed = howMany - orig;
int start = 0;
List selected = new ArrayList(needed);
synchronized (_reorganizeLock) {
for (Iterator iter = _strictCapacityOrder.iterator(); selected.size() < needed && iter.hasNext(); ) {
PeerProfile prof = (PeerProfile)iter.next();
if (matches.contains(prof.getPeer()) ||
(exclude != null && exclude.contains(prof.getPeer())) ||
_failingPeers.containsKey(prof.getPeer()) ) {
// we randomize the whole list when rebuilding it, but randomizing
// the entire list on each peer selection is a bit crazy
start = _context.random().nextInt(_notFailingPeersList.size());
for (int i = 0; i < _notFailingPeersList.size() && selected.size() < needed; i++) {
int curIndex = (i+start) % _notFailingPeersList.size();
Hash cur = (Hash)_notFailingPeersList.get(curIndex);
if (matches.contains(cur) ||
(exclude != null && exclude.contains(cur))) {
continue;
} else if (onlyNotFailing && _highCapacityPeers.containsKey(cur)) {
// we dont want the good peers, just random ones
continue;
} else {
if (isOk(prof.getPeer()))
selected.add(prof.getPeer());
if (isOk(cur))
selected.add(cur);
}
}
}
if (_log.shouldLog(Log.INFO))
_log.info("Selecting all not failing found " + (matches.size()-orig) + " new peers: " + selected);
_log.info("Selecting all not failing (strict? " + onlyNotFailing + " start=" + start
+ ") found " + selected.size() + " new peers: " + selected);
matches.addAll(selected);
}
if (matches.size() < howMany) {
@@ -408,6 +433,7 @@ public class ProfileOrganizer {
_fastPeers.clear();
_highCapacityPeers.clear();
_notFailingPeers.clear();
_notFailingPeersList.clear();
_wellIntegratedPeers.clear();
for (Iterator iter = allPeers.iterator(); iter.hasNext(); ) {
@@ -417,7 +443,9 @@ public class ProfileOrganizer {
locked_unfailAsNecessary();
locked_promoteFastAsNecessary();
Collections.shuffle(_notFailingPeersList, _context.random());
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Profiles reorganized. averages: [integration: " + _thresholdIntegrationValue
+ ", capacity: " + _thresholdCapacityValue + ", speed: " + _thresholdSpeedValue + "]");
@@ -654,12 +682,11 @@ public class ProfileOrganizer {
/** called after locking the reorganizeLock */
private PeerProfile locked_getProfile(Hash peer) {
if (_notFailingPeers.containsKey(peer))
return (PeerProfile)_notFailingPeers.get(peer);
else if (_failingPeers.containsKey(peer))
return (PeerProfile)_failingPeers.get(peer);
else
return null;
PeerProfile cur = (PeerProfile)_notFailingPeers.get(peer);
if (cur != null)
return cur;
cur = (PeerProfile)_failingPeers.get(peer);
return cur;
}
/**
@@ -690,6 +717,9 @@ public class ProfileOrganizer {
// the CLI shouldn't depend upon the netDb
if (netDb == null) return true;
if (_context.router() == null) return true;
if ( (_context.shitlist() != null) && (_context.shitlist().isShitlisted(peer)) )
return false; // never select a shitlisted peer
if (null != netDb.lookupRouterInfoLocally(peer)) {
if (_log.shouldLog(Log.INFO))
_log.info("Peer " + peer.toBase64() + " is locally known, allowing its use");
@@ -714,6 +744,7 @@ public class ProfileOrganizer {
_highCapacityPeers.remove(profile.getPeer());
_wellIntegratedPeers.remove(profile.getPeer());
_notFailingPeers.remove(profile.getPeer());
_notFailingPeersList.remove(profile.getPeer());
} else {
_failingPeers.remove(profile.getPeer());
_fastPeers.remove(profile.getPeer());
@@ -721,6 +752,7 @@ public class ProfileOrganizer {
_wellIntegratedPeers.remove(profile.getPeer());
_notFailingPeers.put(profile.getPeer(), profile);
_notFailingPeersList.add(profile.getPeer());
if (_thresholdCapacityValue <= profile.getCapacityValue()) {
_highCapacityPeers.put(profile.getPeer(), profile);
if (_log.shouldLog(Log.DEBUG))

View File

@@ -363,8 +363,8 @@ public class FragmentHandler {
}
if (removed && !_msg.getReleased()) {
noteFailure(_msg.getMessageId());
if (_log.shouldLog(Log.ERROR))
_log.error("Dropped failed fragmented message: " + _msg);
if (_log.shouldLog(Log.WARN))
_log.warn("Dropped failed fragmented message: " + _msg);
_context.statManager().addRateData("tunnel.fragmentedDropped", _msg.getFragmentCount(), _msg.getLifetime());
_msg.failed();
} else {

View File

@@ -120,7 +120,7 @@ public class FragmentedMessage {
_lastReceived = isLast;
_toRouter = toRouter;
_toTunnel = toTunnel;
if (isLast)
if (_highFragmentNum < 0)
_highFragmentNum = 0;
}

View File

@@ -80,6 +80,11 @@ public class InboundMessageDistributor implements GarlicMessageReceiver.CloveRec
// ok, they want us to send it remotely, but that'd bust our anonymity,
// so we send it out a tunnel first
TunnelInfo out = _context.tunnelManager().selectOutboundTunnel(_client);
if (out == null) {
if (_log.shouldLog(Log.ERROR))
_log.error("no outbound tunnel to send the client message for " + _client + ": " + msg);
return;
}
if (_log.shouldLog(Log.INFO))
_log.info("distributing inbound tunnel message back out " + out
+ " targetting " + target.toBase64().substring(0,4));

View File

@@ -17,10 +17,13 @@ class OutboundReceiver implements TunnelGateway.Receiver {
private RouterContext _context;
private Log _log;
private TunnelCreatorConfig _config;
private RouterInfo _nextHopCache;
public OutboundReceiver(RouterContext ctx, TunnelCreatorConfig cfg) {
_context = ctx;
_log = ctx.logManager().getLog(OutboundReceiver.class);
_config = cfg;
_nextHopCache = _context.netDb().lookupRouterInfoLocally(_config.getPeer(1));
}
public void receiveEncrypted(byte encrypted[]) {
@@ -30,8 +33,11 @@ class OutboundReceiver implements TunnelGateway.Receiver {
if (_log.shouldLog(Log.DEBUG))
_log.debug("received encrypted, sending out " + _config + ": " + msg);
RouterInfo ri = _context.netDb().lookupRouterInfoLocally(_config.getPeer(1));
RouterInfo ri = _nextHopCache;
if (ri == null)
ri = _context.netDb().lookupRouterInfoLocally(_config.getPeer(1));
if (ri != null) {
_nextHopCache = ri;
send(msg, ri);
} else {
if (_log.shouldLog(Log.DEBUG))
@@ -65,8 +71,10 @@ class OutboundReceiver implements TunnelGateway.Receiver {
if (_log.shouldLog(Log.DEBUG))
_log.debug("lookup of " + _config.getPeer(1).toBase64().substring(0,4)
+ " successful? " + (ri != null));
if (ri != null)
if (ri != null) {
_nextHopCache = ri;
send(_msg, ri);
}
}
}

View File

@@ -38,6 +38,7 @@ public class TunnelDispatcher implements Service {
/** what is the date/time on which the last non-locally-created tunnel expires? */
private long _lastParticipatingExpiration;
private BloomFilterIVValidator _validator;
private LeaveTunnel _leaveJob;
/** Creates a new instance of TunnelDispatcher */
public TunnelDispatcher(RouterContext ctx) {
@@ -50,6 +51,7 @@ public class TunnelDispatcher implements Service {
_participatingConfig = new HashMap();
_lastParticipatingExpiration = 0;
_validator = null;
_leaveJob = new LeaveTunnel(ctx);
ctx.statManager().createRateStat("tunnel.participatingTunnels",
"How many tunnels are we participating in?", "Tunnels",
new long[] { 10*60*1000l, 60*60*1000l, 3*60*60*1000l, 24*60*60*1000l });
@@ -176,7 +178,7 @@ public class TunnelDispatcher implements Service {
_context.statManager().addRateData("tunnel.joinParticipant", 1, 0);
if (cfg.getExpiration() > _lastParticipatingExpiration)
_lastParticipatingExpiration = cfg.getExpiration();
_context.jobQueue().addJob(new LeaveTunnel(_context, cfg));
_leaveJob.add(cfg);
}
/**
* We are the outbound endpoint in this tunnel, and did not create it
@@ -200,7 +202,7 @@ public class TunnelDispatcher implements Service {
if (cfg.getExpiration() > _lastParticipatingExpiration)
_lastParticipatingExpiration = cfg.getExpiration();
_context.jobQueue().addJob(new LeaveTunnel(_context, cfg));
_leaveJob.add(cfg);
}
/**
@@ -228,7 +230,7 @@ public class TunnelDispatcher implements Service {
if (cfg.getExpiration() > _lastParticipatingExpiration)
_lastParticipatingExpiration = cfg.getExpiration();
_context.jobQueue().addJob(new LeaveTunnel(_context, cfg));
_leaveJob.add(cfg);
}
public int getParticipatingCount() {
@@ -336,10 +338,11 @@ public class TunnelDispatcher implements Service {
_context.statManager().addRateData("tunnel.dispatchEndpoint", 1, 0);
} else {
_context.messageHistory().droppedTunnelDataMessageUnknown(msg.getUniqueId(), msg.getTunnelId().getTunnelId());
if (_log.shouldLog(Log.ERROR))
_log.error("no matching participant/endpoint for id=" + msg.getTunnelId().getTunnelId()
+ ": existing = " + _participants.keySet()
+ " / " + _outboundEndpoints.keySet());
int level = (_context.router().getUptime() > 10*60*1000 ? Log.ERROR : Log.WARN);
if (_log.shouldLog(level))
_log.log(level, "no matching participant/endpoint for id=" + msg.getTunnelId().getTunnelId()
+ " expiring in " + DataHelper.formatDuration(msg.getMessageExpiration()-_context.clock().now())
+ ": existing = " + _participants.size() + " / " + _outboundEndpoints.size());
}
}
@@ -374,8 +377,9 @@ public class TunnelDispatcher implements Service {
_context.statManager().addRateData("tunnel.dispatchInbound", 1, 0);
} else {
_context.messageHistory().droppedTunnelGatewayMessageUnknown(msg.getUniqueId(), msg.getTunnelId().getTunnelId());
if (_log.shouldLog(Log.ERROR))
_log.error("no matching tunnel for id=" + msg.getTunnelId().getTunnelId()
int level = (_context.router().getUptime() > 10*60*1000 ? Log.ERROR : Log.WARN);
if (_log.shouldLog(level))
_log.log(level, "no matching tunnel for id=" + msg.getTunnelId().getTunnelId()
+ ": gateway message expiring in "
+ DataHelper.formatDuration(msg.getMessageExpiration()-_context.clock().now())
+ "/"
@@ -383,7 +387,7 @@ public class TunnelDispatcher implements Service {
+ " messageId " + msg.getUniqueId()
+ "/" + msg.getMessage().getUniqueId()
+ " messageType: " + msg.getMessage().getClass().getName()
+ " existing = " + _inboundGateways.keySet());
+ " existing = " + _inboundGateways.size());
}
long dispatchTime = _context.clock().now() - before;
@@ -423,7 +427,7 @@ public class TunnelDispatcher implements Service {
if (_log.shouldLog(Log.DEBUG))
_log.debug("dispatch outbound through " + outboundTunnel.getTunnelId()
+ ": " + msg);
if (msg.getMessageExpiration() < before) {
if (msg.getMessageExpiration() < before - Router.CLOCK_FUDGE_FACTOR) {
if (_log.shouldLog(Log.ERROR))
_log.error("why are you sending a tunnel message that expired "
+ (before-msg.getMessageExpiration()) + "ms ago? "
@@ -438,9 +442,10 @@ public class TunnelDispatcher implements Service {
} else {
_context.messageHistory().droppedTunnelGatewayMessageUnknown(msg.getUniqueId(), outboundTunnel.getTunnelId());
if (_log.shouldLog(Log.ERROR))
_log.error("no matching outbound tunnel for id=" + outboundTunnel
+ ": existing = " + _outboundGateways.keySet());
int level = (_context.router().getUptime() > 10*60*1000 ? Log.ERROR : Log.WARN);
if (_log.shouldLog(level))
_log.log(level, "no matching outbound tunnel for id=" + outboundTunnel
+ ": existing = " + _outboundGateways.size());
}
long dispatchTime = _context.clock().now() - before;
@@ -473,16 +478,59 @@ public class TunnelDispatcher implements Service {
public void renderStatusHTML(Writer out) throws IOException {}
private class LeaveTunnel extends JobImpl {
private HopConfig _config;
private List _configs;
private List _times;
public LeaveTunnel(RouterContext ctx, HopConfig config) {
public LeaveTunnel(RouterContext ctx) {
super(ctx);
_config = config;
getTiming().setStartAfter(config.getExpiration() + 2*Router.CLOCK_FUDGE_FACTOR);
_configs = new ArrayList(128);
_times = new ArrayList(128);
}
public void add(HopConfig cfg) {
Long dropTime = new Long(cfg.getExpiration() + 2*Router.CLOCK_FUDGE_FACTOR);
synchronized (LeaveTunnel.this) {
_configs.add(cfg);
_times.add(dropTime);
}
long oldAfter = getTiming().getStartAfter();
if (oldAfter < getContext().clock().now()) {
getTiming().setStartAfter(dropTime.longValue());
getContext().jobQueue().addJob(LeaveTunnel.this);
} else if (oldAfter >= dropTime.longValue()) {
getTiming().setStartAfter(dropTime.longValue());
} else {
// already scheduled for the future, and before this expiration
}
}
public String getName() { return "Leave participant"; }
public void runJob() {
remove(_config);
HopConfig cur = null;
Long nextTime = null;
long now = getContext().clock().now();
synchronized (LeaveTunnel.this) {
if (_configs.size() <= 0)
return;
nextTime = (Long)_times.get(0);
if (nextTime.longValue() <= now) {
cur = (HopConfig)_configs.remove(0);
_times.remove(0);
if (_times.size() > 0)
nextTime = (Long)_times.get(0);
else
nextTime = null;
}
}
if (cur != null)
remove(cur);
if (nextTime != null) {
getTiming().setStartAfter(nextTime.longValue());
getContext().jobQueue().addJob(LeaveTunnel.this);
}
}
}
}

View File

@@ -27,6 +27,7 @@ public class TunnelParticipant {
private InboundEndpointProcessor _inboundEndpointProcessor;
private InboundMessageDistributor _inboundDistributor;
private FragmentHandler _handler;
private RouterInfo _nextHopCache;
public TunnelParticipant(RouterContext ctx, HopConfig config, HopProcessor processor) {
this(ctx, config, processor, null);
@@ -44,6 +45,10 @@ public class TunnelParticipant {
_inboundEndpointProcessor = inEndProc;
if (inEndProc != null)
_inboundDistributor = new InboundMessageDistributor(ctx, inEndProc.getDestination());
if ( (_config != null) && (_config.getSendTo() != null) ) {
_nextHopCache = _context.netDb().lookupRouterInfoLocally(_config.getSendTo());
}
}
public void dispatch(TunnelDataMessage msg, Hash recvFrom) {
@@ -62,7 +67,9 @@ public class TunnelParticipant {
if ( (_config != null) && (_config.getSendTo() != null) ) {
_config.incrementProcessedMessages();
RouterInfo ri = _context.netDb().lookupRouterInfoLocally(_config.getSendTo());
RouterInfo ri = _nextHopCache;
if (ri == null)
ri = _context.netDb().lookupRouterInfoLocally(_config.getSendTo());
if (ri != null) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Send off to nextHop directly (" + _config.getSendTo().toBase64().substring(0,4)
@@ -115,6 +122,7 @@ public class TunnelParticipant {
public void runJob() {
RouterInfo ri = _context.netDb().lookupRouterInfoLocally(_config.getSendTo());
if (ri != null) {
_nextHopCache = ri;
send(_config, _msg, ri);
} else {
if (_log.shouldLog(Log.ERROR))
@@ -134,6 +142,7 @@ public class TunnelParticipant {
public void runJob() {
RouterInfo ri = _context.netDb().lookupRouterInfoLocally(_config.getSendTo());
if (ri != null) {
_nextHopCache = ri;
if (_log.shouldLog(Log.ERROR))
_log.error("Lookup the nextHop (" + _config.getSendTo().toBase64().substring(0,4)
+ " failed, but we found it!! where do we go for " + _config + "? msg dropped: " + _msg);

View File

@@ -8,13 +8,11 @@ import net.i2p.router.tunnel.TunnelCreatorConfig;
class ExpireJob extends JobImpl {
private TunnelPool _pool;
private TunnelCreatorConfig _cfg;
private Object _buildToken;
private boolean _leaseUpdated;
public ExpireJob(RouterContext ctx, TunnelCreatorConfig cfg, TunnelPool pool, Object buildToken) {
public ExpireJob(RouterContext ctx, TunnelCreatorConfig cfg, TunnelPool pool) {
super(ctx);
_pool = pool;
_cfg = cfg;
_buildToken = buildToken;
_leaseUpdated = false;
// give 'em some extra time before dropping 'em
getTiming().setStartAfter(cfg.getExpiration()); // + Router.CLOCK_FUDGE_FACTOR);

Some files were not shown because too many files have changed in this diff Show More