Compare commits

..

222 Commits

Author SHA1 Message Date
jrandom
61c97ab940 0.3.1.2 (backwards compatible, etc) 2004-05-13 23:49:08 +00:00
jrandom
b0a1b3b5ca added some harvest options
dont use javaw, since its a bitch to kill multiple jvms (yeah, this leaves a dos box.  we'll deal until we've got the shutdown admin control)
2004-05-13 23:32:57 +00:00
jrandom
4c7af01edc allow dynamic update to the reliability threshold factor (e.g. rather than the top 2/3rds being considered "reliable", allow that to be the top 1/3, or 1/2, etc)
the router.config var "profileOrganizer.reliabilityThresholdFactor=0.75" (or environment property -DprofileOrganizer.reliabilityThresholdFactor=0.5) etc
2004-05-13 23:24:09 +00:00
jrandom
0d431213cd include the previous period in the measurements (since they're discrete, not rolling)
also include the other elements as necessary by default
2004-05-13 07:14:54 +00:00
jrandom
ad9dd9a2e2 Lots of updates. I'm not calling this 0.3.1.2, still need to
"burn it it" some more, but its looking good.
* test all tunnels we manage every period or two. later we'll want to include some randomization to help fight traffic analysis, but that falls into the i2p 3.0 tunnel chaff / mixing / etc)
* test inbound tunnels correctly (use an outbound tunnel, not direct)
* only give the tunnels 30 seconds to succeed
* mark the tunnel as tested for both the inbound and outbound side and adjust the profiles for all participants accordingly
* keep track of the 'last test time' on a tunnel
* new tunnel test response time profile stat, as well as overall router stat (published in the netDb as "tunnel.testSuccessTime")
* rewrite of the speed calculator - the value it generates now is essentially "how many round trip messages can this router pass in a minute".
  it also allows a few runtime configurable options:
  = speedCalculator.eventThreshold:
    we use the smallest measurement period that has at least this many events in it (10m, 60m, 24h, lifetime)
  = speedCalculator.useInstantaneousRates:
    when we use the estimated round trip time, do we use instantaneous or period averages?
  = speedCalculator.useTunnelTestOnly:
    do we only use the tunnel test time (no db response or tunnel create time, or even estimated round trip times)?
* fix the reliability calculator to use the 10 minute tunnel create successes, not the (almost always 0) 1 minute rate.
* persist the tunnel create response time and send success time correctly (duh)
* add a new main() to PeerProfile - PeerProfile [filename]* will calculate the values of the peer profiles specified.  useful for tweaking the calculator, and/or the configurable options.  ala:
     java -DspeedCalculator.useInstantaneousRates peerProfiles/profile-*.dat
2004-05-13 04:32:26 +00:00
jrandom
c7895ed905 oh, you mean we're supposed to be at least a /little/ resiliant? 2004-05-13 03:54:33 +00:00
jrandom
57d7979d51 removed obsolete code
minor reorganization to help track down whats intermittently b0rking my kaffe instance
logging
2004-05-12 07:55:25 +00:00
jrandom
61f6871cd1 logging and a catastrophic try/catch (no situations have called for this yet, but its worth testing for) 2004-05-12 07:47:22 +00:00
jrandom
406048f7b9 ugly tests to see if the minimal RAW side of SAM works (it does, w00t) 2004-05-11 03:00:53 +00:00
jrandom
6dd5b0fe45 basic datagram tests (that work now :) 2004-05-11 02:44:16 +00:00
jrandom
fd4bc5e3cf keystream fixes 2004-05-11 02:43:52 +00:00
jrandom
3bab2d8957 only append the client's config properties to the SESSION commands (since some of the rest get confused with unknown tags...) 2004-05-11 02:07:27 +00:00
jrandom
af2f5cd2e1 kaffe shits a brick if you want the socket's address after .close() (grumble) 2004-05-11 01:55:22 +00:00
jrandom
d4bb32da82 fix per http://twiki.ntp.org/bin/view/Support/JavaSntpClientDev (thanks duck!)
this may have caused some clock skew problems on the deployed 0.3.1.1, so we'll get this deployed asap
2004-05-11 01:45:18 +00:00
jrandom
08aca6ca61 while (true) { m00; } 2004-05-09 07:23:43 +00:00
jrandom
697b3c6772 SAM .net lib work in progress - dm and firerabbit 2004-05-09 07:16:04 +00:00
jrandom
878525ced8 handle corrupt files more gracefully 2004-05-09 04:14:30 +00:00
shendaras
418531736b imports
Did you miss me?
(shendaras)
2004-05-09 01:31:12 +00:00
jrandom
6c175440c6 added mush.zeit.i2p 2004-05-08 06:41:01 +00:00
jrandom
723a2f2008 include timestamper in installer 2004-05-07 19:01:47 +00:00
jrandom
ea9b9fbf17 0.3.1.1 (tastes like chicken)
backwards compatible but some config changes necessary
2004-05-07 17:52:49 +00:00
jrandom
303e257841 synchronization reduction and keep track of the 'last' job for each runner (to help debug something i see once a week on kaffe) 2004-05-07 17:51:28 +00:00
jrandom
07b6a8ba92 if we lose our I2CP connection to the router, die hard and fast.
(only relevent for people whose socket manager / i2ptunnel / etc are located remote from the router)
2004-05-07 07:01:26 +00:00
jrandom
e216e18368 update the clock more liberally (since we've got the new ntp code) 2004-05-07 04:34:03 +00:00
jrandom
e57c5b4bc2 log to CRIT for jbigi load failure 2004-05-07 04:23:30 +00:00
jrandom
f772d6ddeb /me reboots brain, understands, and thanks mihi 2004-05-07 04:19:43 +00:00
jrandom
cd37c301d9 if (log.shouldLog())
yeah, aspect oriented programming sure would be nice.
2004-05-07 04:07:14 +00:00
jrandom
f5fa26639e minor html cleanup 2004-05-07 03:45:48 +00:00
jrandom
45ec73c115 include a unique request id in the client runner thread name
minor cleanup
2004-05-07 03:33:23 +00:00
jrandom
13952ebd8b include the expiration and messageId in the toString (shown on msg drop due to "unknown tunnel") 2004-05-07 03:31:33 +00:00
jrandom
2df0007a10 logging 2004-05-07 03:29:06 +00:00
jrandom
89bc5db3e1 increase the bundle probability to yet another arbitrary value
add the jobId to log messages to simplify tracing individual parallel sends
logging cleanup
2004-05-07 03:28:22 +00:00
mihi
4021deec7f poke jrandom's eyes into the semantic of an "else" clause
(you may remove both comments when you understood it)

[mihi]
2004-05-07 03:10:57 +00:00
mihi
a3977f37f7 javadoc, no functional changes 2004-05-07 03:06:41 +00:00
jrandom
766c12242e logging, javadoc 2004-05-07 01:45:12 +00:00
jrandom
a82b951aff made private things that don't need to be public
remove semantic inconsistency wrt getRemoteId(false) - it shouldn't ever timeout, since it always returns immediately
javadoc (though i wish i understood the close/close2/sendClose more clearly so i could javadoc that process)
2004-05-07 01:32:48 +00:00
jrandom
997a94eecc removed PHTTP lines since they were only used for time sync
added more info wrt NTP entry
added filename for the SAM bridge
2004-05-06 07:48:45 +00:00
jrandom
635535aac2 implement keyfile persistence (storing name=privKeyDataBase64\n for each name)
filename specified on the command line: SAMBridge [keyfile [listenHost] listenPortNum [ name=val]*]
2004-05-06 07:35:44 +00:00
jrandom
25314fd91a make sure we mark the send as *failed* if we need to reconnect 2004-05-06 04:18:28 +00:00
jrandom
9a06a5758d check shouldBundle only when its ready to be checked (duh) 2004-05-06 01:02:50 +00:00
jrandom
e5a2a9644f *cough* [d'oh] 2004-05-05 23:01:36 +00:00
jrandom
e0e7211852 lets default the read timeout to 5 minutes for clients (that hanging irc disconnect / not disconnected thing) 2004-05-05 22:57:43 +00:00
jrandom
cdaeb4d176 track and publish two new stats:
* netDb.failedPeers (how many peers didn't reply to a lookup in time)
* netDb.searchCount (how many searches we send out in a 3 hour period)
probabalistically include the leaseSet of the sender in the garlic sent
to a peer if the client requests it to be included (aka if they want
replies).  By default, this is enabled (disable by setting the I2CP
prop "shouldBundleReplyInfo=false").  Also, by default the probability is
30% (w00 h00, arbitrary values!), which can be overridden via the I2CP
prop "bundleReplyInfoProbability=80" (or =10, or =100, etc).  The tradeoff
here is quicker replies in exchange for bandwidth (the dbStore).
Yeah, it'd be nice if there were something keeping track of which leaseSet
each client sent to each peer so that it could explicitly include it only
if it were necessary, but for now that's probably overkill.
2004-05-05 22:46:10 +00:00
jrandom
07aa2e280d strip the Connection, Keep-Alive, and Proxy-Connection headers, and always inject Connection: close
(this is the cause of the intermittent "view $page through squid, try to view eepsite, end up requesting through squid" bug)
2004-05-05 07:29:48 +00:00
jrandom
6c4bc67ff3 simplistic streaming test (w00t, the streams worked - no mods necessary. go human, its your birthday, go human, its your birthday) 2004-05-05 04:43:05 +00:00
jrandom
d9f0cc27ef formatting 2004-05-05 03:37:26 +00:00
jrandom
59aec9d289 expose the read timeout for the client and put the default read timeout back to -1 for the server (override via command line, etc) 2004-05-05 03:36:18 +00:00
jrandom
451f4c503d fixed typo on timestamper, keep NetMonitor off by default 2004-05-05 01:32:08 +00:00
duck
cd82089d4d upgrade deprecated argument
fix ze german
(duck)
2004-05-04 17:17:10 +00:00
jrandom
3db8b63cde by default, set the readTimeout to 3 minutes, NOT infinity. Overridable as before (setting the timeout to -1)
add a unique id to the server thread
2004-05-04 08:16:41 +00:00
jrandom
6edf5d1e4f add a unique id to the thread names 2004-05-04 08:15:18 +00:00
jrandom
a23fa6fadd allow multiple concurrent connections to be created
added a unique ID to more threads
2004-05-04 08:14:19 +00:00
jrandom
51eb77e409 logging 2004-05-04 08:13:01 +00:00
jrandom
691326cea8 make sure we kill the threads that failed to ACK, rather than leave them sitting there, waiting forever
logging
2004-05-04 08:09:28 +00:00
jrandom
3cac1238ed handle reclose, logging, more clear notification 2004-05-04 05:53:11 +00:00
jrandom
b04512a4f6 add unique IDs to the threads for easier tracing 2004-05-04 04:46:04 +00:00
jrandom
3a4d0549aa add accept timeouts (default is that if the server doesnt .accept() in 5s, refuse the con)
add unique IDs to the various threads for logging / tracing purposes
2004-05-04 04:44:05 +00:00
jrandom
d7467f5dc3 disconnect isn't an error 2004-05-04 01:58:37 +00:00
jrandom
141902b86d parseParams throws exception on bad formatting, and its perfectly valid to have params with 0 values (e.g. DEST GENERATE\n) 2004-05-04 01:35:09 +00:00
jrandom
5aa680fc93 simple test of whether DEST GENERATE works 2004-05-04 01:32:39 +00:00
jrandom
a790117f5a test the naming commnads (fetching ME, a known host, and an unknown host) 2004-05-04 01:11:44 +00:00
jrandom
2a5a52c810 added xilog.i2p 2004-05-04 00:43:09 +00:00
jrandom
2156f4c2f3 * more verbose errors (include MESSAGE data on the I2P_ERROR reply, not just in the log)
* don't create excess I2PAppContexts (if any old context will do, use the global)
keep track of keys per spec (when DESTINATION=blah, create (or reuse) the destination private
keys).  we still need to persist this data though.
* the DESTINATION in the SESSION STATUS is now the same as the one sent in the
SESSION CREATE, /not/ the base64 of the private key, per spec
* enum is a reserved word in 1.5, so s/enum/names/ for future compatability
* logging
2004-05-03 11:34:38 +00:00
jrandom
2585460286 initial tests for HELLO and create session (style=stream). covers the basics, but doesn't cover a single normal scenario yet 2004-05-03 11:16:59 +00:00
jrandom
1b4af66986 flag as closed /after/ we send the disconnect message *cough* 2004-05-03 11:13:44 +00:00
jrandom
0324bac044 added lucky.i2p, removed lp.i2p 2004-05-03 07:04:12 +00:00
jrandom
2bfbe1ca27 logging (toss a unique ID onto the handler / inactivity threads) 2004-05-03 03:36:38 +00:00
jrandom
60584228d9 refactored packet handling into type specific methods
removed nested synchronization (which had been causing undetected deadlocks)
made sync blocks smaller, though this may have opened holes related to
resent ACK/SYN/CLOSE packets that are delivered in a race.  I'm not as
fluent in the ministreaming lib code as i should be (yet), but duck's thread
dumps were showing hundreds of threads waiting on a lock that'll never get
released (since the only way to release it would be to receive another
packet, and no more packets can be received until the lock is released, etc)
also, I2PSession is threadsafe - i can see no reason to synchronize on it
(and it was being synchronized on only part of the time?)
also, refactored the charset encoding stuff and minor log tweaking
i've been testing this for the last hour or so, on eepsites and squid (large
and small files), as well as irc, and there haven't been any glitches.  but
it needs more testing before it can be released, obviously.
2004-05-03 03:34:25 +00:00
jrandom
44e34f7b11 trim the request line (StringTokenizer w/ " " as a delim doesn't include \n as a delim, etc) 2004-05-02 07:50:20 +00:00
jrandom
7912050647 allow overriding the I2CP port/host 2004-05-02 07:49:22 +00:00
jrandom
2231abd407 default the DIRECTION to BOTH for streams 2004-05-02 07:07:25 +00:00
jrandom
8d17ba4d66 added sungo.i2p 2004-05-02 06:59:38 +00:00
jrandom
8244bdb440 include the timestamper (and fire the client on startup, using a pair of arbitrary NTP hosts - to be configured later) 2004-05-02 05:11:06 +00:00
jrandom
bc3b7ffd86 start the admin listener ASAP (right after reading the config)
fire the LoadClientAppsJob right after the admin listener is booted, which now includes support for the onBoot property (which causes the client to run immediately, instead of waiting 2+ minutes)
(yeah, it'd suck if all routers started up, tried to connect to people, got shitlisted, then 2 minutes later got the right NTP time, 'eh?)
2004-05-02 05:02:10 +00:00
jrandom
e22cb62493 handle /setTime?blah&now=yyyyMMdd_HH:mm:ss.SSSS (updating the router's clock)
yes, we'll want to filter the access to the admin manager ;)
2004-05-02 04:46:52 +00:00
jrandom
e923aa1f72 add the timestamper 2004-05-02 04:29:18 +00:00
jrandom
68a21f1fbb NTP client, GPLed 2004-05-02 04:18:53 +00:00
jrandom
74209e2607 0.3.1 (backwards compatible, still testnet, release later this evening) 2004-04-30 23:04:13 +00:00
jrandom
1a38271104 made the event name more consistent 2004-04-30 23:01:35 +00:00
jrandom
e5ab5d6a5a new stat: client.sendAckTime containing the average time to get an ack for a client message send
this stat is published in the netDb, but the quantity fields (how many acks the stat is averaged over) is h4x0red
(it always reads "666", since otherwise it'd be fairly easy to identify what routers run servers, and i can live without knowing the quantity)
2004-04-30 07:56:05 +00:00
jrandom
2745ff727f don't include a peer by default 2004-04-30 07:16:30 +00:00
jrandom
24ea383937 don't harvest so much data 2004-04-30 07:15:29 +00:00
jrandom
9cb11d4d5f allow some overrides that the ExploreJob needs
logging
2004-04-30 07:14:26 +00:00
jrandom
7202ea3340 dont dieFatal() if the first leaseSet lookup fails (this was the cause of those "fast fail" errors [bugId=69])
try up to 6 times to search (or until the expiration, etc)
logging
2004-04-30 07:11:41 +00:00
jrandom
d234ea01d0 logging 2004-04-30 07:09:05 +00:00
jrandom
e246cd37dd simple exponential decay on the exploration
(min/max frequency=1m/30m, doubling every time we don't find something new)
reduce the bredth and duration of explorations
republish less often (every 60s send out one random one [or however many explicit ones])
logging
2004-04-30 07:08:25 +00:00
jrandom
0a4ddedac9 be more forgiving of slow connections (and fix my math in the comments) 2004-04-30 07:03:13 +00:00
jrandom
0e4b80b002 make sure we only try to request from people we know about (*cough*) 2004-04-30 07:02:16 +00:00
jrandom
a460a0dc44 logging, and be more forgiving if the guaranteed/failed comes back before the ack does 2004-04-30 07:00:13 +00:00
jrandom
f7212112b8 mark the ping datapoint before actually sending it, for those instances where a reply can be sent back faster than the ACK of the send 2004-04-30 06:58:42 +00:00
jrandom
86d55b32a6 include the (redundant) rtt in the output file to let tools that dont know how to combine columns do so
*cough*
2004-04-30 06:56:25 +00:00
jrandom
4b0d1aac15 only read from or write to disk if necessary 2004-04-27 08:47:48 +00:00
jrandom
fb7c06aa01 throw in a 10 second pause between starting up each router to try and avoid too much synchronicity 2004-04-27 08:47:00 +00:00
jrandom
5c41be3470 only read from or write to disk if there is new data to transfer
(and set the file modification date to the 'published on' date in the netDb object)
2004-04-27 08:44:23 +00:00
jrandom
a78df1a152 logging (reduce gc churn) 2004-04-27 08:42:40 +00:00
jrandom
34e8db0fe3 logging & formatting to reduce gc churn 2004-04-27 08:41:38 +00:00
jrandom
70faecb8b5 handle the UnsignedInteger's new "IllegalArgumentException on negative" policy 2004-04-27 08:33:15 +00:00
jrandom
237f278479 we only need to reread it if its been updated, dimwit. 2004-04-27 08:31:56 +00:00
jrandom
e766a00a12 dont be such a reuse zealot and just fscking optimize the use case
(aka shift instead of creating heavyweight BigInteger objects)
plus some good ol' caching and gc churn reduction
2004-04-27 08:30:55 +00:00
jrandom
ea03637ec1 cache the hashCode and getBytes data, significantly reducing the contention on these objects 2004-04-27 08:28:16 +00:00
jrandom
d0f6d47b14 logging (reduced temporary object creation by _log.shouldLog) 2004-04-27 08:26:23 +00:00
jrandom
5bf1658d9a dont go into an infinite loop if we shut down before the log manager was fully created
(since the appContext creates a log manager if one doesn't exist, and that create will fail
if we're shutting down, and it'll create a log manager to log the fact that its failing, etc)
2004-04-26 03:32:59 +00:00
jrandom
4ce9fb5b5a new MultiRouter (allows you to fire up mutliple routers in the same JVM)
new VMCommSystem (useful for running large multirouter instances)
new MultiRouterBuilder (helper app for setting up a MultiRouter simulator)
updates to the router to handle multiple routers in the same VM, as well as
deal with the multiple OOM listener stuff
see the javadocs for info on the MultiRouter and MutliRouterBuilder
(yeah, its not ready for prime time, and its really just for the simulator,
so I'm not sure if anyone else is going to use it anyway ;)
2004-04-26 03:30:20 +00:00
jrandom
f80f02da73 use the context to find a location for the sessionKeys.dat file (router.sessionKeys.location=filename in router.config) 2004-04-26 01:09:10 +00:00
jrandom
52ece833a7 logging 2004-04-26 01:00:22 +00:00
jrandom
1ad6dde146 allow a whole set of OOM listeners on threads, not just one
cache the hash's base64 value too
use the context's logging more
logging updates
2004-04-26 00:57:10 +00:00
jrandom
64bcfd23bd expose the way to specify context env properties
remove unused lazy load code (we actively load components in the RouterContext)
2004-04-24 22:32:10 +00:00
jrandom
d659447879 allow overriding the env props 2004-04-24 22:29:01 +00:00
jrandom
e73eb55d75 don't create two contexts just for this I2PTunnel (one implicit from the static new Log(I2PTunnel.class) and one explicit) 2004-04-24 12:51:15 +00:00
jrandom
a52cea29f4 Class.getConstructor pulls the public ones... 2004-04-24 12:49:13 +00:00
jrandom
3d91e59386 la la la 2004-04-24 12:38:21 +00:00
jrandom
393b1d7674 big ol' update to strip out the singletons, replacing them with
a rooted app context.  The core itself has its own I2PAppContext
(see its javadoc for, uh, docs), and the router extends that to
expose the router's singletons.  The main point of this is to
make it so that we can run multiple routers in the same JVM, even
to allow different apps in the same JVM to switch singleton
implementations (e.g. run some routers with one set of profile
calculators, and other routers with a different one).
There is still some work to be done regarding the actual boot up
of multiple routers in a JVM, as well as their configuration,
though the plan is to have the RouterContext override the
I2PAppContext's getProperty/getPropertyNames methods to read from
a config file (seperate ones per context) instead of using the
System.getProperty that the base I2PAppContext uses.
Once the multi-router is working, i'll shim in a VMCommSystem
that doesn't depend upon sockets or threads to read/write (and
that uses configurable message send delays / disconnects / etc,
perhaps using data from the routerContext.getProperty to drive it).
I could hold off until the sim is all working, but there's a
truckload of changes in here and I hate dealing with conflicts ;)
Everything works - I've been running 'er for a while and kicked
the tires a bit, but if you see something amiss, please let me
know.
2004-04-24 11:54:35 +00:00
human
c29a6b95ae Increased logging priority for connection timeouts
(human)
2004-04-23 14:18:48 +00:00
jrandom
567a4e8361 so this is why we're not harvesting the dropped jobs/messages (d'oh)
if you update your harvester.config and rerun the router, it'll start paying attention to it
(no, unfortunately the NetMonitor doesn't periodically read this file)
2004-04-22 03:17:41 +00:00
jrandom
4d3e4c1a15 d'oh 2004-04-22 03:11:12 +00:00
jrandom
afeecdf4af logging, formatting 2004-04-22 03:09:03 +00:00
human
4fe7105e2f Implemented timeout handling to I2PTunnelServer 2004-04-21 17:58:26 +00:00
human
d7c3a53f2d Initial implementation of read() timeout on I2PSocket. Let's see whether it
could solve duck's problems with dangling threads...
(human)
2004-04-21 17:56:16 +00:00
jrandom
58e7574a6a pull from the right field for netDb lookups sent 2004-04-20 20:58:07 +00:00
jrandom
94ab703c7c added prepareGUI, buildGUI,. distGUI targets 2004-04-20 20:56:55 +00:00
human
90350786e6 s/InterruptedException/InterruptedIOException/
(human)
2004-04-20 15:43:04 +00:00
human
8038e1ee7d I2PSocketManager.connect() should have thrown InterruptedIOException, and *not*
InterruptedException (oops!)
(human)
2004-04-20 15:38:55 +00:00
jrandom
65f1a5fed6 write out the public dest every time we connect, /including/ the first time. (thanks duck) 2004-04-20 13:30:09 +00:00
jrandom
64b94ab124 0.3.0.4 (backwards compatible, release info / docs / etc coming later today [is today tuesday already?] 2004-04-20 09:18:53 +00:00
jrandom
c03cb1de5e revised GUI fetch/build/dist process - at the top level, run
'ant prepGUI' to fetch and prepare the jfreechart code
'ant buildGUI' to build the jars necessary
'ant distGUI' to build a gui.zip that contains the jars and a
license notice related to the LGPL and APL software linked
within it.
("installing" the GUI == unzip gui.zip into the I2P install dir)
2004-04-20 09:13:07 +00:00
jrandom
f0004290b4 oops, pulled the wrong entry 2004-04-20 07:55:37 +00:00
jrandom
7e1b49a742 fixed up some of the cleanup code to handle out of order responses
minor refactoring, formatting
2004-04-20 07:42:53 +00:00
jrandom
d26c56e467 verbose4life 2004-04-20 07:39:47 +00:00
jrandom
a51e0c26e5 added the eepProxy and harvester as part of the default clientApps run on startup
(with a commented out set of lines for a heartbeat client/server)
updated -cp lines accordingly
use javaw for windows users (so they can close the damn dos boxes)
toss the default logger logs into logs/ (say that three times fast)
formatting
2004-04-20 07:32:21 +00:00
jrandom
180d39534c include the harvester & heartbeat monitor (but not their GUIs) 2004-04-20 07:27:41 +00:00
jrandom
203d0e870a allow the user to override the I2CP options (exposed on the command line, ala
SAMBridge [[listenHost ]listenPort[ name=val]*]
where listenHost defaults to localhost, listenPort defaults to 7656, and name=val
can be the I2CP options to override (e.g. i2cp.tcp.host=localhost i2cp.tcp.port=4001)
2004-04-20 07:26:34 +00:00
jrandom
bed7d09764 delete that stupid 'interactive' mode where we dump things to stdout on command
(hello, we have an admin console now, duh)
formatting touchups.
2004-04-20 07:06:39 +00:00
jrandom
3c762c9a02 short circuit some handling when building custom length tunnels
if a client only wants 0 hop tunnels, give them 0 hop tunnels (rather than wasting a 2+ hop on it)
make inNetPool.dropped and inNetPool.duplicate rate stats, not frequency stats
formatting, minor refactoring
2004-04-20 02:42:56 +00:00
jrandom
ba5f0fb70b correctly differentiate between handled & matched requests
logging and some minor refactoring
2004-04-20 02:18:20 +00:00
human
ebc3e05f23 * Made the SAM bridge aware of the new exceptions thrown by
I2PSocketManager.connect(), with better error reporting to SAM clients;
* made SAMStreamSession destroy the associated I2PSocketManager when being
  closed.
(human)
2004-04-19 21:52:52 +00:00
human
674ad899f9 Made HTTPTunnel aware of the new exceptions thrown by
I2PSocketManager.connect()
(human)
2004-04-19 21:48:14 +00:00
human
d945eb6fcf Made all the ministreaming-based apps aware of the new exceptions thrown by
I2PSocketManager.connect()
(human)
2004-04-19 21:47:06 +00:00
human
fb170e3c42 * Made I2PSocketManager.connect() throw several kinds of exceptions, for
better error reporting;
* Added an I2PSocketManager.destroySocketManager() method, that closes all
  the managed sockets and destroys the associated I2PSession.
(human)
2004-04-19 21:45:04 +00:00
human
3658cca3e5 Further simplified I2P repliable datagram format: they now contain
senderPubDest + S(H(payload)) + payload
(human)
2004-04-19 21:43:06 +00:00
jrandom
5e78a41b75 remove unnecessary scrolls and packs 2004-04-18 22:53:07 +00:00
jrandom
c23d8efe08 publish the new data points (crypto.garlic.decryptFail, tunnel.unknownTunnelTimeLeft) 2004-04-18 03:40:42 +00:00
jrandom
0d3d4b60ce added stat - crypto.garlic.decryptFail
formatting / logging
2004-04-18 03:36:12 +00:00
jrandom
38091c3c25 added stat - tunnel.unknownTunnelTimeLeft which gathers the time until expiration of tunnel messages we're dropping because we dont know about the tunnel Id.
formatting / logging
2004-04-18 03:33:53 +00:00
jrandom
f0cd04ebc3 increased the delay to 2 minutes after startup before running client apps
tabs/spaces
2004-04-18 02:50:54 +00:00
human
3295c18829 * Added DATAGRAM supprt;
* refactoring of SAMRawSession.java, to make it derive from
  SAMMessageSession.java (parent class for SAMDatagramSession.java, too);
* removed unuseful cruft;
* some fixes;
* M-x untabify.
(human)
2004-04-17 23:19:20 +00:00
human
ccb309fd92 I2P repliable datagrams 2004-04-17 23:16:28 +00:00
jrandom
8206a26267 sample harvester.config (defining what stats we want to harvest from the netDb) 2004-04-17 03:33:19 +00:00
jrandom
8c7b91bd79 load what stats we want to monitor from a config file (harvester.config) 2004-04-17 03:32:51 +00:00
jrandom
061460f978 insane error handling 2004-04-17 00:43:03 +00:00
jrandom
a47c7b8f27 always send as a guaranteed message (but block as before) - this lets
udp-esque users get transparent sessionKey/sessionTag management.  we'll
probably refactor mode=guaranteed/best_effort into two concepts later,
dealing with blocking and encryption seperately.
logging and formatting fixes
2004-04-17 00:13:28 +00:00
jrandom
a859908e83 handle repeated attempts to close() gracefully
logging, formatting
2004-04-17 00:04:38 +00:00
jrandom
86759d2f9c DatabaseLookupMessageHandler:
added stat - netDb.lookupsReceived
 fixed formatting
HandleDatabaseLookupMessage:
 added stat - netDb.lookupsHandled
 added stat - netDb.lookupsMatched
 fixed formatting
HandleDatabaseStoreMessage:
 added stat - netDb.storeHandled
 fixed formatting
StoreJob:
 added stat - netDb.storeSent
 fixed formatting
 removed old unused code (we do dbStore through tunnels, not garlics)
 logging
SearchJob:
 fixed formatting
 logging
HandleTunnelCreateMessageJob:
 fixed formatting
 logging
PoolingTunnelManagerFacade:
 added stat - tunnel.participatingTunnels
 fixed formatting
 logging
TunnelPool:
 added getParticipatingTunnelCount()
 fixed formatting
 logging
StatisticsManager:
 revamped whats published
 fixed formatting
 logging
 fixed formatting
2004-04-16 23:52:11 +00:00
human
58c145ba08 Oops! Added missing file...
(human)
2004-04-16 03:44:35 +00:00
human
c0bb3da22f * Added support for SESSION CREATE STYLE=STREAM DIRECTION={CREATE|RECEIVE|BOTH}
* M-x untabify
(human)
2004-04-16 03:42:05 +00:00
human
031338d84d First step for the "connection refused" concept: incoming connections
won't be accepted until the server app actually requires an I2PServerSocket
from the I2PSocketManager.
It allows both to add a little bit of functionality, and to fix a nasty bug: it
was possible to hang an app that connects through the I2PSocketManager but
actually doesn't accept() connections (if 2 connection requests were sent
to the app, the I2PSocketManager got stuck waiting forever on
I2PServerSocketImpl.getNewSocket()).
2004-04-16 03:31:13 +00:00
human
2a619f3fba Slightly updated specs
(human)
2004-04-16 03:22:37 +00:00
jrandom
1c145cbc09 handle corruption / race during update of the peer's routerInfo data 2004-04-16 03:21:20 +00:00
jrandom
5d71fde51b allow a third parameter - # seconds between fetch
this lets you periodically refetch the seeds (I'm using this to fetch the live netDb & run the netmonitor/viewer)
2004-04-16 03:09:48 +00:00
jrandom
eec29f5c68 include the netmonitor (but not the GUI)
delete **/*.class and **/*.java~ (my IDE builds in place and backs up there)
2004-04-16 03:08:01 +00:00
jrandom
8fbd7acf2a initial impl (public domain, yadda yadda yadda) 2004-04-16 02:16:55 +00:00
mihi
7b824e6178 kill long lines
[mihi]
2004-04-14 23:27:50 +00:00
mihi
24c69a26ea untabify
[mihi]
2004-04-14 23:26:59 +00:00
human
7b03c95cfd * Added STREAMing support;
* added NAMING LOOKUP NAME=ME support;
* various cleanups & fixes;
* what else?
(human)
2004-04-14 16:59:47 +00:00
human
d2b09ecfda * Fixed race that (maybe) caused the problems reported by aum on
<http://dev.i2p.net/pipermail/i2p/2004-April/000214.html>;
* slightly revised locking;
* made accept() throw a ConnectException when the I2PServerSocket is closed.
(human)
2004-04-14 15:28:02 +00:00
aum
4cdd42f391 Fixed build.xml to detect os, and launch 'jythonc' or 'jythonc.bat'
according to whether we're running on *nix or windoze. build.xml
should now work on your platform, as long as you have jython installed
and jython is on your execution path.

Got SAM STREAMs working - test code added to i2psamclient.py
as function demoSTREAM()
2004-04-13 17:40:07 +00:00
human
4d0b3b287f SAM bridge integration in the I2P build & packaging system
(human)
2004-04-13 04:41:14 +00:00
human
0d7f784773 Pure-java implementation of the SAM bridge. It actually supports the
HELLO, DEST and NAMING commands, plus SESSIONs with STYLE=RAW. It works with
aum's client-side Python library (modulo a small change in the HELLO command,
required to allow protocol versioning, not yet implemented in the client lib).
(human)
2004-04-13 04:38:52 +00:00
human
66ad54fbf0 Made logs actually go through I2P logging system
(human)
2004-04-13 04:15:46 +00:00
jrandom
33782859b8 the heartbeat engine and gui are good 'nuff for now
(while i want to spend another few days on it, there
are more pressing things and this will meet my needs
for testnet).  the engine works as before, and the
gui now actually plots out and follows the chart over time.
The gui does have a lot of things left to be done before
it can be adopted by joe sixpack -
 * load/store the URLs being monitored so you don't
   have to reenter them on each startup
 * clear out the x axis on refetch (now it just keeps
   growing, which is good and bad)
 * adjustable refresh rate
 * implement snapshots (saving all the current state
   files to a dir, and allowing that dir to be loaded
   all at once)
 * beautification (override the colors, etc)
the net.i2p.heartbeat.** code is all public domain, BUT
net.i2p.heartbeat.gui.JFreeChart* classes depend on the
LGPL'ed jfreechart code, which in turn depends on apache
licensed code (log4j).  for the time being, this code
doesn't include the jfreechart code (and dependencies),
but the ant task in apps/heartbeat/java 'fetchJfreechart'
downloads it and places it under apps/heartbeat/java/lib,
after which you can build the GUI by running the ant task
'buildGUI' (buildGUI / etc are NOT in the standard build
process).
once we figure out all the details to comply with the
requirements of log4j's license we'll do so.  but for now,
the above works.
2004-04-13 03:24:04 +00:00
shendaras
3d294d5771 fix javadoc warning: no @return on void functions
(shendaras)
2004-04-12 10:26:42 +00:00
aum
c889a83707 More update ant tidy-up 2004-04-12 08:53:26 +00:00
aum
6a55af1950 Fixed paths 2004-04-12 08:43:32 +00:00
aum
a85cf2c2af Makefile and build.bat removed since we've switched to ant
README moved up to parent
2004-04-12 08:41:43 +00:00
aum
4c0e3f92d3 Created build.xml for SAM
Moved README out of build dir
2004-04-12 08:32:32 +00:00
shendaras
e3354a805e javadoc, imports
(shendaras)
2004-04-12 08:14:07 +00:00
shendaras
ceb9a935de import stuff (alphabetizing, etc.)
(shendaras)
2004-04-12 08:13:48 +00:00
aum
d3ad111b85 change - now goes to root build dir and does 'ant build' to ensure
the required jars are present
2004-04-12 06:41:24 +00:00
aum
de740b1d9d started adding STREAM support 2004-04-12 05:46:05 +00:00
jrandom
7c155545ae partial impl of the gui, still a few things left to do:
- implement some validation on the state files loaded
- reenable delete and updates to refresh
- integrate the real chart code (currently just plain text instead of the graphs)
- gui updates
i wont spend more than another day on this during the testnet, but i want to get it plotting before continuing.
2004-04-12 02:44:18 +00:00
aum
a7597b2a6d Tested build process on windows.
Updated README, and fixed build.bat, so windows build
of i2psam.jar works.
2004-04-11 10:31:41 +00:00
aum
22916c1904 Corrected Makefile:
- removed relative path for jython.jar, replaced with a def
   which developer must edit

Added README
 - overviews the i2psam.jar building process

Added build.bat
 - an attempt at a build script which might work on Windows, for people
   who don't have 'make' installed
2004-04-11 07:21:28 +00:00
jrandom
a72e479e50 scoping so the test classes are reachable outside the current package 2004-04-10 13:37:29 +00:00
jrandom
60c1776994 fix up packages 2004-04-10 13:35:56 +00:00
jrandom
fbddb24728 license incompatible with i2p license policy - section 2 requires application
developers to use the software in a particular way (to have the software display
"Copyright \xa91996-1999 Corporation for National Research Initiatives; All Rights Reserved")
section 3 has a similar problem.

this violates the rule #2 of the i2p license policy -
All software bundled in the I2P distributions will allow
 2) use with no restrictions on how, when, where, why, or by whom is running it

in addition, using jython does not seem wise for some situations, as the license is
not GPL compatible (aka cannot be used with the GPL'ed SAM code)

sorry for the confusion earlier aum, I had mistakenly seen a COPYING file and
assumed it was Yet Another copy of the GPL.

http://lists.debian.org/debian-python/2001/debian-python-200107/msg00001.html as
well.
2004-04-10 12:56:02 +00:00
shendaras
e716f9e63a format (shendaras) 2004-04-10 11:55:25 +00:00
shendaras
51c49d7c1b format (shendaras) 2004-04-10 11:50:11 +00:00
shendaras
17a1b11f66 beginning of format, updated imports. (shendaras) 2004-04-10 11:45:02 +00:00
shendaras
8a8e68146f beginning of format, updated imports. (shendaras) 2004-04-10 11:39:00 +00:00
shendaras
dbe5dea525 120 code, 160 comments (shendaras) 2004-04-10 11:01:42 +00:00
shendaras
604af822aa see how that looks
(shendaras)
2004-04-10 10:58:11 +00:00
shendaras
435759c21c indent on column, update javadoc
(shendaras)
2004-04-10 10:31:03 +00:00
shendaras
847f094975 @seeRoutine -> @see
(shendaras)
2004-04-10 10:26:19 +00:00
shendaras
b939d86975 once more to fix newline after @param (shendaras) 2004-04-10 10:20:37 +00:00
shendaras
3e5f56b19b final? (shendaras) 2004-04-10 10:17:32 +00:00
shendaras
d81f42e3e9 again? Longer wrapping
(shendaras)
2004-04-10 10:08:33 +00:00
shendaras
4fb3d34786 see how that looks
(shendaras)
2004-04-10 10:01:17 +00:00
jrandom
9a0a527b2b try with different settings... 2004-04-10 09:55:11 +00:00
jrandom
ba8fb23b9d editor testing (ignore for now) 2004-04-10 09:43:29 +00:00
shendaras
99790695a2 Javadoc, imports, and (potentially) some indentation. Maybe it won't do anything.... who knows?
(shendaras)
2004-04-10 09:12:59 +00:00
aum
e3a86bb150 code.leo is an xml-format file that holds the I2P SAM server and
client sources in a dissected XML form.

If you're working on I2P SAM, we strongly encourage you to install
the Leo editor (http://leo.sf.net), and use it to edit the
sources. Otherwise, we're stuck with the menial task of re-importing
your changes into the Leo tree. Thanks for your understanding and
co-operation.
2004-04-10 08:21:01 +00:00
aum
0ac1e885bd Description of what lives here and how to build it 2004-04-10 08:18:42 +00:00
aum
36aca1d39b i2psamclient.py is a Python API allowing Python apps to access
I2P via SAM. File contains a demo function, which both tests
the library, and shows simple examples of how to use the API.
Run epydoc on this file to get good doco.
2004-04-10 08:16:18 +00:00
aum
d0192b4cab Implements the I2P SAM server, in Jython (www.jython.org) 2004-04-10 08:12:22 +00:00
aum
a3a7a585d7 Added Makefile for building i2p SAM server jarfile 2004-04-10 08:11:24 +00:00
aum
b437d858f0 Added Jython license document, copied verbatim from website 2004-04-10 07:00:54 +00:00
aum
06f78178da removed jython.jar from this dir, should have gone into lib
(which I've already done)
2004-04-10 06:57:32 +00:00
aum
06412cc5c0 Ahh, this time for real
Added jython.jar in lib directory, in binary mode.
2004-04-10 06:56:19 +00:00
aum
1b86b9170f Added in binary mode this time, so should be ok 2004-04-10 06:52:43 +00:00
aum
6e71d34390 Oops, forgot to add jython.jar as a binary 2004-04-10 06:48:29 +00:00
aum
0e880f2479 Added jython.jar, into a directory of its own, because it is
likely that two or more I2P facilities will need it.

This seems a more acceptable alternative than hard-linking
jython.jar code into each app using it (which would result
in bloatage).
2004-04-10 06:47:29 +00:00
shendaras
400a35de1d Make the variable's purpose a little more obvious
(shendaras)
2004-04-10 06:47:15 +00:00
shendaras
c47bfce010 Some crappy, half-assed attempt at javadoc stuff; removed (commented out, rather) the fromProxy stuff for *Handler.java. Feel free to put it back in if it's really needed....
(shendaras)
2004-04-10 06:27:18 +00:00
jrandom
73db7b399e added the heartbeat to the build (but not in the installer, yet) 2004-04-10 05:20:12 +00:00
jrandom
f8a47c3c6a initial impl (heartbeat ping/pong works, no gui yet, but the stats generated are pretty readable) 2004-04-10 04:11:39 +00:00
jrandom
ee119de6c4 javadoc fix 2004-04-10 04:06:47 +00:00
jrandom
f37c0ed612 name all threads, and (nearly) always use I2PThread (in case we add some pooling/throttling/monitoring or whatnot later) 2004-04-09 01:22:04 +00:00
duck
6b1d671aed Little restyle of output text
(duck)
2004-04-09 00:58:10 +00:00
mihi
44bbcd7033 make build process "a bit" faster
[mihi]
2004-04-08 18:24:07 +00:00
mihi
e56dcba9d3 update protocol (formal things)
[mihi]
2004-04-08 18:23:48 +00:00
jrandom
e8a2130094 updated for new paths / mingw setup 2004-04-08 10:40:43 +00:00
jrandom
be13c14376 javadoc cleanup to remove those damn warnings 2004-04-08 09:07:53 +00:00
jrandom
6f0d0bed0b yall dont need these 2004-04-08 05:03:47 +00:00
475 changed files with 57706 additions and 31947 deletions

View File

@@ -0,0 +1,39 @@
The Heartbeat GUI loads up the stat files generated by the Heartbeat
engine and renders them visually, offering a way to drill through different
data points and take snapshots as things change (by saving particular stat
files for later). The GUI itself doesn't need to be on the same machine
as the Heartbeat engine - it pulls the stat files through any URL - even
through the EepProxy.
An example Heartbeat GUI config file follows
# how often do we want to pull new data to render
refreshFrequency=60
## for each peer test we may want to include in the GUI:
# where to find the current stat file (URL or filename)
stat.0.location=http://dev.i2p.net/stats/heartbeatStat_khWY_30s_1kb.txt
## optional entries for each peer test describing what we want shown
## (and how we want it shown)
# do we want to plot the send time (from when the ping was sent until the pong server got it)?
stat.0.plot.current.send=true
# do we want to plot the receive time (from when the pong was sent until reception)?
stat.0.plot.current.receive=true
# do we want to plot the lost messages?
stat.0.plot.current.lost=true
# what color should the current lines be rendered in?
stat.0.plot.current.color=BLUE
## optional entries for each peer test describing what averages we want
## rendered
# plot 1 minute send average?
stat.0.plot.1m.send=true
# plot 1 minute receive average?
stat.0.plot.1m.receive=true
# plot 1 minute lost message average?
stat.0.plot.1m.lost=true
# what color should the 1 minute averages be rendered as?
stat.0.plot.1m.color=GREEN
## repeated for all of the averaged periods, e.g.
## stat.0.plot.30m, .60m, 1440m (1 day)
There may be some other options, such as where to store snapshot files, whether
to generate PNG images, etc.

View File

@@ -0,0 +1,122 @@
Heartbeat
Application layer tool for monitoring the long term health of the
network by periodically testing peers, generating stats, and
rendering them visually. The engine (both server and client) should
work headless and seperate from the GUI, exposing the data in a simple
to parse (and human readable) text file for each peer being tested.
The GUI then periodically refreshes itself by loading those files (
either locally or from a URL) and renders the current state accordingly,
giving users a way to check that the network is alive, devs a tool to
both monitor the state of the network and to debug different situations (by
accessing the stat file - either live or archived).
The heartbeat configuration file is organized as a standard properties
file (by default located at heartbeat.config, but that can be overridden by
passing a filename as the first argument to the Heartbeat command):
# where the router is located (default is localhost)
i2cpHost=localhost
# I2CP port for the router (default is 7654)
i2cpPort=4001
# How many hops we want the router to put in our tunnels (default is 2)
numHops=2
# where our private destination keys are located - if this doesn't exist,
# a new one will be created and saved there (by default, heartbeat.keys)
privateDestinationFile=heartbeat_r2.keys
## peer tests configured below:
# destination peer for test 0
peer.0.peer=[destination in base64]
# where will we write out the stat data?
peer.0.statFile=heartbeatStat_khWY_30s_1kb.txt
# how many minutes will we keep stats for?
peer.0.statDuration=30
# how often will we write out new stat data (in seconds)?
peer.0.statFrequency=60
# how often will we send a ping to the peer (in seconds)?
peer.0.sendFrequency=30
# how many bytes will be included in the ping?
peer.0.sendSize=1024
# take a guess...
peer.0.comment=Test with localhost sending 1KB of data every 30 seconds
# we can keep track of a few moving averages - this value includes a whitespace
# delimited list of numbers, each specifying a period to calculate the average
# over (in minutes)
peer.0.averagePeriods=1 5 30
## repeat the peer.0.* for as many tests as desired, incrementing as necessary
If there are no peer.* lines, it will simply run a pong server. If any data is
missing, it will use the defaults (though there are no defaults for peer.* lines) -
running the Heartbeat app with no heartbeat configuration file whatsoever will create
a new pong server (storing its keys at heartbeat.keys) and using the I2P router at
localhost:7654.
The stat file generated for each set of peer.n.* lines contains the current state
of the test, its averages, as well as any other interesting data points. An example
stat file follows (hopefully it is self explanatory):
peer khWYqCETu9YtPUvGV92ocsbEW5DezhKlIG7ci8RLX3g=
local u-9hlR1ik2hemXf0HvKMfeRgrS86CbNQh25e7XBhaQE=
peerDest [base 64 of the full destination]
localDest [base 64 of the full destination]
numTunnelHops 2
comment Test with localhost sending 30KB every 20 seconds
sendFrequency 20
sendSize 30720
sessionStart 20040409.22:51:10.915
currentTime 20040409.23:31:39.607
numPending 2
lifetimeSent 118
lifetimeRecv 113
#averages minutes sendMs recvMs numLost
periodAverage 1 1843 771 0
periodAverage 5 786 752 1
periodAverage 30 855 735 3
#action status date and time sent sendMs replyMs
EVENT OK 20040409.23:21:44.742 691 670
EVENT OK 20040409.23:22:05.201 671 581
EVENT OK 20040409.23:22:26.301 1182 1452
EVENT OK 20040409.23:22:47.322 24304 1723
EVENT OK 20040409.23:23:08.232 2293 1081
EVENT OK 20040409.23:23:29.332 1392 641
EVENT OK 20040409.23:23:50.262 641 761
EVENT OK 20040409.23:24:11.102 651 701
EVENT OK 20040409.23:24:31.401 841 621
EVENT OK 20040409.23:24:52.061 651 681
EVENT OK 20040409.23:25:12.480 701 1623
EVENT OK 20040409.23:25:32.990 1442 1212
EVENT OK 20040409.23:25:54.230 591 631
EVENT OK 20040409.23:26:14.620 620 691
EVENT OK 20040409.23:26:35.199 1793 1432
EVENT OK 20040409.23:26:56.570 661 641
EVENT OK 20040409.23:27:17.200 641 660
EVENT OK 20040409.23:27:38.120 611 921
EVENT OK 20040409.23:27:58.699 831 621
EVENT OK 20040409.23:28:19.559 801 661
EVENT OK 20040409.23:28:40.279 601 611
EVENT OK 20040409.23:29:00.648 601 621
EVENT OK 20040409.23:29:21.288 701 661
EVENT LOST 20040409.23:29:41.828
EVENT LOST 20040409.23:30:02.327
EVENT LOST 20040409.23:30:22.656
EVENT OK 20040409.23:31:24.305 1843 771
The actual ping and pong messages sent are formatted trivially -
ping messages contain
$from $series $type $sentOn $size $payload
while pong messages contain
$from $series $type $sentOn $receivedOn $size $payload
$series is a number describing the sending client's test (so that you can
ping the same peer with different configurations concurrently, varying things
like the frequency and size of the message, window, etc).
They are sent as raw binary messages though, so see I2PAdapter.sendPing(..)
and I2PAdapter.sendPong(..) for the details.
To get valid measurements, of course, you will want to make sure that
both the heartbeat client and pong server have synchronized clocks (even
more so than I2P requires). It is highly recommended that only NTP
synchronized peers be used for heartbeat tests.

View File

@@ -0,0 +1,66 @@
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="all" name="heartbeat">
<target name="all" depends="clean, buildGUI" />
<target name="build" depends="builddep, jar" />
<target name="buildGUI" depends="build, jarGUI" />
<target name="builddep">
<ant dir="../../../core/java/" target="build" />
</target>
<target name="compile">
<mkdir dir="./build" />
<mkdir dir="./build/obj" />
<javac srcdir="./src" debug="true" destdir="./build/obj" includes="**/*.java" excludes="net/i2p/heartbeat/gui/**" classpath="../../../core/java/build/i2p.jar" />
</target>
<target name="compileGUI">
<mkdir dir="./build" />
<mkdir dir="./build/obj" />
<javac debug="true" destdir="./build/obj">
<src path="src/" />
<classpath path="../../../core/java/build/i2p.jar" />
<classpath path="../../jfreechart/jfreechart-0.9.17/lib/jcommon-0.9.2.jar" />
<classpath path="../../jfreechart/jfreechart-0.9.17/lib/log4j-1.2.8.jar" />
<classpath path="../../jfreechart/jfreechart-0.9.17/jfreechart-0.9.17.jar" />
</javac>
</target>
<target name="jar" depends="compile">
<jar destfile="./build/heartbeat.jar" basedir="./build/obj" includes="**/*.class">
<manifest>
<attribute name="Main-Class" value="net.i2p.heartbeat.Heartbeat" />
<attribute name="Class-Path" value="i2p.jar heartbeat.jar" />
</manifest>
</jar>
</target>
<target name="jarGUI" depends="compileGUI">
<copy file="../../jfreechart/jfreechart-0.9.17/jfreechart-0.9.17.jar" todir="build/" />
<copy file="../../jfreechart/jfreechart-0.9.17/lib/log4j-1.2.8.jar" todir="build/" />
<copy file="../../jfreechart/jfreechart-0.9.17/lib/jcommon-0.9.2.jar" todir="build/" />
<jar destfile="./build/heartbeatGUI.jar" basedir="./build/obj" includes="**">
<manifest>
<attribute name="Main-Class" value="net.i2p.heartbeat.gui.HeartbeatMonitor" />
<attribute name="Class-Path" value="log4j-1.2.8.jar jcommon-0.9.2.jar jfreechart-0.9.17.jar heartbeatGUI.jar i2p.jar" />
</manifest>
</jar>
<echo message="You will need to copy the log4j, jcommon, and jfreechart jar files into your lib dir" />
</target>
<target name="javadoc">
<mkdir dir="./build" />
<mkdir dir="./build/javadoc" />
<javadoc
sourcepath="./src:../../../core/java/src:../../../core/java/test" destdir="./build/javadoc"
packagenames="*"
use="true"
access="package"
splitindex="true"
windowtitle="I2P heartbeat monitor" />
</target>
<target name="clean">
<delete dir="./build" />
</target>
<target name="cleandep" depends="clean">
<ant dir="../../../core/java/" target="cleandep" />
<ant dir="../../../core/java/" target="cleandep" />
</target>
<target name="distclean" depends="clean">
<ant dir="../../../core/java/" target="distclean" />
</target>
</project>

View File

@@ -0,0 +1,468 @@
package net.i2p.heartbeat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;
import net.i2p.data.DataFormatException;
import net.i2p.data.Destination;
import net.i2p.util.Log;
/**
* Define the configuration for testing against one particular peer as a client
*/
public class ClientConfig {
private static final Log _log = new Log(ClientConfig.class);
private Destination _peer;
private Destination _us;
private String _statFile;
private int _statDuration;
private int _statFrequency;
private int _sendFrequency;
private int _sendSize;
private int _numHops;
private String _comment;
private int _averagePeriods[];
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_PREFIX = "peer.";
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_PEER = ".peer";
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_STATFILE = ".statFile";
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_STATDURATION = ".statDuration";
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_STATFREQUENCY = ".statFrequency";
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_SENDFREQUENCY = ".sendFrequency";
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_SENDSIZE = ".sendSize";
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_COMMENT = ".comment";
/**
* @seeRoutine ClientConfig#load
* @seeRoutine ClientConfig#store
*/
public static final String PROP_AVERAGEPERIODS = ".averagePeriods";
/**
* Default constructor...
*/
public ClientConfig() {
this(null, null, null, -1, -1, -1, -1, 0, null, null);
}
/**
* Create a dummy client config to be fetched from the specified location
* @param location the location to fetch from
*/
public ClientConfig(String location) {
this(null, null, location, -1, -1, -1, -1, 0, null, null);
}
/**
* @param peer who we will test against
* @param us who we are
* @param statLocation where the stat data should be stored/fetched
* @param duration how many minutes to keep events for
* @param statFreq how often to write out stats
* @param sendFreq how often to send pings
* @param sendSize how large the pings should be
* @param numHops how many hops is the current Heartbeat app using
* @param comment describe this test
* @param averagePeriods list of minutes to summarize over
*/
public ClientConfig(Destination peer, Destination us, String statLocation, int duration, int statFreq, int sendFreq,
int sendSize, int numHops, String comment, int averagePeriods[]) {
_peer = peer;
_us = us;
_statFile = statLocation;
_statDuration = duration;
_statFrequency = statFreq;
_sendFrequency = sendFreq;
_sendSize = sendSize;
_numHops = numHops;
_comment = comment;
_averagePeriods = averagePeriods;
}
/**
* Retrieves the peer to test against
*
* @return the Destination (peer)
*/
public Destination getPeer() {
return _peer;
}
/**
* Sets the peer to test against
*
* @param peer the Destination (peer)
*/
public void setPeer(Destination peer) {
_peer = peer;
}
/**
* Retrieves who we are when we test
*
* @return the Destination (us)
*/
public Destination getUs() {
return _us;
}
/**
* Sets who we are when we test
*
* @param us the Destination (us)
*/
public void setUs(Destination us) {
_us = us;
}
/**
* Retrieves the location to write the current stats to
*
* @return the name of the file
*/
public String getStatFile() {
return _statFile;
}
/**
* Sets the name of the location we write the current stats to
*
* @param statFile the name of the file
*/
public void setStatFile(String statFile) {
_statFile = statFile;
}
/**
* Retrieves how many minutes of statistics should be maintained within the window for this client
*
* @return the number of minutes
*/
public int getStatDuration() {
return _statDuration;
}
/**
* Sets how many minutes of statistics should be maintained within the window for this client
*
* @param durationMinutes the number of minutes
*/
public void setStatDuration(int durationMinutes) {
_statDuration = durationMinutes;
}
/**
* Retrieves how frequently the stats are written out (in seconds)
*
* @return the frequency in seconds
*/
public int getStatFrequency() {
return _statFrequency;
}
/**
* Sets how frequently the stats are written out (in seconds)
*
* @param freqSeconds the frequency in seconds
*/
public void setStatFrequency(int freqSeconds) {
_statFrequency = freqSeconds;
}
/**
* Retrieves how frequenty we send messages to the peer (in seconds)
*
* @return the frequency in seconds
*/
public int getSendFrequency() {
return _sendFrequency;
}
/**
* Sets how frequenty we send messages to the peer (in seconds)
*
* @param freqSeconds the frequency in seconds
*/
public void setSendFrequency(int freqSeconds) {
_sendFrequency = freqSeconds;
}
/**
* Retrieves how many bytes the ping messages should be (min values ~700, max ~32KB)
*
* @return the size in bytes
*/
public int getSendSize() {
return _sendSize;
}
/**
* Sets how many bytes the ping messages should be (min values ~700, max ~32KB)
*
* @param numBytes the size in bytes
*/
public void setSendSize(int numBytes) {
_sendSize = numBytes;
}
/**
* Retrieves the brief, 1 line description of the test. Useful comments are along the lines of "The peer is located on a fast router and connection with 2
* hop tunnels".
*
* @return the brief comment
*/
public String getComment() {
return _comment;
}
/**
* Sets a brief, 1 line description (comment) of the test.
*
* @param comment the brief comment
*/
public void setComment(String comment) {
_comment = comment;
}
/**
* Retrieves the periods that the client's tests should be averaged over.
*
* @return list of periods (in minutes) that the data should be averaged over, or null
*/
public int[] getAveragePeriods() {
return _averagePeriods;
}
/**
* Sets the periods that the client's tests should be averaged over.
*
* @param periods the list of periods (in minutes) that the data should be averaged over, or null
*/
public void setAveragePeriods(int periods[]) {
_averagePeriods = periods;
}
/**
* Make sure we're keeping track of the average over the given time period.
*
* @param minutes how many minutes to monitor
*/
public void addAveragePeriod(int minutes) {
if (_averagePeriods != null) {
for (int i = 0; i < _averagePeriods.length; i++) {
if (_averagePeriods[i] == minutes)
return;
}
}
int numPeriods = 1;
if (_averagePeriods != null)
numPeriods += _averagePeriods.length;
int periods[] = new int[numPeriods];
if (_averagePeriods != null)
System.arraycopy(_averagePeriods, 0, periods, 0, _averagePeriods.length);
periods[periods.length-1] = minutes;
Arrays.sort(periods);
_averagePeriods = periods;
}
/**
* Retrieves how many hops this test engine is configured to use for its outbound and inbound tunnels
*
* @return the number of hops
*/
public int getNumHops() {
return _numHops;
}
/**
* Sets how many hops this test engine is configured to use for its outbound and inbound tunnels
*
* @param numHops the number of hops
*/
public void setNumHops(int numHops) {
_numHops = numHops;
}
/**
* Load the client config from the properties specified, deriving the current config entry from the peer number.
*
* @param clientConfig the properties to load from
* @param peerNum the number associated with the peer
* @return true if it was loaded correctly, false if there were errors
*/
public boolean load(Properties clientConfig, int peerNum) {
if ((clientConfig == null) || (peerNum < 0)) return false;
String peerVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_PEER);
String statFileVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_STATFILE);
String statDurationVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_STATDURATION);
String statFrequencyVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_STATFREQUENCY);
String sendFrequencyVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_SENDFREQUENCY);
String sendSizeVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_SENDSIZE);
String commentVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_COMMENT);
String periodsVal = clientConfig.getProperty(PROP_PREFIX + peerNum + PROP_AVERAGEPERIODS);
if ((peerVal == null) || (statFileVal == null) || (statDurationVal == null) || (statFrequencyVal == null)
|| (sendFrequencyVal == null) || (sendSizeVal == null)) {
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Peer number " + peerNum + " does not exist");
}
return false;
}
try {
int duration = getInt(statDurationVal);
int statFreq = getInt(statFrequencyVal);
int sendFreq = getInt(sendFrequencyVal);
int sendSize = getInt(sendSizeVal);
if ((duration <= 0) || (statFreq <= 0) || (sendFreq <= 0) || (sendSize <= 0)) {
if (_log.shouldLog(Log.WARN)) {
_log.warn("Invalid client config: duration [" + statDurationVal + "] stat frequency ["
+ statFrequencyVal + "] send frequency [" + sendFrequencyVal + "] send size ["
+ sendSizeVal + "]");
}
return false;
}
statFileVal = statFileVal.trim();
if (statFileVal.length() <= 0) {
if (_log.shouldLog(Log.WARN)) {
_log.warn("Stat file is blank for peer " + peerNum);
}
return false;
}
Destination d = new Destination();
d.fromBase64(peerVal);
if (commentVal == null) {
commentVal = "";
}
commentVal = commentVal.trim();
commentVal = commentVal.replace('\n', '_');
List periods = new ArrayList(4);
if (periodsVal != null) {
StringTokenizer tok = new StringTokenizer(periodsVal);
while (tok.hasMoreTokens()) {
String periodVal = tok.nextToken();
int minutes = getInt(periodVal);
if (minutes > 0) {
periods.add(new Integer(minutes));
}
}
}
int avgPeriods[] = new int[periods.size()];
for (int i = 0; i < periods.size(); i++) {
avgPeriods[i] = ((Integer) periods.get(i)).intValue();
}
_comment = commentVal;
_statDuration = duration;
_statFrequency = statFreq;
_sendFrequency = sendFreq;
_sendSize = sendSize;
_statFile = statFileVal;
_peer = d;
_averagePeriods = avgPeriods;
return true;
} catch (DataFormatException dfe) {
_log.error("Peer destination for " + peerNum + " was invalid: " + peerVal);
return false;
}
}
/**
* Store the client config to the properties specified, deriving the current config entry from the peer number.
*
* @param clientConfig the properties to store to
* @param peerNum the number associated with the peer
* @return true if it was stored correctly, false if there were errors
*/
public boolean store(Properties clientConfig, int peerNum) {
if ((_peer == null) || (_sendFrequency <= 0) || (_sendSize <= 0) || (_statDuration <= 0)
|| (_statFrequency <= 0) || (_statFile == null)) { return false; }
String comment = _comment;
if (comment == null) {
comment = "";
}
comment = comment.trim();
comment = comment.replace('\n', '_');
StringBuffer buf = new StringBuffer(32);
if (_averagePeriods != null) {
for (int i = 0; i < _averagePeriods.length; i++) {
buf.append(_averagePeriods[i]).append(' ');
}
}
clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_PEER, _peer.toBase64());
clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_STATFILE, _statFile);
clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_STATDURATION, _statDuration + "");
clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_STATFREQUENCY, _statFrequency + "");
clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_SENDFREQUENCY, _sendFrequency + "");
clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_SENDSIZE, _sendSize + "");
clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_COMMENT, comment);
clientConfig.setProperty(PROP_PREFIX + peerNum + PROP_AVERAGEPERIODS, buf.toString());
return true;
}
private static final int getInt(String val) {
if (val == null) return -1;
try {
int i = Integer.parseInt(val);
return i;
} catch (NumberFormatException nfe) {
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Value [" + val + "] is not a valid integer");
}
return -1;
}
}
}

View File

@@ -0,0 +1,130 @@
package net.i2p.heartbeat;
import net.i2p.data.Destination;
import net.i2p.util.Clock;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
/**
* Responsible for actually conducting the tests, coordinating the storing of the
* stats, and the management of the rates. This has its own thread specific for
* pumping data around as well.
*
*/
class ClientEngine {
private static final Log _log = new Log(ClientEngine.class);
/** who can send our pings? */
private Heartbeat _heartbeat;
/** actual test state */
private PeerData _data;
/** have we been stopped? */
private boolean _active;
/** used to generate engine IDs */
private static int __id = 0;
/** this engine's id, unique to the {test,sendingClient,startTime} */
private int _id;
private static PeerDataWriter writer = new PeerDataWriter();
/**
* Create a new engine that will send its pings through the given heartbeat
* system, and will coordinate the test according to the configuration specified.
* @param heartbeat the Heartbeat to send pings through
* @param config the Configuration to load configuration from =p
*/
public ClientEngine(Heartbeat heartbeat, ClientConfig config) {
_heartbeat = heartbeat;
_data = new PeerData(config);
_active = false;
_id = ++__id;
}
/** stop sending any more pings or writing any more state */
public void stopEngine() {
_active = false;
if (_log.shouldLog(Log.INFO))
_log.info("Stopping engine talking to peer " + _data.getConfig().getPeer().calculateHash().toBase64());
}
/** start up the test (this does not block, as it fires up the test thread) */
public void startEngine() {
_active = true;
I2PThread t = new I2PThread(new ClientRunner());
t.setName("HeartbeatClient " + _id);
t.start();
}
/**
* Who are we testing?
* @return the Destination (peer) we're testing
*/
public Destination getPeer() {
return _data.getConfig().getPeer();
}
/**
* What is our series identifier (used to locally identify a test)
* @return the series identifier
*/
public int getSeriesNum() {
return _id;
}
/**
* receive notification from the heartbeat system that a pong was received in
* reply to a ping we have sent.
*
* @param sentOn when did we send the ping?
* @param replyOn when did the peer send the pong?
*/
public void receivePong(long sentOn, long replyOn) {
_data.pongReceived(sentOn, replyOn);
}
/** fire off a new ping */
private void doSend() {
long now = Clock.getInstance().now();
_data.addPing(now);
_heartbeat.sendPing(_data.getConfig().getPeer(), _id, now, _data.getConfig().getSendSize());
}
/** our actual heartbeat pumper - this drives the test */
private class ClientRunner implements Runnable {
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
if (_log.shouldLog(Log.INFO))
_log.info("Starting engine talking to peer " + _data.getConfig().getPeer().calculateHash().toBase64());
// when do we need to send the next PING?
long nextSend = Clock.getInstance().now();
// when do we need to write out the next state data?
long nextWrite = Clock.getInstance().now();
while (_active) {
if (Clock.getInstance().now() >= nextSend) {
doSend();
nextSend = Clock.getInstance().now() + _data.getConfig().getSendFrequency() * 1000;
}
if (Clock.getInstance().now() >= nextWrite) {
boolean written = writer.persist(_data);
if (!written) {
if (_log.shouldLog(Log.ERROR)) _log.error("Unable to write the client state data");
} else {
if (_log.shouldLog(Log.DEBUG)) _log.debug("Client state data written");
}
}
_data.cleanup();
try {
Thread.sleep(1000);
} catch (InterruptedException ie) {
}
}
}
}
}

View File

@@ -0,0 +1,254 @@
package net.i2p.heartbeat;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Properties;
import net.i2p.data.Destination;
import net.i2p.util.Log;
/**
* Main driver for the heartbeat engine, loading 0 or more tests, firing
* up a ClientEngine for each, and serving as a pong server. If there isn't
* a configuration file, or if the configuration file doesn't specify any tests,
* it simply sits around as a pong server, passively responding to whatever is
* sent its way. <p />
*
* The config file format is examplified below:
* <pre>
* # where the router is located (default is localhost)
* i2cpHost=localhost
* # I2CP port for the router (default is 7654)
* i2cpPort=4001
* # How many hops we want the router to put in our tunnels (default is 2)
* numHops=2
* # where our private destination keys are located - if this doesn't exist,
* # a new one will be created and saved there (by default, heartbeat.keys)
* privateDestinationFile=heartbeat_r2.keys
* # where do we want to export the plain base64 of our destination?
* publicDestinationFile=heartbeat_r2.txt
*
* ## peer tests configured below:
*
* # destination peer for test 0
* peer.0.peer=[destination in base64]
* # where will we write out the stat data?
* peer.0.statFile=heartbeatStat_khWY_30s_1kb.txt
* # how many minutes will we keep stats for?
* peer.0.statDuration=30
* # how often will we write out new stat data (in seconds)?
* peer.0.statFrequency=60
* # how often will we send a ping to the peer (in seconds)?
* peer.0.sendFrequency=30
* # how many bytes will be included in the ping?
* peer.0.sendSize=1024
* # take a guess...
* peer.0.comment=Test with localhost sending 1KB of data every 30 seconds
* # we can keep track of a few moving averages - this value includes a whitespace
* # delimited list of numbers, each specifying a period to calculate the average
* # over (in minutes)
* peer.0.averagePeriods=1 5 30
* ## repeat the peer.0.* for as many tests as desired, incrementing as necessary
* </pre>
*
*/
public class Heartbeat {
private static final Log _log = new Log(Heartbeat.class);
/** location containing this heartbeat's config */
private String _configFile;
/** clientNum (Integer) to ClientConfig mapping */
private Map _clientConfigs;
/** series num (Integer) to ClientEngine mapping */
private Map _clientEngines;
/** helper class for managing our I2P send/receive and message formatting */
private I2PAdapter _adapter;
/** our own callback that the I2PAdapter notifies on ping or pong messages */
private PingPongAdapter _eventAdapter;
/** if there are no command line arguments, load the config from "heartbeat.config" */
public static final String CONFIG_FILE_DEFAULT = "heartbeat.config";
/**
* build up a new heartbeat manager, but don't actually do anything
* @param configFile the name of the configuration file
*/
public Heartbeat(String configFile) {
_configFile = configFile;
_clientConfigs = new HashMap();
_clientEngines = new HashMap();
_eventAdapter = new PingPongAdapter();
_adapter = new I2PAdapter();
_adapter.setListener(_eventAdapter);
}
private Heartbeat() {
}
/** load up the config data (but don't build any engines or start them up) */
public void loadConfig() {
Properties props = new Properties();
FileInputStream fin = null;
File configFile = new File(_configFile);
if (configFile.exists()) {
try {
fin = new FileInputStream(_configFile);
props.load(fin);
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error reading the config data", ioe);
}
} finally {
if (fin != null) try {
fin.close();
} catch (IOException ioe) {
}
}
}
loadBaseConfig(props);
loadClientConfigs(props);
}
/**
* send a ping message to the peer
*
* @param peer peer to ping
* @param seriesNum id used to keep track of multiple pings (of different size/frequency) to a peer
* @param now current time to be sent in the ping (so we can watch for it in the pong)
* @param size total message size to send
*/
void sendPing(Destination peer, int seriesNum, long now, int size) {
if (_adapter.getIsConnected()) _adapter.sendPing(peer, seriesNum, now, size);
}
/**
* load up the base data (I2CP config, etc)
* @param props the properties to load from
*/
private void loadBaseConfig(Properties props) {
_adapter.loadConfig(props);
}
/**
* load up all of the test config data
* @param props the properties to load from
* */
private void loadClientConfigs(Properties props) {
int i = 0;
while (true) {
ClientConfig config = new ClientConfig();
if (!config.load(props, i)) {
break;
}
_clientConfigs.put(new Integer(i), config);
i++;
}
}
/** connect to the network */
private void connect() {
boolean connected = _adapter.connect();
if (!connected) _log.error("Unable to connect to the router");
}
/** disconnect from the network */
private void disconnect() {
_adapter.disconnect();
}
/** start up all of the tests */
public void startEngines() {
for (Iterator iter = _clientConfigs.values().iterator(); iter.hasNext();) {
ClientConfig config = (ClientConfig) iter.next();
ClientEngine engine = new ClientEngine(this, config);
config.setUs(_adapter.getLocalDestination());
config.setNumHops(_adapter.getNumHops());
_clientEngines.put(new Integer(engine.getSeriesNum()), engine);
engine.startEngine();
}
}
/** stop all of the tests */
public void stopEngines() {
for (Iterator iter = _clientEngines.values().iterator(); iter.hasNext();) {
ClientEngine engine = (ClientEngine) iter.next();
engine.stopEngine();
}
_clientEngines.clear();
}
/**
* Fire up a new heartbeat system, waiting until, well, forever. Builds
* a new heartbeat system, loads the config, connects to the network, starts
* the engines, and then sits back and relaxes, responding to any pings and
* running any tests. <p />
*
* <code> <b>Usage: </b> Heartbeat [<i>configFileName</i>]</code> <p />
* @param args the list of args passed to the program from the command-line
*/
public static void main(String args[]) {
String configFile = CONFIG_FILE_DEFAULT;
if (args.length == 1) {
configFile = args[0];
}
if (_log.shouldLog(Log.INFO)) {
_log.info("Starting up with config file " + configFile);
}
Heartbeat heartbeat = new Heartbeat(configFile);
heartbeat.loadConfig();
heartbeat.connect();
heartbeat.startEngines();
Object o = new Object();
while (true) {
try {
synchronized (o) {
o.wait();
}
} catch (InterruptedException ie) {
}
}
}
/**
* Receive event notification from the I2PAdapter
*
*/
private class PingPongAdapter implements I2PAdapter.PingPongEventListener {
/**
* We were pinged, so always just send a pong back.
*
* @param from who sent us the ping?
* @param seriesNum what series did the sender specify?
* @param sentOn when did the sender say they sent their ping?
* @param data arbitrary payload data
*/
public void receivePing(Destination from, int seriesNum, Date sentOn, byte[] data) {
if (_adapter.getIsConnected()) {
_adapter.sendPong(from, seriesNum, sentOn, data);
}
}
/**
* We received a pong, so find the right client engine and tell it about the pong.
*
* @param from who sent us the pong
* @param seriesNum our client ID
* @param sentOn when did we send the ping?
* @param replyOn when did they send their pong?
* @param data the arbitrary data we sent in the ping (that they sent back in the pong)
*/
public void receivePong(Destination from, int seriesNum, Date sentOn, Date replyOn, byte[] data) {
ClientEngine engine = (ClientEngine) _clientEngines.get(new Integer(seriesNum));
if (engine.getPeer().equals(from)) {
engine.receivePong(sentOn.getTime(), replyOn.getTime());
}
}
}
}

View File

@@ -0,0 +1,603 @@
package net.i2p.heartbeat;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Arrays;
import java.util.Date;
import java.util.Properties;
import net.i2p.I2PException;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.I2PSession;
import net.i2p.client.I2PSessionException;
import net.i2p.client.I2PSessionListener;
import net.i2p.data.DataFormatException;
import net.i2p.data.DataHelper;
import net.i2p.data.Destination;
import net.i2p.util.Clock;
import net.i2p.util.Log;
/**
* Tie-in to the I2P SDK for the Heartbeat system, talking to the I2PSession and
* dealing with the raw ping and pong messages.
*
*/
class I2PAdapter {
private final static Log _log = new Log(I2PAdapter.class);
/** I2CP host */
private String _i2cpHost;
/** I2CP port */
private int _i2cpPort;
/** how long do we want our tunnels to be? */
private int _numHops;
/** filename containing the heartbeat engine's private destination info */
private String _privateDestFile;
/** filename to store the heartbeat engine's public destination in base64*/
private String _publicDestFile;
/** our destination */
private Destination _localDest;
/** who do we tell? */
private PingPongEventListener _listener;
/** how do we talk to the router */
private I2PSession _session;
/** object that receives our i2cp notifications from the session and tells us */
private I2PListener _i2pListener;
/**
* This config property tells us where the private destination data for our
* connection (or if it doesn't exist, where will we save it)
*/
private static final String DEST_FILE_PROP = "privateDestinationFile";
/** by default, the private destination data is in "heartbeat.keys" */
private static final String DEST_FILE_DEFAULT = "heartbeat.keys";
/** where will we export the public destination in base 64? */
private static final String PUBLIC_DEST_FILE_PROP = "publicDestinationFile";
/** where will we export the public destination in base 64? */
private static final String PUBLIC_DEST_FILE_DEFAULT = "heartbeat.txt";
/** This config property defines where the I2P router is */
private static final String I2CP_HOST_PROP = "i2cpHost";
/** by default, the I2P host is "localhost" */
private static final String I2CP_HOST_DEFAULT = "localhost";
/** This config property defines the I2CP port on the router */
private static final String I2CP_PORT_PROP = "i2cpPort";
/** by default, the I2CP port is 7654 */
private static final int I2CP_PORT_DEFAULT = 7654;
/** This property defines how many hops we want in our tunnels. */
public static final String NUMHOPS_PROP = "numHops";
/** by default, use 2 hop tunnels */
public static final int NUMHOPS_DEFAULT = 2;
/**
* Constructs an I2PAdapter . . .
*/
public I2PAdapter() {
_privateDestFile = null;
_publicDestFile = null;
_i2cpHost = null;
_i2cpPort = -1;
_localDest = null;
_listener = null;
_session = null;
_numHops = 0;
}
/**
* who are we?
* @return the destination (us)
*/
public Destination getLocalDestination() {
return _localDest;
}
/**
* who gets notified when we receive a ping or a pong?
* @return the event listener who gets notified
*/
public PingPongEventListener getListener() {
return _listener;
}
/**
* Sets who gets notified when we receive a ping or a pong
* @param listener the event listener to get notified
*/
public void setListener(PingPongEventListener listener) {
_listener = listener;
}
/**
* how many hops do we want in our tunnels?
* @return the number of hops
*/
public int getNumHops() {
return _numHops;
}
/**
* are we connected?
* @return true or false . . .
*/
public boolean getIsConnected() {
return _session != null;
}
/**
* Read in all of the config data
* @param props the properties to load from
*/
void loadConfig(Properties props) {
String privDestFile = props.getProperty(DEST_FILE_PROP, DEST_FILE_DEFAULT);
String pubDestFile = props.getProperty(PUBLIC_DEST_FILE_PROP, PUBLIC_DEST_FILE_DEFAULT);
String host = props.getProperty(I2CP_HOST_PROP, I2CP_HOST_DEFAULT);
String port = props.getProperty(I2CP_PORT_PROP, "" + I2CP_PORT_DEFAULT);
String numHops = props.getProperty(NUMHOPS_PROP, "" + NUMHOPS_DEFAULT);
int portNum = -1;
try {
portNum = Integer.parseInt(port);
} catch (NumberFormatException nfe) {
if (_log.shouldLog(Log.WARN)) {
_log.warn("Invalid I2CP port specified [" + port + "]");
}
portNum = I2CP_PORT_DEFAULT;
}
int hops = -1;
try {
hops = Integer.parseInt(numHops);
} catch (NumberFormatException nfe) {
if (_log.shouldLog(Log.WARN)) {
_log.warn("Invalid # hops specified [" + numHops + "]");
}
hops = NUMHOPS_DEFAULT;
}
_numHops = hops;
_privateDestFile = privDestFile;
_publicDestFile = pubDestFile;
_i2cpHost = host;
_i2cpPort = portNum;
}
/**
* write out the config to the props
* @param props the properties to write to
*/
void storeConfig(Properties props) {
if (_privateDestFile != null) {
props.setProperty(DEST_FILE_PROP, _privateDestFile);
} else {
props.setProperty(DEST_FILE_PROP, DEST_FILE_DEFAULT);
}
if (_publicDestFile != null) {
props.setProperty(PUBLIC_DEST_FILE_PROP, _publicDestFile);
} else {
props.setProperty(PUBLIC_DEST_FILE_PROP, PUBLIC_DEST_FILE_DEFAULT);
}
if (_i2cpHost != null) {
props.setProperty(I2CP_HOST_PROP, _i2cpHost);
} else {
props.setProperty(I2CP_HOST_PROP, I2CP_HOST_DEFAULT);
}
if (_i2cpPort > 0) {
props.setProperty(I2CP_PORT_PROP, "" + _i2cpPort);
} else {
props.setProperty(I2CP_PORT_PROP, "" + I2CP_PORT_DEFAULT);
}
props.setProperty(NUMHOPS_PROP, "" + _numHops);
}
private static final int TYPE_PING = 0;
private static final int TYPE_PONG = 1;
/**
* send a ping message to the peer
*
* @param peer peer to ping
* @param seriesNum id used to keep track of multiple pings (of different size/frequency) to a peer
* @param now current time to be sent in the ping (so we can watch for it in the pong)
* @param size total message size to send
*
* @throws IllegalStateException if we are not connected to the router
*/
public void sendPing(Destination peer, int seriesNum, long now, int size) {
if (_session == null) throw new IllegalStateException("Not connected to the router");
ByteArrayOutputStream baos = new ByteArrayOutputStream(size);
try {
_localDest.writeBytes(baos);
DataHelper.writeLong(baos, 2, seriesNum);
DataHelper.writeLong(baos, 1, TYPE_PING);
DataHelper.writeDate(baos, new Date(now));
int padding = size - baos.size();
byte paddingData[] = new byte[padding];
Arrays.fill(paddingData, (byte) 0x2A);
DataHelper.writeLong(baos, 2, padding);
baos.write(paddingData);
boolean sent = _session.sendMessage(peer, baos.toByteArray());
if (!sent) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error sending the ping to " + peer.calculateHash().toBase64() + " for series "
+ seriesNum);
}
} else {
if (_log.shouldLog(Log.INFO)) {
_log.info("Ping sent to " + peer.calculateHash().toBase64() + " for series " + seriesNum);
}
}
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error sending the ping", ioe);
}
} catch (DataFormatException dfe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error writing out the ping message", dfe);
}
} catch (I2PSessionException ise) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error writing out the ping message", ise);
}
}
}
/**
* send a pong message to the peer
*
* @param peer peer to pong
* @param seriesNum id given to us in the ping
* @param sentOn date the peer said they sent us the message
* @param data payload the peer sent us in the ping
*
* @throws IllegalStateException if we are not connected to the router
*/
public void sendPong(Destination peer, int seriesNum, Date sentOn, byte data[]) {
if (_session == null) throw new IllegalStateException("Not connected to the router");
ByteArrayOutputStream baos = new ByteArrayOutputStream(data.length + 768);
try {
_localDest.writeBytes(baos);
DataHelper.writeLong(baos, 2, seriesNum);
DataHelper.writeLong(baos, 1, TYPE_PONG);
DataHelper.writeDate(baos, sentOn);
DataHelper.writeDate(baos, new Date(Clock.getInstance().now()));
DataHelper.writeLong(baos, 2, data.length);
baos.write(data);
boolean sent = _session.sendMessage(peer, baos.toByteArray());
if (!sent) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error sending the pong to " + peer.calculateHash().toBase64() + " for series "
+ seriesNum + " which was sent on " + sentOn);
}
} else {
if (_log.shouldLog(Log.INFO)) {
_log.info("Pong sent to " + peer.calculateHash().toBase64() + " for series " + seriesNum
+ " which was sent on " + sentOn);
}
}
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error sending the ping", ioe);
}
} catch (DataFormatException dfe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error writing out the pong message", dfe);
}
} catch (I2PSessionException ise) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error writing out the pong message", ise);
}
}
}
/**
* We've received this data from I2P - parse it into a ping or a pong
* and notify accordingly
* @param data the data to handle
*/
private void handleMessage(byte data[]) {
ByteArrayInputStream bais = new ByteArrayInputStream(data);
try {
Destination from = new Destination();
from.readBytes(bais);
int series = (int) DataHelper.readLong(bais, 2);
long type = DataHelper.readLong(bais, 1);
Date sentOn = DataHelper.readDate(bais);
Date receivedOn = null;
if (type == TYPE_PONG) {
receivedOn = DataHelper.readDate(bais);
}
int size = (int) DataHelper.readLong(bais, 2);
byte payload[] = new byte[size];
int read = DataHelper.read(bais, payload);
if (read != size) { throw new IOException("Malformed payload - read " + read + " instead of " + size); }
if (_listener == null) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Listener isn't set, but we received a valid message of type " + type + " sent from "
+ from.calculateHash().toBase64());
}
return;
}
if (type == TYPE_PING) {
if (_log.shouldLog(Log.INFO)) {
_log.info("Ping received from " + from.calculateHash().toBase64() + " on series " + series
+ " sent on " + sentOn + " containing " + size + " bytes");
}
_listener.receivePing(from, series, sentOn, payload);
} else if (type == TYPE_PONG) {
if (_log.shouldLog(Log.INFO)) {
_log.info("Pong received from " + from.calculateHash().toBase64() + " on series " + series
+ " sent on " + sentOn + " with pong sent on " + receivedOn + " containing " + size
+ " bytes");
}
_listener.receivePong(from, series, sentOn, receivedOn, payload);
} else {
throw new IOException("Invalid message type " + type);
}
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error handling the message", ioe);
}
} catch (DataFormatException dfe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error parsing the message", dfe);
}
}
}
/**
* connect to the I2P router and either authenticate ourselves with the
* destination we're given, or create a new one and write that to the
* destination file.
*
* @return true if we connect successfully, false otherwise
*/
boolean connect() {
I2PClient client = I2PClientFactory.createClient();
Destination us = null;
File destFile = new File(_privateDestFile);
us = verifyDestination(client, destFile);
if (us == null) return false;
// if we're here, we got a destination. lets connect
FileInputStream fin = null;
try {
fin = new FileInputStream(destFile);
Properties options = getOptions();
I2PSession session = client.createSession(fin, options);
I2PListener lsnr = new I2PListener();
session.setSessionListener(lsnr);
session.connect();
_localDest = session.getMyDestination();
if (_log.shouldLog(Log.INFO)) {
_log.info("I2CP Session created and connected as " + _localDest.calculateHash().toBase64());
}
_session = session;
_i2pListener = lsnr;
} catch (I2PSessionException ise) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error connecting", ise);
}
return false;
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error loading the destionation", ioe);
}
return false;
} finally {
if (fin != null) try {
fin.close();
} catch (IOException ioe) {
}
}
return true;
}
/**
* load, verify, or create a destination
*
* @param client the client
* @param destFile the file holding the destination
* @return the destination loaded, or null if there was an error
*/
private Destination verifyDestination(I2PClient client, File destFile) {
Destination us = null;
FileInputStream fin = null;
if (destFile.exists()) {
try {
fin = new FileInputStream(destFile);
us = new Destination();
us.readBytes(fin);
if (_log.shouldLog(Log.INFO)) {
_log.info("Existing destination loaded: [" + us.toBase64() + "]");
}
FileOutputStream fos = null;
try {
fos = new FileOutputStream(_publicDestFile);
fos.write(us.toBase64().getBytes());
fos.flush();
} catch (IOException fioe) {
_log.error("Error writing out the plain destination to [" + _publicDestFile + "]", fioe);
} finally {
if (fos != null) try { fos.close(); } catch (IOException fioe) {}
}
} catch (IOException ioe) {
if (fin != null) try {
fin.close();
} catch (IOException ioe2) {
}
fin = null;
destFile.delete();
us = null;
} catch (DataFormatException dfe) {
if (fin != null) try {
fin.close();
} catch (IOException ioe2) {
}
fin = null;
destFile.delete();
us = null;
} finally {
if (fin != null) try {
fin.close();
} catch (IOException ioe2) {
}
fin = null;
}
}
if (us == null) {
// need to create a new one
FileOutputStream fos = null;
try {
fos = new FileOutputStream(destFile);
us = client.createDestination(fos);
if (_log.shouldLog(Log.INFO)) {
_log.info("New destination created: [" + us.toBase64() + "]");
}
fos.close();
try {
fos = new FileOutputStream(_publicDestFile);
fos.write(us.toBase64().getBytes());
fos.flush();
} catch (IOException fioe) {
_log.error("Error writing out the plain destination to [" + _publicDestFile + "]", fioe);
} finally {
if (fos != null) try { fos.close(); } catch (IOException fioe) {}
fos = null;
}
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error writing out the destination keys being created", ioe);
}
return null;
} catch (I2PException ie) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error creating the destination", ie);
}
return null;
} finally {
if (fos != null) try {
fos.close();
} catch (IOException ioe) {
}
}
}
return us;
}
/**
* I2PSession connect options
* @return the options as Properties
*/
private Properties getOptions() {
Properties props = new Properties();
// this should be BEST_EFFORT, but i'm too lazy to update the code to handle tracking
// sessionTags and sessionKeys, marking them as delivered on pong.
props.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_GUARANTEED);
props.setProperty(I2PClient.PROP_TCP_HOST, _i2cpHost);
props.setProperty(I2PClient.PROP_TCP_PORT, _i2cpPort + "");
props.setProperty("tunnels.depthInbound", "" + _numHops);
props.setProperty("tunnels.depthOutbound", "" + _numHops);
return props;
}
/** disconnect from the I2P router */
void disconnect() {
if (_session != null) {
try {
_session.destroySession();
} catch (I2PSessionException ise) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Error destroying the session", ise);
}
}
_session = null;
}
}
/**
* Defines an event notification system for receiving pings and pongs
*
*/
public interface PingPongEventListener {
/**
* receive a ping message from the peer
*
* @param from peer that sent us the ping
* @param seriesNum id the peer sent us in the ping
* @param sentOn date the peer said they sent us the message
* @param data payload from the ping
*/
void receivePing(Destination from, int seriesNum, Date sentOn, byte data[]);
/**
* receive a pong message from the peer
*
* @param from peer that sent us the pong
* @param seriesNum id the peer sent us in the pong (that we sent them in the ping)
* @param sentOn when we sent out the ping
* @param replyOn when they sent out the pong
* @param data payload from the ping/pong
*/
void receivePong(Destination from, int seriesNum, Date sentOn, Date replyOn, byte data[]);
}
/**
* Receive data from the session and pass it along to handleMessage for parsing/dispersal
*
*/
private class I2PListener implements I2PSessionListener {
/* (non-Javadoc)
* @see net.i2p.client.I2PSessionListener#disconnected(net.i2p.client.I2PSession)
*/
public void disconnected(I2PSession session) {
if (_log.shouldLog(Log.ERROR)) {
_log.error("Session disconnected");
}
disconnect();
}
/* (non-Javadoc)
* @see net.i2p.client.I2PSessionListener#errorOccurred(net.i2p.client.I2PSession, java.lang.String, java.lang.Throwable)
*/
public void errorOccurred(I2PSession session, String message, Throwable error) {
if (_log.shouldLog(Log.ERROR)) _log.error("Error occurred", error);
}
/* (non-Javadoc)
* @see net.i2p.client.I2PSessionListener#reportAbuse(net.i2p.client.I2PSession, int)
*/
public void reportAbuse(I2PSession session, int severity) {
if (_log.shouldLog(Log.ERROR)) _log.error("Abuse reported");
}
/* (non-Javadoc)
* @see net.i2p.client.I2PSessionListener#messageAvailable(net.i2p.client.I2PSession, int, long)
*/
public void messageAvailable(I2PSession session, int msgId, long size) {
try {
byte data[] = session.receiveMessage(msgId);
handleMessage(data);
} catch (I2PSessionException ise) {
if (_log.shouldLog(Log.ERROR)) _log.error("Error receiving the message", ise);
disconnect();
}
}
}
}

View File

@@ -0,0 +1,384 @@
package net.i2p.heartbeat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.HashSet;
import java.util.Map;
import java.util.TreeMap;
import net.i2p.stat.Rate;
import net.i2p.stat.RateStat;
import net.i2p.util.Clock;
import net.i2p.util.Log;
/**
* Contain the current window of data for a particular series of ping/pong stats
* sent to a peer. This should be periodically kept clean by calling cleanup()
* to timeout expired pings and to drop data outside the window.
*
*/
public class PeerData {
private final static Log _log = new Log(PeerData.class);
/** peer / sequence / config in this data series */
private ClientConfig _peer;
/** date sent (Long) to EventDataPoint containing the datapoints sent in the current period */
private Map _dataPoints;
/** date sent (Long) to EventDataPoint containing pings that haven't yet timed out or been ponged */
private Map _pendingPings;
private long _sessionStart;
private long _lifetimeSent;
private long _lifetimeReceived;
/** rate averaging the time to send over a variety of periods */
private RateStat _sendRate;
/** rate averaging the time to receive over a variety of periods */
private RateStat _receiveRate;
/** rate averaging the frequency of lost messages over a variety of periods */
private RateStat _lostRate;
/** how long we wait before timing out pending pings (30 seconds) */
private static final long TIMEOUT_PERIOD = 60 * 1000;
/** synchronize on this when updating _dataPoints or _pendingPings */
private Object _updateLock = new Object();
/**
* Creates a PeerData . . .
* @param config configuration to load from
*/
public PeerData(ClientConfig config) {
_peer = config;
_dataPoints = new TreeMap();
_pendingPings = new TreeMap();
_sessionStart = Clock.getInstance().now();
_lifetimeSent = 0;
_lifetimeReceived = 0;
_sendRate = new RateStat("sendRate", "How long it takes to send", "peer",
getPeriods(config.getAveragePeriods()));
_receiveRate = new RateStat("receiveRate", "How long it takes to receive", "peer",
getPeriods(config.getAveragePeriods()));
_lostRate = new RateStat("lostRate", "How frequently we lose messages", "peer",
getPeriods(config.getAveragePeriods()));
}
/**
* turn the periods (# minutes) into rate periods (# milliseconds)
* @param periods (in minutes)
* @return an array of periods (in milliseconds)
*/
private static long[] getPeriods(int periods[]) {
long rv[] = null;
if (periods == null) periods = new int[0];
rv = new long[periods.length];
for (int i = 0; i < periods.length; i++)
rv[i] = (long) periods[i] * 60 * 1000; // they're in minutes
Arrays.sort(rv);
return rv;
}
/**
* how many pings are still outstanding?
* @return the number of pings outstanding
*/
public int getPendingCount() {
synchronized (_updateLock) {
return _pendingPings.size();
}
}
/**
* how many data points are available in the current window?
* @return the number of datapoints available
*/
public int getDataPointCount() {
synchronized (_updateLock) {
return _dataPoints.size();
}
}
/**
* when did this test begin?
* @return when the test began
*/
public long getSessionStart() { return _sessionStart; }
public void setSessionStart(long when) { _sessionStart = when; }
/**
* how many pings have we sent for this test?
* @return the number of pings sent
*/
public long getLifetimeSent() { return _lifetimeSent; }
/**
* how many pongs have we received for this test?
* @return the number of pings received
*/
public long getLifetimeReceived() { return _lifetimeReceived; }
/**
* @return the client configuration
*/
public ClientConfig getConfig() {
return _peer;
}
/**
* What periods are we averaging the data over (in minutes)?
* @return the periods as an array of ints (in minutes)
*/
public int[] getAveragePeriods() {
return (_peer.getAveragePeriods() != null ? _peer.getAveragePeriods() : new int[0]);
}
/**
* average time to send over the given period.
*
* @param period number of minutes to retrieve the average for
* @return milliseconds average, or -1 if we dont track that period
*/
public double getAverageSendTime(int period) {
return getAverage(_sendRate, period);
}
/**
* average time to receive over the given period.
*
* @param period number of minutes to retrieve the average for
* @return milliseconds average, or -1 if we dont track that period
*/
public double getAverageReceiveTime(int period) {
return getAverage(_receiveRate, period);
}
/**
* number of lost messages over the given period.
*
* @param period number of minutes to retrieve the average for
* @return number of lost messages in the period, or -1 if we dont track that period
*/
public double getLostMessages(int period) {
Rate rate = _lostRate.getRate(period * 60 * 1000);
if (rate == null) return -1;
return rate.getCurrentTotalValue();
}
private double getAverage(RateStat stat, int period) {
Rate rate = stat.getRate(period * 60 * 1000);
if (rate == null) return -1;
return rate.getAverageValue();
}
/**
* Return an ordered list of data points in the current window (after doing a cleanup)
*
* @return list of EventDataPoint objects
*/
public List getDataPoints() {
cleanup();
synchronized (_updateLock) {
return new ArrayList(_dataPoints.values());
}
}
/**
* We have sent the peer a ping on this series (using the send time as given)
* @param dateSent when the ping was sent
*/
public void addPing(long dateSent) {
EventDataPoint sent = new EventDataPoint(dateSent);
synchronized (_updateLock) {
_pendingPings.put(new Long(dateSent), sent);
}
_lifetimeSent++;
}
/**
* we have received a pong from the peer on this series
*
* @param dateSent when we sent the ping
* @param pongSent when the peer received the ping and sent the pong
*/
public void pongReceived(long dateSent, long pongSent) {
long now = Clock.getInstance().now();
synchronized (_updateLock) {
EventDataPoint data = (EventDataPoint) _pendingPings.remove(new Long(dateSent));
if (data != null) {
data.setPongReceived(now);
data.setPongSent(pongSent);
data.setWasPonged(true);
locked_addDataPoint(data);
} else {
_log.warn("Pong received, but no matching ping? ping sent at = " + dateSent);
}
}
_sendRate.addData(pongSent - dateSent, 0);
_receiveRate.addData(now - pongSent, 0);
_lifetimeReceived++;
}
protected void addDataPoint(EventDataPoint data) {
synchronized (_updateLock) {
locked_addDataPoint(data);
}
}
private void locked_addDataPoint(EventDataPoint data) {
Object val = _dataPoints.put(new Long(data.getPingSent()), data);
if (val != null) {
if (_log.shouldLog(Log.WARN))
_log.warn("Duplicate data point received: " + data);
}
}
/**
* drop all datapoints outside the window we're watching, and timeout all
* pending pings not ponged in the TIMEOUT_PERIOD, both updating the lost message
* rate and coallescing all of the rates.
*
*/
public void cleanup() {
long dropBefore = Clock.getInstance().now() - _peer.getStatDuration() * 60 * 1000;
long timeoutBefore = Clock.getInstance().now() - TIMEOUT_PERIOD;
long numDropped = 0;
long numTimedOut = 0;
synchronized (_updateLock) {
numDropped = locked_dropExpired(dropBefore);
numTimedOut = locked_timeoutPending(timeoutBefore);
}
_lostRate.addData(numTimedOut, 0);
_receiveRate.coallesceStats();
_sendRate.coallesceStats();
_lostRate.coallesceStats();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Peer data cleaned up " + numTimedOut + " timed out pings and removed " + numDropped
+ " old entries");
}
/**
* Drop all data points that are already too old for us to be interested in
*
* @param when the earliest ping send time we care about
* @return number of data points dropped
*/
private int locked_dropExpired(long when) {
Set toDrop = new HashSet(4);
// drop the failed and really old
for (Iterator iter = _dataPoints.keySet().iterator(); iter.hasNext(); ) {
Long pingTime = (Long)iter.next();
if (pingTime.longValue() < when)
toDrop.add(pingTime);
}
for (Iterator iter = toDrop.iterator(); iter.hasNext(); ) {
_dataPoints.remove(iter.next());
}
return toDrop.size();
}
/**
* timeout and remove all pings that were sent before the given time,
* moving them from the set of pending pings to the set of data points
*
* @param when the earliest ping send time we care about
* @return number of pings timed out
*/
private int locked_timeoutPending(long when) {
Set toDrop = new HashSet(4);
for (Iterator iter = _pendingPings.keySet().iterator(); iter.hasNext(); ) {
Long pingTime = (Long)iter.next();
if (pingTime.longValue() < when) {
toDrop.add(pingTime);
EventDataPoint point = (EventDataPoint)_pendingPings.get(pingTime);
point.setWasPonged(false);
locked_addDataPoint(point);
}
}
for (Iterator iter = toDrop.iterator(); iter.hasNext(); ) {
_pendingPings.remove(iter.next());
}
return toDrop.size();
}
/** actual data point for the peer */
public class EventDataPoint {
private boolean _wasPonged;
private long _pingSent;
private long _pongSent;
private long _pongReceived;
/**
* Creates an EventDataPoint
*/
public EventDataPoint() { this(-1); }
/**
* Creates an EventDataPoint with pingtime associated with it =)
* @param pingSentOn the time a ping was sent
*/
public EventDataPoint(long pingSentOn) {
_wasPonged = false;
_pingSent = pingSentOn;
_pongSent = -1;
_pongReceived = -1;
}
/**
* when did we send this ping?
* @return the time the ping was sent
*/
public long getPingSent() { return _pingSent; }
public void setPingSent(long when) { _pingSent = when; }
/**
* when did the peer receive the ping?
* @return the time the ping was receieved
*/
public long getPongSent() {
return _pongSent;
}
/**
* Set the time the peer received the ping
* @param when the time to set
*/
public void setPongSent(long when) {
_pongSent = when;
}
/**
* when did we receive the peer's pong?
* @return the time we receieved the pong
*/
public long getPongReceived() {
return _pongReceived;
}
/**
* Set the time the peer's pong was receieved
* @param when the time to set
*/
public void setPongReceived(long when) {
_pongReceived = when;
}
/**
* did the peer reply in time?
* @return true or false, whether we got a reply in time */
public boolean getWasPonged() {
return _wasPonged;
}
/**
* Set whether we receieved the peer's reply in time
* @param pong true or false
*/
public void setWasPonged(boolean pong) {
_wasPonged = pong;
}
}
}

View File

@@ -0,0 +1,142 @@
package net.i2p.heartbeat;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Locale;
import net.i2p.util.Clock;
import net.i2p.util.Log;
/**
* Actually write out the stats for peer test
*
*/
public class PeerDataWriter {
private final static Log _log = new Log(PeerDataWriter.class);
/**
* persist the peer state to the location specified in the peer config
*
* @param data the peer data to persist
* @return true if it was persisted correctly, false on error
*/
public boolean persist(PeerData data) {
String filename = data.getConfig().getStatFile();
File statFile = new File(filename);
FileOutputStream fos = null;
try {
fos = new FileOutputStream(statFile);
persist(data, fos);
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error persisting the peer data for "
+ data.getConfig().getPeer().calculateHash().toBase64(), ioe);
return false;
} finally {
if (fos != null) try {
fos.close();
} catch (IOException ioe) {
}
}
return true;
}
/**
* persists the peer state to the output stream
* @param data the peer data to persist
* @param out where to persist the data
* @return true if it was persisted correctly [always (as implemented)], false on error
* @throws IOException
*/
public boolean persist(PeerData data, OutputStream out) throws IOException {
String header = getHeader(data);
out.write(header.getBytes());
out.write("#action\tstatus\tdate and time sent \tsendMs\treplyMs\troundTrip\n".getBytes());
for (Iterator iter = data.getDataPoints().iterator(); iter.hasNext();) {
PeerData.EventDataPoint point = (PeerData.EventDataPoint) iter.next();
String line = getEvent(point);
out.write(line.getBytes());
}
return true;
}
private String getHeader(PeerData data) {
StringBuffer buf = new StringBuffer(1024);
buf.append("peer \t").append(data.getConfig().getPeer().calculateHash().toBase64()).append('\n');
buf.append("local \t").append(data.getConfig().getUs().calculateHash().toBase64()).append('\n');
buf.append("peerDest \t").append(data.getConfig().getPeer().toBase64()).append('\n');
buf.append("localDest \t").append(data.getConfig().getUs().toBase64()).append('\n');
buf.append("numTunnelHops\t").append(data.getConfig().getNumHops()).append('\n');
buf.append("comment \t").append(data.getConfig().getComment()).append('\n');
buf.append("sendFrequency\t").append(data.getConfig().getSendFrequency()).append('\n');
buf.append("sendSize \t").append(data.getConfig().getSendSize()).append('\n');
buf.append("sessionStart \t").append(getTime(data.getSessionStart())).append('\n');
buf.append("currentTime \t").append(getTime(Clock.getInstance().now())).append('\n');
buf.append("numPending \t").append(data.getPendingCount()).append('\n');
buf.append("lifetimeSent \t").append(data.getLifetimeSent()).append('\n');
buf.append("lifetimeRecv \t").append(data.getLifetimeReceived()).append('\n');
int periods[] = data.getAveragePeriods();
buf.append("#averages\tminutes\tsendMs\trecvMs\tnumLost\troundTrip\n");
for (int i = 0; i < periods.length; i++) {
buf.append("periodAverage\t").append(periods[i]).append('\t');
buf.append(getNum(data.getAverageSendTime(periods[i]))).append('\t');
buf.append(getNum(data.getAverageReceiveTime(periods[i]))).append('\t');
buf.append(getNum(data.getLostMessages(periods[i]))).append('\t');
double rtt = data.getAverageSendTime(periods[i])
+ data.getAverageReceiveTime(periods[i]);
buf.append(getNum(rtt)).append('\n');
}
return buf.toString();
}
private String getEvent(PeerData.EventDataPoint point) {
StringBuffer buf = new StringBuffer(128);
buf.append("EVENT\t");
if (point.getWasPonged())
buf.append("OK\t");
else
buf.append("LOST\t");
buf.append(getTime(point.getPingSent())).append('\t');
if (point.getWasPonged()) {
buf.append(point.getPongSent() - point.getPingSent()).append('\t');
buf.append(point.getPongReceived() - point.getPongSent()).append('\t');
buf.append(point.getPongReceived() - point.getPingSent()).append('\t');
}
buf.append('\n');
return buf.toString();
}
private static final SimpleDateFormat _fmt = new SimpleDateFormat("yyyyMMdd.HH:mm:ss.SSS", Locale.UK);
/**
* Converts a time (long) to text
* @param when the time to convert
* @return the textual representation
*/
public String getTime(long when) {
synchronized (_fmt) {
return _fmt.format(new Date(when));
}
}
private static final DecimalFormat _numFmt = new DecimalFormat("#0", new DecimalFormatSymbols(Locale.UK));
/**
* Converts a number (double) to text
* @param val the number to convert
* @return the textual representation
*/
public String getNum(double val) {
synchronized (_numFmt) {
return _numFmt.format(val);
}
}
}

View File

@@ -0,0 +1,108 @@
package net.i2p.heartbeat.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import net.i2p.util.Log;
/**
* Render the control widgets (refresh/load/snapshot and the
* tabbed panel with the plot config data)
*
*/
class HeartbeatControlPane extends JPanel {
private final static Log _log = new Log(HeartbeatControlPane.class);
private HeartbeatMonitorGUI _gui;
private JTabbedPane _configPane;
private final static Color WHITE = new Color(255, 255, 255);
private final static Color LIGHT_BLUE = new Color(180, 180, 255);
private final static Color BLACK = new Color(0, 0, 0);
private Color _background = WHITE;
private Color _foreground = BLACK;
/**
* Constructs a control panel onto the gui
* @param gui the gui the panel is associated with
*/
public HeartbeatControlPane(HeartbeatMonitorGUI gui) {
_gui = gui;
initializeComponents();
}
/**
* Adds a test to the panel
* @param config the configuration for the test
*/
public void addTest(PeerPlotConfig config) {
_configPane.addTab(config.getTitle(), null, new JScrollPane(new PeerPlotConfigPane(config, this)), config.getSummary());
_configPane.setBackgroundAt(_configPane.getTabCount()-1, _background);
_configPane.setForegroundAt(_configPane.getTabCount()-1, _foreground);
_gui.pack();
}
/**
* Removes a test from the panel
* @param config the configuration for the test
*/
public void removeTest(PeerPlotConfig config) {
_gui.getMonitor().getState().removeTest(config);
int index = _configPane.indexOfTab(config.getTitle());
if (index >= 0)
_configPane.removeTabAt(index);
}
/**
* Callback: when tests have changed
*/
public void testsUpdated() {
List knownNames = new ArrayList(8);
for (int i = 0; i < _gui.getMonitor().getState().getTestCount(); i++) {
PeerPlotState state = _gui.getMonitor().getState().getTest(i);
String title = state.getPlotConfig().getTitle();
knownNames.add(state.getPlotConfig().getTitle());
if (_configPane.indexOfTab(title) >= 0) {
_log.debug("We already know about [" + title + "]");
} else {
_log.info("The test [" + title + "] is new to us");
PeerPlotConfigPane pane = new PeerPlotConfigPane(state.getPlotConfig(), this);
_configPane.addTab(state.getPlotConfig().getTitle(), null, new JScrollPane(pane), state.getPlotConfig().getSummary());
_configPane.setBackgroundAt(_configPane.getTabCount()-1, _background);
_configPane.setForegroundAt(_configPane.getTabCount()-1, _foreground);
}
}
List toRemove = new ArrayList(4);
for (int i = 0; i < _configPane.getTabCount(); i++) {
if (knownNames.contains(_configPane.getTitleAt(i))) {
// noop
} else {
toRemove.add(_configPane.getTitleAt(i));
}
}
for (int i = 0; i < toRemove.size(); i++) {
String title = (String)toRemove.get(i);
_log.info("Removing test [" + title + "]");
_configPane.removeTabAt(_configPane.indexOfTab(title));
}
}
private void initializeComponents() {
if (_gui != null)
setBackground(_gui.getBackground());
else
setBackground(_background);
setLayout(new BorderLayout());
HeartbeatMonitorCommandBar bar = new HeartbeatMonitorCommandBar(_gui);
bar.setBackground(getBackground());
add(bar, BorderLayout.NORTH);
_configPane = new JTabbedPane(JTabbedPane.LEFT);
_configPane.setBackground(_background);
//add(_configPane, BorderLayout.CENTER);
add(_configPane, BorderLayout.SOUTH);
}
}

View File

@@ -0,0 +1,110 @@
package net.i2p.heartbeat.gui;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
/**
* The HeartbeatMonitor, complete with main()! Act now, and it's only 5 easy
* payments of $19.95 (plus shipping and handling)! You heard me, only _5_
* easy payments of $19.95 (plus shipping and handling)! <p />
*
* (fine print: something about some states in the US requiring the addition
* of sales tax... or something) <p />
*
* (finer print: Satan owns you. Deal with it.) <p />
*
* (even finer print: usage: <code>HeartbeatMonitor [configFilename]</code>)
*/
public class HeartbeatMonitor implements PeerPlotStateFetcher.FetchStateReceptor, PeerPlotConfig.UpdateListener {
private final static Log _log = new Log(HeartbeatMonitor.class);
private HeartbeatMonitorState _state;
private HeartbeatMonitorGUI _gui;
/**
* Delegating constructor.
* @see HeartbeatMonitor#HeartbeatMonitor(String)
*/
public HeartbeatMonitor() { this(null); }
/**
* Creates a HeartbeatMonitor . . .
* @param configFilename the configuration file to read from
*/
public HeartbeatMonitor(String configFilename) {
_state = new HeartbeatMonitorState(configFilename);
_gui = new HeartbeatMonitorGUI(this);
}
/**
* Starts the game rollin'
*/
public void runMonitor() {
loadConfig();
I2PThread t = new I2PThread(new HeartbeatMonitorRunner(this));
t.setName("HeartbeatMonitor");
t.setDaemon(false);
t.start();
_log.debug("Monitor started");
}
/**
* give us all the data/config available
* @return the current state (data/config)
*/
HeartbeatMonitorState getState() {
return _state;
}
/** for all of the peer tests being monitored, refetch the data and rerender */
void refetchData() {
_log.debug("Refetching data");
for (int i = 0; i < _state.getTestCount(); i++)
PeerPlotStateFetcher.fetchPeerPlotState(this, _state.getTest(i));
}
/** (re)load the config defining what peer tests we are monitoring (and how to render) */
void loadConfig() {
//for (int i = 0; i < 10; i++) {
// load("fake" + i);
//}
}
/**
* Loads config data
* @param location the name of the location to load data from
*/
public void load(String location) {
PeerPlotConfig cfg = new PeerPlotConfig(location);
cfg.addListener(this);
PeerPlotState state = new PeerPlotState(cfg);
PeerPlotStateFetcher.fetchPeerPlotState(this, state);
}
/* (non-Javadoc)
* @see PeerPlotStateFetcher.FetchStateReceptor#peerPlotStateFetched
*/
public synchronized void peerPlotStateFetched(PeerPlotState state) {
_state.addTest(state);
_gui.stateUpdated();
}
/** store the config defining what peer tests we are monitoring (and how to render) */
void storeConfig() {}
/**
* And now, the main function, the one you've all been waiting for! . . .
* @param args da args. Should take 1, which is the location to load config data from
*/
public static void main(String args[]) {
Thread.currentThread().setName("HeartbeatMonitor.main");
if (args.length == 1)
new HeartbeatMonitor(args[0]).runMonitor();
else
new HeartbeatMonitor().runMonitor();
}
public void configUpdated(PeerPlotConfig config) {
_log.debug("Config updated, revamping the gui");
_gui.stateUpdated();
}
}

View File

@@ -0,0 +1,67 @@
package net.i2p.heartbeat.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class HeartbeatMonitorCommandBar extends JPanel {
private HeartbeatMonitorGUI _gui;
private JComboBox _refreshRate;
private JTextField _location;
/**
* Constructs a command bar onto the gui
* @param gui the gui the command bar is associated with
*/
public HeartbeatMonitorCommandBar(HeartbeatMonitorGUI gui) {
_gui = gui;
initializeComponents();
}
private void refreshChanged(ItemEvent evt) {}
private void loadCalled() {
_gui.getMonitor().load(_location.getText());
}
private void browseCalled() {
JFileChooser chooser = new JFileChooser(_location.getText());
chooser.setBackground(_gui.getBackground());
chooser.setMultiSelectionEnabled(false);
int rv = chooser.showDialog(this, "Load");
if (rv == JFileChooser.APPROVE_OPTION)
_gui.getMonitor().load(chooser.getSelectedFile().getAbsolutePath());
}
private void initializeComponents() {
_refreshRate = new JComboBox(new DefaultComboBoxModel(new Object[] {"10 second refresh", "30 second refresh", "1 minute refresh", "5 minute refresh"}));
_refreshRate.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { refreshChanged(evt); } });
_refreshRate.setEnabled(false);
_refreshRate.setBackground(_gui.getBackground());
//add(_refreshRate);
JLabel loadLabel = new JLabel("Load from: ");
loadLabel.setBackground(_gui.getBackground());
add(loadLabel);
_location = new JTextField(20);
_location.setToolTipText("Either specify a local filename or a fully qualified URL");
_location.setBackground(_gui.getBackground());
add(_location);
JButton browse = new JButton("Browse...");
browse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { browseCalled(); } });
browse.setBackground(_gui.getBackground());
add(browse);
JButton load = new JButton("Load");
load.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { loadCalled(); } });
load.setBackground(_gui.getBackground());
add(load);
setBackground(_gui.getBackground());
}
}

View File

@@ -0,0 +1,98 @@
package net.i2p.heartbeat.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
class HeartbeatMonitorGUI extends JFrame {
private HeartbeatMonitor _monitor;
private HeartbeatPlotPane _plotPane;
private HeartbeatControlPane _controlPane;
private final static Color WHITE = new Color(255, 255, 255);
private Color _background = WHITE;
/**
* Creates the GUI for all youz who be too shoopid for text based shitz
* @param monitor the monitor the gui operates over
*/
public HeartbeatMonitorGUI(HeartbeatMonitor monitor) {
super("Heartbeat Monitor");
_monitor = monitor;
initializeComponents();
pack();
//setResizable(false);
setVisible(true);
}
HeartbeatMonitor getMonitor() { return _monitor; }
/** build up all our widgets */
private void initializeComponents() {
getContentPane().setLayout(new BorderLayout());
setBackground(_background);
_plotPane = new JFreeChartHeartbeatPlotPane(this); // new HeartbeatPlotPane(this);
_plotPane.setBackground(_background);
//JScrollPane pane = new JScrollPane(_plotPane);
//pane.setBackground(_background);
getContentPane().add(new JScrollPane(_plotPane), BorderLayout.CENTER);
_controlPane = new HeartbeatControlPane(this);
_controlPane.setBackground(_background);
getContentPane().add(_controlPane, BorderLayout.SOUTH);
//JSplitPane pane = new JSplitPane(JSplitPane.VERTICAL_SPLIT, new JScrollPane(_plotPane), new JScrollPane(_controlPane));
//getContentPane().add(pane, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initializeMenus();
}
/**
* Callback: when the state of the world changes . . .
*/
public void stateUpdated() {
_controlPane.testsUpdated();
_plotPane.stateUpdated();
}
private void exitCalled() {
_monitor.getState().setWasKilled(true);
setVisible(false);
System.exit(0);
}
private void loadConfigCalled() {}
private void saveConfigCalled() {}
private void loadSnapshotCalled() {}
private void saveSnapshotCalled() {}
private void initializeMenus() {
JMenuBar bar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem loadConfig = new JMenuItem("Load config");
loadConfig.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { loadConfigCalled(); } });
JMenuItem saveConfig = new JMenuItem("Save config");
saveConfig.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveConfigCalled(); } });
JMenuItem saveSnapshot = new JMenuItem("Save snapshot");
saveSnapshot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveSnapshotCalled(); } });
JMenuItem loadSnapshot = new JMenuItem("Load snapshot");
loadSnapshot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { loadSnapshotCalled(); } });
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exitCalled(); } });
fileMenu.add(loadConfig);
fileMenu.add(saveConfig);
fileMenu.add(loadSnapshot);
fileMenu.add(saveSnapshot);
fileMenu.add(exit);
bar.add(fileMenu);
setJMenuBar(bar);
}
}

View File

@@ -0,0 +1,32 @@
package net.i2p.heartbeat.gui;
import net.i2p.util.Log;
/**
* Periodically fire off necessary events (instructing the heartbeat monitor when
* to refetch the data, etc). This is the only active thread in the heartbeat
* monitor (outside the swing/jvm threads)
*/
class HeartbeatMonitorRunner implements Runnable {
private final static Log _log = new Log(HeartbeatMonitorRunner.class);
private HeartbeatMonitor _monitor;
/**
* Creates the thread . . .
* @param monitor the monitor the thread runs over
*/
public HeartbeatMonitorRunner(HeartbeatMonitor monitor) {
_monitor = monitor;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
while (!_monitor.getState().getWasKilled()) {
_monitor.refetchData();
try { Thread.sleep(_monitor.getState().getRefreshRateMs()); } catch (InterruptedException ie) {}
}
_log.info("Stopping the heartbeat monitor runner");
}
}

View File

@@ -0,0 +1,129 @@
package net.i2p.heartbeat.gui;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* manage the current state of the GUI - all data points, as well as any
* rendering or configuration options.
*/
class HeartbeatMonitorState {
private String _configFile;
private List _peerPlotState;
private int _currentPeerPlotConfig;
private int _refreshRateMs;
private boolean _killed;
/** by default, refresh every 30 seconds */
private final static int DEFAULT_REFRESH_RATE = 30*1000;
/** where do we load/store config info from? */
private final static String DEFAULT_CONFIG_FILE = "heartbeatMonitor.config";
/**
* A delegating constructor.
* @see HeartbeatMonitorState#HeartbeatMonitorState(String)
*/
public HeartbeatMonitorState() { this(DEFAULT_CONFIG_FILE); }
/**
* Constructs the state, loading from the specified location
* @param configFile the name of the file to load info from
*/
public HeartbeatMonitorState(String configFile) {
_peerPlotState = Collections.synchronizedList(new ArrayList());
_refreshRateMs = DEFAULT_REFRESH_RATE;
_configFile = configFile;
_killed = false;
_currentPeerPlotConfig = 0;
}
/**
* how many tests are we monitoring?
* @return the number of tests
*/
public int getTestCount() { return _peerPlotState.size(); }
/**
* Retrieves the current info of a test for a certain peer . . .
* @param peer a number associated with a certain peer
* @return the test data
*/
public PeerPlotState getTest(int peer) { return (PeerPlotState)_peerPlotState.get(peer); }
/**
* Adds a test . . .
* @param peerState the test (by state) to add . . .
*/
public void addTest(PeerPlotState peerState) {
if (!_peerPlotState.contains(peerState))
_peerPlotState.add(peerState);
}
/**
* Removes a test . . .
* @param peerState the test (by state) to remove . . .
*/
public void removeTest(PeerPlotState peerState) { _peerPlotState.remove(peerState); }
/**
* Removes a test . . .
* @param peerConfig the test (by config) to remove . . .
*/
public void removeTest(PeerPlotConfig peerConfig) {
for (int i = 0; i < getTestCount(); i++) {
PeerPlotState state = getTest(i);
if (state.getPlotConfig() == peerConfig) {
removeTest(state);
return;
}
}
}
/**
* which of the tests are we currently editing/viewing?
* @return the number associated with the test
*/
public int getPeerPlotConfig() { return _currentPeerPlotConfig; }
/**
* Sets the test we are currently editting/viewing
* @param whichTest the number associated with the test
*/
public void setPeerPlotConfig(int whichTest) { _currentPeerPlotConfig = whichTest; }
/**
* how frequently should we update the data?
* @return the current frequency (in milliseconds)
*/
public int getRefreshRateMs() { return _refreshRateMs; }
/**
* Sets how frequently we should update data
* @param ms the frequency (in milliseconds)
*/
public void setRefreshRateMs(int ms) { _refreshRateMs = ms; }
/**
* where is our config stored?
* @return the name of the config file
*/
public String getConfigFile() { return _configFile; }
/**
* Sets where our config is stored
* @param filename the name of the config file
*/
public void setConfigFile(String filename) { _configFile = filename; }
/**
* have we been shut down?
* @return true if we have, false otherwise
*/
public boolean getWasKilled() { return _killed; }
/**
* Sets if we have been shutdown or not
* @param killed true if we've been shutdown, false otherwise
*/
public void setWasKilled(boolean killed) { _killed = killed; }
}

View File

@@ -0,0 +1,62 @@
package net.i2p.heartbeat.gui;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import net.i2p.heartbeat.PeerDataWriter;
import net.i2p.util.Log;
/**
* Render the graph and legend
*/
class HeartbeatPlotPane extends JPanel {
private final static Log _log = new Log(HeartbeatPlotPane.class);
protected HeartbeatMonitorGUI _gui;
private JTextArea _text;
/**
* Constructs the plot pane
* @param gui the gui the pane is attached to
*/
public HeartbeatPlotPane(HeartbeatMonitorGUI gui) {
_gui = gui;
initializeComponents();
}
/**
* Callback: when things change . . .
*/
public void stateUpdated() {
StringBuffer buf = new StringBuffer(32*1024);
PeerDataWriter writer = new PeerDataWriter();
for (int i = 0; i < _gui.getMonitor().getState().getTestCount(); i++) {
StaticPeerData data = _gui.getMonitor().getState().getTest(i).getCurrentData();
ByteArrayOutputStream baos = new ByteArrayOutputStream(4096);
try {
writer.persist(data, baos);
} catch (IOException ioe) {
_log.error("wtf, error writing to a byte array?", ioe);
}
buf.append(new String(baos.toByteArray())).append("\n\n\n");
}
_text.setText(buf.toString());
}
protected void initializeComponents() {
setBackground(_gui.getBackground());
//Dimension size = new Dimension(800, 600);
_text = new JTextArea("",30,80); // 16, 60);
_text.setAutoscrolls(true);
_text.setEditable(false);
// _text.setLineWrap(true);
// add(new JScrollPane(_text));
add(_text);
// add(new JScrollPane(_text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
// setPreferredSize(size);
}
}

View File

@@ -0,0 +1,231 @@
package net.i2p.heartbeat.gui;
import java.awt.Color;
import java.awt.Font;
import java.util.List;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.XYItemRenderer;
import org.jfree.chart.renderer.XYLineAndShapeRenderer;
import org.jfree.data.XYSeries;
import org.jfree.data.XYSeriesCollection;
import net.i2p.heartbeat.PeerData;
import net.i2p.util.Log;
class JFreeChartAdapter {
private final static Log _log = new Log(JFreeChartAdapter.class);
private final static Color WHITE = new Color(255, 255, 255);
ChartPanel createPanel(HeartbeatMonitorState state) {
ChartPanel panel = new ChartPanel(createChart(state));
panel.setDisplayToolTips(true);
panel.setEnforceFileExtensions(true);
panel.setHorizontalZoom(true);
panel.setVerticalZoom(true);
panel.setMouseZoomable(true, true);
panel.getChart().setBackgroundPaint(WHITE);
return panel;
}
JFreeChart createChart(HeartbeatMonitorState state) {
Plot plot = createPlot(state);
JFreeChart chart = new JFreeChart("I2P Heartbeat performance", Font.getFont("arial"), plot, true);
return chart;
}
void updateChart(ChartPanel panel, HeartbeatMonitorState state) {
XYPlot plot = (XYPlot)panel.getChart().getPlot();
plot.setDataset(getCollection(state));
updateLines(plot, state);
}
private long getFirst(HeartbeatMonitorState state) {
long first = -1;
for (int i = 0; i < state.getTestCount(); i++) {
List dataPoints = state.getTest(i).getCurrentData().getDataPoints();
if ( (dataPoints != null) && (dataPoints.size() > 0) ) {
PeerData.EventDataPoint data = (PeerData.EventDataPoint)dataPoints.get(0);
if ( (first < 0) || (first > data.getPingSent()) )
first = data.getPingSent();
}
}
return first;
}
Plot createPlot(HeartbeatMonitorState state) {
XYItemRenderer renderer = new XYLineAndShapeRenderer(); // new XYDotRenderer(); //
XYPlot plot = new XYPlot(getCollection(state), new DateAxis(), new NumberAxis("ms"), renderer);
updateLines(plot, state);
return plot;
}
private void updateLines(XYPlot plot, HeartbeatMonitorState state) {
if (true) return;
if (state == null) return;
for (int i = 0; i < state.getTestCount(); i++) {
PeerPlotConfig config = state.getTest(i).getPlotConfig();
PeerPlotConfig.PlotSeriesConfig curConfig = config.getCurrentSeriesConfig();
XYSeriesCollection col = ((XYSeriesCollection)plot.getDataset());
for (int j = 0; j < col.getSeriesCount(); j++) {
//XYItemRenderer renderer = plot.getRendererForDataset(col.getSeries(j));
XYItemRenderer renderer = plot.getRendererForDataset(col);
if (col.getSeriesName(j).startsWith(config.getTitle() + " send")) {
if (curConfig.getPlotSendTime()) {
//renderer.setPaint(curConfig.getPlotLineColor());
}
}
if (col.getSeriesName(j).startsWith(config.getTitle() + " receive")) {
if (curConfig.getPlotReceiveTime()) {
//renderer.setPaint(curConfig.getPlotLineColor());
}
}
if (col.getSeriesName(j).startsWith(config.getTitle() + " lost")) {
if (curConfig.getPlotLostMessages()) {
//renderer.setPaint(curConfig.getPlotLineColor());
}
}
}
}
}
XYSeriesCollection getCollection(HeartbeatMonitorState state) {
XYSeriesCollection col = new XYSeriesCollection();
if (state != null) {
for (int i = 0; i < state.getTestCount(); i++) {
addTest(col, state.getTest(i));
}
} else {
XYSeries series = new XYSeries("latency", false, false);
series.add(System.currentTimeMillis(), 0);
col.addSeries(series);
}
return col;
}
void addTest(XYSeriesCollection col, PeerPlotState state) {
PeerPlotConfig config = state.getPlotConfig();
PeerPlotConfig.PlotSeriesConfig curConfig = config.getCurrentSeriesConfig();
addLines(col, curConfig, config.getTitle(), state.getCurrentData().getDataPoints());
addAverageLines(col, config, config.getTitle(), state.getCurrentData());
}
/**
* @param config preferences for how to display this test
* @param lineName minimal name of the test (e.g. "jxHa.32KB.60s")
* @param data List of PeerData.EventDataPoint describing all of the events in the test
*/
void addLines(XYSeriesCollection col, PeerPlotConfig.PlotSeriesConfig config, String lineName, List data) {
if (config.getPlotSendTime()) {
XYSeries sendSeries = getSendSeries(data);
sendSeries.setName(lineName + " send");
sendSeries.setDescription("milliseconds for the ping to reach the peer");
col.addSeries(sendSeries);
}
if (config.getPlotReceiveTime()) {
XYSeries recvSeries = getReceiveSeries(data);
recvSeries.setName(lineName + " receive");
recvSeries.setDescription("milliseconds for the peer's pong to reach the sender");
col.addSeries(recvSeries);
}
if (config.getPlotLostMessages()) {
XYSeries lostSeries = getLostSeries(data);
lostSeries.setName(lineName + " lost");
lostSeries.setDescription("number of ping/pong messages lost");
col.addSeries(lostSeries);
}
}
/**
* Add a data series for each average that we're configured to render
*
* @param config preferences for how to display this test
* @param lineName minimal name of the test (e.g. "jxHa.32KB.60s")
* @param data List of PeerData.EventDataPoint describing all of the events in the test
*/
void addAverageLines(XYSeriesCollection col, PeerPlotConfig config, String lineName, StaticPeerData data) {
if (data.getDataPointCount() <= 0) return;
PeerData.EventDataPoint start = (PeerData.EventDataPoint)data.getDataPoints().get(0);
PeerData.EventDataPoint finish = (PeerData.EventDataPoint)data.getDataPoints().get(data.getDataPointCount()-1);
List configs = config.getAverageSeriesConfigs();
for (int i = 0; i < configs.size(); i++) {
PeerPlotConfig.PlotSeriesConfig cfg = (PeerPlotConfig.PlotSeriesConfig)configs.get(i);
int minutes = (int)cfg.getPeriod()/(60*1000);
if (cfg.getPlotSendTime()) {
double time = data.getAverageSendTime(minutes);
if (time > 0) {
XYSeries series = new XYSeries(lineName + " send " + minutes + "m avg [" + time + "]", false, false);
series.add(start.getPingSent(), time);
series.add(finish.getPingSent(), time);
series.setDescription("send time, averaged over the last " + minutes + " minutes");
col.addSeries(series);
}
}
if (cfg.getPlotReceiveTime()) {
double time = data.getAverageReceiveTime(minutes);
if (time > 0) {
XYSeries series = new XYSeries(lineName + " receive " + minutes + "m avg[" + time + "]", false, false);
series.add(start.getPingSent(), time);
series.add(finish.getPingSent(), time);
series.setDescription("receive time, averaged over the last " + minutes + " minutes");
col.addSeries(series);
}
}
if (cfg.getPlotLostMessages()) {
double num = data.getLostMessages(minutes);
if (num > 0) {
XYSeries series = new XYSeries(lineName + " lost messages (" + num + " in " + minutes + "m)", false, false);
series.add(start.getPingSent(), num);
series.add(finish.getPingSent(), num);
series.setDescription("number of messages lost in the last " + minutes + " minutes");
col.addSeries(series);
}
}
}
}
XYSeries getSendSeries(List data) {
XYSeries series = new XYSeries("sent", false, false);
for (int i = 0; i < data.size(); i++) {
PeerData.EventDataPoint point = (PeerData.EventDataPoint)data.get(i);
if (point.getWasPonged()) {
series.add(point.getPingSent(), point.getPongSent()-point.getPingSent());
} else {
// series.add(data.getPingSent(), 0);
}
}
return series;
}
XYSeries getReceiveSeries(List data) {
XYSeries series = new XYSeries("receive", false, false);
for (int i = 0; i < data.size(); i++) {
PeerData.EventDataPoint point = (PeerData.EventDataPoint)data.get(i);
if (point.getWasPonged()) {
series.add(point.getPingSent(), point.getPongReceived()-point.getPongSent());
} else {
// series.add(data.getPingSent(), 0);
}
}
return series;
}
XYSeries getLostSeries(List data) {
XYSeries series = new XYSeries("lost", false, false);
for (int i = 0; i < data.size(); i++) {
PeerData.EventDataPoint point = (PeerData.EventDataPoint)data.get(i);
if (point.getWasPonged()) {
//series.add(point.getPingSent(), 0);
} else {
series.add(point.getPingSent(), 1);
}
}
return series;
}
}

View File

@@ -0,0 +1,51 @@
package net.i2p.heartbeat.gui;
import java.awt.BorderLayout;
import javax.swing.JLabel;
import javax.swing.JScrollPane;
import org.jfree.chart.ChartPanel;
import net.i2p.util.Log;
/**
* Render the graph and legend
*
*/
class JFreeChartHeartbeatPlotPane extends HeartbeatPlotPane {
private final static Log _log = new Log(JFreeChartHeartbeatPlotPane.class);
private ChartPanel _panel;
private JFreeChartAdapter _adapter;
public JFreeChartHeartbeatPlotPane(HeartbeatMonitorGUI gui) {
super(gui);
}
public void stateUpdated() {
if (_panel == null) {
remove(0); // remove the dummy
_adapter = new JFreeChartAdapter();
_panel = _adapter.createPanel(_gui.getMonitor().getState());
_panel.setBackground(_gui.getBackground());
add(new JScrollPane(_panel), BorderLayout.CENTER);
_gui.pack();
} else {
_adapter.updateChart(_panel, _gui.getMonitor().getState());
//_gui.pack();
}
}
protected void initializeComponents() {
// noop
setLayout(new BorderLayout());
add(new JLabel(), BorderLayout.CENTER);
//dummy.setBackground(_gui.getBackground());
//dummy.setPreferredSize(new Dimension(800,600));
//add(dummy);
//add(_panel);
}
}

View File

@@ -0,0 +1,367 @@
package net.i2p.heartbeat.gui;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import net.i2p.data.Destination;
import net.i2p.util.Log;
import net.i2p.heartbeat.ClientConfig;
/**
* Configure how we want to render a particular clientConfig in the GUI
*/
class PeerPlotConfig {
private final static Log _log = new Log(PeerPlotConfig.class);
/** where can we find the current state/data (either as a filename or a URL)? */
private String _location;
/** what test are we defining the plot data for? */
private ClientConfig _config;
/** how should we render the current data set? */
private PlotSeriesConfig _currentSeriesConfig;
/** how should we render the various averages available? */
private List _averageSeriesConfigs;
private Set _listeners;
private boolean _disabled;
/**
* Delegating constructor . . .
* @param location the name of the file/URL to get the data from
*/
public PeerPlotConfig(String location) {
this(location, null, null, null);
}
/**
* Constructs a config =)
* @param location the location of the file/URL to get the data from
* @param config the client's configuration
* @param currentSeriesConfig the series config
* @param averageSeriesConfigs the average
*/
public PeerPlotConfig(String location, ClientConfig config, PlotSeriesConfig currentSeriesConfig, List averageSeriesConfigs) {
_location = location;
if (config == null)
config = new ClientConfig(location);
_config = config;
if (currentSeriesConfig != null)
_currentSeriesConfig = currentSeriesConfig;
else
_currentSeriesConfig = new PlotSeriesConfig(0);
if (averageSeriesConfigs != null) {
_averageSeriesConfigs = averageSeriesConfigs;
} else {
rebuildAverageSeriesConfigs();
}
_listeners = Collections.synchronizedSet(new HashSet(2));
_disabled = false;
}
/**
* 'Rebuilds' the average series stuff from the client configuration
*/
public void rebuildAverageSeriesConfigs() {
int periods[] = _config.getAveragePeriods();
if (periods == null) {
_averageSeriesConfigs = Collections.synchronizedList(new ArrayList(0));
} else {
Arrays.sort(periods);
_averageSeriesConfigs = Collections.synchronizedList(new ArrayList(periods.length));
for (int i = 0; i < periods.length; i++) {
_averageSeriesConfigs.add(new PlotSeriesConfig(periods[i]*60*1000));
}
}
}
/**
* Adds an average period
* @param minutes the number of minutes averaged over
*/
public void addAverage(int minutes) {
_config.addAveragePeriod(minutes);
TreeMap ordered = new TreeMap();
for (int i = 0; i < _averageSeriesConfigs.size(); i++) {
PlotSeriesConfig cfg = (PlotSeriesConfig)_averageSeriesConfigs.get(i);
ordered.put(new Long(cfg.getPeriod()), cfg);
}
Long period = new Long(minutes*60*1000);
if (!ordered.containsKey(period))
ordered.put(period, new PlotSeriesConfig(minutes*60*1000));
List cfgs = Collections.synchronizedList(new ArrayList(ordered.size()));
for (Iterator iter = ordered.values().iterator(); iter.hasNext(); )
cfgs.add(iter.next());
_averageSeriesConfigs = cfgs;
}
/**
* Where is the current state data supposed to be found? This must either be a
* local file path or a URL
* @return the current location
*/
public String getLocation() { return _location; }
/**
* The location the current state data is supposed to be found. This must either be
* a local file path or a URL
* @param location the location
*/
public void setLocation(String location) {
_location = location;
fireUpdate();
}
/**
* What are we configuring?
* @return the client configuration
*/
public ClientConfig getClientConfig() { return _config; }
/**
* Sets what we are currently configuring
* @param config the new config
*/
public void setClientConfig(ClientConfig config) {
_config = config;
fireUpdate();
}
/**
* How do we want to render the current data set?
* @return the way we currently render the data
*/
public PlotSeriesConfig getCurrentSeriesConfig() { return _currentSeriesConfig; }
/**
* Sets how we want to render the current data set.
* @param config the new config
*/
public void setCurrentSeriesConfig(PlotSeriesConfig config) {
_currentSeriesConfig = config;
fireUpdate();
}
/**
* How do we want to render the averages?
* @return the way we currently render the averages
*/
public List getAverageSeriesConfigs() { return _averageSeriesConfigs; }
/**
* Sets how we want to render the averages
* @param configs the new configs
*/
public void setAverageSeriesConfigs(List configs) { _averageSeriesConfigs = configs; }
/**
* four char description of the peer
* @return the name
*/
public String getPeerName() {
Destination peer = getClientConfig().getPeer();
if (peer == null)
return "????";
else
return peer.calculateHash().toBase64().substring(0, 4);
}
/**
* title: name.packetsize.sendfrequency
* @return the title
*/
public String getTitle() {
return getPeerName() + '.' + getSize() + '.' + getClientConfig().getSendFrequency();
}
/**
* summary. includes:name, size, sendfrequency, and # of hops
* @return the summary
*/
public String getSummary() {
return "Send peer " + getPeerName() + ' ' + getSize() + " every " +
getClientConfig().getSendFrequency() + " seconds through " +
getClientConfig().getNumHops() + "-hop tunnels";
}
private String getSize() {
int bytes = getClientConfig().getSendSize();
if (bytes < 1024)
return bytes + "b";
else
return bytes/1024 + "kb";
}
/**
* we've got someone who wants to be notified of changes to the plot config
* @param lsnr the listener to be added
*/
public void addListener(UpdateListener lsnr) { _listeners.add(lsnr); }
/**
* remove a listener
* @param lsnr the listener to remove
*/
public void removeListener(UpdateListener lsnr) { _listeners.remove(lsnr); }
void fireUpdate() {
if (_disabled) return;
for (Iterator iter = _listeners.iterator(); iter.hasNext(); ) {
((UpdateListener)iter.next()).configUpdated(this);
}
}
/**
* Disables notification of events listeners
* @see PeerPlotConfig#fireUpdate()
*/
public void disableEvents() { _disabled = true; }
/**
* Enables notification of events listeners
* @see PeerPlotConfig#fireUpdate()
*/
public void enableEvents() { _disabled = false; }
/**
* How do we want to render a particular dataset (either the current or the averaged values)?
*/
public class PlotSeriesConfig {
private long _period;
private boolean _plotSendTime;
private boolean _plotReceiveTime;
private boolean _plotLostMessages;
private Color _plotLineColor;
/**
* Delegating constructor . . .
* @param period the period for the config
* (0 for current, otherwise # of milliseconds being averaged over)
*/
public PlotSeriesConfig(long period) {
this(period, false, false, false, null);
if (period <= 0) {
_plotSendTime = true;
_plotReceiveTime = true;
_plotLostMessages = true;
}
}
/**
* Creates a config for the rendering of a particular dataset)
* @param period the period for the config
* (0 for current, otherwise # of milliseconds being averaged over)
* @param plotSend do we plot send times?
* @param plotReceive do we plot receive times?
* @param plotLost do we plot lost packets?
* @param plotColor in what color?
*/
public PlotSeriesConfig(long period, boolean plotSend, boolean plotReceive, boolean plotLost, Color plotColor) {
_period = period;
_plotSendTime = plotSend;
_plotReceiveTime = plotReceive;
_plotLostMessages = plotLost;
_plotLineColor = plotColor;
}
/**
* Retrieves the plot config this plot series config is a part of
* @return the plot config
*/
public PeerPlotConfig getPlotConfig() { return PeerPlotConfig.this; }
/**
* What period is this series config describing?
* @return 0 for current, otherwise # milliseconds that are being averaged over
*/
public long getPeriod() { return _period; }
/**
* Sets the period this series config is describing
* @param period the period
* (0 for current, otherwise # milliseconds that are being averaged over)
*/
public void setPeriod(long period) {
_period = period;
fireUpdate();
}
/**
* Should we render the time to send (ping to peer)?
* @return true or false . . .
*/
public boolean getPlotSendTime() { return _plotSendTime; }
/**
* Sets whether we render the time to send (ping to peer) or not
* @param shouldPlot true or false
*/
public void setPlotSendTime(boolean shouldPlot) {
_plotSendTime = shouldPlot;
fireUpdate();
}
/**
* Should we render the time to receive (peer pong to us)?
* @return true or false . . .
*/
public boolean getPlotReceiveTime() { return _plotReceiveTime; }
/**
* Sets whether we render the time to receive (peer pong to us)
* @param shouldPlot true or false
*/
public void setPlotReceiveTime(boolean shouldPlot) {
_plotReceiveTime = shouldPlot;
fireUpdate();
}
/**
* Should we render the number of messages lost (ping sent, no pong received in time)?
* @return true or false . . .
*/
public boolean getPlotLostMessages() { return _plotLostMessages; }
/**
* Sets whether we render the number of messages lost (ping sent, no pong received in time) or not
* @param shouldPlot true or false
*/
public void setPlotLostMessages(boolean shouldPlot) {
_plotLostMessages = shouldPlot;
fireUpdate();
}
/**
* What color should we plot the data with?
* @return the color
*/
public Color getPlotLineColor() { return _plotLineColor; }
/**
* Sets the color we should plot the data with
* @param color the color to use
*/
public void setPlotLineColor(Color color) {
_plotLineColor = color;
fireUpdate();
}
}
/**
* An interface for listening to updates . . .
*/
public interface UpdateListener {
/**
* @param config the peer plot config that changes
* @see PeerPlotConfig#fireUpdate()
*/
void configUpdated(PeerPlotConfig config);
}
}

View File

@@ -0,0 +1,370 @@
package net.i2p.heartbeat.gui;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.List;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import net.i2p.util.Log;
class PeerPlotConfigPane extends JPanel implements PeerPlotConfig.UpdateListener {
private final static Log _log = new Log(PeerPlotConfigPane.class);
private PeerPlotConfig _config;
private HeartbeatControlPane _parent;
private JLabel _title;
private JButton _delete;
private JLabel _fromLabel;
private JTextField _from;
private JTextArea _comments;
private JLabel _peerLabel;
private JTextField _peerKey;
private JLabel _localLabel;
private JTextField _localKey;
private OptionLine _options[];
private Random _rnd = new Random();
private final static Color WHITE = new Color(255, 255, 255);
private Color _background = WHITE;
/**
* Constructs a pane
* @param config the plot config it represents
* @param pane the pane this one is attached to
*/
public PeerPlotConfigPane(PeerPlotConfig config, HeartbeatControlPane pane) {
_config = config;
_parent = pane;
if (_parent != null)
_background = _parent.getBackground();
_config.addListener(this);
initializeComponents();
}
/** called when the user wants to stop monitoring this test */
private void delete() {
_parent.removeTest(_config);
}
private void initializeComponents() {
buildComponents();
placeComponents(this);
refreshView();
//setBorder(new BevelBorder(BevelBorder.RAISED));
setBackground(_background);
}
/**
* place all the gui components onto the given panel
* @param body the panel to place the components on
*/
private void placeComponents(JPanel body) {
body.setLayout(new GridBagLayout());
GridBagConstraints cts = new GridBagConstraints();
// row 0: title + delete
cts.gridx = 0;
cts.gridy = 0;
cts.gridwidth = 5;
cts.anchor = GridBagConstraints.WEST;
cts.fill = GridBagConstraints.NONE;
body.add(_title, cts);
cts.gridx = 5;
cts.gridwidth = 1;
cts.anchor = GridBagConstraints.NORTHWEST;
cts.fill = GridBagConstraints.BOTH;
body.add(_delete, cts);
// row 1: from + location
cts.gridx = 0;
cts.gridy = 1;
cts.gridwidth = 1;
cts.fill = GridBagConstraints.NONE;
body.add(_fromLabel, cts);
cts.gridx = 1;
cts.gridwidth = 5;
cts.fill = GridBagConstraints.BOTH;
body.add(_from, cts);
// row 2: comment
cts.gridx = 0;
cts.gridy = 2;
cts.gridwidth = 6;
cts.fill = GridBagConstraints.BOTH;
body.add(_comments, cts);
// row 3: peer + peerKey
cts.gridx = 0;
cts.gridy = 3;
cts.gridwidth = 1;
cts.fill = GridBagConstraints.NONE;
body.add(_peerLabel, cts);
cts.gridx = 1;
cts.gridwidth = 5;
cts.fill = GridBagConstraints.BOTH;
body.add(_peerKey, cts);
// row 4: local + localKey
cts.gridx = 0;
cts.gridy = 4;
cts.gridwidth = 1;
cts.fill = GridBagConstraints.NONE;
body.add(_localLabel, cts);
cts.gridx = 1;
cts.gridwidth = 5;
cts.fill = GridBagConstraints.BOTH;
body.add(_localKey, cts);
// row 5-N: data row
for (int i = 0; i < _options.length; i++) {
cts.gridx = 0;
cts.gridy = 5 + i;
cts.gridwidth = 1;
cts.fill = GridBagConstraints.NONE;
cts.anchor = GridBagConstraints.WEST;
if (_options[i]._durationMinutes <= 0)
body.add(new JLabel("Data: "), cts);
else
body.add(new JLabel(_options[i]._durationMinutes + "m avg: "), cts);
cts.gridx = 1;
body.add(_options[i]._send, cts);
cts.gridx = 2;
body.add(_options[i]._recv, cts);
cts.gridx = 3;
body.add(_options[i]._lost, cts);
cts.gridx = 4;
body.add(_options[i]._all, cts);
cts.gridx = 5;
body.add(_options[i]._color, cts);
}
}
/** build all of the gui components */
private void buildComponents() {
_title = new JLabel(_config.getSummary());
_title.setBackground(_background);
_delete = new JButton("Delete");
_delete.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { delete(); } });
_delete.setEnabled(false);
_delete.setBackground(_background);
_fromLabel = new JLabel("Location: ");
_fromLabel.setBackground(_background);
_from = new JTextField(_config.getLocation());
_from.setEditable(false);
_from.setBackground(_background);
_comments = new JTextArea(_config.getClientConfig().getComment(), 2, 20);
// _comments = new JTextArea(_config.getClientConfig().getComment(), 2, 40);
_comments.setEditable(false);
_comments.setBackground(_background);
_peerLabel = new JLabel("Peer: ");
_peerLabel.setBackground(_background);
_peerKey = new JTextField(_config.getClientConfig().getPeer().toBase64(), 8);
_peerKey.setBackground(_background);
_localLabel = new JLabel("Local: ");
_localLabel.setBackground(_background);
_localKey = new JTextField(_config.getClientConfig().getUs().toBase64(), 8);
_localKey.setBackground(_background);
int averagedPeriods[] = _config.getClientConfig().getAveragePeriods();
if (averagedPeriods == null)
averagedPeriods = new int[0];
_options = new OptionLine[1 + averagedPeriods.length];
_options[0] = new OptionLine(0);
for (int i = 0; i < averagedPeriods.length; i++) {
_options[1+i] = new OptionLine(averagedPeriods[i]);
}
}
/** the settings have changed - revise */
private void refreshView() {
for (int i = 0; i < _options.length; i++) {
PeerPlotConfig.PlotSeriesConfig cfg = getConfig(_options[i]._durationMinutes);
if (cfg == null) {
_log.warn("Config for minutes " + _options[i]._durationMinutes + " was not found?");
continue;
}
//_log.debug("Refreshing view for minutes ["+ _options[i]._durationMinutes + "]: send [" +
// _options[i]._send.isSelected() + "/" + cfg.getPlotSendTime() + "] recv [" +
// _options[i]._recv.isSelected() + "/" + cfg.getPlotReceiveTime() + "] lost [" +
// _options[i]._lost.isSelected() + "/" + cfg.getPlotLostMessages() + "]");
_options[i]._send.setSelected(cfg.getPlotSendTime());
_options[i]._recv.setSelected(cfg.getPlotReceiveTime());
_options[i]._lost.setSelected(cfg.getPlotLostMessages());
if (cfg.getPlotLineColor() != null)
_options[i]._color.setBackground(cfg.getPlotLineColor());
}
}
/**
* find the right config for the given period
* @param minutes the minutes to locate the config by
* @return the config for the given period, or null
*/
private PeerPlotConfig.PlotSeriesConfig getConfig(int minutes) {
if (minutes <= 0)
return _config.getCurrentSeriesConfig();
List configs = _config.getAverageSeriesConfigs();
for (int i = 0; i < configs.size(); i++) {
PeerPlotConfig.PlotSeriesConfig cfg = (PeerPlotConfig.PlotSeriesConfig)configs.get(i);
if (cfg.getPeriod() == minutes * 60*1000)
return cfg;
}
return null;
}
/**
* notified that the config has been updated
* @param config the config that was been updated
*/
public void configUpdated(PeerPlotConfig config) { refreshView(); }
private class ChooseColor implements ActionListener {
private int _minutes;
private JButton _button;
/**
* @param minutes the minutes (line) to change the color of...
* @param button the associated button
*/
public ChooseColor(int minutes, JButton button) {
_minutes = minutes;
_button = button;
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent evt) {
PeerPlotConfig.PlotSeriesConfig cfg = getConfig(_minutes);
Color origColor = null;
if (cfg != null)
origColor = cfg.getPlotLineColor();
Color color = JColorChooser.showDialog(PeerPlotConfigPane.this, "What color should this line be?", origColor);
if (color != null) {
if (cfg != null)
cfg.setPlotLineColor(color);
_button.setBackground(color);
}
}
}
private class OptionLine {
int _durationMinutes;
JCheckBox _send;
JCheckBox _recv;
JCheckBox _lost;
JCheckBox _all;
JButton _color;
/**
* Creates an OptionLine.
* @param durationMinutes the minutes =)
*/
public OptionLine(int durationMinutes) {
_durationMinutes = durationMinutes;
_send = new JCheckBox("send time");
_send.setBackground(_background);
_recv = new JCheckBox("receive time");
_recv.setBackground(_background);
_lost = new JCheckBox("lost messages");
_lost.setBackground(_background);
_all = new JCheckBox("all");
_all.setBackground(_background);
_color = new JButton("color");
int r = _rnd.nextInt(255);
if (r < 0) r = -r;
int g = _rnd.nextInt(255);
if (g < 0) g = -g;
int b = _rnd.nextInt(255);
if (b < 0) b = -b;
//_color.setBackground(new Color(r, g, b));
_color.setBackground(_background);
_send.addActionListener(new UpdateListener(OptionLine.this, _durationMinutes));
_recv.addActionListener(new UpdateListener(OptionLine.this, _durationMinutes));
_lost.addActionListener(new UpdateListener(OptionLine.this, _durationMinutes));
_all.addActionListener(new UpdateListener(OptionLine.this, _durationMinutes));
_color.addActionListener(new ChooseColor(durationMinutes, _color));
_color.setEnabled(false);
}
}
private class UpdateListener implements ActionListener {
private OptionLine _line;
private int _minutes;
/**
* Update Listener constructor . . .
* @param line the line
* @param minutes the minutes
*/
public UpdateListener(OptionLine line, int minutes) {
_line = line;
_minutes = minutes;
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent evt) {
PeerPlotConfig.PlotSeriesConfig cfg = getConfig(_minutes);
cfg.getPlotConfig().disableEvents();
_log.debug("Updating data for minutes ["+ _line._durationMinutes + "]: send [" +
_line._send.isSelected() + "/" + cfg.getPlotSendTime() + "] recv [" +
_line._recv.isSelected() + "/" + cfg.getPlotReceiveTime() + "] lost [" +
_line._lost.isSelected() + "/" + cfg.getPlotLostMessages() + "]: config = " + cfg);
boolean force = _line._all.isSelected();
cfg.setPlotSendTime(_line._send.isSelected() || force);
cfg.setPlotReceiveTime(_line._recv.isSelected() || force);
cfg.setPlotLostMessages(_line._lost.isSelected() || force);
cfg.getPlotConfig().enableEvents();
cfg.getPlotConfig().fireUpdate();
}
}
/**
* Unit test stuff
* @param args da arsg
*/
public final static void main(String args[]) {
Test t = new Test();
t.runTest();
}
private final static class Test implements PeerPlotStateFetcher.FetchStateReceptor {
/**
* Runs da test
*/
public void runTest() {
PeerPlotConfig cfg = new PeerPlotConfig("C:\\testnet\\r2\\heartbeatStat_10s_30kb.txt");
PeerPlotState state = new PeerPlotState(cfg);
PeerPlotStateFetcher.fetchPeerPlotState(this, state);
try { Thread.sleep(60*1000); } catch (InterruptedException ie) {}
System.exit(-1);
}
/* (non-Javadoc)
* @see net.i2p.heartbeat.gui.PeerPlotStateFetcher.FetchStateReceptor#peerPlotStateFetched(net.i2p.heartbeat.gui.PeerPlotState)
*/
public void peerPlotStateFetched(PeerPlotState state) {
javax.swing.JFrame f = new javax.swing.JFrame("Test");
f.getContentPane().add(new JScrollPane(new PeerPlotConfigPane(state.getPlotConfig(), null)));
f.pack();
f.setVisible(true);
}
}
}

View File

@@ -0,0 +1,95 @@
package net.i2p.heartbeat.gui;
/**
* Current data + plot config for a particular test
*
*/
class PeerPlotState {
private StaticPeerData _currentData;
private PeerPlotConfig _plotConfig;
/**
* Delegating constructor . . .
* @see PeerPlotState#PeerPlotState(PeerPlotConfig, StaticPeerData)
*/
public PeerPlotState() {
this(null, null);
}
/**
* Delegating constructor . . .
* @param config plot config
* @see PeerPlotState#PeerPlotState(PeerPlotConfig, StaticPeerData)
*/
public PeerPlotState(PeerPlotConfig config) {
this(config, new StaticPeerData(config.getClientConfig()));
}
/**
* Creates a PeerPlotState
* @param config plot config
* @param data peer data
*/
public PeerPlotState(PeerPlotConfig config, StaticPeerData data) {
_plotConfig = config;
_currentData = data;
}
/**
* Add an average
* @param minutes mins averaged over
* @param sendMs how much later did the peer receieve
* @param recvMs how much later did we receieve
* @param lost how many were lost
*/
public void addAverage(int minutes, int sendMs, int recvMs, int lost) {
// make sure we've got the config entry for the average
_plotConfig.addAverage(minutes);
// add the data point...
_currentData.addAverage(minutes, sendMs, recvMs, lost);
}
/**
* we successfully got a ping/pong through
*
* @param sendTime when did the ping get sent?
* @param sendMs how much later did the peer receive the ping?
* @param recvMs how much later than that did we receive the pong?
*/
public void addSuccess(long sendTime, int sendMs, int recvMs) {
_currentData.addData(sendTime, sendMs, recvMs);
}
/**
* we lost a ping/pong
*
* @param sendTime when did we send the ping?
*/
public void addLost(long sendTime) {
_currentData.addData(sendTime);
}
/**
* data set to render
* @return the data set
*/
public StaticPeerData getCurrentData() { return _currentData; }
/**
* Sets the data set to render
* @param data the data set
*/
public void setCurrentData(StaticPeerData data) { _currentData = data; }
/**
* configuration options on how to render the data set
* @return the config options
*/
public PeerPlotConfig getPlotConfig() { return _plotConfig; }
/**
* Sets the configuration options on how to render the data
* @param config the config options
*/
public void setPlotConfig(PeerPlotConfig config) { _plotConfig = config; }
}

View File

@@ -0,0 +1,363 @@
package net.i2p.heartbeat.gui;
import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.StringTokenizer;
import net.i2p.data.DataFormatException;
import net.i2p.data.Destination;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
class PeerPlotStateFetcher {
private final static Log _log = new Log(PeerPlotStateFetcher.class);
/**
* Fetch and fill the specified state structure
* @param receptor the 'receptor' (callbacks)
* @param state the state
*/
public static void fetchPeerPlotState(FetchStateReceptor receptor, PeerPlotState state) {
I2PThread t = new I2PThread(new Fetcher(receptor, state));
t.setDaemon(true);
t.setName("Fetch state from " + state.getPlotConfig().getLocation());
t.start();
}
/**
* Callback stuff . . .
*/
public interface FetchStateReceptor {
/**
* Called when a peer plot state is fetched
* @param state state that was fetched
*/
void peerPlotStateFetched(PeerPlotState state);
}
private static class Fetcher implements Runnable {
private PeerPlotState _state;
private FetchStateReceptor _receptor;
/**
* Creates a Fetcher thread
* @param receptor the 'receptor' (callbacks)
* @param state the state
*/
public Fetcher(FetchStateReceptor receptor, PeerPlotState state) {
_state = state;
_receptor = receptor;
}
/* (non-Javadoc)
* @see java.lang.Runnable#run()
*/
public void run() {
String loc = _state.getPlotConfig().getLocation();
_log.debug("Load called [" + loc + "]");
InputStream in = null;
try {
try {
URL location = new URL(loc);
in = location.openStream();
} catch (MalformedURLException mue) {
_log.debug("Not a url [" + loc + "]");
in = null;
}
if (in == null)
in = new FileInputStream(loc);
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
while ( (line = reader.readLine()) != null) {
handleLine(line);
}
if (valid())
_receptor.peerPlotStateFetched(_state);
} catch (IOException ioe) {
_log.error("Error retrieving from the location [" + loc + "]", ioe);
} finally {
if (in != null) try { in.close(); } catch (IOException ioe) {}
}
}
/**
* check to make sure we've got everything we need
* @return true [always]
*/
boolean valid() {
return true;
}
/**
* handle a line from the data set - these can be formatted in one of the
* following ways. <p />
*
* <pre>
* peer khWYqCETu9YtPUvGV92ocsbEW5DezhKlIG7ci8RLX3g=
* local u-9hlR1ik2hemXf0HvKMfeRgrS86CbNQh25e7XBhaQE=
* peerDest [base 64 of the full destination]
* localDest [base 64 of the full destination]
* numTunnelHops 2
* comment Test with localhost sending 30KB every 20 seconds
* sendFrequency 20
* sendSize 30720
* sessionStart 20040409.22:51:10.915
* currentTime 20040409.23:31:39.607
* numPending 2
* lifetimeSent 118
* lifetimeRecv 113
* #averages minutes sendMs recvMs numLost
* periodAverage 1 1843 771 0
* periodAverage 5 786 752 1
* periodAverage 30 855 735 3
* #action status date and time sent sendMs replyMs
* EVENT OK 20040409.23:21:44.742 691 670
* EVENT OK 20040409.23:22:05.201 671 581
* EVENT OK 20040409.23:22:26.301 1182 1452
* EVENT OK 20040409.23:22:47.322 24304 1723
* EVENT OK 20040409.23:23:08.232 2293 1081
* EVENT OK 20040409.23:23:29.332 1392 641
* EVENT OK 20040409.23:23:50.262 641 761
* EVENT OK 20040409.23:24:11.102 651 701
* EVENT OK 20040409.23:24:31.401 841 621
* EVENT OK 20040409.23:24:52.061 651 681
* EVENT OK 20040409.23:25:12.480 701 1623
* EVENT OK 20040409.23:25:32.990 1442 1212
* EVENT OK 20040409.23:25:54.230 591 631
* EVENT OK 20040409.23:26:14.620 620 691
* EVENT OK 20040409.23:26:35.199 1793 1432
* EVENT OK 20040409.23:26:56.570 661 641
* EVENT OK 20040409.23:27:17.200 641 660
* EVENT OK 20040409.23:27:38.120 611 921
* EVENT OK 20040409.23:27:58.699 831 621
* EVENT OK 20040409.23:28:19.559 801 661
* EVENT OK 20040409.23:28:40.279 601 611
* EVENT OK 20040409.23:29:00.648 601 621
* EVENT OK 20040409.23:29:21.288 701 661
* EVENT LOST 20040409.23:29:41.828
* EVENT LOST 20040409.23:30:02.327
* EVENT LOST 20040409.23:30:22.656
* EVENT OK 20040409.23:31:24.305 1843 771
* </pre>
*
* @param line (see above)
*/
private void handleLine(String line) {
if (line.startsWith("peerDest"))
handlePeerDest(line);
else if (line.startsWith("localDest"))
handleLocalDest(line);
else if (line.startsWith("numTunnelHops"))
handleNumTunnelHops(line);
else if (line.startsWith("comment"))
handleComment(line);
else if (line.startsWith("sendFrequency"))
handleSendFrequency(line);
else if (line.startsWith("sendSize"))
handleSendSize(line);
else if (line.startsWith("periodAverage"))
handlePeriodAverage(line);
else if (line.startsWith("EVENT"))
handleEvent(line);
else if (line.startsWith("numPending"))
handleNumPending(line);
else if (line.startsWith("sessionStart"))
handleSessionStart(line);
else
_log.debug("Not handled: " + line);
}
private void handlePeerDest(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
String destKey = tok.nextToken();
try {
Destination d = new Destination();
d.fromBase64(destKey);
_state.getPlotConfig().getClientConfig().setPeer(d);
_log.debug("Setting the peer to " + d.calculateHash().toBase64());
} catch (DataFormatException dfe) {
_log.error("Unable to parse the peerDest line: [" + line + "]", dfe);
}
}
private void handleLocalDest(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
String destKey = tok.nextToken();
try {
Destination d = new Destination();
d.fromBase64(destKey);
_state.getPlotConfig().getClientConfig().setUs(d);
} catch (DataFormatException dfe) {
_log.error("Unable to parse the localDest line: [" + line + "]", dfe);
}
}
private void handleComment(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
StringBuffer buf = new StringBuffer(line.length()-32);
while (tok.hasMoreTokens())
buf.append(tok.nextToken()).append(' ');
_state.getPlotConfig().getClientConfig().setComment(buf.toString());
}
private void handleNumTunnelHops(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
String num = tok.nextToken();
try {
int val = Integer.parseInt(num);
_state.getPlotConfig().getClientConfig().setNumHops(val);
} catch (NumberFormatException nfe) {
_log.error("Unable to parse the numTunnelHops line: [" + line + "]", nfe);
}
}
private void handleNumPending(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
String num = tok.nextToken();
try {
int val = Integer.parseInt(num);
_state.getCurrentData().setPendingCount(val);
} catch (NumberFormatException nfe) {
_log.error("Unable to parse the numPending line: [" + line + "]", nfe);
}
}
private void handleSendFrequency(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
String num = tok.nextToken();
try {
int val = Integer.parseInt(num);
_state.getPlotConfig().getClientConfig().setSendFrequency(val);
} catch (NumberFormatException nfe) {
_log.error("Unable to parse the sendFrequency line: [" + line + "]", nfe);
}
}
private void handleSendSize(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
String num = tok.nextToken();
try {
int val = Integer.parseInt(num);
_state.getPlotConfig().getClientConfig().setSendSize(val);
} catch (NumberFormatException nfe) {
_log.error("Unable to parse the sendSize line: [" + line + "]", nfe);
}
}
private void handleSessionStart(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
String date = tok.nextToken();
try {
long when = getDate(date);
_state.getCurrentData().setSessionStart(when);
} catch (NumberFormatException nfe) {
_log.error("Unable to parse the sessionStart line: [" + line + "]", nfe);
}
}
private void handlePeriodAverage(String line) {
StringTokenizer tok = new StringTokenizer(line);
tok.nextToken(); // ignore;
try {
// periodAverage minutes sendMs recvMs numLost
int min = Integer.parseInt(tok.nextToken());
int send = Integer.parseInt(tok.nextToken());
int recv = Integer.parseInt(tok.nextToken());
int lost = Integer.parseInt(tok.nextToken());
_state.addAverage(min, send, recv, lost);
} catch (NumberFormatException nfe) {
_log.error("Unable to parse the sendSize line: [" + line + "]", nfe);
}
}
private void handleEvent(String line) {
StringTokenizer tok = new StringTokenizer(line);
// * EVENT OK 20040409.23:29:21.288 701 661
// * EVENT LOST 20040409.23:29:41.828
tok.nextToken(); // ignore first two
tok.nextToken();
try {
long when = getDate(tok.nextToken());
if (when < 0) {
_log.error("Invalid EVENT line: [" + line + "]");
return;
}
if (tok.hasMoreTokens()) {
int sendMs = Integer.parseInt(tok.nextToken());
int recvMs = Integer.parseInt(tok.nextToken());
_state.addSuccess(when, sendMs, recvMs);
} else {
_state.addLost(when);
}
} catch (NumberFormatException nfe) {
_log.error("Unable to parse the EVENT line: [" + line + "]", nfe);
}
}
private static final SimpleDateFormat _fmt = new SimpleDateFormat("yyyyMMdd.HH:mm:ss.SSS", Locale.UK);
private long getDate(String date) {
synchronized (_fmt) {
try {
return _fmt.parse(date).getTime();
} catch (ParseException pe) {
_log.error("Unable to parse the date [" + date + "]", pe);
return -1;
}
}
}
private void fakeRun() {
try {
Destination peer = new Destination();
Destination us = new Destination();
peer.fromBase64("3RPLOkQGlq8anNyNWhjbMyHxpAvUyUJKbiUejI80DnPR59T3blc7-XrBhQ2iPbf-BRAR~v1j34Kpba1eDyhPk2gevsE6ULO1irarJ3~C9WcQH2wAbNiVwfWqbh6onQ~YmkSpGNwGHD6ytwbvTyXeBJ" +
"cS8e6gmfNN-sYLn1aQu8UqWB3D6BmTfLtyS3eqWVk66Nrzmwy8E1Hvq5z~1lukYb~cyiDO1oZHAOLyUQtd9eN16yJY~2SRG8LiscpPMl9nSJUr6fmXMUubW-M7QGFH82Om-735PJUk6WMy1Hi9Vgh4Pxhdl7g" +
"fqGRWioFABdhcypb7p1Ca77p73uabLDFK-SjIYmdj7TwSdbNa6PCmzEvCEW~IZeZmnZC5B6pK30AdmD9vc641wUGce9xTJVfNRupf5L7pSsVIISix6FkKQk-FTW2RsZKLbuMCYMaPzLEx5gzODEqtI6Jf2teM" +
"d5xCz51RPayDJl~lJ-W0IWYfosnjM~KxYaqc4agviBuF5ZWeAAAA");
us.fromBase64("W~JFpqSH8uopylox2V5hMbpcHSsb-dJkSKvdJ1vj~KQcUFJWXFyfbetBAukcGH5S559aK9oslU0qbVoMDlJITVC4OXfXSnVbJBP1IhsK8SvjSYicjmIi2fA~k4HvSh9Wxu~bg8yo~jgfHA8tjYpp" +
"K9QKc56BpkJb~hx0nNGy4Ny9eW~6A5AwAmHvwdt5NqcREYRMjRd63dMGm8BcEe-6FbOyMo3dnIFcETWAe8TCeoMxm~S1n~6Jlinw3ETxv-L6lQkhFFWnC5zyzQ~4JhVxxT3taTMYXg8td4CBGmrS078jcjW63" +
"rlSiQgZBlYfN3iEYmurhuIEV9NXRcmnMrBOQUAoXPpVuRIxJbaQNDL71FO2iv424n4YjKs84suAho34GGQKq7WoL5V5KQgihfcl0f~xne-qP3FtpoPFeyA9x-sA2JWDAsxoZlfvgkiP5eyOn23prT9TJK47HC" +
"VilHSV11uTVaC4Jc5YsjoBCZadWbgQnMCKlZ4jk-bLE1PSWLg7AAAA");
_state.getPlotConfig().getClientConfig().setPeer(peer);
_state.getPlotConfig().getClientConfig().setUs(us);
_state.getPlotConfig().getClientConfig().setNumHops(2);
_state.getPlotConfig().getClientConfig().setComment("we do stuff\nreally nifty stuff. really");
_state.getPlotConfig().getClientConfig().setAveragePeriods(new int[] { 1, 5, 30, 60 });
int rnd = new java.util.Random().nextInt();
if (rnd > 0)
rnd = rnd % 10;
else
rnd = (-rnd) % 10;
_state.getPlotConfig().getClientConfig().setSendFrequency(rnd);
_state.getPlotConfig().getClientConfig().setSendSize(16*1024);
_state.getPlotConfig().getClientConfig().setStatDuration(10);
_state.getPlotConfig().rebuildAverageSeriesConfigs();
_state.setCurrentData(new StaticPeerData(_state.getPlotConfig().getClientConfig()));
_receptor.peerPlotStateFetched(_state);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

View File

@@ -0,0 +1,134 @@
package net.i2p.heartbeat.gui;
import java.util.HashMap;
import java.util.Map;
import net.i2p.heartbeat.ClientConfig;
import net.i2p.heartbeat.PeerData;
/**
* Raw data points for a test
*/
class StaticPeerData extends PeerData {
private int _pending;
/** Integer (period, in minutes) to Integer (milliseconds) for sending a ping */
private Map _averageSendTimes;
/** Integer (period, in minutes) to Integer (milliseconds) for receiving a pong */
private Map _averageReceiveTimes;
/** Integer (period, in minutes) to Integer (num messages) of how many messages were lost on average */
private Map _lostMessages;
/**
* Creates a static peer data with a specified client config ... duh
* @param config the client config
*/
public StaticPeerData(ClientConfig config) {
super(config);
_averageSendTimes = new HashMap(4);
_averageReceiveTimes = new HashMap(4);
_lostMessages = new HashMap(4);
}
/**
* Adds averaged data
* @param minutes the minutes (averaged over)
* @param sendMs the send time (ping) in milliseconds
* @param recvMs the receive time (pong) in milliseconds
* @param lost the number lost
*/
public void addAverage(int minutes, int sendMs, int recvMs, int lost) {
_averageSendTimes.put(new Integer(minutes), new Integer(sendMs));
_averageReceiveTimes.put(new Integer(minutes), new Integer(recvMs));
_lostMessages.put(new Integer(minutes), new Integer(lost));
}
/**
* Sets the number pending
* @param numPending the number pending
*/
public void setPendingCount(int numPending) { _pending = numPending; }
/* (non-Javadoc)
* @see net.i2p.heartbeat.PeerData#setSessionStart(long)
*/
public void setSessionStart(long when) { super.setSessionStart(when); }
/**
* Adds data
* @param sendTime the time it was sent
* @param sendMs the send time (ping) in milliseconds
* @param recvMs the receive time (pong) in milliseconds
*/
public void addData(long sendTime, int sendMs, int recvMs) {
PeerData.EventDataPoint dataPoint = new PeerData.EventDataPoint(sendTime);
dataPoint.setPongSent(sendTime + sendMs);
dataPoint.setPongReceived(sendTime + sendMs + recvMs);
dataPoint.setWasPonged(true);
addDataPoint(dataPoint);
}
/**
* Adds data
* @param sendTime the time it was sent
*/
public void addData(long sendTime) {
PeerData.EventDataPoint dataPoint = new PeerData.EventDataPoint(sendTime);
dataPoint.setWasPonged(false);
addDataPoint(dataPoint);
}
/**
* how many pings are still outstanding?
* @return the number of pings outstanding
*/
public int getPendingCount() { return _pending; }
/**
* average time to send over the given period.
*
* @param period number of minutes to retrieve the average for
* @return milliseconds average, or -1 if we dont track that period
*/
public double getAverageSendTime(int period) {
Integer i = (Integer)_averageSendTimes.get(new Integer(period));
if (i == null)
return -1;
else
return i.doubleValue();
}
/**
* average time to receive over the given period.
*
* @param period number of minutes to retrieve the average for
* @return milliseconds average, or -1 if we dont track that period
*/
public double getAverageReceiveTime(int period) {
Integer i = (Integer)_averageReceiveTimes.get(new Integer(period));
if (i == null)
return -1;
else
return i.doubleValue();
}
/**
* number of lost messages over the given period.
*
* @param period number of minutes to retrieve the average for
* @return number of lost messages in the period, or -1 if we dont track that period
*/
public double getLostMessages(int period) {
Integer i = (Integer)_lostMessages.get(new Integer(period));
if (i == null)
return -1;
else
return i.doubleValue();
}
/* (non-Javadoc)
* @see net.i2p.heartbeat.PeerData#cleanup()
*/
public void cleanup() {}
}

View File

@@ -4,7 +4,7 @@
<target name="build" depends="builddep, jar" />
<target name="builddep">
<ant dir="../../ministreaming/java/" target="build" />
<ant dir="../../../core/java/" target="build" />
<!-- ministreaming will build core -->
</target>
<target name="compile">
<mkdir dir="./build" />
@@ -37,11 +37,11 @@
<delete dir="./build" />
</target>
<target name="cleandep" depends="clean">
<ant dir="../../../core/java/" target="cleandep" />
<!-- ministreaming will clean core -->
<ant dir="../../ministreaming/java/" target="distclean" />
</target>
<target name="distclean" depends="clean">
<ant dir="../../../core/java/" target="distclean" />
<!-- ministreaming will clean core -->
<ant dir="../../ministreaming/java/" target="distclean" />
</target>
</project>

View File

@@ -19,49 +19,69 @@ public class HTTPListener extends Thread {
private String listenHost;
private SocketManagerProducer smp;
public HTTPListener(SocketManagerProducer smp, int port,
String listenHost) {
this.smp = smp;
this.port = port;
start();
/**
* A public constructor. It contstructs things. In this case,
* it constructs a nice HTTPListener, for all your listening on
* HTTP needs. Yep. That's right.
* @param smp A SocketManagerProducer, producing Sockets, no doubt
* @param port A port, to connect to.
* @param listenHost A host, to connect to.
*/
public HTTPListener(SocketManagerProducer smp, int port, String listenHost) {
this.smp = smp;
this.port = port;
start();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run() {
try {
InetAddress lh = listenHost == null
? null
: InetAddress.getByName(listenHost);
ServerSocket ss = new ServerSocket(port, 0, lh);
while(true) {
Socket s = ss.accept();
new HTTPSocketHandler(this, s);
}
} catch (IOException ex) {
_log.error("Error while accepting connections", ex);
}
try {
InetAddress lh = listenHost == null ? null : InetAddress.getByName(listenHost);
ServerSocket ss = new ServerSocket(port, 0, lh);
while (true) {
Socket s = ss.accept();
new HTTPSocketHandler(this, s);
}
} catch (IOException ex) {
_log.error("Error while accepting connections", ex);
}
}
private boolean proxyUsed=false;
private boolean proxyUsed = false;
/**
* Query whether this is the first use of the proxy or not
* @return Whether this is the first proxy use, no doubt.
*/
public boolean firstProxyUse() {
// FIXME: check a config option here
if (true) return false;
if (proxyUsed) {
return false;
} else {
proxyUsed=true;
return true;
}
// FIXME: check a config option here
if (true) return false;
if (proxyUsed) {
return false;
} else {
proxyUsed = true;
return true;
}
}
/**
* @return The SocketManagerProducer being used.
*/
public SocketManagerProducer getSMP() {
return smp;
return smp;
}
/** @deprecated */
/**
* Outputs with HTTP 1.1 flair that a feature isn't implemented.
* @param out The stream the text goes to.
* @deprecated
* @throws IOException
*/
public void handleNotImplemented(OutputStream out) throws IOException {
out.write(("HTTP/1.1 200 Document following\n\n"+
"<h1>Feature not implemented</h1>").getBytes("ISO-8859-1"));
out.flush();
out.write(("HTTP/1.1 200 Document following\n\n" + "<h1>Feature not implemented</h1>").getBytes("ISO-8859-1"));
out.flush();
}
}
}

View File

@@ -21,34 +21,42 @@ public class HTTPSocketHandler extends Thread {
private HTTPListener httpl;
private RootHandler h;
/**
* A public constructor.
* @param httpl An HTTPListener, to listen for HTTP, no doubt
* @param s A socket.
*/
public HTTPSocketHandler(HTTPListener httpl, Socket s) {
this.httpl = httpl;
this.s=s;
h = RootHandler.getInstance();
start();
this.httpl = httpl;
this.s = s;
h = RootHandler.getInstance();
start();
}
/* (non-Javadoc)
* @see java.lang.Thread#run()
*/
public void run() {
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(s.getInputStream());
out = new BufferedOutputStream(s.getOutputStream());
Request req = new Request(in);
h.handle(req, httpl, out);
} catch (IOException ex) {
_log.error("Error while handling data", ex);
} finally {
try {
if (in != null) in.close();
if (out != null) {
out.flush();
out.close();
}
s.close();
} catch (IOException ex) {
_log.error("IOException in finalizer", ex);
}
}
InputStream in = null;
OutputStream out = null;
try {
in = new BufferedInputStream(s.getInputStream());
out = new BufferedOutputStream(s.getOutputStream());
Request req = new Request(in);
h.handle(req, httpl, out);
} catch (IOException ex) {
_log.error("Error while handling data", ex);
} finally {
try {
if (in != null) in.close();
if (out != null) {
out.flush();
out.close();
}
s.close();
} catch (IOException ex) {
_log.error("IOException in finalizer", ex);
}
}
}
}
}

View File

@@ -41,13 +41,12 @@ public class HTTPTunnel {
*
* @param initialManagers a list of socket managers to use
* @param maxManagers how many managers to have in the cache
* @param mcDonaldsMode whether to throw away a manager after use
* @param shouldThrowAwayManagers whether to throw away a manager after use
* @param listenPort which port to listen on
*/
public HTTPTunnel(I2PSocketManager[] initialManagers, int maxManagers,
boolean mcDonaldsMode, int listenPort) {
this(initialManagers, maxManagers, mcDonaldsMode, listenPort,
"127.0.0.1", 7654);
public HTTPTunnel(I2PSocketManager[] initialManagers, int maxManagers, boolean shouldThrowAwayManagers,
int listenPort) {
this(initialManagers, maxManagers, shouldThrowAwayManagers, listenPort, "127.0.0.1", 7654);
}
/**
@@ -55,56 +54,55 @@ public class HTTPTunnel {
*
* @param initialManagers a list of socket managers to use
* @param maxManagers how many managers to have in the cache
* @param mcDonaldsMode whether to throw away a manager after use
* @param shouldThrowAwayManagers whether to throw away a manager after use
* @param listenPort which port to listen on
* @param i2cpAddress the I2CP address
* @param i2cpPort the I2CP port
*/
public HTTPTunnel(I2PSocketManager[] initialManagers, int maxManagers,
boolean mcDonaldsMode, int listenPort,
String i2cpAddress, int i2cpPort) {
SocketManagerProducer smp =
new SocketManagerProducer(initialManagers, maxManagers,
mcDonaldsMode, i2cpAddress, i2cpPort);
new HTTPListener(smp, listenPort, "127.0.0.1");
public HTTPTunnel(I2PSocketManager[] initialManagers, int maxManagers, boolean shouldThrowAwayManagers,
int listenPort, String i2cpAddress, int i2cpPort) {
SocketManagerProducer smp = new SocketManagerProducer(initialManagers, maxManagers, shouldThrowAwayManagers,
i2cpAddress, i2cpPort);
new HTTPListener(smp, listenPort, "127.0.0.1");
}
/**
* The all important main function, allowing HTTPTunnel to be
* stand-alone, a program in it's own right, and all that jazz.
* @param args A list of String passed to the program
*/
public static void main(String[] args) {
String host = "127.0.0.1";
int port = 7654, max = 1;
boolean mc = false;
if (args.length >1) {
if (args.length == 4) {
host = args[2];
port = Integer.parseInt(args[3]);
} else if (args.length != 2) {
showInfo(); return;
}
max = Integer.parseInt(args[1]);
} else if (args.length != 1) {
showInfo(); return;
}
if (max == 0) {
max = 1;
} else if (max <0) {
max = -max;
mc = true;
}
new HTTPTunnel(null, max, mc, Integer.parseInt(args[0]), host, port);
String host = "127.0.0.1";
int port = 7654, max = 1;
boolean throwAwayManagers = false;
if (args.length > 1) {
if (args.length == 4) {
host = args[2];
port = Integer.parseInt(args[3]);
} else if (args.length != 2) {
showInfo();
return;
}
max = Integer.parseInt(args[1]);
} else if (args.length != 1) {
showInfo();
return;
}
if (max == 0) {
max = 1;
} else if (max < 0) {
max = -max;
throwAwayManagers = true;
}
new HTTPTunnel(null, max, throwAwayManagers, Integer.parseInt(args[0]), host, port);
}
private static void showInfo() {
System.out.println
("Usage: java HTTPTunnel <listenPort> [<max> "+
"[<i2cphost> <i2cpport>]]\n"+
" <listenPort> port to listen for browsers\n"+
" <max> max number of SocketMangers in pool, "+
"use neg. number\n"+
" to use each SocketManager only once "+
"(default: 1)\n"+
" <i2cphost> host to connect to the router "+
"(default: 127.0.0.1)\n"+
" <i2cpport> port to connect to the router "+
"(default: 7654)");
System.out.println("Usage: java HTTPTunnel <listenPort> [<max> " + "[<i2cphost> <i2cpport>]]\n"
+ " <listenPort> port to listen for browsers\n"
+ " <max> max number of SocketMangers in pool, " + "use neg. number\n"
+ " to use each SocketManager only once " + "(default: 1)\n"
+ " <i2cphost> host to connect to the router " + "(default: 127.0.0.1)\n"
+ " <i2cpport> port to connect to the router " + "(default: 7654)");
}
}
}

View File

@@ -22,109 +22,132 @@ public class Request {
private String proto;
private String params;
private String postData;
/**
* A constructor, creating a request from an InputStream
* @param in InputStream from which we "read-in" a Request
* @throws IOException
*/
public Request(InputStream in) throws IOException {
BufferedReader br = new BufferedReader
(new InputStreamReader(in, "ISO-8859-1"));
String line = br.readLine();
if (line == null) { // no data at all
method = null;
_log.error("Connection but no data");
return;
}
int pos = line.indexOf(" ");
if (pos == -1) {
method = line;
url="";
_log.error("Malformed HTTP request: "+line);
} else {
method = line.substring(0,pos);
url=line.substring(pos+1);
}
proto="";
pos = url.indexOf(" ");
if (pos != -1) {
proto=url.substring(pos); // leading space intended
url = url.substring(0,pos);
}
StringBuffer sb = new StringBuffer(512);
while((line=br.readLine()) != null) {
if (line.length() == 0) break;
sb.append(line).append("\r\n");
}
params = sb.toString(); // no leading empty line!
sb = new StringBuffer();
// hack for POST requests, ripped from HttpClient
// this won't work for large POSTDATA
// FIXME: do this better, please.
if (!method.equals("GET")) {
while (br.ready()) { // empty the buffer (POST requests)
int i=br.read();
if (i != -1) {
sb.append((char)i);
}
}
postData = sb.toString();
} else {
postData="";
}
BufferedReader br = new BufferedReader(new InputStreamReader(in, "ISO-8859-1"));
String line = br.readLine();
if (line == null) { // no data at all
method = null;
_log.error("Connection but no data");
return;
}
int pos = line.indexOf(" ");
if (pos == -1) {
method = line;
url = "";
_log.error("Malformed HTTP request: " + line);
} else {
method = line.substring(0, pos);
url = line.substring(pos + 1);
}
proto = "";
pos = url.indexOf(" ");
if (pos != -1) {
proto = url.substring(pos); // leading space intended
url = url.substring(0, pos);
}
StringBuffer sb = new StringBuffer(512);
while ((line = br.readLine()) != null) {
if (line.length() == 0) break;
sb.append(line).append("\r\n");
}
params = sb.toString(); // no leading empty line!
sb = new StringBuffer();
// hack for POST requests, ripped from HttpClient
// this won't work for large POSTDATA
// FIXME: do this better, please.
if (!method.equals("GET")) {
while (br.ready()) { // empty the buffer (POST requests)
int i = br.read();
if (i != -1) {
sb.append((char) i);
}
}
postData = sb.toString();
} else {
postData = "";
}
}
/**
* @return A Request as an array of bytes of a String in ISO-8859-1 format
* @throws IOException
*/
public byte[] toByteArray() throws IOException {
if (method == null) return null;
return toISO8859_1String().getBytes("ISO-8859-1");
if (method == null) return null;
return toISO8859_1String().getBytes("ISO-8859-1");
}
private String toISO8859_1String() throws IOException {
if (method == null) return null;
return method+" "+url+proto+"\r\n"+params+"\r\n"+postData;
if (method == null) return null;
return method + " " + url + proto + "\r\n" + params + "\r\n" + postData;
}
/**
* @return the URL of the request
*/
public String getURL() {
return url;
return url;
}
/**
* Sets the URL of the Request
* @param newURL the new URL
*/
public void setURL(String newURL) {
url=newURL;
url = newURL;
}
/**
* Retrieves the value of a param.
* @param name The name of the param
* @return The value of the param, or null
*/
public String getParam(String name) {
try {
BufferedReader br= new BufferedReader(new StringReader(params));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith(name)) {
return line.substring(name.length());
}
}
return null;
} catch (IOException ex) {
_log.error("Error getting parameter", ex);
return null;
}
try {
BufferedReader br = new BufferedReader(new StringReader(params));
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith(name)) { return line.substring(name.length()); }
}
return null;
} catch (IOException ex) {
_log.error("Error getting parameter", ex);
return null;
}
}
/**
* Sets the value of a param.
* @param name the name of the param
* @param value the value to be set
*/
public void setParam(String name, String value) {
try {
StringBuffer sb = new StringBuffer(params.length()+value.length());
BufferedReader br= new BufferedReader(new StringReader(params));
String line;
boolean replaced = false;
while((line=br.readLine()) != null) {
if (line.startsWith(name)) {
replaced=true;
if (value == null) continue; // kill param
line = name+value;
}
sb.append(line).append("\r\n");
}
if (!replaced && value != null) {
sb.append(name).append(value).append("\r\n");
}
params=sb.toString();
} catch (IOException ex) {
_log.error("Error getting parameter", ex);
}
try {
StringBuffer sb = new StringBuffer(params.length() + value.length());
BufferedReader br = new BufferedReader(new StringReader(params));
String line;
boolean replaced = false;
while ((line = br.readLine()) != null) {
if (line.startsWith(name)) {
replaced = true;
if (value == null) continue; // kill param
line = name + value;
}
sb.append(line).append("\r\n");
}
if (!replaced && value != null) {
sb.append(name).append(value).append("\r\n");
}
params = sb.toString();
} catch (IOException ex) {
_log.error("Error getting parameter", ex);
}
}
}
}

View File

@@ -1,7 +1,12 @@
package net.i2p.httptunnel;
import java.util.*;
import net.i2p.client.streaming.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Properties;
import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.client.streaming.I2PSocketManagerFactory;
/**
* Produces SocketManagers in a thread and gives them to those who
@@ -14,57 +19,58 @@ public class SocketManagerProducer extends Thread {
private int port;
private String host;
private int maxManagers;
private boolean mcDonalds;
private boolean shouldThrowAwayManagers;
public SocketManagerProducer(I2PSocketManager[] initialManagers,
int maxManagers,
boolean mcDonaldsMode,
String host, int port) {
if (maxManagers < 1) {
throw new IllegalArgumentException("maxManagers < 1");
}
this.host=host;
this.port=port;
mcDonalds=mcDonaldsMode;
if (initialManagers != null) {
myManagers.addAll(Arrays.asList(initialManagers));
}
this.maxManagers=maxManagers;
mcDonalds=mcDonaldsMode;
setDaemon(true);
start();
/**
* Public constructor creating a SocketManagerProducer
* @param initialManagers a list of socket managers to use
* @param maxManagers how many managers to have in the cache
* @param shouldThrowAwayManagers whether to throw away a manager after use
* @param host which host to listen on
* @param port which port to listen on
*/
public SocketManagerProducer(I2PSocketManager[] initialManagers, int maxManagers, boolean shouldThrowAwayManagers,
String host, int port) {
if (maxManagers < 1) { throw new IllegalArgumentException("maxManagers < 1"); }
this.host = host;
this.port = port;
this.shouldThrowAwayManagers = shouldThrowAwayManagers;
if (initialManagers != null) {
myManagers.addAll(Arrays.asList(initialManagers));
}
this.maxManagers = maxManagers;
this.shouldThrowAwayManagers = shouldThrowAwayManagers;
setDaemon(true);
start();
}
/**
* Thread producing new SocketManagers.
*/
public void run() {
while (true) {
synchronized(this) {
// without mcDonalds mode, we most probably need no
// new managers.
while (!mcDonalds && myManagers.size() == maxManagers) {
myWait();
}
}
// produce a new manager, regardless whether it is needed
// or not. Do not synchronized this part, since it can be
// quite time-consuming.
I2PSocketManager newManager =
I2PSocketManagerFactory.createManager(host, port,
new Properties());
// when done, check if it is needed.
synchronized(this) {
while(myManagers.size() == maxManagers) {
myWait();
}
myManagers.add(newManager);
notifyAll();
}
}
while (true) {
synchronized (this) {
// without mcDonalds mode, we most probably need no
// new managers.
while (!shouldThrowAwayManagers && myManagers.size() == maxManagers) {
myWait();
}
}
// produce a new manager, regardless whether it is needed
// or not. Do not synchronized this part, since it can be
// quite time-consuming.
I2PSocketManager newManager = I2PSocketManagerFactory.createManager(host, port, new Properties());
// when done, check if it is needed.
synchronized (this) {
while (myManagers.size() == maxManagers) {
myWait();
}
myManagers.add(newManager);
notifyAll();
}
}
}
/**
* Get a manager for connecting to a given destination. Each
* destination will always get the same manager.
@@ -73,12 +79,12 @@ public class SocketManagerProducer extends Thread {
* @return the SocketManager to use
*/
public synchronized I2PSocketManager getManager(String dest) {
I2PSocketManager result = (I2PSocketManager) usedManagers.get(dest);
if (result == null) {
result = getManager();
usedManagers.put(dest,result);
}
return result;
I2PSocketManager result = (I2PSocketManager) usedManagers.get(dest);
if (result == null) {
result = getManager();
usedManagers.put(dest, result);
}
return result;
}
/**
@@ -89,23 +95,26 @@ public class SocketManagerProducer extends Thread {
* @return the SocketManager to use
*/
public synchronized I2PSocketManager getManager() {
while (myManagers.size() == 0) {
myWait(); // no manager here, so wait until one is produced
}
int which = (int)(Math.random()*myManagers.size());
I2PSocketManager result = (I2PSocketManager) myManagers.get(which);
if (mcDonalds) {
myManagers.remove(which);
notifyAll();
}
return result;
while (myManagers.size() == 0) {
myWait(); // no manager here, so wait until one is produced
}
int which = (int) (Math.random() * myManagers.size());
I2PSocketManager result = (I2PSocketManager) myManagers.get(which);
if (shouldThrowAwayManagers) {
myManagers.remove(which);
notifyAll();
}
return result;
}
/**
* Wait until InterruptedException
*/
public void myWait() {
try {
wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
try {
wait();
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
}

View File

@@ -1,9 +1,11 @@
package net.i2p.httptunnel.filter;
import net.i2p.util.Log;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Collection;
import java.util.Iterator;
import java.io.*;
import java.util.*;
import net.i2p.util.Log;
/**
* Chain multiple filters. Decorator pattern...
@@ -11,40 +13,49 @@ import java.util.*;
public class ChainFilter implements Filter {
private static final Log _log = new Log(ChainFilter.class);
public Collection filters;
private Collection filters; // perhaps protected?
/**
* @param filters A collection (list) of filters to chain to
*/
public ChainFilter(Collection filters) {
this.filters=filters;
this.filters = filters;
}
/* (non-Javadoc)
* @see net.i2p.httptunnel.filter.Filter#filter(byte[])
*/
public byte[] filter(byte[] toFilter) {
byte[] buf = toFilter;
for (Iterator it = filters.iterator(); it.hasNext();) {
Filter f = (Filter) it.next();
buf = f.filter(buf);
}
return buf;
byte[] buf = toFilter;
for (Iterator it = filters.iterator(); it.hasNext();) {
Filter f = (Filter) it.next();
buf = f.filter(buf);
}
return buf;
}
/* (non-Javadoc)
* @see net.i2p.httptunnel.filter.Filter#finish()
*/
public byte[] finish() {
// this is a bit complicated. Think about it...
try {
byte[] buf = EMPTY;
for (Iterator it = filters.iterator(); it.hasNext();) {
Filter f = (Filter) it.next();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (buf.length != 0) {
baos.write(f.filter(buf));
}
baos.write(f.finish());
buf = baos.toByteArray();
}
return buf;
} catch (IOException ex) {
_log.error("Error chaining filters", ex);
return EMPTY;
}
// this is a bit complicated. Think about it...
try {
byte[] buf = EMPTY;
for (Iterator it = filters.iterator(); it.hasNext();) {
Filter f = (Filter) it.next();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
if (buf.length != 0) {
baos.write(f.filter(buf));
}
baos.write(f.finish());
buf = baos.toByteArray();
}
return buf;
} catch (IOException ex) {
_log.error("Error chaining filters", ex);
return EMPTY;
}
}
}
}

View File

@@ -12,11 +12,14 @@ public interface Filter {
/**
* Filter some data. Not all filtered data need to be returned.
* @param toFilter the bytes that are to be filtered.
* @return the filtered data
*/
public byte[] filter(byte[] toFilter);
/**
* Data stream has finished. Return all of the rest data.
* @return the rest of the data
*/
public byte[] finish();
}
}

View File

@@ -5,11 +5,17 @@ package net.i2p.httptunnel.filter;
*/
public class NullFilter implements Filter {
/* (non-Javadoc)
* @see net.i2p.httptunnel.filter.Filter#filter(byte[])
*/
public byte[] filter(byte[] toFilter) {
return toFilter;
return toFilter;
}
/* (non-Javadoc)
* @see net.i2p.httptunnel.filter.Filter#finish()
*/
public byte[] finish() {
return EMPTY;
return EMPTY;
}
}
}

View File

@@ -1,9 +1,11 @@
package net.i2p.httptunnel.handler;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.SocketException;
import net.i2p.I2PException;
import net.i2p.client.naming.NamingService;
@@ -17,6 +19,7 @@ import net.i2p.httptunnel.SocketManagerProducer;
import net.i2p.httptunnel.filter.Filter;
import net.i2p.httptunnel.filter.NullFilter;
import net.i2p.util.Log;
import net.i2p.I2PAppContext;
/**
* Handler for browsing Eepsites.
@@ -24,70 +27,88 @@ import net.i2p.util.Log;
public class EepHandler {
private static final Log _log = new Log(EepHandler.class);
private static I2PAppContext _context = new I2PAppContext();
protected ErrorHandler errorHandler;
/* package private */ EepHandler(ErrorHandler eh) {
errorHandler=eh;
}
public void handle(Request req, HTTPListener httpl, OutputStream out,
boolean fromProxy, String destination)
throws IOException {
SocketManagerProducer smp = httpl.getSMP();
Destination dest = NamingService.getInstance().lookup(destination);
if (dest == null) {
errorHandler.handle(req, httpl, out,
"Could not lookup host: "+destination);
return;
}
I2PSocketManager sm = smp.getManager(destination);
Filter f = new NullFilter(); //FIXME: use other filter
req.setParam("Host: ", dest.toBase64());
if (!handle(req, f, out, dest, sm)) {
errorHandler.handle(req, httpl, out, "Unable to reach peer");
}
/* package private */EepHandler(ErrorHandler eh) {
errorHandler = eh;
}
public boolean handle(Request req, Filter f, OutputStream out,
Destination dest, I2PSocketManager sm)
throws IOException {
I2PSocket s = null;
boolean written = false;
try {
synchronized(sm) {
s = sm.connect(dest, new I2PSocketOptions());
}
InputStream in = new BufferedInputStream(s.getInputStream());
OutputStream sout = new BufferedOutputStream(s.getOutputStream());
sout.write(req.toByteArray());
sout.flush();
byte[] buffer = new byte[16384], filtered;
int len;
while ((len=in.read(buffer)) != -1) {
if (len != buffer.length) {
byte[] b2 = new byte[len];
System.arraycopy(buffer, 0, b2, 0, len);
filtered=f.filter(b2);
} else {
filtered=f.filter(buffer);
}
written=true;
out.write(filtered);
}
filtered=f.finish();
written=true;
out.write(filtered);
out.flush();
} catch (IOException ex) {
_log.error("Error while handling eepsite request");
return written;
} catch (I2PException ex) {
_log.error("Error while handling eepsite request");
return written;
} finally {
if (s != null) s.close();
}
return true;
/**
* @param req the Request
* @param httpl an HTTPListener
* @param out where to write the results
* @param destination destination as a string, (subject to naming
* service lookup)
* @throws IOException
*/
public void handle(Request req, HTTPListener httpl, OutputStream out,
/* boolean fromProxy, */String destination) throws IOException {
SocketManagerProducer smp = httpl.getSMP();
Destination dest = _context.namingService().lookup(destination);
if (dest == null) {
errorHandler.handle(req, httpl, out, "Could not lookup host: " + destination);
return;
}
I2PSocketManager sm = smp.getManager(destination);
Filter f = new NullFilter(); //FIXME: use other filter
req.setParam("Host: ", dest.toBase64());
if (!handle(req, f, out, dest, sm)) {
errorHandler.handle(req, httpl, out, "Unable to reach peer");
}
}
/**
* @param req the Request to send out
* @param f a Filter to apply to the bytes retrieved from the Destination
* @param out where to write the results
* @param dest the Destination of the Request
* @param sm an I2PSocketManager, to get a socket for the Destination
* @return boolean, true if something was written, false otherwise.
* @throws IOException
*/
public boolean handle(Request req, Filter f, OutputStream out, Destination dest,
I2PSocketManager sm) throws IOException {
I2PSocket s = null;
boolean written = false;
try {
synchronized (sm) {
s = sm.connect(dest, new I2PSocketOptions());
}
InputStream in = new BufferedInputStream(s.getInputStream());
OutputStream sout = new BufferedOutputStream(s.getOutputStream());
sout.write(req.toByteArray());
sout.flush();
byte[] buffer = new byte[16384], filtered;
int len;
while ((len = in.read(buffer)) != -1) {
if (len != buffer.length) {
byte[] b2 = new byte[len];
System.arraycopy(buffer, 0, b2, 0, len);
filtered = f.filter(b2);
} else {
filtered = f.filter(buffer);
}
written = true;
out.write(filtered);
}
filtered = f.finish();
written = true;
out.write(filtered);
out.flush();
} catch (SocketException ex) {
_log.error("Error while handling eepsite request");
return written;
} catch (IOException ex) {
_log.error("Error while handling eepsite request");
return written;
} catch (I2PException ex) {
_log.error("Error while handling eepsite request");
return written;
} finally {
if (s != null) s.close();
}
return true;
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.IOException;
import java.io.OutputStream;
@@ -13,24 +14,28 @@ public class ErrorHandler {
private static final Log _log = new Log(ErrorHandler.class);
/* package private */ ErrorHandler() {
/* package private */ErrorHandler() {
}
public void handle(Request req, HTTPListener httpl,
OutputStream out, String error) throws IOException {
// FIXME: Make nicer messages for more likely errors.
out.write(("HTTP/1.1 500 Internal Server Error\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n")
.getBytes("ISO-8859-1"));
out.write(("<html><head><title>"+error+"</title></head><body><h1>"+
error+"</h1>An internal error occurred while "+
"handling a request by HTTPTunnel:<br><b>"+error+
"</b><h2>Complete request:</h2><b>---</b><br><i><pre>\r\n")
.getBytes("ISO-8859-1"));
out.write(req.toByteArray());
out.write(("</pre></i><br><b>---</b></body></html>")
.getBytes("ISO-8859-1"));
out.flush();
/**
* @param req the Request
* @param httpl an HTTPListener
* @param out where to write the results
* @param error the error that happened
* @throws IOException
*/
public void handle(Request req, HTTPListener httpl, OutputStream out, String error) throws IOException {
// FIXME: Make nicer messages for more likely errors.
out
.write(("HTTP/1.1 500 Internal Server Error\r\n" + "Content-Type: text/html; charset=iso-8859-1\r\n\r\n")
.getBytes("ISO-8859-1"));
out
.write(("<html><head><title>" + error + "</title></head><body><h1>" + error
+ "</h1>An internal error occurred while " + "handling a request by HTTPTunnel:<br><b>" + error + "</b><h2>Complete request:</h2><b>---</b><br><i><pre>\r\n")
.getBytes("ISO-8859-1"));
out.write(req.toByteArray());
out.write(("</pre></i><br><b>---</b></body></html>").getBytes("ISO-8859-1"));
out.flush();
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.IOException;
import java.io.OutputStream;
@@ -14,36 +15,53 @@ public class LocalHandler {
private static final Log _log = new Log(LocalHandler.class);
/* package private */ LocalHandler() {
}
public void handle(Request req, HTTPListener httpl, OutputStream out,
boolean fromProxy) throws IOException {
//FIXME: separate multiple pages, not only a start page
//FIXME: provide some info on this page
out.write(("HTTP/1.1 200 Document following\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n\r\n"+
"<html><head><title>Welcome to I2P HTTPTunnel</title>"+
"</head><body><h1>Welcome to I2P HTTPTunnel</h1>You can "+
"browse Eepsites by adding an eepsite name to the request."+
"</body></html>").getBytes("ISO-8859-1"));
out.flush();
/* package private */LocalHandler() {
}
public void handleProxyConfWarning(Request req, HTTPListener httpl,
OutputStream out) throws IOException {
//FIXME
/**
* @param req the Request
* @param httpl an HTTPListener
* @param out where to write the results
* @throws IOException
*/
public void handle(Request req, HTTPListener httpl, OutputStream out
/*, boolean fromProxy */) throws IOException {
//FIXME: separate multiple pages, not only a start page
//FIXME: provide some info on this page
out
.write(("HTTP/1.1 200 Document following\r\n" + "Content-Type: text/html; charset=iso-8859-1\r\n\r\n"
+ "<html><head><title>Welcome to I2P HTTPTunnel</title>"
+ "</head><body><h1>Welcome to I2P HTTPTunnel</h1>You can "
+ "browse Eepsites by adding an eepsite name to the request." + "</body></html>")
.getBytes("ISO-8859-1"));
out.flush();
}
/**
* Currently always throws an IO Exception
* @param req the Request
* @param httpl an HTTPListener
* @param out where to write the results
* @throws IOException
*/
public void handleProxyConfWarning(Request req, HTTPListener httpl, OutputStream out) throws IOException {
//FIXME
throw new IOException("jrandom ate the deprecated method. mooo");
//httpl.handleNotImplemented(out);
//httpl.handleNotImplemented(out);
}
public void handleHTTPWarning(Request req, HTTPListener httpl,
OutputStream out, boolean fromProxy)
throws IOException {
// FIXME
/**
* Currently always throws an IO Exception
* @param req the Request
* @param httpl an HTTPListener
* @param out where to write the results
* @throws IOException
*/
public void handleHTTPWarning(Request req, HTTPListener httpl, OutputStream out /*, boolean fromProxy */)
throws IOException {
// FIXME
throw new IOException("jrandom ate the deprecated method. mooo");
//httpl.handleNotImplemented(out);
//httpl.handleNotImplemented(out);
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.IOException;
import java.io.OutputStream;
@@ -11,6 +12,7 @@ import net.i2p.httptunnel.SocketManagerProducer;
import net.i2p.httptunnel.filter.Filter;
import net.i2p.httptunnel.filter.NullFilter;
import net.i2p.util.Log;
import net.i2p.I2PAppContext;
/**
* Handler for proxying "normal" HTTP requests.
@@ -18,30 +20,36 @@ import net.i2p.util.Log;
public class ProxyHandler extends EepHandler {
private static final Log _log = new Log(ErrorHandler.class);
private static I2PAppContext _context = new I2PAppContext();
/* package private */ ProxyHandler(ErrorHandler eh) {
super(eh);
/* package private */ProxyHandler(ErrorHandler eh) {
super(eh);
}
public void handle(Request req, HTTPListener httpl, OutputStream out,
boolean fromProxy) throws IOException {
SocketManagerProducer smp = httpl.getSMP();
Destination dest = findProxy();
if (dest == null) {
errorHandler.handle(req, httpl, out,
"Could not find proxy");
return;
}
// one manager for all proxy requests
I2PSocketManager sm = smp.getManager("--proxy--");
Filter f = new NullFilter(); //FIXME: use other filter
if (!handle(req, f, out, dest, sm)) {
errorHandler.handle(req, httpl, out, "Unable to reach peer");
}
/**
* @param req a Request
* @param httpl an HTTPListener
* @param out where to write the results
* @throws IOException
*/
public void handle(Request req, HTTPListener httpl, OutputStream out
/*, boolean fromProxy */) throws IOException {
SocketManagerProducer smp = httpl.getSMP();
Destination dest = findProxy();
if (dest == null) {
errorHandler.handle(req, httpl, out, "Could not find proxy");
return;
}
// one manager for all proxy requests
I2PSocketManager sm = smp.getManager("--proxy--");
Filter f = new NullFilter(); //FIXME: use other filter
if (!handle(req, f, out, dest, sm)) {
errorHandler.handle(req, httpl, out, "Unable to reach peer");
}
}
private Destination findProxy() {
//FIXME!
return NamingService.getInstance().lookup("squid.i2p");
//FIXME!
return _context.namingService().lookup("squid.i2p");
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.httptunnel.handler;
import java.io.IOException;
import java.io.OutputStream;
@@ -14,96 +15,104 @@ public class RootHandler {
private static final Log _log = new Log(RootHandler.class);
private RootHandler() {
errorHandler=new ErrorHandler();
localHandler=new LocalHandler();
proxyHandler=new ProxyHandler(errorHandler);
eepHandler=new EepHandler(errorHandler);
errorHandler = new ErrorHandler();
localHandler = new LocalHandler();
proxyHandler = new ProxyHandler(errorHandler);
eepHandler = new EepHandler(errorHandler);
}
private ErrorHandler errorHandler;
private ProxyHandler proxyHandler;
private LocalHandler localHandler;
private EepHandler eepHandler;
private static RootHandler instance;
/**
* Singleton stuff
* @return the one and only instance, yay!
*/
public static synchronized RootHandler getInstance() {
if (instance == null) {
instance = new RootHandler();
}
return instance;
if (instance == null) {
instance = new RootHandler();
}
return instance;
}
public void handle(Request req, HTTPListener httpl,
OutputStream out) throws IOException {
String url=req.getURL();
System.out.println(url);
boolean byProxy = false;
int pos;
if (url.startsWith("http://")) { // access via proxy
byProxy=true;
if (httpl.firstProxyUse()) {
localHandler.handleProxyConfWarning(req,httpl,out);
return;
}
url = url.substring(7);
pos = url.indexOf("/");
String host;
String rest;
if (pos == -1) {
errorHandler.handle(req, httpl, out, "No host end in URL");
return;
} else {
host = url.substring(0,pos);
url = url.substring(pos);
if ("i2p".equals(host) || "i2p.i2p".equals(host)) {
// normal request; go on below...
} else if (host.endsWith(".i2p")) {
// "old" service request, send a redirect...
out.write(("HTTP/1.1 302 Moved\r\nLocation: "+
"http://i2p.i2p/"+host+url+
"\r\n\r\n").getBytes("ISO-8859-1"));
return;
} else {
// this is for proxying to the real web
proxyHandler.handle(req, httpl, out, true);
return;
}
}
}
if (url.equals("/")) { // main page
url="/_/local/index";
} else if (!url.startsWith("/")) {
errorHandler.handle(req, httpl, out,
"No leading slash in URL: "+url);
return;
}
String dest;
url=url.substring(1);
pos = url.indexOf("/");
if (pos == -1) {
dest=url;
url="/";
} else {
dest = url.substring(0,pos);
url=url.substring(pos);
}
req.setURL(url);
if (dest.equals("_")) { // no eepsite
if (url.startsWith("/local/")) { // local request
req.setURL(url.substring(6));
localHandler.handle(req, httpl, out, byProxy);
} else if (url.startsWith("/http/")) { // http warning
localHandler.handleHTTPWarning(req, httpl, out, byProxy);
} else if (url.startsWith("/proxy/")) { // http proxying
req.setURL("http://"+url.substring(7));
proxyHandler.handle(req, httpl, out, byProxy);
} else {
errorHandler.handle(req, httpl, out,
"No local handler for this URL: "+url);
}
} else {
eepHandler.handle(req, httpl, out, byProxy, dest);
}
/**
* The _ROOT_ handler: it passes its workload off to the other handlers.
* @param req a Request
* @param httpl an HTTPListener
* @param out where to write the results
* @throws IOException
*/
public void handle(Request req, HTTPListener httpl, OutputStream out) throws IOException {
String url = req.getURL();
System.out.println(url);
/* boolean byProxy = false; */
int pos;
if (url.startsWith("http://")) { // access via proxy
/* byProxy=true; */
if (httpl.firstProxyUse()) {
localHandler.handleProxyConfWarning(req, httpl, out);
return;
}
url = url.substring(7);
pos = url.indexOf("/");
String host;
String rest;
if (pos == -1) {
errorHandler.handle(req, httpl, out, "No host end in URL");
return;
} else {
host = url.substring(0, pos);
url = url.substring(pos);
if ("i2p".equals(host) || "i2p.i2p".equals(host)) {
// normal request; go on below...
} else if (host.endsWith(".i2p")) {
// "old" service request, send a redirect...
out
.write(("HTTP/1.1 302 Moved\r\nLocation: " + "http://i2p.i2p/" + host + url + "\r\n\r\n")
.getBytes("ISO-8859-1"));
return;
} else {
// this is for proxying to the real web
proxyHandler.handle(req, httpl, out /*, true */);
return;
}
}
}
if (url.equals("/")) { // main page
url = "/_/local/index";
} else if (!url.startsWith("/")) {
errorHandler.handle(req, httpl, out, "No leading slash in URL: " + url);
return;
}
String dest;
url = url.substring(1);
pos = url.indexOf("/");
if (pos == -1) {
dest = url;
url = "/";
} else {
dest = url.substring(0, pos);
url = url.substring(pos);
}
req.setURL(url);
if (dest.equals("_")) { // no eepsite
if (url.startsWith("/local/")) { // local request
req.setURL(url.substring(6));
localHandler.handle(req, httpl, out /*, byProxy */);
} else if (url.startsWith("/http/")) { // http warning
localHandler.handleHTTPWarning(req, httpl, out /*, byProxy */);
} else if (url.startsWith("/proxy/")) { // http proxying
req.setURL("http://" + url.substring(7));
proxyHandler.handle(req, httpl, out /*, byProxy */);
} else {
errorHandler.handle(req, httpl, out, "No local handler for this URL: " + url);
}
} else {
eepHandler.handle(req, httpl, out, /* byProxy, */dest);
}
}
}
}

View File

@@ -4,7 +4,7 @@
<target name="build" depends="builddep, jar" />
<target name="builddep">
<ant dir="../../ministreaming/java/" target="build" />
<ant dir="../../../core/java/" target="build" />
<!-- ministreaming will build core -->
</target>
<target name="compile">
<mkdir dir="./build" />
@@ -37,11 +37,11 @@
<delete dir="./build" />
</target>
<target name="cleandep" depends="clean">
<ant dir="../../../core/java/" target="cleandep" />
<!-- ministreaming will clean core -->
<ant dir="../../ministreaming/java/" target="distclean" />
</target>
<target name="distclean" depends="clean">
<ant dir="../../../core/java/" target="distclean" />
<!-- ministreaming will clean core -->
<ant dir="../../ministreaming/java/" target="distclean" />
</target>
</project>

View File

@@ -16,16 +16,19 @@ class BufferLogger implements Logging {
private final static Log _log = new Log(BufferLogger.class);
private ByteArrayOutputStream _baos;
private boolean _ignore;
public BufferLogger() {
_baos = new ByteArrayOutputStream(512);
_ignore = false;
_baos = new ByteArrayOutputStream(512);
_ignore = false;
}
private final static String EMPTY = "";
public String getBuffer() {
if (_ignore) return EMPTY;
else return new String(_baos.toByteArray());
public String getBuffer() {
if (_ignore)
return EMPTY;
else
return new String(_baos.toByteArray());
}
/**
@@ -36,26 +39,27 @@ class BufferLogger implements Logging {
*
*/
public void ignoreFurtherActions() {
_ignore = true;
synchronized (_baos) {
_baos.reset();
}
_baos = null;
_ignore = true;
synchronized (_baos) {
_baos.reset();
}
_baos = null;
}
/**
* Pass in some random data
* @param s String containing what we're logging.
*/
public void log(String s) {
if (_ignore) return;
if (s != null) {
_log.debug("logging [" + s + "]");
try {
_baos.write(s.getBytes());
_baos.write('\n');
} catch (IOException ioe) {
_log.error("Error logging [" + s + "]");
}
}
if (_ignore) return;
if (s != null) {
_log.debug("logging [" + s + "]");
try {
_baos.write(s.getBytes());
_baos.write('\n');
} catch (IOException ioe) {
_log.error("Error logging [" + s + "]");
}
}
}
}
}

File diff suppressed because it is too large Load Diff

View File

@@ -17,45 +17,48 @@ public class I2PTunnelClient extends I2PTunnelClientBase {
private static final Log _log = new Log(I2PTunnelClient.class);
protected Destination dest;
private static final long DEFAULT_READ_TIMEOUT = 5*60*1000; // -1
protected long readTimeout = DEFAULT_READ_TIMEOUT;
public I2PTunnelClient(int localPort, String destination,
Logging l, boolean ownDest,
EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "SynSender");
public I2PTunnelClient(int localPort, String destination, Logging l, boolean ownDest, EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "SynSender");
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openClientResult", "error");
return;
}
try {
dest=I2PTunnel.destFromName(destination);
if (dest == null) {
l.log("Could not resolve " + destination + ".");
return;
}
} catch (DataFormatException e) {
l.log("Bad format in destination \"" + destination + "\".");
notifyEvent("openClientResult", "error");
return;
}
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openClientResult", "error");
return;
}
setName(getLocalPort() + " -> " + destination);
try {
dest = I2PTunnel.destFromName(destination);
if (dest == null) {
l.log("Could not resolve " + destination + ".");
return;
}
} catch (DataFormatException e) {
l.log("Bad format in destination \"" + destination + "\".");
notifyEvent("openClientResult", "error");
return;
}
startRunning();
setName(getLocalPort() + " -> " + destination);
notifyEvent("openClientResult", "ok");
startRunning();
notifyEvent("openClientResult", "ok");
}
public void setReadTimeout(long ms) { readTimeout = ms; }
public long getReadTimeout() { return readTimeout; }
protected void clientConnectionRun(Socket s) {
try {
I2PSocket i2ps = createI2PSocket(dest);
new I2PTunnelRunner(s, i2ps, sockLock, null);
} catch (I2PException ex) {
_log.info("Error connecting", ex);
l.log("Unable to reach peer");
// s has been initialized before the try block...
closeSocket(s);
}
try {
I2PSocket i2ps = createI2PSocket(dest);
i2ps.setReadTimeout(readTimeout);
new I2PTunnelRunner(s, i2ps, sockLock, null);
} catch (Exception ex) {
_log.info("Error connecting", ex);
l.log(ex.getMessage());
closeSocket(s);
}
}
}

View File

@@ -4,7 +4,10 @@
package net.i2p.i2ptunnel;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.ConnectException;
import java.net.InetAddress;
import java.net.NoRouteToHostException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.UnknownHostException;
@@ -20,16 +23,18 @@ import net.i2p.client.streaming.I2PSocketManagerFactory;
import net.i2p.client.streaming.I2PSocketOptions;
import net.i2p.data.Destination;
import net.i2p.util.EventDispatcher;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public abstract class I2PTunnelClientBase extends I2PTunnelTask
implements Runnable {
public abstract class I2PTunnelClientBase extends I2PTunnelTask implements Runnable {
private static final Log _log = new Log(I2PTunnelClientBase.class);
protected Logging l;
private static final long DEFAULT_CONNECT_TIMEOUT = 60*1000;
private static final long DEFAULT_CONNECT_TIMEOUT = 60 * 1000;
private static volatile long __clientId = 0;
private long _clientId;
protected Object sockLock = new Object(); // Guards sockMgr and mySockets
private I2PSocketManager sockMgr;
private List mySockets = new ArrayList();
@@ -40,12 +45,12 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
private boolean listenerReady = false;
private ServerSocket ss;
private Object startLock = new Object();
private boolean startRunning = false;
private Object closeLock = new Object();
private byte[] pubkey;
private String handlerName;
@@ -55,101 +60,97 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
// I2PTunnelClientBase(localPort, ownDest, l, (EventDispatcher)null);
//}
public I2PTunnelClientBase(int localPort, boolean ownDest,
Logging l, EventDispatcher notifyThis,
String handlerName) {
super(localPort+" (uninitialized)", notifyThis);
this.localPort=localPort;
this.l = l;
this.handlerName=handlerName;
public I2PTunnelClientBase(int localPort, boolean ownDest, Logging l, EventDispatcher notifyThis, String handlerName) {
super(localPort + " (uninitialized)", notifyThis);
_clientId = ++__clientId;
this.localPort = localPort;
this.l = l;
this.handlerName = handlerName + _clientId;
synchronized(sockLock) {
if (ownDest) {
sockMgr=buildSocketManager();
} else {
sockMgr=getSocketManager();
}
}
if (sockMgr == null) throw new NullPointerException();
l.log("I2P session created");
Thread t = new Thread(this);
t.setName("Client");
listenerReady=false;
t.start();
open=true;
synchronized (this) {
while (!listenerReady) {
try {
wait();
}
catch (InterruptedException e) {
// ignore
}
}
}
if (open && listenerReady) {
l.log("Ready! Port " + getLocalPort());
notifyEvent("openBaseClientResult", "ok");
} else {
l.log("Error!");
notifyEvent("openBaseClientResult", "error");
}
synchronized (sockLock) {
if (ownDest) {
sockMgr = buildSocketManager();
} else {
sockMgr = getSocketManager();
}
}
if (sockMgr == null) throw new NullPointerException();
l.log("I2P session created");
Thread t = new I2PThread(this);
t.setName("Client " + _clientId);
listenerReady = false;
t.start();
open = true;
synchronized (this) {
while (!listenerReady) {
try {
wait();
} catch (InterruptedException e) {
// ignore
}
}
}
if (open && listenerReady) {
l.log("Ready! Port " + getLocalPort());
notifyEvent("openBaseClientResult", "ok");
} else {
l.log("Error!");
notifyEvent("openBaseClientResult", "error");
}
}
private static I2PSocketManager socketManager;
protected static synchronized I2PSocketManager getSocketManager() {
if (socketManager == null) {
socketManager = buildSocketManager();
}
return socketManager;
if (socketManager == null) {
socketManager = buildSocketManager();
}
return socketManager;
}
protected static I2PSocketManager buildSocketManager() {
Properties props = new Properties();
props.putAll(System.getProperties());
return I2PSocketManagerFactory.createManager
(I2PTunnel.host, Integer.parseInt(I2PTunnel.port), props);
Properties props = new Properties();
props.putAll(System.getProperties());
return I2PSocketManagerFactory.createManager(I2PTunnel.host, Integer.parseInt(I2PTunnel.port), props);
}
public final int getLocalPort() {
return localPort;
}
protected final InetAddress getListenHost(Logging l) {
try {
return InetAddress.getByName(I2PTunnel.listenHost);
} catch (UnknownHostException uhe) {
l.log("Could not find listen host to bind to [" +
I2PTunnel.host + "]");
_log.error("Error finding host to bind", uhe);
notifyEvent("openBaseClientResult", "error");
return null;
}
try {
return InetAddress.getByName(I2PTunnel.listenHost);
} catch (UnknownHostException uhe) {
l.log("Could not find listen host to bind to [" + I2PTunnel.host + "]");
_log.error("Error finding host to bind", uhe);
notifyEvent("openBaseClientResult", "error");
return null;
}
}
/**
* Actually start working on incoming connections. *Must* be
* called by derived classes after initialization.
*
*/
public final void startRunning() {
synchronized (startLock) {
startRunning = true;
startLock.notify();
}
synchronized (startLock) {
startRunning = true;
startLock.notify();
}
}
/**
* create the default options (using the default timeout, etc)
*
*/
private I2PSocketOptions getDefaultOptions() {
I2PSocketOptions opts = new I2PSocketOptions();
opts.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
return opts;
I2PSocketOptions opts = new I2PSocketOptions();
opts.setConnectTimeout(DEFAULT_CONNECT_TIMEOUT);
return opts;
}
/**
@@ -160,8 +161,8 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
* @param dest The destination to connect to
* @return a new I2PSocket
*/
public I2PSocket createI2PSocket(Destination dest) throws I2PException {
return createI2PSocket(dest, getDefaultOptions());
public I2PSocket createI2PSocket(Destination dest) throws I2PException, ConnectException, NoRouteToHostException, InterruptedIOException {
return createI2PSocket(dest, getDefaultOptions());
}
/**
@@ -172,55 +173,60 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
* @param dest The destination to connect to
* @param opt Option to be used to open when opening the socket
* @return a new I2PSocket
*
* @throws ConnectException if the peer refuses the connection
* @throws NoRouteToHostException if the peer is not found or not reachable
* @throws InterruptedIOException if the connection timeouts
* @throws I2PException if there is some other I2P-related problem
*/
public I2PSocket createI2PSocket(Destination dest, I2PSocketOptions opt) throws I2PException {
I2PSocket i2ps;
public I2PSocket createI2PSocket(Destination dest, I2PSocketOptions opt) throws I2PException, ConnectException, NoRouteToHostException, InterruptedIOException {
I2PSocket i2ps;
synchronized (sockLock) {
i2ps = sockMgr.connect(dest, opt);
mySockets.add(i2ps);
}
i2ps = sockMgr.connect(dest, opt);
synchronized (sockLock) {
mySockets.add(i2ps);
}
return i2ps;
return i2ps;
}
public final void run() {
try {
InetAddress addr = getListenHost(l);
if (addr == null) return;
ss = new ServerSocket(localPort, 0, addr);
// If a free port was requested, find out what we got
if (localPort == 0) {
localPort = ss.getLocalPort();
}
notifyEvent("clientLocalPort", new Integer(ss.getLocalPort()));
l.log("Listening for clients on port " + localPort +
" of " + I2PTunnel.listenHost);
// Notify constructor that port is ready
synchronized(this) {
listenerReady = true;
notify();
}
try {
InetAddress addr = getListenHost(l);
if (addr == null) return;
ss = new ServerSocket(localPort, 0, addr);
// Wait until we are authorized to process data
synchronized (startLock) {
while (!startRunning) {
try {
startLock.wait();
} catch (InterruptedException ie) {}
}
}
// If a free port was requested, find out what we got
if (localPort == 0) {
localPort = ss.getLocalPort();
}
notifyEvent("clientLocalPort", new Integer(ss.getLocalPort()));
l.log("Listening for clients on port " + localPort + " of " + I2PTunnel.listenHost);
while (true) {
Socket s = ss.accept();
manageConnection(s);
}
} catch (IOException ex) {
_log.error("Error listening for connections", ex);
notifyEvent("openBaseClientResult", "error");
}
// Notify constructor that port is ready
synchronized (this) {
listenerReady = true;
notify();
}
// Wait until we are authorized to process data
synchronized (startLock) {
while (!startRunning) {
try {
startLock.wait();
} catch (InterruptedException ie) {
}
}
}
while (true) {
Socket s = ss.accept();
manageConnection(s);
}
} catch (IOException ex) {
_log.error("Error listening for connections", ex);
notifyEvent("openBaseClientResult", "error");
}
}
/**
@@ -229,59 +235,60 @@ public abstract class I2PTunnelClientBase extends I2PTunnelTask
* @param s Socket to take care of
*/
protected void manageConnection(Socket s) {
new ClientConnectionRunner(s, handlerName);
new ClientConnectionRunner(s, handlerName);
}
public boolean close(boolean forced) {
if (!open) return true;
// FIXME: here we might have to wait quite a long time if
// there is a connection attempt atm. But without waiting we
// might risk to create an orphan socket. Would be better
// to return with an error in that situation quickly.
synchronized(sockLock) {
mySockets.retainAll(sockMgr.listSockets());
if (!forced && mySockets.size() != 0) {
l.log("There are still active connections!");
_log.debug("can't close: there are still active connections!");
for (Iterator it = mySockets.iterator(); it.hasNext();) {
l.log("->"+it.next());
}
return false;
}
l.log("Closing client "+toString());
try {
if (ss != null) ss.close();
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
l.log("Client closed.");
open=false;
return true;
}
if (!open) return true;
// FIXME: here we might have to wait quite a long time if
// there is a connection attempt atm. But without waiting we
// might risk to create an orphan socket. Would be better
// to return with an error in that situation quickly.
synchronized (sockLock) {
mySockets.retainAll(sockMgr.listSockets());
if (!forced && mySockets.size() != 0) {
l.log("There are still active connections!");
_log.debug("can't close: there are still active connections!");
for (Iterator it = mySockets.iterator(); it.hasNext();) {
l.log("->" + it.next());
}
return false;
}
l.log("Closing client " + toString());
try {
if (ss != null) ss.close();
} catch (IOException ex) {
ex.printStackTrace();
return false;
}
l.log("Client closed.");
open = false;
return true;
}
}
public static void closeSocket(Socket s) {
try {
s.close();
} catch (IOException ex) {
_log.error("Could not close socket", ex);
}
try {
s.close();
} catch (IOException ex) {
_log.error("Could not close socket", ex);
}
}
public class ClientConnectionRunner extends Thread {
private Socket s;
public ClientConnectionRunner(Socket s, String name) {
this.s=s;
setName(name);
start();
}
public void run() {
clientConnectionRun(s);
}
private static volatile long __runnerId = 0;
public class ClientConnectionRunner extends I2PThread {
private Socket s;
public ClientConnectionRunner(Socket s, String name) {
this.s = s;
setName(name + '.' + (++__runnerId));
start();
}
public void run() {
clientConnectionRun(s);
}
}
/**

View File

@@ -19,30 +19,30 @@ public class I2PTunnelGUI extends Frame implements ActionListener, Logging {
TextField input;
TextArea log;
I2PTunnel t;
public I2PTunnelGUI(I2PTunnel t) {
super("I2PTunnel control panel");
this.t=t;
setLayout(new BorderLayout());
add("South", input=new TextField());
input.addActionListener(this);
Font font = new Font("Monospaced",Font.PLAIN,12);
add("Center",log=new TextArea("",20,80,TextArea.SCROLLBARS_VERTICAL_ONLY));
log.setFont(font);
log.setEditable(false);
log("enter 'help' for help.");
pack();
show();
super("I2PTunnel control panel");
this.t = t;
setLayout(new BorderLayout());
add("South", input = new TextField());
input.addActionListener(this);
Font font = new Font("Monospaced", Font.PLAIN, 12);
add("Center", log = new TextArea("", 20, 80, TextArea.SCROLLBARS_VERTICAL_ONLY));
log.setFont(font);
log.setEditable(false);
log("enter 'help' for help.");
pack();
show();
}
public void log(String s) {
log.append(s+"\n");
log.append(s + "\n");
}
public void actionPerformed(ActionEvent evt) {
log("I2PTunnel>"+input.getText());
t.runCommand(input.getText(), this);
log("---");
input.setText("");
log("I2PTunnel>" + input.getText());
t.runCommand(input.getText(), this);
log("---");
input.setText("");
}
}
}

View File

@@ -8,7 +8,11 @@ import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
import java.util.Date;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import net.i2p.I2PException;
import net.i2p.client.streaming.I2PSocket;
@@ -19,316 +23,381 @@ import net.i2p.util.EventDispatcher;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public class I2PTunnelHTTPClient extends I2PTunnelClientBase
implements Runnable {
private static final Log _log =
new Log(I2PTunnelHTTPClient.class);
/**
* Act as a mini HTTP proxy, handling various different types of requests,
* forwarding them through I2P appropriately, and displaying the reply. Supported
* request formats are: <pre>
* $method http://$site[$port]/$path $protocolVersion
* or
* $method $path $protocolVersion\nHost: $site
* or
* $method http://i2p/$site/$path $protocolVersion
* or
* $method /$site/$path $protocolVersion
* </pre>
*
* If the $site resolves with the I2P naming service, then it is directed towards
* that eepsite, otherwise it is directed towards this client's outproxy (typically
* "squid.i2p"). Only HTTP is supported (no HTTPS, ftp, mailto, etc). Both GET
* and POST have been tested, though other $methods should work.
*
*/
public class I2PTunnelHTTPClient extends I2PTunnelClientBase implements Runnable {
private static final Log _log = new Log(I2PTunnelHTTPClient.class);
private String wwwProxy;
private final static byte[] ERR_REQUEST_DENIED = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: REQUEST DENIED</H1>You attempted to connect to a non-I2P website or location.<BR>".getBytes();
private final static byte[] ERR_DESTINATION_UNKNOWN = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: NOT FOUND</H1>That Desitination was not found. Perhaps you pasted in the wrong BASE64 I2P Destination or the link you are following is bad. The host (or the WWW proxy, if you're using one) could also be temporarily offline. Could not find the following Destination:<BR><BR>".getBytes();
private final static byte[] ERR_TIMEOUT = "HTTP/1.1 404 Not Found\r\nContent-Type: text/html; charset=iso-8859-1\r\nCache-control: no-cache\r\n\r\n<html><body><H1>I2P ERROR: TIMEOUT</H1>That Desitination was reachable, but timed out getting a response. This may be a temporary error, so you should simply try to refresh, though if the problem persists, the remote destination may have issues. Could not get a response from the following Destination:<BR><BR>".getBytes();
private final static byte[] ERR_REQUEST_DENIED =
("HTTP/1.1 404 Not Found\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: REQUEST DENIED</H1>"+
"You attempted to connect to a non-I2P website or location.<BR>")
.getBytes();
//public I2PTunnelHTTPClient(int localPort, Logging l,
// boolean ownDest,
// String wwwProxy) {
// I2PTunnelHTTPClient(localPort, l, ownDest, wwwProxy,
// (EventDispatcher)null);
//}
private final static byte[] ERR_DESTINATION_UNKNOWN =
("HTTP/1.1 404 Not Found\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n"+
"\r\n"+
"<html><body><H1>I2P ERROR: NOT FOUND</H1>"+
"That Desitination was not found. Perhaps you pasted in the wrong "+
"BASE64 I2P Destination or the link you are following is bad. "+
"The host (or the WWW proxy, if you're using one) could also be "+
"temporarily offline. You may want to <b>retry</b>. "+
"Could not find the following Destination:<BR><BR>")
.getBytes();
private final static byte[] ERR_TIMEOUT =
("HTTP/1.1 404 Not Found\r\n"+
"Content-Type: text/html; charset=iso-8859-1\r\n"+
"Cache-control: no-cache\r\n\r\n"+
"<html><body><H1>I2P ERROR: TIMEOUT</H1>"+
"That Desitination was reachable, but timed out getting a "+
"response. This is likely a temporary error, so you should simply "+
"try to refresh, though if the problem persists, the remote "+
"destination may have issues. Could not get a response from "+
"the following Destination:<BR><BR>")
.getBytes();
public I2PTunnelHTTPClient(int localPort, Logging l,
boolean ownDest,
String wwwProxy, EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "HTTPHandler");
/** used to assign unique IDs to the threads / clients. no logic or functionality */
private static volatile long __clientId = 0;
public I2PTunnelHTTPClient(int localPort, Logging l, boolean ownDest, String wwwProxy, EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "HTTPHandler " + (++__clientId));
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openHTTPClientResult", "error");
return;
}
this.wwwProxy = wwwProxy;
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openHTTPClientResult", "error");
return;
}
setName(getLocalPort()
+ " -> HTTPClient [WWW outproxy: " + this.wwwProxy + "]");
this.wwwProxy = wwwProxy;
startRunning();
setName(getLocalPort() + " -> HTTPClient [WWW outproxy: " + this.wwwProxy + "]");
notifyEvent("openHTTPClientResult", "ok");
startRunning();
notifyEvent("openHTTPClientResult", "ok");
}
protected void clientConnectionRun(Socket s) {
OutputStream out = null;
String targetRequest = null;
boolean usingWWWProxy = false;
InactivityTimeoutThread timeoutThread = null;
try {
out = s.getOutputStream();
BufferedReader br = new BufferedReader
(new InputStreamReader(s.getInputStream(),
"ISO-8859-1"));
String line, method=null, protocol=null, host=null, destination=null;
StringBuffer newRequest=new StringBuffer();
while ((line=br.readLine()) != null) {
if (method==null) { // first line (GET /base64/realaddr)
int pos=line.indexOf(" ");
if (pos == -1) break;
method=line.substring(0, pos);
String request = line.substring(pos+1);
if (request.startsWith("/") &&
System.getProperty("i2ptunnel.noproxy") != null) {
request="http://i2p"+request;
}
pos = request.indexOf("//");
if (pos == -1) {
method=null;
break;
}
protocol=request.substring(0,pos+2);
request=request.substring(pos+2);
OutputStream out = null;
String targetRequest = null;
boolean usingWWWProxy = false;
InactivityTimeoutThread timeoutThread = null;
try {
out = s.getOutputStream();
BufferedReader br = new BufferedReader(new InputStreamReader(s.getInputStream(), "ISO-8859-1"));
String line, method = null, protocol = null, host = null, destination = null;
StringBuffer newRequest = new StringBuffer();
while ((line = br.readLine()) != null) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Line=[" + line + "]");
if (line.startsWith("Connection: ") ||
line.startsWith("Keep-Alive: ") ||
line.startsWith("Proxy-Connection: "))
continue;
if (method == null) { // first line (GET /base64/realaddr)
if (_log.shouldLog(Log.DEBUG))
_log.debug("Method is null for [" + line + "]");
int pos = line.indexOf(" ");
if (pos == -1) break;
method = line.substring(0, pos);
String request = line.substring(pos + 1);
if (request.startsWith("/") && System.getProperty("i2ptunnel.noproxy") != null) {
request = "http://i2p" + request;
}
pos = request.indexOf("//");
if (pos == -1) {
method = null;
break;
}
protocol = request.substring(0, pos + 2);
request = request.substring(pos + 2);
targetRequest = request;
targetRequest = request;
pos = request.indexOf("/");
if (pos == -1) {
method=null;
break;
}
host=request.substring(0,pos);
pos = request.indexOf("/");
if (pos == -1) {
method = null;
break;
}
host = request.substring(0, pos);
// Quick hack for foo.bar.i2p
if (host.toLowerCase().endsWith( ".i2p")) {
destination=host;
host=getHostName(destination);
line=method+" "+request.substring(pos);
} else if (host.indexOf(".") != -1) {
// The request must be forwarded to a WWW proxy
destination = wwwProxy;
usingWWWProxy = true;
} else {
request=request.substring(pos+1);
pos = request.indexOf("/");
destination=request.substring(0,pos);
line=method+" "+request.substring(pos);
}
// Quick hack for foo.bar.i2p
if (host.toLowerCase().endsWith(".i2p")) {
destination = host;
host = getHostName(destination);
line = method + " " + request.substring(pos);
} else if (host.indexOf(".") != -1) {
// The request must be forwarded to a WWW proxy
destination = wwwProxy;
usingWWWProxy = true;
if (_log.shouldLog(Log.DEBUG))
_log.debug("Host doesnt end with .i2p and it contains a period [" + host + "]: wwwProxy!");
} else {
request = request.substring(pos + 1);
pos = request.indexOf("/");
destination = request.substring(0, pos);
line = method + " " + request.substring(pos);
}
boolean isValid = usingWWWProxy ||
isSupportedAddress(host, protocol);
if (!isValid) {
if (_log.shouldLog(Log.INFO))
_log.info("notValid(" + host + ")");
method=null;
destination=null;
break;
} else if (!usingWWWProxy) {
if (_log.shouldLog(Log.INFO))
_log.info("host=getHostName(" + destination + ")");
host=getHostName(destination); // hide original host
}
boolean isValid = usingWWWProxy || isSupportedAddress(host, protocol);
if (!isValid) {
if (_log.shouldLog(Log.INFO)) _log.info("notValid(" + host + ")");
method = null;
destination = null;
break;
} else if (!usingWWWProxy) {
if (_log.shouldLog(Log.INFO)) _log.info("host=getHostName(" + destination + ")");
host = getHostName(destination); // hide original host
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("METHOD:"+method+":");
_log.debug("PROTOC:"+protocol+":");
_log.debug("HOST :"+host+":");
_log.debug("DEST :"+destination+":");
}
} else if (line.startsWith("Host: ") && !usingWWWProxy) {
line="Host: "+host;
if (_log.shouldLog(Log.INFO))
_log.info("Setting host = " + host);
}
newRequest.append(line).append("\r\n"); // HTTP spec
if (line.length()==0) break;
}
while (br.ready()) { // empty the buffer (POST requests)
int i=br.read();
if (i != -1) {
newRequest.append((char)i);
}
}
if (method==null || destination==null) {
l.log("No HTTP method found in the request.");
if (out != null) {
out.write(ERR_REQUEST_DENIED);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
Destination dest=I2PTunnel.destFromName(destination);
if (dest == null) {
l.log("Could not resolve "+destination+".");
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest,
usingWWWProxy, destination);
s.close();
return;
}
String remoteID;
I2PSocket i2ps = createI2PSocket(dest);
byte[] data=newRequest.toString().getBytes("ISO-8859-1");
I2PTunnelRunner runner = new I2PTunnelRunner(s, i2ps, sockLock, data);
timeoutThread = new InactivityTimeoutThread(runner, out, targetRequest, usingWWWProxy, s);
timeoutThread.start();
} catch (IOException ex) {
if (timeoutThread != null) timeoutThread.disable();
_log.error("Error sending syn", ex);
handleHTTPClientException(ex, out, targetRequest,
usingWWWProxy, wwwProxy);
closeSocket(s);
} catch (I2PException ex) {
if (timeoutThread != null) timeoutThread.disable();
_log.info("Error sending syn", ex);
l.log("Unable to reach peer");
handleHTTPClientException(ex, out, targetRequest,
usingWWWProxy, wwwProxy);
closeSocket(s);
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("METHOD:" + method + ":");
_log.debug("PROTOC:" + protocol + ":");
_log.debug("HOST :" + host + ":");
_log.debug("DEST :" + destination + ":");
}
} else {
if (line.startsWith("Host: ") && !usingWWWProxy) {
line = "Host: " + host;
if (_log.shouldLog(Log.INFO))
_log.info("Setting host = " + host);
}
}
if (line.length() == 0) {
newRequest.append("Connection: close\r\n\r\n");
break;
} else {
newRequest.append(line).append("\r\n"); // HTTP spec
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("NewRequest header: [" + newRequest.toString() + "]");
while (br.ready()) { // empty the buffer (POST requests)
int i = br.read();
if (i != -1) {
newRequest.append((char) i);
}
}
if (method == null || destination == null) {
l.log("No HTTP method found in the request.");
if (out != null) {
out.write(ERR_REQUEST_DENIED);
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
s.close();
return;
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Destination: " + destination);
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
l.log("Could not resolve " + destination + ".");
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, destination);
s.close();
return;
}
String remoteID;
I2PSocket i2ps = createI2PSocket(dest);
byte[] data = newRequest.toString().getBytes("ISO-8859-1");
I2PTunnelRunner runner = new I2PTunnelRunner(s, i2ps, sockLock, data);
timeoutThread = new InactivityTimeoutThread(runner, out, targetRequest, usingWWWProxy, s);
timeoutThread.start();
} catch (SocketException ex) {
if (timeoutThread != null) timeoutThread.disable();
_log.info("Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, wwwProxy);
closeSocket(s);
} catch (IOException ex) {
if (timeoutThread != null) timeoutThread.disable();
_log.info("Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, wwwProxy);
closeSocket(s);
} catch (I2PException ex) {
if (timeoutThread != null) timeoutThread.disable();
_log.info("Error trying to connect", ex);
l.log(ex.getMessage());
handleHTTPClientException(ex, out, targetRequest, usingWWWProxy, wwwProxy);
closeSocket(s);
}
}
private static final long INACTIVITY_TIMEOUT = 120*1000;
private static final long INACTIVITY_TIMEOUT = 120 * 1000;
private static volatile long __timeoutId = 0;
private class InactivityTimeoutThread extends I2PThread {
private Socket s;
private I2PTunnelRunner _runner;
private OutputStream _out;
private String _targetRequest;
private boolean _useWWWProxy;
private boolean _disabled;
private Object _disableLock = new Object();
public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest, boolean useWWWProxy, Socket s) {
this.s=s;
_runner = runner;
_out = out;
_targetRequest = targetRequest;
_useWWWProxy = useWWWProxy;
_disabled = false;
}
public void disable() {
_disabled = true;
synchronized (_disableLock) { _disableLock.notifyAll(); }
}
public void run() {
while (!_disabled) {
if (_runner.isFinished()) {
if (_log.shouldLog(Log.INFO))
_log.info("HTTP client request completed prior to timeout");
return;
}
if (_runner.getLastActivityOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {
if (_runner.getStartedOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {
if (_log.shouldLog(Log.WARN))
_log.warn("HTTP client request timed out (lastActivity: " + new Date(_runner.getLastActivityOn()) + ", startedOn: " + new Date(_runner.getLastActivityOn()) + ")");
timeout();
return;
} else {
// runner hasn't been going to long enough
}
} else {
// there has been activity in the period
}
synchronized (_disableLock) {
try {
_disableLock.wait(INACTIVITY_TIMEOUT);
} catch (InterruptedException ie) {}
}
}
}
private void timeout() {
_log.info("Inactivity timeout reached");
l.log("Inactivity timeout reached");
if (_out != null) {
try {
if (_runner.getLastActivityOn() > 0) {
// some data has been sent, so don't 404 it
} else {
writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest,
_useWWWProxy, wwwProxy);
}
} catch (IOException ioe) {
_log.warn("Error writing out the 'timeout' message", ioe);
}
} else {
_log.warn("Client disconnected before we could say we timed out");
}
closeSocket(s);
}
private Socket s;
private I2PTunnelRunner _runner;
private OutputStream _out;
private String _targetRequest;
private boolean _useWWWProxy;
private boolean _disabled;
private Object _disableLock = new Object();
public InactivityTimeoutThread(I2PTunnelRunner runner, OutputStream out, String targetRequest,
boolean useWWWProxy, Socket s) {
this.s = s;
_runner = runner;
_out = out;
_targetRequest = targetRequest;
_useWWWProxy = useWWWProxy;
_disabled = false;
long timeoutId = ++__timeoutId;
setName("InactivityThread " + timeoutId);
}
public void disable() {
_disabled = true;
synchronized (_disableLock) {
_disableLock.notifyAll();
}
}
public void run() {
while (!_disabled) {
if (_runner.isFinished()) {
if (_log.shouldLog(Log.INFO)) _log.info("HTTP client request completed prior to timeout");
return;
}
if (_runner.getLastActivityOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {
if (_runner.getStartedOn() < Clock.getInstance().now() - INACTIVITY_TIMEOUT) {
if (_log.shouldLog(Log.WARN))
_log.warn("HTTP client request timed out (lastActivity: "
+ new Date(_runner.getLastActivityOn()) + ", startedOn: "
+ new Date(_runner.getLastActivityOn()) + ")");
timeout();
return;
} else {
// runner hasn't been going to long enough
}
} else {
// there has been activity in the period
}
synchronized (_disableLock) {
try {
_disableLock.wait(INACTIVITY_TIMEOUT);
} catch (InterruptedException ie) {
}
}
}
}
private void timeout() {
_log.info("Inactivity timeout reached");
l.log("Inactivity timeout reached");
if (_out != null) {
try {
if (_runner.getLastActivityOn() > 0) {
// some data has been sent, so don't 404 it
} else {
writeErrorMessage(ERR_TIMEOUT, _out, _targetRequest, _useWWWProxy, wwwProxy);
}
} catch (IOException ioe) {
_log.warn("Error writing out the 'timeout' message", ioe);
}
} else {
_log.warn("Client disconnected before we could say we timed out");
}
closeSocket(s);
}
}
private final static String getHostName(String host) {
try {
Destination dest=I2PTunnel.destFromName(host);
if (dest == null) return "i2p";
return dest.toBase64();
} catch (DataFormatException dfe) {
return "i2p";
}
}
private static void writeErrorMessage(byte[] errMessage, OutputStream out,
String targetRequest,
boolean usingWWWProxy,
String wwwProxy)
throws IOException {
if (out != null) {
out.write(errMessage);
if (targetRequest != null) {
out.write(targetRequest.getBytes());
if (usingWWWProxy)
out.write(("<br>WWW proxy: " +
wwwProxy).getBytes());
}
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
try {
Destination dest = I2PTunnel.destFromName(host);
if (dest == null) return "i2p";
return dest.toBase64();
} catch (DataFormatException dfe) {
return "i2p";
}
}
private static void handleHTTPClientException (Exception ex, OutputStream out,
String targetRequest,
boolean usingWWWProxy,
String wwwProxy) {
if (out != null) {
try {
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest,
usingWWWProxy, wwwProxy);
} catch (IOException ioe) {
_log.warn("Error writing out the 'destination was unknown' "+
"message", ioe);
}
} else {
_log.warn("Client disconnected before we could say that destination "+
"was unknown", ex);
}
private static void writeErrorMessage(byte[] errMessage, OutputStream out, String targetRequest,
boolean usingWWWProxy, String wwwProxy) throws IOException {
if (out != null) {
out.write(errMessage);
if (targetRequest != null) {
out.write(targetRequest.getBytes());
if (usingWWWProxy) out.write(("<br>WWW proxy: " + wwwProxy).getBytes());
}
out.write("<p /><i>Generated on: ".getBytes());
out.write(new Date().toString().getBytes());
out.write("</i></body></html>\n".getBytes());
out.flush();
}
}
private final static String SUPPORTED_HOSTS[] = { "i2p", "www.i2p.com",
"i2p." };
private static void handleHTTPClientException(Exception ex, OutputStream out, String targetRequest,
boolean usingWWWProxy, String wwwProxy) {
if (out != null) {
try {
writeErrorMessage(ERR_DESTINATION_UNKNOWN, out, targetRequest, usingWWWProxy, wwwProxy);
} catch (IOException ioe) {
_log.warn("Error writing out the 'destination was unknown' " + "message", ioe);
}
} else {
_log.warn("Client disconnected before we could say that destination " + "was unknown", ex);
}
}
private final static String SUPPORTED_HOSTS[] = { "i2p", "www.i2p.com", "i2p."};
private boolean isSupportedAddress(String host, String protocol) {
if ( (host == null) || (protocol == null) ) return false;
boolean found = false;
String lcHost = host.toLowerCase();
for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {
if (SUPPORTED_HOSTS[i].equals(lcHost)) {
found = true;
break;
}
}
if ((host == null) || (protocol == null)) return false;
boolean found = false;
String lcHost = host.toLowerCase();
for (int i = 0; i < SUPPORTED_HOSTS.length; i++) {
if (SUPPORTED_HOSTS[i].equals(lcHost)) {
found = true;
break;
}
}
if (!found) {
try {
Destination d = I2PTunnel.destFromName(host);
if (d == null) return false;
} catch (DataFormatException dfe) {}
}
return protocol.equalsIgnoreCase("http://");
if (!found) {
try {
Destination d = I2PTunnel.destFromName(host);
if (d == null) return false;
} catch (DataFormatException dfe) {
}
}
return protocol.equalsIgnoreCase("http://");
}
}

View File

@@ -6,6 +6,7 @@ package net.i2p.i2ptunnel;
import java.io.BufferedOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InterruptedIOException;
import java.io.OutputStream;
import java.net.Socket;
import java.net.SocketException;
@@ -13,26 +14,29 @@ import java.util.HashMap;
import net.i2p.client.I2PSession;
import net.i2p.client.streaming.I2PSocket;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public class I2PTunnelRunner extends Thread {
public class I2PTunnelRunner extends I2PThread {
private final static Log _log = new Log(I2PTunnelRunner.class);
private static volatile long __runnerId;
private long _runnerId;
/**
* max bytes streamed in a packet - smaller ones might be filled
* up to this size. Larger ones are not split (at least not on
* Sun's impl of BufferedOutputStream), but that is the streaming
* api's job...
*/
static int MAX_PACKET_SIZE = 1024*32;
static int MAX_PACKET_SIZE = 1024 * 32;
static final int NETWORK_BUFFER_SIZE = MAX_PACKET_SIZE;
private Socket s;
private I2PSocket i2ps;
Object slock, finishLock = new Object();
boolean finished=false;
boolean finished = false;
HashMap ostreams, sockets;
I2PSession session;
byte[] initialData;
@@ -41,17 +45,17 @@ public class I2PTunnelRunner extends Thread {
/** when the runner started up */
private long startedOn;
public I2PTunnelRunner(Socket s, I2PSocket i2ps, Object slock,
byte[] initialData) {
this.s=s;
this.i2ps=i2ps;
this.slock=slock;
this.initialData = initialData;
lastActivityOn = -1;
startedOn = -1;
_log.info("I2PTunnelRunner started");
setName("I2PTunnelRunner");
start();
public I2PTunnelRunner(Socket s, I2PSocket i2ps, Object slock, byte[] initialData) {
this.s = s;
this.i2ps = i2ps;
this.slock = slock;
this.initialData = initialData;
lastActivityOn = -1;
startedOn = -1;
_log.info("I2PTunnelRunner started");
_runnerId = ++__runnerId;
setName("I2PTunnelRunner " + _runnerId);
start();
}
/**
@@ -59,126 +63,138 @@ public class I2PTunnelRunner extends Thread {
* [aka we're done running the streams]?
*
*/
public boolean isFinished() { return finished; }
public boolean isFinished() {
return finished;
}
/**
* When was the last data for this runner sent or received? (-1 if no data
* has been transferred yet)
* When was the last data for this runner sent or received?
*
* @return date (ms since the epoch), or -1 if no data has been transferred yet
*
*/
public long getLastActivityOn() { return lastActivityOn; }
private void updateActivity() { lastActivityOn = Clock.getInstance().now(); }
public long getLastActivityOn() {
return lastActivityOn;
}
private void updateActivity() {
lastActivityOn = Clock.getInstance().now();
}
/**
* When this runner started up transferring data
*
*/
public long getStartedOn() { return startedOn; }
public void run() {
startedOn = Clock.getInstance().now();
try {
InputStream in = s.getInputStream();
OutputStream out = new BufferedOutputStream(s.getOutputStream(),
NETWORK_BUFFER_SIZE);
InputStream i2pin = i2ps.getInputStream();
OutputStream i2pout = new BufferedOutputStream
(i2ps.getOutputStream(), MAX_PACKET_SIZE);
if (initialData != null) {
synchronized(slock) {
i2pout.write(initialData);
i2pout.flush();
}
}
Thread t1 = new StreamForwarder(in, i2pout);
Thread t2 = new StreamForwarder(i2pin, out);
synchronized(finishLock) {
while (!finished) {
finishLock.wait();
}
}
// now one connection is dead - kill the other as well.
s.close();
s = null;
i2ps.close();
i2ps = null;
t1.join();
t2.join();
} catch (InterruptedException ex) {
_log.error("Interrupted", ex);
} catch (IOException ex) {
ex.printStackTrace();
_log.error("Error forwarding", ex);
} finally {
try {
if (s != null) s.close();
if (i2ps != null) i2ps.close();
} catch (IOException ex) {
ex.printStackTrace();
_log.error("Could not close socket", ex);
}
}
public long getStartedOn() {
return startedOn;
}
private class StreamForwarder extends Thread {
public void run() {
startedOn = Clock.getInstance().now();
try {
InputStream in = s.getInputStream();
OutputStream out = new BufferedOutputStream(s.getOutputStream(), NETWORK_BUFFER_SIZE);
InputStream i2pin = i2ps.getInputStream();
OutputStream i2pout = new BufferedOutputStream(i2ps.getOutputStream(), MAX_PACKET_SIZE);
if (initialData != null) {
synchronized (slock) {
i2pout.write(initialData);
i2pout.flush();
}
}
Thread t1 = new StreamForwarder(in, i2pout);
Thread t2 = new StreamForwarder(i2pin, out);
synchronized (finishLock) {
while (!finished) {
finishLock.wait();
}
}
// now one connection is dead - kill the other as well.
s.close();
s = null;
i2ps.close();
i2ps = null;
t1.join();
t2.join();
} catch (InterruptedException ex) {
_log.error("Interrupted", ex);
} catch (IOException ex) {
ex.printStackTrace();
_log.debug("Error forwarding", ex);
} finally {
try {
if (s != null) s.close();
if (i2ps != null) i2ps.close();
} catch (IOException ex) {
ex.printStackTrace();
_log.error("Could not close socket", ex);
}
}
}
InputStream in;
OutputStream out;
private StreamForwarder(InputStream in, OutputStream out) {
this.in=in;
this.out=out;
setName("StreamForwarder");
start();
}
private volatile long __forwarderId = 0;
private class StreamForwarder extends I2PThread {
public void run() {
byte[] buffer = new byte[NETWORK_BUFFER_SIZE];
try {
int len;
while ((len=in.read(buffer)) != -1) {
out.write(buffer, 0, len);
if (len > 0)
updateActivity();
if (in.available()==0) {
try {
Thread.sleep(I2PTunnel.PACKET_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (in.available()==0) {
out.flush(); // make sure the data get though
}
}
} catch (SocketException ex) {
// this *will* occur when the other threads closes the socket
synchronized(finishLock) {
if (!finished)
_log.error("Error reading and writing", ex);
else
_log.warn("You may ignore this", ex);
}
} catch (IOException ex) {
if (!finished)
_log.error("Error forwarding", ex);
else
_log.warn("You may ignore this", ex);
} finally {
try {
out.close();
in.close();
} catch (IOException ex) {
_log.error("Error closing streams", ex);
}
synchronized(finishLock) {
finished=true;
finishLock.notifyAll();
// the main thread will close sockets etc. now
}
}
}
}
InputStream in;
OutputStream out;
private StreamForwarder(InputStream in, OutputStream out) {
this.in = in;
this.out = out;
setName("StreamForwarder " + _runnerId + "." + (++__forwarderId));
start();
}
public void run() {
byte[] buffer = new byte[NETWORK_BUFFER_SIZE];
try {
int len;
while ((len = in.read(buffer)) != -1) {
out.write(buffer, 0, len);
if (len > 0) updateActivity();
if (in.available() == 0) {
try {
Thread.sleep(I2PTunnel.PACKET_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if (in.available() == 0) {
out.flush(); // make sure the data get though
}
}
} catch (SocketException ex) {
// this *will* occur when the other threads closes the socket
synchronized (finishLock) {
if (!finished) {
_log.debug("Socket closed - error reading and writing",
ex);
}
}
} catch (InterruptedIOException ex) {
_log.warn("Closing connection due to timeout (error: \""
+ ex.getMessage() + "\")");
} catch (IOException ex) {
if (!finished)
_log.error("Error forwarding", ex);
else
_log.warn("You may ignore this", ex);
} finally {
try {
out.close();
in.close();
} catch (IOException ex) {
_log.error("Error closing streams", ex);
}
synchronized (finishLock) {
finished = true;
finishLock.notifyAll();
// the main thread will close sockets etc. now
}
}
}
}
}

View File

@@ -11,7 +11,8 @@ import java.io.InputStream;
import java.net.InetAddress;
import java.net.Socket;
import java.net.SocketException;
import java.util.*;
import java.util.Iterator;
import java.util.Properties;
import net.i2p.I2PException;
import net.i2p.client.I2PClient;
@@ -22,11 +23,11 @@ import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.client.streaming.I2PSocketManagerFactory;
import net.i2p.data.Base64;
import net.i2p.util.EventDispatcher;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public class I2PTunnelServer extends I2PTunnelTask
implements Runnable {
public class I2PTunnelServer extends I2PTunnelTask implements Runnable {
private final static Log _log = new Log(I2PTunnelServer.class);
private I2PSocketManager sockMgr;
@@ -38,101 +39,126 @@ public class I2PTunnelServer extends I2PTunnelTask
private int remotePort;
private Logging l;
public I2PTunnelServer(InetAddress host, int port,
String privData, Logging l,
EventDispatcher notifyThis) {
super(host+":"+port+" <- "+privData, notifyThis);
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(privData));
init(host, port, bais, privData, l);
}
public I2PTunnelServer(InetAddress host, int port,
File privkey, String privkeyname,
Logging l, EventDispatcher notifyThis) {
super(host+":"+port+" <- "+privkeyname, notifyThis);
try {
init(host, port, new FileInputStream(privkey), privkeyname, l);
} catch (IOException ioe) {
_log.error("Error starting server", ioe);
notifyEvent("openServerResult", "error");
}
}
public I2PTunnelServer(InetAddress host, int port,
InputStream privData, String privkeyname,
Logging l, EventDispatcher notifyThis) {
super(host+":"+port+" <- "+privkeyname, notifyThis);
init(host, port, privData, privkeyname, l);
}
private void init(InetAddress host, int port, InputStream privData,
String privkeyname, Logging l) {
this.l=l;
this.remoteHost=host;
this.remotePort=port;
I2PClient client = I2PClientFactory.createClient();
Properties props = new Properties();
props.putAll(System.getProperties());
synchronized(slock) {
sockMgr = I2PSocketManagerFactory.createManager
(privData, I2PTunnel.host,
Integer.parseInt(I2PTunnel.port), props);
}
l.log("Ready!");
notifyEvent("openServerResult", "ok");
open=true;
Thread t = new Thread(this);
t.setName("Server");
t.start();
private static final long DEFAULT_READ_TIMEOUT = -1; // 3*60*1000;
/** default timeout to 3 minutes - override if desired */
private long readTimeout = DEFAULT_READ_TIMEOUT;
public I2PTunnelServer(InetAddress host, int port, String privData, Logging l, EventDispatcher notifyThis) {
super(host + ":" + port + " <- " + privData, notifyThis);
ByteArrayInputStream bais = new ByteArrayInputStream(Base64.decode(privData));
init(host, port, bais, privData, l);
}
public I2PTunnelServer(InetAddress host, int port, File privkey, String privkeyname, Logging l,
EventDispatcher notifyThis) {
super(host + ":" + port + " <- " + privkeyname, notifyThis);
try {
init(host, port, new FileInputStream(privkey), privkeyname, l);
} catch (IOException ioe) {
_log.error("Error starting server", ioe);
notifyEvent("openServerResult", "error");
}
}
public I2PTunnelServer(InetAddress host, int port, InputStream privData, String privkeyname, Logging l, EventDispatcher notifyThis) {
super(host + ":" + port + " <- " + privkeyname, notifyThis);
init(host, port, privData, privkeyname, l);
}
private void init(InetAddress host, int port, InputStream privData, String privkeyname, Logging l) {
this.l = l;
this.remoteHost = host;
this.remotePort = port;
I2PClient client = I2PClientFactory.createClient();
Properties props = new Properties();
props.putAll(System.getProperties());
synchronized (slock) {
sockMgr = I2PSocketManagerFactory.createManager(privData, I2PTunnel.host, Integer.parseInt(I2PTunnel.port),
props);
}
l.log("Ready!");
notifyEvent("openServerResult", "ok");
open = true;
}
private static volatile long __serverId = 0;
/**
* Start running the I2PTunnelServer.
*
*/
public void startRunning() {
Thread t = new I2PThread(this);
t.setName("Server " + (++__serverId));
t.start();
}
/**
* Set the read idle timeout for newly-created connections (in
* milliseconds). After this time expires without data being reached from
* the I2P network, the connection itself will be closed.
*/
public void setReadTimeout(long ms) {
readTimeout = ms;
}
/**
* Get the read idle timeout for newly-created connections (in
* milliseconds).
*
* @return The read timeout used for connections
*/
public long getReadTimeout() {
return readTimeout;
}
public boolean close(boolean forced) {
if (!open) return true;
synchronized(lock) {
if (!forced && sockMgr.listSockets().size() != 0) {
l.log("There are still active connections!");
for (Iterator it = sockMgr.listSockets().iterator();
it.hasNext();) {
l.log("->"+it.next());
}
return false;
}
l.log("Shutting down server "+toString());
try {
if (i2pss != null) i2pss.close();
sockMgr.getSession().destroySession();
} catch (I2PException ex) {
_log.error("Error destroying the session", ex);
System.exit(1);
}
l.log("Server shut down.");
open=false;
return true;
}
if (!open) return true;
synchronized (lock) {
if (!forced && sockMgr.listSockets().size() != 0) {
l.log("There are still active connections!");
for (Iterator it = sockMgr.listSockets().iterator(); it.hasNext();) {
l.log("->" + it.next());
}
return false;
}
l.log("Shutting down server " + toString());
try {
if (i2pss != null) i2pss.close();
sockMgr.getSession().destroySession();
} catch (I2PException ex) {
_log.error("Error destroying the session", ex);
System.exit(1);
}
l.log("Server shut down.");
open = false;
return true;
}
}
public void run() {
try {
I2PServerSocket i2pss = sockMgr.getServerSocket();
while (true) {
I2PSocket i2ps = i2pss.accept();
//local is fast, so synchronously. Does not need that many
//threads.
try {
Socket s = new Socket(remoteHost, remotePort);
new I2PTunnelRunner(s, i2ps, slock, null);
} catch (SocketException ex) {
i2ps.close();
}
}
} catch (I2PException ex) {
_log.error("Error while waiting for I2PConnections", ex);
} catch (IOException ex) {
_log.error("Error while waiting for I2PConnections", ex);
}
}
try {
I2PServerSocket i2pss = sockMgr.getServerSocket();
while (true) {
I2PSocket i2ps = i2pss.accept();
//local is fast, so synchronously. Does not need that many
//threads.
try {
i2ps.setReadTimeout(readTimeout);
Socket s = new Socket(remoteHost, remotePort);
new I2PTunnelRunner(s, i2ps, slock, null);
} catch (SocketException ex) {
i2ps.close();
}
}
} catch (I2PException ex) {
_log.error("Error while waiting for I2PConnections", ex);
} catch (IOException ex) {
_log.error("Error while waiting for I2PConnections", ex);
}
}
}

View File

@@ -27,49 +27,86 @@ public abstract class I2PTunnelTask implements EventDispatcher {
//}
protected I2PTunnelTask(String name, EventDispatcher notifyThis) {
attachEventDispatcher(notifyThis);
this.name=name;
this.id = -1;
attachEventDispatcher(notifyThis);
this.name = name;
this.id = -1;
}
/** for apps that use multiple I2PTunnel instances */
public void setTunnel(I2PTunnel pTunnel) { tunnel = pTunnel; }
public void setTunnel(I2PTunnel pTunnel) {
tunnel = pTunnel;
}
public int getId() {
return this.id;
}
public boolean isOpen() {return open;}
public boolean isOpen() {
return open;
}
public void setId(int id) {
this.id = id;
}
protected void setName(String name) {
this.name=name;
this.name = name;
}
protected void routerDisconnected() {
tunnel.routerDisconnected();
}
protected void routerDisconnected() { tunnel.routerDisconnected(); }
public abstract boolean close(boolean forced);
public void disconnected(I2PSession session) { routerDisconnected(); }
public void errorOccurred(I2PSession session, String message,
Throwable error) {}
public void reportAbuse(I2PSession session, int severity) {}
public void disconnected(I2PSession session) {
routerDisconnected();
}
public void errorOccurred(I2PSession session, String message, Throwable error) {
}
public void reportAbuse(I2PSession session, int severity) {
}
public String toString() {
return name;
return name;
}
/* Required by the EventDispatcher interface */
public EventDispatcher getEventDispatcher() { return _event; }
public void attachEventDispatcher(EventDispatcher e) { _event.attachEventDispatcher(e.getEventDispatcher()); }
public void detachEventDispatcher(EventDispatcher e) { _event.detachEventDispatcher(e.getEventDispatcher()); }
public void notifyEvent(String e, Object a) { _event.notifyEvent(e,a); }
public Object getEventValue(String n) { return _event.getEventValue(n); }
public Set getEvents() { return _event.getEvents(); }
public void ignoreEvents() { _event.ignoreEvents(); }
public void unIgnoreEvents() { _event.unIgnoreEvents(); }
public Object waitEventValue(String n) { return _event.waitEventValue(n); }
}
public EventDispatcher getEventDispatcher() {
return _event;
}
public void attachEventDispatcher(EventDispatcher e) {
_event.attachEventDispatcher(e.getEventDispatcher());
}
public void detachEventDispatcher(EventDispatcher e) {
_event.detachEventDispatcher(e.getEventDispatcher());
}
public void notifyEvent(String e, Object a) {
_event.notifyEvent(e, a);
}
public Object getEventValue(String n) {
return _event.getEventValue(n);
}
public Set getEvents() {
return _event.getEvents();
}
public void ignoreEvents() {
_event.ignoreEvents();
}
public void unIgnoreEvents() {
_event.unIgnoreEvents();
}
public Object waitEventValue(String n) {
return _event.waitEventValue(n);
}
}

View File

@@ -14,6 +14,7 @@ import net.i2p.I2PException;
import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.data.Destination;
import net.i2p.util.EventDispatcher;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
public class I2Ping extends I2PTunnelTask implements Runnable {
@@ -21,17 +22,17 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
private static final int PING_COUNT = 3;
private static final int CPING_COUNT = 5;
private static final int PING_TIMEOUT= 5000;
private static final int PING_TIMEOUT = 5000;
private static final long PING_DISTANCE=1000;
private static final long PING_DISTANCE = 1000;
private int MAX_SIMUL_PINGS=10; // not really final...
private int MAX_SIMUL_PINGS = 10; // not really final...
private boolean countPing=false;
private boolean countPing = false;
private I2PSocketManager sockMgr;
private Logging l;
private boolean finished=false;
private boolean finished = false;
private String command;
private long timeout = PING_TIMEOUT;
@@ -39,190 +40,183 @@ public class I2Ping extends I2PTunnelTask implements Runnable {
private int simulPings = 0;
private long lastPingTime = 0;
private Object lock = new Object(), slock = new Object();
private Object lock = new Object(), slock = new Object();
//public I2Ping(String cmd, Logging l,
// boolean ownDest) {
// I2Ping(cmd, l, (EventDispatcher)null);
//}
public I2Ping(String cmd, Logging l,
boolean ownDest, EventDispatcher notifyThis) {
super("I2Ping ["+cmd+"]", notifyThis);
this.l=l;
command=cmd;
synchronized(slock) {
if (ownDest) {
sockMgr = I2PTunnelClient.buildSocketManager();
} else {
sockMgr = I2PTunnelClient.getSocketManager();
}
}
Thread t = new Thread(this);
t.setName("Client");
t.start();
open=true;
public I2Ping(String cmd, Logging l, boolean ownDest, EventDispatcher notifyThis) {
super("I2Ping [" + cmd + "]", notifyThis);
this.l = l;
command = cmd;
synchronized (slock) {
if (ownDest) {
sockMgr = I2PTunnelClient.buildSocketManager();
} else {
sockMgr = I2PTunnelClient.getSocketManager();
}
}
Thread t = new I2PThread(this);
t.setName("Client");
t.start();
open = true;
}
public void run() {
l.log("*** I2Ping results:");
try {
runCommand(command);
} catch (InterruptedException ex) {
l.log("*** Interrupted");
_log.error("Pinger interrupted",ex);
} catch (IOException ex) {
_log.error("Pinger exception",ex);
}
l.log("*** Finished.");
synchronized(lock) {
finished=true;
}
close(false);
l.log("*** I2Ping results:");
try {
runCommand(command);
} catch (InterruptedException ex) {
l.log("*** Interrupted");
_log.error("Pinger interrupted", ex);
} catch (IOException ex) {
_log.error("Pinger exception", ex);
}
l.log("*** Finished.");
synchronized (lock) {
finished = true;
}
close(false);
}
public void runCommand(String cmd) throws InterruptedException,
IOException {
if (cmd.startsWith("-t ")) { // timeout
cmd = cmd.substring(3);
int pos = cmd.indexOf(" ");
if (pos == -1) {
l.log("Syntax error");
return;
} else {
timeout = Long.parseLong(cmd.substring(0, pos));
cmd=cmd.substring(pos+1);
}
}
if (cmd.startsWith("-m ")) { // max simultaneous pings
cmd = cmd.substring(3);
int pos = cmd.indexOf(" ");
if (pos == -1) {
l.log("Syntax error");
return;
} else {
MAX_SIMUL_PINGS = Integer.parseInt(cmd.substring(0, pos));
cmd=cmd.substring(pos+1);
}
}
if (cmd.startsWith("-c ")) { // "count" ping
countPing=true;
cmd=cmd.substring(3);
}
if (cmd.equals("-h")) { // ping all hosts
cmd="-l hosts.txt";
}
if (cmd.startsWith("-l ")) { // ping a list of hosts
BufferedReader br = new BufferedReader
(new FileReader(cmd.substring(3)));
String line;
List pingHandlers = new ArrayList();
while ((line = br.readLine()) != null) {
if (line.startsWith("#")) continue; // comments
if (line.startsWith(";")) continue;
if (line.startsWith("!")) continue;
if (line.indexOf("=") != -1) { // maybe file is hosts.txt?
line=line.substring(0,line.indexOf("="));
}
pingHandlers.add(new PingHandler(line));
}
br.close();
for (Iterator it= pingHandlers.iterator(); it.hasNext(); ) {
Thread t = (Thread) it.next();
t.join();
}
public void runCommand(String cmd) throws InterruptedException, IOException {
if (cmd.startsWith("-t ")) { // timeout
cmd = cmd.substring(3);
int pos = cmd.indexOf(" ");
if (pos == -1) {
l.log("Syntax error");
return;
} else {
timeout = Long.parseLong(cmd.substring(0, pos));
cmd = cmd.substring(pos + 1);
}
}
if (cmd.startsWith("-m ")) { // max simultaneous pings
cmd = cmd.substring(3);
int pos = cmd.indexOf(" ");
if (pos == -1) {
l.log("Syntax error");
return;
} else {
MAX_SIMUL_PINGS = Integer.parseInt(cmd.substring(0, pos));
cmd = cmd.substring(pos + 1);
}
}
if (cmd.startsWith("-c ")) { // "count" ping
countPing = true;
cmd = cmd.substring(3);
}
if (cmd.equals("-h")) { // ping all hosts
cmd = "-l hosts.txt";
}
if (cmd.startsWith("-l ")) { // ping a list of hosts
BufferedReader br = new BufferedReader(new FileReader(cmd.substring(3)));
String line;
List pingHandlers = new ArrayList();
while ((line = br.readLine()) != null) {
if (line.startsWith("#")) continue; // comments
if (line.startsWith(";")) continue;
if (line.startsWith("!")) continue;
if (line.indexOf("=") != -1) { // maybe file is hosts.txt?
line = line.substring(0, line.indexOf("="));
}
pingHandlers.add(new PingHandler(line));
}
br.close();
for (Iterator it = pingHandlers.iterator(); it.hasNext();) {
Thread t = (Thread) it.next();
t.join();
}
} else {
Thread t = new PingHandler(cmd);
t.join();
}
} else {
Thread t = new PingHandler(cmd);
t.join();
}
}
public boolean close(boolean forced) {
if (!open) return true;
synchronized(lock) {
if (!forced && !finished) {
l.log("There are still pings running!");
return false;
}
l.log("Closing pinger "+toString());
l.log("Pinger closed.");
open=false;
return true;
}
if (!open) return true;
synchronized (lock) {
if (!forced && !finished) {
l.log("There are still pings running!");
return false;
}
l.log("Closing pinger " + toString());
l.log("Pinger closed.");
open = false;
return true;
}
}
public boolean ping(Destination dest) throws I2PException {
try {
synchronized(simulLock) {
while (simulPings >= MAX_SIMUL_PINGS) {
simulLock.wait();
}
simulPings++;
while (lastPingTime + PING_DISTANCE >
System.currentTimeMillis()) {
// no wait here, to delay all pingers
Thread.sleep(PING_DISTANCE/2);
}
lastPingTime=System.currentTimeMillis();
}
boolean sent = sockMgr.ping(dest, PING_TIMEOUT);
synchronized(simulLock) {
simulPings--;
simulLock.notifyAll();
}
return sent;
} catch (InterruptedException ex) {
_log.error("Interrupted", ex);
return false;
}
try {
synchronized (simulLock) {
while (simulPings >= MAX_SIMUL_PINGS) {
simulLock.wait();
}
simulPings++;
while (lastPingTime + PING_DISTANCE > System.currentTimeMillis()) {
// no wait here, to delay all pingers
Thread.sleep(PING_DISTANCE / 2);
}
lastPingTime = System.currentTimeMillis();
}
boolean sent = sockMgr.ping(dest, PING_TIMEOUT);
synchronized (simulLock) {
simulPings--;
simulLock.notifyAll();
}
return sent;
} catch (InterruptedException ex) {
_log.error("Interrupted", ex);
return false;
}
}
public class PingHandler extends I2PThread {
private String destination;
public class PingHandler extends Thread {
private String destination;
public PingHandler(String dest) {
this.destination=dest;
setName("PingHandler for " + dest);
start();
}
public void run() {
try {
Destination dest=I2PTunnel.destFromName(destination);
if (dest == null) {
synchronized(lock) { // Logger is not thread safe
l.log("Unresolvable: "+destination+"");
}
return;
}
int cnt = countPing ? CPING_COUNT : PING_COUNT;
StringBuffer pingResults = new StringBuffer
(2*cnt+ destination.length()+3);
for (int i=0;i<cnt; i++) {
boolean sent;
sent = ping(dest);
if (countPing) {
if (!sent) {
pingResults.append(i).append(" ");
break;
} else if (i == cnt - 1) {
pingResults.append("+ ");
}
} else {
pingResults.append(sent?"+ ":"- ");
}
// System.out.println(sent+" -> "+destination);
}
pingResults.append(" ").append(destination);
synchronized(lock) { // Logger is not thread safe
l.log(pingResults.toString());
}
} catch (I2PException ex) {
_log.error("Error pinging " + destination, ex);
}
}
public PingHandler(String dest) {
this.destination = dest;
setName("PingHandler for " + dest);
start();
}
public void run() {
try {
Destination dest = I2PTunnel.destFromName(destination);
if (dest == null) {
synchronized (lock) { // Logger is not thread safe
l.log("Unresolvable: " + destination + "");
}
return;
}
int cnt = countPing ? CPING_COUNT : PING_COUNT;
StringBuffer pingResults = new StringBuffer(2 * cnt + destination.length() + 3);
for (int i = 0; i < cnt; i++) {
boolean sent;
sent = ping(dest);
if (countPing) {
if (!sent) {
pingResults.append(i).append(" ");
break;
} else if (i == cnt - 1) {
pingResults.append("+ ");
}
} else {
pingResults.append(sent ? "+ " : "- ");
}
// System.out.println(sent+" -> "+destination);
}
pingResults.append(" ").append(destination);
synchronized (lock) { // Logger is not thread safe
l.log(pingResults.toString());
}
} catch (I2PException ex) {
_log.error("Error pinging " + destination, ex);
}
}
}
}
}

View File

@@ -3,7 +3,6 @@
*/
package net.i2p.i2ptunnel;
public interface Logging {
public void log(String s);
}
}

View File

@@ -151,283 +151,285 @@ public class TunnelManager implements Runnable {
private I2PTunnel _tunnel;
private ServerSocket _socket;
private boolean _keepAccepting;
public TunnelManager(int listenPort) {
this(null, listenPort);
this(null, listenPort);
}
public TunnelManager(String listenHost, int listenPort) {
_tunnel = new I2PTunnel();
_keepAccepting = true;
try {
if (listenHost != null) {
_socket = new ServerSocket(listenPort, 0, InetAddress.getByName(listenHost));
_log.info("Listening for tunnel management clients on " + listenHost + ":" + listenPort);
} else {
_socket = new ServerSocket(listenPort);
_log.info("Listening for tunnel management clients on localhost:" + listenPort);
}
} catch (Exception e) {
_log.error("Error starting up tunnel management listener on " + listenPort, e);
}
_tunnel = new I2PTunnel();
_keepAccepting = true;
try {
if (listenHost != null) {
_socket = new ServerSocket(listenPort, 0, InetAddress.getByName(listenHost));
_log.info("Listening for tunnel management clients on " + listenHost + ":" + listenPort);
} else {
_socket = new ServerSocket(listenPort);
_log.info("Listening for tunnel management clients on localhost:" + listenPort);
}
} catch (Exception e) {
_log.error("Error starting up tunnel management listener on " + listenPort, e);
}
}
public static void main(String args[]) {
int port = 7676;
String host = null;
if (args.length == 1) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe) {
_log.error("Usage: TunnelManager [host] [port]");
return;
}
} else if (args.length == 2) {
host = args[0];
try {
port = Integer.parseInt(args[1]);
} catch (NumberFormatException nfe) {
_log.error("Usage: TunnelManager [host] [port]");
return;
}
}
int port = 7676;
String host = null;
if (args.length == 1) {
try {
port = Integer.parseInt(args[0]);
} catch (NumberFormatException nfe) {
_log.error("Usage: TunnelManager [host] [port]");
return;
}
} else if (args.length == 2) {
host = args[0];
try {
port = Integer.parseInt(args[1]);
} catch (NumberFormatException nfe) {
_log.error("Usage: TunnelManager [host] [port]");
return;
}
}
TunnelManager mgr = new TunnelManager(host, port);
Thread t = new Thread(mgr, "Listener");
t.start();
TunnelManager mgr = new TunnelManager(host, port);
Thread t = new I2PThread(mgr, "Listener");
t.start();
}
public void run() {
if (_socket == null) {
_log.error("Unable to start listening, since the socket was not bound. Already running?");
return;
}
_log.debug("Running");
try {
while (_keepAccepting) {
Socket socket = _socket.accept();
_log.debug("Client accepted");
if (socket != null) {
Thread t = new I2PThread(new TunnelManagerClientRunner(this, socket));
t.setName("TunnelManager Client");
t.setPriority(I2PThread.MIN_PRIORITY);
t.start();
}
}
} catch (IOException ioe) {
_log.error("Error accepting connections", ioe);
} catch (Exception e) {
_log.error("Other error?!", e);
} finally {
if (_socket != null) try { _socket.close(); } catch (IOException ioe) {}
}
try { Thread.sleep(5000); } catch (InterruptedException ie) {}
if (_socket == null) {
_log.error("Unable to start listening, since the socket was not bound. Already running?");
return;
}
_log.debug("Running");
try {
while (_keepAccepting) {
Socket socket = _socket.accept();
_log.debug("Client accepted");
if (socket != null) {
Thread t = new I2PThread(new TunnelManagerClientRunner(this, socket));
t.setName("TunnelManager Client");
t.setPriority(I2PThread.MIN_PRIORITY);
t.start();
}
}
} catch (IOException ioe) {
_log.error("Error accepting connections", ioe);
} catch (Exception e) {
_log.error("Other error?!", e);
} finally {
if (_socket != null) try {
_socket.close();
} catch (IOException ioe) {
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException ie) {
}
}
public void error(String msg, OutputStream out) throws IOException {
out.write(msg.getBytes());
out.write('\n');
out.write(msg.getBytes());
out.write('\n');
}
public void processQuit(OutputStream out) throws IOException {
out.write("Nice try".getBytes());
out.write('\n');
out.write("Nice try".getBytes());
out.write('\n');
}
public void processList(OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
long startCommand = Clock.getInstance().now();
_tunnel.runCommand("list", buf);
Object obj = _tunnel.waitEventValue("listDone");
long endCommand = Clock.getInstance().now();
String str = buf.getBuffer();
_log.debug("ListDone complete after " + (endCommand-startCommand) + "ms: [" + str + "]");
out.write(str.getBytes());
out.write('\n');
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
long startCommand = Clock.getInstance().now();
_tunnel.runCommand("list", buf);
Object obj = _tunnel.waitEventValue("listDone");
long endCommand = Clock.getInstance().now();
String str = buf.getBuffer();
_log.debug("ListDone complete after " + (endCommand - startCommand) + "ms: [" + str + "]");
out.write(str.getBytes());
out.write('\n');
buf.ignoreFurtherActions();
}
public void processListenOn(String ip, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("listen_on " + ip, buf);
String status = (String)_tunnel.waitEventValue("listen_onResult");
out.write((status + "\n").getBytes());
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("listen_on " + ip, buf);
String status = (String) _tunnel.waitEventValue("listen_onResult");
out.write((status + "\n").getBytes());
buf.ignoreFurtherActions();
}
/**
* "lookup <name>" returns with the result in base64, else "Unknown host" [or something like that],
* then a newline.
*
*/
public void processLookup(String name, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("lookup " + name, buf);
String rv = (String)_tunnel.waitEventValue("lookupResult");
out.write(rv.getBytes());
out.write('\n');
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("lookup " + name, buf);
String rv = (String) _tunnel.waitEventValue("lookupResult");
out.write(rv.getBytes());
out.write('\n');
buf.ignoreFurtherActions();
}
public void processTestDestination(String destKey, OutputStream out) throws IOException {
try {
Destination d = new Destination();
d.fromBase64(destKey);
out.write("valid\n".getBytes());
} catch (DataFormatException dfe) {
out.write("invalid\n".getBytes());
}
out.flush();
try {
Destination d = new Destination();
d.fromBase64(destKey);
out.write("valid\n".getBytes());
} catch (DataFormatException dfe) {
out.write("invalid\n".getBytes());
}
out.flush();
}
public void processConvertPrivate(String priv, OutputStream out) throws IOException {
try {
Destination dest = new Destination();
dest.fromBase64(priv);
String str = dest.toBase64();
out.write(str.getBytes());
out.write('\n');
} catch (DataFormatException dfe) {
_log.error("Error converting private data", dfe);
out.write("Error converting private key\n".getBytes());
}
try {
Destination dest = new Destination();
dest.fromBase64(priv);
String str = dest.toBase64();
out.write(str.getBytes());
out.write('\n');
} catch (DataFormatException dfe) {
_log.error("Error converting private data", dfe);
out.write("Error converting private key\n".getBytes());
}
}
public void processClose(String which, boolean forced, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand((forced?"close forced ":"close ") + which, buf);
String str = (String)_tunnel.waitEventValue("closeResult");
out.write((str + "\n").getBytes());
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
_tunnel.runCommand((forced ? "close forced " : "close ") + which, buf);
String str = (String) _tunnel.waitEventValue("closeResult");
out.write((str + "\n").getBytes());
buf.ignoreFurtherActions();
}
/**
* "genkey" returns with the base64 of the destination, followed by a tab, then the base64 of that
* destination's private keys, then a newline.
*
*/
public void processGenKey(OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("gentextkeys", buf);
String priv = (String)_tunnel.waitEventValue("privateKey");
String pub = (String)_tunnel.waitEventValue("publicDestination");
out.write((pub + "\t" + priv).getBytes());
out.write('\n');
buf.ignoreFurtherActions();
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("gentextkeys", buf);
String priv = (String) _tunnel.waitEventValue("privateKey");
String pub = (String) _tunnel.waitEventValue("publicDestination");
out.write((pub + "\t" + priv).getBytes());
out.write('\n');
buf.ignoreFurtherActions();
}
public void processOpenClient(int listenPort, String peer, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("client " + listenPort + " " + peer, buf);
Integer taskId = (Integer)_tunnel.waitEventValue("clientTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String)_tunnel.waitEventValue("openClientResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("client " + listenPort + " " + peer, buf);
Integer taskId = (Integer) _tunnel.waitEventValue("clientTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String) _tunnel.waitEventValue("openClientResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
Integer port = (Integer)_tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
+ "]\n").getBytes());
buf.ignoreFurtherActions();
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
}
public void processOpenHTTPClient(int listenPort,
String proxy,
OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("httpclient " + listenPort + " " + proxy, buf);
Integer taskId = (Integer)_tunnel.waitEventValue("httpclientTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String)_tunnel.waitEventValue("openHTTPClientResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
public void processOpenHTTPClient(int listenPort, String proxy, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("httpclient " + listenPort + " " + proxy, buf);
Integer taskId = (Integer) _tunnel.waitEventValue("httpclientTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String) _tunnel.waitEventValue("openHTTPClientResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
Integer port = (Integer)_tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
+ "]\n").getBytes());
buf.ignoreFurtherActions();
}
public void processOpenSOCKSTunnel(int listenPort,
OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("sockstunnel " + listenPort, buf);
Integer taskId = (Integer)_tunnel.waitEventValue("sockstunnelTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String)_tunnel.waitEventValue("openSOCKSTunnelResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
Integer port = (Integer)_tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue()
+ "]\n").getBytes());
buf.ignoreFurtherActions();
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
}
public void processOpenServer(String serverHost, int serverPort, String privateKeys, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("textserver " + serverHost + " " + serverPort + " " + privateKeys, buf);
Integer taskId = (Integer)_tunnel.waitEventValue("serverTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String)_tunnel.waitEventValue("openServerResult");
public void processOpenSOCKSTunnel(int listenPort, OutputStream out) throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("sockstunnel " + listenPort, buf);
Integer taskId = (Integer) _tunnel.waitEventValue("sockstunnelTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String) _tunnel.waitEventValue("openSOCKSTunnelResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
if (listenPort != 0) {
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
return;
}
Integer port = (Integer) _tunnel.waitEventValue("clientLocalPort");
out.write((rv + " " + port.intValue() + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
}
public void processOpenServer(String serverHost, int serverPort, String privateKeys, OutputStream out)
throws IOException {
BufferLogger buf = new BufferLogger();
_tunnel.runCommand("textserver " + serverHost + " " + serverPort + " " + privateKeys, buf);
Integer taskId = (Integer) _tunnel.waitEventValue("serverTaskId");
if (taskId.intValue() < 0) {
out.write("error\n".getBytes());
buf.ignoreFurtherActions();
return;
}
String rv = (String) _tunnel.waitEventValue("openServerResult");
if (rv.equals("error")) {
out.write((rv + "\n").getBytes());
buf.ignoreFurtherActions();
return;
}
out.write((rv + " [" + taskId.intValue() + "]\n").getBytes());
buf.ignoreFurtherActions();
}
/**
* Frisbee.
*
*/
public void unknownCommand(String command, OutputStream out) throws IOException {
out.write("Unknown command: ".getBytes());
out.write(command.getBytes());
out.write("\n".getBytes());
out.write("Unknown command: ".getBytes());
out.write(command.getBytes());
out.write("\n".getBytes());
}
}
}

View File

@@ -3,15 +3,14 @@
*/
package net.i2p.i2ptunnel;
import net.i2p.util.Log;
import java.util.StringTokenizer;
import java.net.Socket;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.BufferedReader;
import java.io.OutputStream;
import java.net.Socket;
import java.util.StringTokenizer;
import net.i2p.util.Log;
/**
* Runner thread that reads commands from the socket and fires off commands to
@@ -22,172 +21,174 @@ class TunnelManagerClientRunner implements Runnable {
private final static Log _log = new Log(TunnelManagerClientRunner.class);
private TunnelManager _mgr;
private Socket _clientSocket;
public TunnelManagerClientRunner(TunnelManager mgr, Socket socket) {
_clientSocket = socket;
_mgr = mgr;
}
public void run() {
_log.debug("Client running");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(_clientSocket.getInputStream()));
OutputStream out = _clientSocket.getOutputStream();
String cmd = reader.readLine();
if (cmd != null)
processCommand(cmd, out);
} catch (IOException ioe) {
_log.error("Error processing client commands", ioe);
} finally {
if (_clientSocket != null) try { _clientSocket.close(); } catch (IOException ioe) {}
}
_log.debug("Client closed");
public TunnelManagerClientRunner(TunnelManager mgr, Socket socket) {
_clientSocket = socket;
_mgr = mgr;
}
public void run() {
_log.debug("Client running");
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(_clientSocket.getInputStream()));
OutputStream out = _clientSocket.getOutputStream();
String cmd = reader.readLine();
if (cmd != null) processCommand(cmd, out);
} catch (IOException ioe) {
_log.error("Error processing client commands", ioe);
} finally {
if (_clientSocket != null) try {
_clientSocket.close();
} catch (IOException ioe) {
}
}
_log.debug("Client closed");
}
/**
* Parse the command string and fire off the appropriate tunnelManager method,
* sending the results to the output stream
*/
private void processCommand(String command, OutputStream out) throws IOException {
_log.debug("Processing [" + command + "]");
StringTokenizer tok = new StringTokenizer(command);
if (!tok.hasMoreTokens()) {
_mgr.unknownCommand(command, out);
} else {
String cmd = tok.nextToken();
if ("quit".equalsIgnoreCase(cmd)) {
_mgr.processQuit(out);
} else if ("lookup".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processLookup(tok.nextToken(), out);
else
_mgr.error("Usage: lookup <hostname>", out);
} else if ("testdestination".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processTestDestination(tok.nextToken(), out);
else
_mgr.error("Usage: testdestination <publicDestination>", out);
} else if ("convertprivate".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processConvertPrivate(tok.nextToken(), out);
else
_mgr.error("Usage: convertprivate <privateData>", out);
} else if ("close".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens()) {
String closeArg;
if ((closeArg = tok.nextToken()).equals("forced")) {
if (tok.hasMoreTokens()) {
_mgr.processClose(tok.nextToken(), true, out);
} else {
_mgr.error("Usage: close [forced] <jobnumber>|all", out);
}
} else {
_mgr.processClose(closeArg, false, out);
}
} else {
_mgr.error("Usage: close [forced] <jobnumber>|all", out);
}
} else if ("genkey".equalsIgnoreCase(cmd)) {
_mgr.processGenKey(out);
} else if ("list".equalsIgnoreCase(cmd)) {
_mgr.processList(out);
} else if ("listen_on".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens()) {
_mgr.processListenOn(tok.nextToken(), out);
} else {
_mgr.error("Usage: listen_on <ip>", out);
}
} else if ("openclient".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String peer = null;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenPort> <peer>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenport> <peer>", out);
return;
}
peer = tok.nextToken();
_mgr.processOpenClient(listenPort, peer, out);
} else if ("openhttpclient".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String proxy = "squid.i2p";
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openhttpclient <listenPort> [<proxy>]",out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (tok.hasMoreTokens()) {
proxy = tok.nextToken();
}
if (tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenport> [<proxy>]",out);
return;
}
_mgr.processOpenHTTPClient(listenPort, proxy, out);
} else if ("opensockstunnel".equalsIgnoreCase(cmd)) {
int listenPort = 0;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: opensockstunnel <listenPort>",out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (tok.hasMoreTokens()) {
_mgr.error("Usage: opensockstunnel <listenport>",out);
return;
}
_mgr.processOpenSOCKSTunnel(listenPort, out);
} else if ("openserver".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String serverHost = null;
String serverKeys = null;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
serverHost = tok.nextToken();
_log.debug("Processing [" + command + "]");
StringTokenizer tok = new StringTokenizer(command);
if (!tok.hasMoreTokens()) {
_mgr.unknownCommand(command, out);
} else {
String cmd = tok.nextToken();
if ("quit".equalsIgnoreCase(cmd)) {
_mgr.processQuit(out);
} else if ("lookup".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processLookup(tok.nextToken(), out);
else
_mgr.error("Usage: lookup <hostname>", out);
} else if ("testdestination".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processTestDestination(tok.nextToken(), out);
else
_mgr.error("Usage: testdestination <publicDestination>", out);
} else if ("convertprivate".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens())
_mgr.processConvertPrivate(tok.nextToken(), out);
else
_mgr.error("Usage: convertprivate <privateData>", out);
} else if ("close".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens()) {
String closeArg;
if ((closeArg = tok.nextToken()).equals("forced")) {
if (tok.hasMoreTokens()) {
_mgr.processClose(tok.nextToken(), true, out);
} else {
_mgr.error("Usage: close [forced] <jobnumber>|all", out);
}
} else {
_mgr.processClose(closeArg, false, out);
}
} else {
_mgr.error("Usage: close [forced] <jobnumber>|all", out);
}
} else if ("genkey".equalsIgnoreCase(cmd)) {
_mgr.processGenKey(out);
} else if ("list".equalsIgnoreCase(cmd)) {
_mgr.processList(out);
} else if ("listen_on".equalsIgnoreCase(cmd)) {
if (tok.hasMoreTokens()) {
_mgr.processListenOn(tok.nextToken(), out);
} else {
_mgr.error("Usage: listen_on <ip>", out);
}
} else if ("openclient".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String peer = null;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenPort> <peer>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenport> <peer>", out);
return;
}
peer = tok.nextToken();
_mgr.processOpenClient(listenPort, peer, out);
} else if ("openhttpclient".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String proxy = "squid.i2p";
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openhttpclient <listenPort> [<proxy>]", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (tok.hasMoreTokens()) {
proxy = tok.nextToken();
}
if (tok.hasMoreTokens()) {
_mgr.error("Usage: openclient <listenport> [<proxy>]", out);
return;
}
_mgr.processOpenHTTPClient(listenPort, proxy, out);
} else if ("opensockstunnel".equalsIgnoreCase(cmd)) {
int listenPort = 0;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: opensockstunnel <listenPort>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (tok.hasMoreTokens()) {
_mgr.error("Usage: opensockstunnel <listenport>", out);
return;
}
_mgr.processOpenSOCKSTunnel(listenPort, out);
} else if ("openserver".equalsIgnoreCase(cmd)) {
int listenPort = 0;
String serverHost = null;
String serverKeys = null;
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
serverHost = tok.nextToken();
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
serverKeys = tok.nextToken();
_mgr.processOpenServer(serverHost, listenPort, serverKeys, out);
} else {
_mgr.unknownCommand(command, out);
}
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
try {
String portStr = tok.nextToken();
listenPort = Integer.parseInt(portStr);
} catch (NumberFormatException nfe) {
_mgr.error("Bad listen port", out);
return;
}
if (!tok.hasMoreTokens()) {
_mgr.error("Usage: openserver <serverHost> <serverPort> <serverKeys>", out);
return;
}
serverKeys = tok.nextToken();
_mgr.processOpenServer(serverHost, listenPort, serverKeys, out);
} else {
_mgr.unknownCommand(command, out);
}
}
}
}
}

View File

@@ -26,31 +26,30 @@ public class I2PSOCKSTunnel extends I2PTunnelClientBase {
// I2PSOCKSTunnel(localPort, l, ownDest, (EventDispatcher)null);
//}
public I2PSOCKSTunnel(int localPort, Logging l, boolean ownDest,
EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "SOCKSHandler");
public I2PSOCKSTunnel(int localPort, Logging l, boolean ownDest, EventDispatcher notifyThis) {
super(localPort, ownDest, l, notifyThis, "SOCKSHandler");
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openSOCKSTunnelResult", "error");
return;
}
setName(getLocalPort() + " -> SOCKSTunnel");
if (waitEventValue("openBaseClientResult").equals("error")) {
notifyEvent("openSOCKSTunnelResult", "error");
return;
}
startRunning();
setName(getLocalPort() + " -> SOCKSTunnel");
notifyEvent("openSOCKSTunnelResult", "ok");
startRunning();
notifyEvent("openSOCKSTunnelResult", "ok");
}
protected void clientConnectionRun(Socket s) {
try {
SOCKSServer serv = SOCKSServerFactory.createSOCKSServer(s);
Socket clientSock = serv.getClientSocket();
I2PSocket destSock = serv.getDestinationI2PSocket();
new I2PTunnelRunner (clientSock, destSock, sockLock, null);
} catch (SOCKSException e) {
_log.error("Error from SOCKS connection: " + e.getMessage());
closeSocket(s);
}
try {
SOCKSServer serv = SOCKSServerFactory.createSOCKSServer(s);
Socket clientSock = serv.getClientSocket();
I2PSocket destSock = serv.getDestinationI2PSocket();
new I2PTunnelRunner(clientSock, destSock, sockLock, null);
} catch (SOCKSException e) {
_log.error("Error from SOCKS connection: " + e.getMessage());
closeSocket(s);
}
}
}
}

View File

@@ -42,189 +42,168 @@ public class SOCKS5Server extends SOCKSServer {
* @param clientSock client socket
*/
public SOCKS5Server(Socket clientSock) {
this.clientSock = clientSock;
this.clientSock = clientSock;
}
public Socket getClientSocket() throws SOCKSException {
setupServer();
setupServer();
return clientSock;
return clientSock;
}
protected void setupServer() throws SOCKSException {
if (setupCompleted) {
return;
}
if (setupCompleted) { return; }
DataInputStream in;
DataOutputStream out;
try {
in = new DataInputStream(clientSock.getInputStream());
out = new DataOutputStream(clientSock.getOutputStream());
DataInputStream in;
DataOutputStream out;
try {
in = new DataInputStream(clientSock.getInputStream());
out = new DataOutputStream(clientSock.getOutputStream());
init(in, out);
manageRequest(in, out);
} catch (IOException e) {
throw new SOCKSException("Connection error ("
+ e.getMessage() + ")");
}
init(in, out);
manageRequest(in, out);
} catch (IOException e) {
throw new SOCKSException("Connection error (" + e.getMessage() + ")");
}
setupCompleted = true;
setupCompleted = true;
}
/**
* SOCKS5 connection initialization. This method assumes that
* SOCKS "VER" field has been stripped from the input stream.
*/
private void init (DataInputStream in,
DataOutputStream out) throws IOException, SOCKSException {
int nMethods = in.readByte() & 0xff;
boolean methodOk = false;
int method = Method.NO_ACCEPTABLE_METHODS;
private void init(DataInputStream in, DataOutputStream out) throws IOException, SOCKSException {
int nMethods = in.readByte() & 0xff;
boolean methodOk = false;
int method = Method.NO_ACCEPTABLE_METHODS;
for (int i = 0; i < nMethods; ++i) {
method = in.readByte() & 0xff;
if (method == Method.NO_AUTH_REQUIRED) {
// That's fine, we do support this method
break;
}
}
boolean canContinue = false;
switch (method) {
case Method.NO_AUTH_REQUIRED:
_log.debug("no authentication required");
sendInitReply(Method.NO_AUTH_REQUIRED, out);
return;
default:
_log.debug("no suitable authentication methods found ("
+ Integer.toHexString(method)+ ")");
sendInitReply(Method.NO_ACCEPTABLE_METHODS, out);
throw new SOCKSException("Unsupported authentication method");
}
for (int i = 0; i < nMethods; ++i) {
method = in.readByte() & 0xff;
if (method == Method.NO_AUTH_REQUIRED) {
// That's fine, we do support this method
break;
}
}
boolean canContinue = false;
switch (method) {
case Method.NO_AUTH_REQUIRED:
_log.debug("no authentication required");
sendInitReply(Method.NO_AUTH_REQUIRED, out);
return;
default:
_log.debug("no suitable authentication methods found (" + Integer.toHexString(method) + ")");
sendInitReply(Method.NO_ACCEPTABLE_METHODS, out);
throw new SOCKSException("Unsupported authentication method");
}
}
/**
* SOCKS5 request management. This method assumes that all the
* stuff preceding or enveloping the actual request (e.g. protocol
* initialization, integrity/confidentiality encapsulations, etc)
* has been stripped out of the input/output streams.
*/
private void manageRequest(DataInputStream in,
DataOutputStream out) throws IOException, SOCKSException {
int socksVer = in.readByte() & 0xff;
if (socksVer != SOCKS_VERSION_5) {
_log.debug("error in SOCKS5 request (protocol != 5? wtf?)");
throw new SOCKSException("Invalid protocol version in request");
}
int command = in.readByte() & 0xff;
switch (command) {
case Command.CONNECT:
break;
case Command.BIND:
_log.debug("BIND command is not supported!");
sendRequestReply(Reply.COMMAND_NOT_SUPPORTED,
AddressType.DOMAINNAME, null,
"0.0.0.0", 0, out);
throw new SOCKSException("BIND command not supported");
case Command.UDP_ASSOCIATE:
_log.debug("UDP ASSOCIATE command is not supported!");
sendRequestReply(Reply.COMMAND_NOT_SUPPORTED,
AddressType.DOMAINNAME, null,
"0.0.0.0", 0, out);
throw new SOCKSException("UDP ASSOCIATE command not supported");
default:
_log.debug("unknown command in request ("
+ Integer.toHexString(command) + ")");
throw new SOCKSException("Invalid command in request");
}
private void manageRequest(DataInputStream in, DataOutputStream out) throws IOException, SOCKSException {
int socksVer = in.readByte() & 0xff;
if (socksVer != SOCKS_VERSION_5) {
_log.debug("error in SOCKS5 request (protocol != 5? wtf?)");
throw new SOCKSException("Invalid protocol version in request");
}
{
// Reserved byte, should be 0x00
byte rsv = in.readByte();
}
int command = in.readByte() & 0xff;
switch (command) {
case Command.CONNECT:
break;
case Command.BIND:
_log.debug("BIND command is not supported!");
sendRequestReply(Reply.COMMAND_NOT_SUPPORTED, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
throw new SOCKSException("BIND command not supported");
case Command.UDP_ASSOCIATE:
_log.debug("UDP ASSOCIATE command is not supported!");
sendRequestReply(Reply.COMMAND_NOT_SUPPORTED, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
throw new SOCKSException("UDP ASSOCIATE command not supported");
default:
_log.debug("unknown command in request (" + Integer.toHexString(command) + ")");
throw new SOCKSException("Invalid command in request");
}
int addressType = in.readByte() & 0xff;
switch (addressType) {
case AddressType.IPV4:
connHostName = new String("");
for (int i = 0; i < 4; ++i) {
int octet = in.readByte() & 0xff;
connHostName += Integer.toString(octet);
if (i != 3) {
connHostName += ".";
}
}
_log.warn("IPV4 address type in request: " + connHostName
+ ". Is your client secure?");
break;
case AddressType.DOMAINNAME:
{
int addrLen = in.readByte() & 0xff;
if (addrLen == 0) {
_log.debug("0-sized address length? wtf?");
throw new SOCKSException("Illegal DOMAINNAME length");
}
byte addr[] = new byte[addrLen];
in.readFully(addr);
connHostName = new String(addr);
}
_log.debug("DOMAINNAME address type in request: " + connHostName);
break;
case AddressType.IPV6:
_log.warn("IP V6 address type in request! Is your client secure?"
+ " (IPv6 is not supported, anyway :-)");
sendRequestReply(Reply.ADDRESS_TYPE_NOT_SUPPORTED,
AddressType.DOMAINNAME, null,
"0.0.0.0", 0, out);
throw new SOCKSException("IPV6 addresses not supported");
default:
_log.debug("unknown address type in request ("
+ Integer.toHexString(command) + ")");
throw new SOCKSException("Invalid addresses type in request");
}
connPort = in.readUnsignedShort();
if (connPort == 0) {
_log.debug("trying to connect to TCP port 0? Dropping!");
throw new SOCKSException("Invalid port number in request");
}
{
// Reserved byte, should be 0x00
byte rsv = in.readByte();
}
int addressType = in.readByte() & 0xff;
switch (addressType) {
case AddressType.IPV4:
connHostName = new String("");
for (int i = 0; i < 4; ++i) {
int octet = in.readByte() & 0xff;
connHostName += Integer.toString(octet);
if (i != 3) {
connHostName += ".";
}
}
_log.warn("IPV4 address type in request: " + connHostName + ". Is your client secure?");
break;
case AddressType.DOMAINNAME:
{
int addrLen = in.readByte() & 0xff;
if (addrLen == 0) {
_log.debug("0-sized address length? wtf?");
throw new SOCKSException("Illegal DOMAINNAME length");
}
byte addr[] = new byte[addrLen];
in.readFully(addr);
connHostName = new String(addr);
}
_log.debug("DOMAINNAME address type in request: " + connHostName);
break;
case AddressType.IPV6:
_log.warn("IP V6 address type in request! Is your client secure?" + " (IPv6 is not supported, anyway :-)");
sendRequestReply(Reply.ADDRESS_TYPE_NOT_SUPPORTED, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
throw new SOCKSException("IPV6 addresses not supported");
default:
_log.debug("unknown address type in request (" + Integer.toHexString(command) + ")");
throw new SOCKSException("Invalid addresses type in request");
}
connPort = in.readUnsignedShort();
if (connPort == 0) {
_log.debug("trying to connect to TCP port 0? Dropping!");
throw new SOCKSException("Invalid port number in request");
}
}
protected void confirmConnection() throws SOCKSException {
DataInputStream in;
DataOutputStream out;
try {
out = new DataOutputStream(clientSock.getOutputStream());
sendRequestReply(Reply.SUCCEEDED,
AddressType.IPV4,
InetAddress.getByName("127.0.0.1"),
null, 1, out);
} catch (IOException e) {
throw new SOCKSException("Connection error ("
+ e.getMessage() + ")");
}
DataInputStream in;
DataOutputStream out;
try {
out = new DataOutputStream(clientSock.getOutputStream());
sendRequestReply(Reply.SUCCEEDED, AddressType.IPV4, InetAddress.getByName("127.0.0.1"), null, 1, out);
} catch (IOException e) {
throw new SOCKSException("Connection error (" + e.getMessage() + ")");
}
}
/**
* Send the specified reply during SOCKS5 initialization
*/
private void sendInitReply(int replyCode,
DataOutputStream out) throws IOException {
ByteArrayOutputStream reps = new ByteArrayOutputStream();
private void sendInitReply(int replyCode, DataOutputStream out) throws IOException {
ByteArrayOutputStream reps = new ByteArrayOutputStream();
reps.write(SOCKS_VERSION_5);
reps.write(replyCode);
reps.write(SOCKS_VERSION_5);
reps.write(replyCode);
byte[] reply = reps.toByteArray();
byte[] reply = reps.toByteArray();
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Sending init reply:\n" + HexDump.dump(reply));
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Sending init reply:\n" + HexDump.dump(reply));
}
out.write(reply);
out.write(reply);
}
/**
@@ -232,78 +211,72 @@ public class SOCKS5Server extends SOCKSServer {
* one of inetAddr or domainName can be null, depending on
* addressType.
*/
private void sendRequestReply(int replyCode,
int addressType,
InetAddress inetAddr,
String domainName,
int bindPort,
DataOutputStream out) throws IOException {
ByteArrayOutputStream reps = new ByteArrayOutputStream();
DataOutputStream dreps = new DataOutputStream(reps);
dreps.write(SOCKS_VERSION_5);
dreps.write(replyCode);
private void sendRequestReply(int replyCode, int addressType, InetAddress inetAddr, String domainName,
int bindPort, DataOutputStream out) throws IOException {
ByteArrayOutputStream reps = new ByteArrayOutputStream();
DataOutputStream dreps = new DataOutputStream(reps);
// Reserved byte, should be 0x00
dreps.write(0x00);
dreps.write(SOCKS_VERSION_5);
dreps.write(replyCode);
dreps.write(addressType);
switch (addressType) {
case AddressType.IPV4:
dreps.write(inetAddr.getAddress());
break;
case AddressType.DOMAINNAME:
dreps.writeByte(domainName.length());
dreps.writeBytes(domainName);
break;
default:
_log.error("unknown address type passed to sendReply() ("
+ Integer.toHexString(addressType) + ")! wtf?");
return;
}
// Reserved byte, should be 0x00
dreps.write(0x00);
dreps.writeShort(bindPort);
dreps.write(addressType);
byte[] reply = reps.toByteArray();
switch (addressType) {
case AddressType.IPV4:
dreps.write(inetAddr.getAddress());
break;
case AddressType.DOMAINNAME:
dreps.writeByte(domainName.length());
dreps.writeBytes(domainName);
break;
default:
_log.error("unknown address type passed to sendReply() (" + Integer.toHexString(addressType) + ")! wtf?");
return;
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Sending request reply:\n" + HexDump.dump(reply));
}
dreps.writeShort(bindPort);
out.write(reply);
byte[] reply = reps.toByteArray();
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Sending request reply:\n" + HexDump.dump(reply));
}
out.write(reply);
}
/*
* Some namespaces to enclose SOCKS protocol codes
*/
private class Method {
private static final int NO_AUTH_REQUIRED = 0x00;
private static final int NO_ACCEPTABLE_METHODS = 0xff;
private static final int NO_AUTH_REQUIRED = 0x00;
private static final int NO_ACCEPTABLE_METHODS = 0xff;
}
private class AddressType {
private static final int IPV4 = 0x01;
private static final int DOMAINNAME = 0x03;
private static final int IPV6 = 0x04;
private static final int IPV4 = 0x01;
private static final int DOMAINNAME = 0x03;
private static final int IPV6 = 0x04;
}
private class Command {
private static final int CONNECT = 0x01;
private static final int BIND = 0x02;
private static final int UDP_ASSOCIATE = 0x03;
private static final int CONNECT = 0x01;
private static final int BIND = 0x02;
private static final int UDP_ASSOCIATE = 0x03;
}
private class Reply {
private static final int SUCCEEDED = 0x00;
private static final int GENERAL_SOCKS_SERVER_FAILURE = 0x01;
private static final int CONNECTION_NOT_ALLOWED_BY_RULESET = 0x02;
private static final int NETWORK_UNREACHABLE = 0x03;
private static final int HOST_UNREACHABLE = 0x04;
private static final int CONNECTION_REFUSED = 0x05;
private static final int TTL_EXPIRED = 0x06;
private static final int COMMAND_NOT_SUPPORTED = 0x07;
private static final int ADDRESS_TYPE_NOT_SUPPORTED = 0x08;
private static final int SUCCEEDED = 0x00;
private static final int GENERAL_SOCKS_SERVER_FAILURE = 0x01;
private static final int CONNECTION_NOT_ALLOWED_BY_RULESET = 0x02;
private static final int NETWORK_UNREACHABLE = 0x03;
private static final int HOST_UNREACHABLE = 0x04;
private static final int CONNECTION_REFUSED = 0x05;
private static final int TTL_EXPIRED = 0x06;
private static final int COMMAND_NOT_SUPPORTED = 0x07;
private static final int ADDRESS_TYPE_NOT_SUPPORTED = 0x08;
}
}
}

View File

@@ -14,10 +14,10 @@ package net.i2p.i2ptunnel.socks;
public class SOCKSException extends Exception {
public SOCKSException() {
super();
super();
}
public SOCKSException(String s) {
super(s);
super(s);
}
}
}

View File

@@ -6,16 +6,17 @@
*/
package net.i2p.i2ptunnel.socks;
import java.io.IOException;
import java.net.Socket;
import java.net.SocketException;
import net.i2p.I2PException;
import net.i2p.client.streaming.I2PSocket;
import net.i2p.client.streaming.I2PSocketManager;
import net.i2p.client.streaming.I2PSocketManagerFactory;
import net.i2p.client.streaming.I2PSocketOptions;
import net.i2p.data.DataFormatException;
import net.i2p.I2PException;
import net.i2p.i2ptunnel.I2PTunnel;
import net.i2p.util.Log;
/**
@@ -48,7 +49,6 @@ public abstract class SOCKSServer {
*/
public abstract Socket getClientSocket() throws SOCKSException;
/**
* Confirm to the client that the connection has succeeded
*/
@@ -61,40 +61,46 @@ public abstract class SOCKSServer {
* @return an I2PSocket connected with the destination
*/
public I2PSocket getDestinationI2PSocket() throws SOCKSException {
setupServer();
setupServer();
if (connHostName == null) {
_log.error("BUG: destination host name has not been initialized!");
throw new SOCKSException("BUG! See the logs!");
}
if (connPort == 0) {
_log.error("BUG: destination port has not been initialized!");
throw new SOCKSException("BUG! See the logs!");
}
if (connHostName == null) {
_log.error("BUG: destination host name has not been initialized!");
throw new SOCKSException("BUG! See the logs!");
}
if (connPort == 0) {
_log.error("BUG: destination port has not been initialized!");
throw new SOCKSException("BUG! See the logs!");
}
// FIXME: here we should read our config file, select an
// outproxy, and instantiate the proper socket class that
// handles the outproxy itself (SOCKS4a, SOCKS5, HTTP CONNECT...).
I2PSocket destSock;
// FIXME: here we should read our config file, select an
// outproxy, and instantiate the proper socket class that
// handles the outproxy itself (SOCKS4a, SOCKS5, HTTP CONNECT...).
I2PSocket destSock;
try {
if (connHostName.toLowerCase().endsWith(".i2p")) {
_log.debug("connecting to " + connHostName + "...");
I2PSocketManager sm = I2PSocketManagerFactory.createManager();
destSock = sm.connect(I2PTunnel.destFromName(connHostName),
new I2PSocketOptions());
confirmConnection();
_log.debug("connection confirmed - exchanging data...");
} else {
_log.error("We don't support outproxies (yet)");
throw new SOCKSException("Ouproxies not supported (yet)");
}
} catch (DataFormatException e) {
throw new SOCKSException("Error in destination format");
} catch (I2PException e) {
throw new SOCKSException("I2P error (" + e.getMessage() + ")");
}
return destSock;
try {
if (connHostName.toLowerCase().endsWith(".i2p")) {
_log.debug("connecting to " + connHostName + "...");
I2PSocketManager sm = I2PSocketManagerFactory.createManager();
destSock = sm.connect(I2PTunnel.destFromName(connHostName), new I2PSocketOptions());
confirmConnection();
_log.debug("connection confirmed - exchanging data...");
} else {
_log.error("We don't support outproxies (yet)");
throw new SOCKSException("Ouproxies not supported (yet)");
}
} catch (DataFormatException e) {
throw new SOCKSException("Error in destination format");
} catch (SocketException e) {
throw new SOCKSException("Error connecting ("
+ e.getMessage() + ")");
} catch (IOException e) {
throw new SOCKSException("Error connecting ("
+ e.getMessage() + ")");
} catch (I2PException e) {
throw new SOCKSException("Error connecting ("
+ e.getMessage() + ")");
}
return destSock;
}
}

View File

@@ -27,27 +27,26 @@ public class SOCKSServerFactory {
* @param s a Socket used to choose the SOCKS server type
*/
public static SOCKSServer createSOCKSServer(Socket s) throws SOCKSException {
SOCKSServer serv;
SOCKSServer serv;
try {
DataInputStream in = new DataInputStream(s.getInputStream());
int socksVer = in.readByte();
switch (socksVer) {
case 0x05: // SOCKS version 5
serv = new SOCKS5Server(s);
break;
default:
_log.debug("SOCKS protocol version not supported ("
+ Integer.toHexString(socksVer) + ")");
return null;
}
} catch (IOException e) {
_log.debug("error reading SOCKS protocol version");
throw new SOCKSException("Connection error ("
+ e.getMessage() + ")");
}
try {
DataInputStream in = new DataInputStream(s.getInputStream());
int socksVer = in.readByte();
return serv;
switch (socksVer) {
case 0x05:
// SOCKS version 5
serv = new SOCKS5Server(s);
break;
default:
_log.debug("SOCKS protocol version not supported (" + Integer.toHexString(socksVer) + ")");
return null;
}
} catch (IOException e) {
_log.debug("error reading SOCKS protocol version");
throw new SOCKSException("Connection error (" + e.getMessage() + ")");
}
return serv;
}
}
}

View File

@@ -0,0 +1,590 @@
The code for the GUI applications netviewer and the
heartbeat GUI have been released into the public domain,
but they make use of the LGPL JFreeChart library (which
in turn depends upon the APL log4j library). These
external components, contained within the files:
lib/jfreechart-0.9.17.jar
lib/jcommon-0.9.2.jar
lib/log4j-1.2.8.jar
were retrieved and built from the source at
http://www.jfree.org/jfreechart/jfreechart-0.9.17.zip
As a whole, the netviewer and heartbeat GUI applications
therefore must state:
This product includes software developed by the
Apache Software Foundation (http://www.apache.org/).
The LGPL just makes us state prominently that we use LGPL'ed
code (the JFreeChart code), and since we make no modifications
to it, section 6.b of the LGPL seems to apply.
The relevent licenses are shown below.
*****************************************************************
For the jfreechart-0.9.17.jar and jcommon-0.9.2.jar, the
LGPL is relevent:
*****************************************************************
GNU LESSER GENERAL PUBLIC LICENSE
Version 2.1, February 1999
Copyright (C) 1991, 1999 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.
[This is the first released version of the Lesser GPL. It also counts
as the successor of the GNU Library Public License, version 2, hence
the version number 2.1.]
Preamble
The licenses for most software are designed to take away your
freedom to share and change it. By contrast, the GNU General Public
Licenses are intended to guarantee your freedom to share and change
free software--to make sure the software is free for all its users.
This license, the Lesser General Public License, applies to some
specially designated software packages--typically libraries--of the
Free Software Foundation and other authors who decide to use it. You
can use it too, but we suggest you first think carefully about whether
this license or the ordinary General Public License is the better
strategy to use in any particular case, based on the explanations below.
When we speak of free software, we are referring to freedom of use,
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 and use pieces of
it in new free programs; and that you are informed that you can do
these things.
To protect your rights, we need to make restrictions that forbid
distributors to deny you these rights or to ask you to surrender these
rights. These restrictions translate to certain responsibilities for
you if you distribute copies of the library or if you modify it.
For example, if you distribute copies of the library, whether gratis
or for a fee, you must give the recipients all the rights that we gave
you. You must make sure that they, too, receive or can get the source
code. If you link other code with the library, you must provide
complete object files to the recipients, so that they can relink them
with the library after making changes to the library and recompiling
it. And you must show them these terms so they know their rights.
We protect your rights with a two-step method: (1) we copyright the
library, and (2) we offer you this license, which gives you legal
permission to copy, distribute and/or modify the library.
To protect each distributor, we want to make it very clear that
there is no warranty for the free library. Also, if the library is
modified by someone else and passed on, the recipients should know
that what they have is not the original version, so that the original
author's reputation will not be affected by problems that might be
introduced by others.
Finally, software patents pose a constant threat to the existence of
any free program. We wish to make sure that a company cannot
effectively restrict the users of a free program by obtaining a
restrictive license from a patent holder. Therefore, we insist that
any patent license obtained for a version of the library must be
consistent with the full freedom of use specified in this license.
Most GNU software, including some libraries, is covered by the
ordinary GNU General Public License. This license, the GNU Lesser
General Public License, applies to certain designated libraries, and
is quite different from the ordinary General Public License. We use
this license for certain libraries in order to permit linking those
libraries into non-free programs.
When a program is linked with a library, whether statically or using
a shared library, the combination of the two is legally speaking a
combined work, a derivative of the original library. The ordinary
General Public License therefore permits such linking only if the
entire combination fits its criteria of freedom. The Lesser General
Public License permits more lax criteria for linking other code with
the library.
We call this license the "Lesser" General Public License because it
does Less to protect the user's freedom than the ordinary General
Public License. It also provides other free software developers Less
of an advantage over competing non-free programs. These disadvantages
are the reason we use the ordinary General Public License for many
libraries. However, the Lesser license provides advantages in certain
special circumstances.
For example, on rare occasions, there may be a special need to
encourage the widest possible use of a certain library, so that it becomes
a de-facto standard. To achieve this, non-free programs must be
allowed to use the library. A more frequent case is that a free
library does the same job as widely used non-free libraries. In this
case, there is little to gain by limiting the free library to free
software only, so we use the Lesser General Public License.
In other cases, permission to use a particular library in non-free
programs enables a greater number of people to use a large body of
free software. For example, permission to use the GNU C Library in
non-free programs enables many more people to use the whole GNU
operating system, as well as its variant, the GNU/Linux operating
system.
Although the Lesser General Public License is Less protective of the
users' freedom, it does ensure that the user of a program that is
linked with the Library has the freedom and the wherewithal to run
that program using a modified version of the Library.
The precise terms and conditions for copying, distribution and
modification follow. Pay close attention to the difference between a
"work based on the library" and a "work that uses the library". The
former contains code derived from the library, whereas the latter must
be combined with the library in order to run.
GNU LESSER GENERAL PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. This License Agreement applies to any software library or other
program which contains a notice placed by the copyright holder or
other authorized party saying it may be distributed under the terms of
this Lesser General Public License (also called "this License").
Each licensee is addressed as "you".
A "library" means a collection of software functions and/or data
prepared so as to be conveniently linked with application programs
(which use some of those functions and data) to form executables.
The "Library", below, refers to any such software library or work
which has been distributed under these terms. A "work based on the
Library" means either the Library or any derivative work under
copyright law: that is to say, a work containing the Library or a
portion of it, either verbatim or with modifications and/or translated
straightforwardly into another language. (Hereinafter, translation is
included without limitation in the term "modification".)
"Source code" for a work means the preferred form of the work for
making modifications to it. For a library, 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 library.
Activities other than copying, distribution and modification are not
covered by this License; they are outside its scope. The act of
running a program using the Library is not restricted, and output from
such a program is covered only if its contents constitute a work based
on the Library (independent of the use of the Library in a tool for
writing it). Whether that is true depends on what the Library does
and what the program that uses the Library does.
1. You may copy and distribute verbatim copies of the Library's
complete 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 distribute a copy of this License along with the
Library.
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 Library or any portion
of it, thus forming a work based on the Library, 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) The modified work must itself be a software library.
b) You must cause the files modified to carry prominent notices
stating that you changed the files and the date of any change.
c) You must cause the whole of the work to be licensed at no
charge to all third parties under the terms of this License.
d) If a facility in the modified Library refers to a function or a
table of data to be supplied by an application program that uses
the facility, other than as an argument passed when the facility
is invoked, then you must make a good faith effort to ensure that,
in the event an application does not supply such function or
table, the facility still operates, and performs whatever part of
its purpose remains meaningful.
(For example, a function in a library to compute square roots has
a purpose that is entirely well-defined independent of the
application. Therefore, Subsection 2d requires that any
application-supplied function or table used by this function must
be optional: if the application does not supply it, the square
root function must still compute square roots.)
These requirements apply to the modified work as a whole. If
identifiable sections of that work are not derived from the Library,
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 Library, 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 Library.
In addition, mere aggregation of another work not based on the Library
with the Library (or with a work based on the Library) on a volume of
a storage or distribution medium does not bring the other work under
the scope of this License.
3. You may opt to apply the terms of the ordinary GNU General Public
License instead of this License to a given copy of the Library. To do
this, you must alter all the notices that refer to this License, so
that they refer to the ordinary GNU General Public License, version 2,
instead of to this License. (If a newer version than version 2 of the
ordinary GNU General Public License has appeared, then you can specify
that version instead if you wish.) Do not make any other change in
these notices.
Once this change is made in a given copy, it is irreversible for
that copy, so the ordinary GNU General Public License applies to all
subsequent copies and derivative works made from that copy.
This option is useful when you wish to copy part of the code of
the Library into a program that is not a library.
4. You may copy and distribute the Library (or a portion or
derivative of it, under Section 2) in object code or executable form
under the terms of Sections 1 and 2 above provided that you 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.
If distribution of 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 satisfies the requirement to
distribute the source code, even though third parties are not
compelled to copy the source along with the object code.
5. A program that contains no derivative of any portion of the
Library, but is designed to work with the Library by being compiled or
linked with it, is called a "work that uses the Library". Such a
work, in isolation, is not a derivative work of the Library, and
therefore falls outside the scope of this License.
However, linking a "work that uses the Library" with the Library
creates an executable that is a derivative of the Library (because it
contains portions of the Library), rather than a "work that uses the
library". The executable is therefore covered by this License.
Section 6 states terms for distribution of such executables.
When a "work that uses the Library" uses material from a header file
that is part of the Library, the object code for the work may be a
derivative work of the Library even though the source code is not.
Whether this is true is especially significant if the work can be
linked without the Library, or if the work is itself a library. The
threshold for this to be true is not precisely defined by law.
If such an object file uses only numerical parameters, data
structure layouts and accessors, and small macros and small inline
functions (ten lines or less in length), then the use of the object
file is unrestricted, regardless of whether it is legally a derivative
work. (Executables containing this object code plus portions of the
Library will still fall under Section 6.)
Otherwise, if the work is a derivative of the Library, you may
distribute the object code for the work under the terms of Section 6.
Any executables containing that work also fall under Section 6,
whether or not they are linked directly with the Library itself.
6. As an exception to the Sections above, you may also combine or
link a "work that uses the Library" with the Library to produce a
work containing portions of the Library, and distribute that work
under terms of your choice, provided that the terms permit
modification of the work for the customer's own use and reverse
engineering for debugging such modifications.
You must give prominent notice with each copy of the work that the
Library is used in it and that the Library and its use are covered by
this License. You must supply a copy of this License. If the work
during execution displays copyright notices, you must include the
copyright notice for the Library among them, as well as a reference
directing the user to the copy of this License. Also, you must do one
of these things:
a) Accompany the work with the complete corresponding
machine-readable source code for the Library including whatever
changes were used in the work (which must be distributed under
Sections 1 and 2 above); and, if the work is an executable linked
with the Library, with the complete machine-readable "work that
uses the Library", as object code and/or source code, so that the
user can modify the Library and then relink to produce a modified
executable containing the modified Library. (It is understood
that the user who changes the contents of definitions files in the
Library will not necessarily be able to recompile the application
to use the modified definitions.)
b) Use a suitable shared library mechanism for linking with the
Library. A suitable mechanism is one that (1) uses at run time a
copy of the library already present on the user's computer system,
rather than copying library functions into the executable, and (2)
will operate properly with a modified version of the library, if
the user installs one, as long as the modified version is
interface-compatible with the version that the work was made with.
c) Accompany the work with a written offer, valid for at
least three years, to give the same user the materials
specified in Subsection 6a, above, for a charge no more
than the cost of performing this distribution.
d) If distribution of the work is made by offering access to copy
from a designated place, offer equivalent access to copy the above
specified materials from the same place.
e) Verify that the user has already received a copy of these
materials or that you have already sent this user a copy.
For an executable, the required form of the "work that uses the
Library" must include any data and utility programs needed for
reproducing the executable from it. However, as a special exception,
the materials to be 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.
It may happen that this requirement contradicts the license
restrictions of other proprietary libraries that do not normally
accompany the operating system. Such a contradiction means you cannot
use both them and the Library together in an executable that you
distribute.
7. You may place library facilities that are a work based on the
Library side-by-side in a single library together with other library
facilities not covered by this License, and distribute such a combined
library, provided that the separate distribution of the work based on
the Library and of the other library facilities is otherwise
permitted, and provided that you do these two things:
a) Accompany the combined library with a copy of the same work
based on the Library, uncombined with any other library
facilities. This must be distributed under the terms of the
Sections above.
b) Give prominent notice with the combined library of the fact
that part of it is a work based on the Library, and explaining
where to find the accompanying uncombined form of the same work.
8. You may not copy, modify, sublicense, link with, or distribute
the Library except as expressly provided under this License. Any
attempt otherwise to copy, modify, sublicense, link with, or
distribute the Library 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.
9. 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 Library or its derivative works. These actions are
prohibited by law if you do not accept this License. Therefore, by
modifying or distributing the Library (or any work based on the
Library), you indicate your acceptance of this License to do so, and
all its terms and conditions for copying, distributing or modifying
the Library or works based on it.
10. Each time you redistribute the Library (or any work based on the
Library), the recipient automatically receives a license from the
original licensor to copy, distribute, link with or modify the Library
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 with
this License.
11. 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 Library at all. For example, if a patent
license would not permit royalty-free redistribution of the Library 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 Library.
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.
12. If the distribution and/or use of the Library is restricted in
certain countries either by patents or by copyrighted interfaces, the
original copyright holder who places the Library 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.
13. The Free Software Foundation may publish revised and/or new
versions of the Lesser 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 Library
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 Library does not specify a
license version number, you may choose any version ever published by
the Free Software Foundation.
14. If you wish to incorporate parts of the Library into other free
programs whose distribution conditions are incompatible with these,
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
15. BECAUSE THE LIBRARY IS LICENSED FREE OF CHARGE, THERE IS NO
WARRANTY FOR THE LIBRARY, TO THE EXTENT PERMITTED BY APPLICABLE LAW.
EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR
OTHER PARTIES PROVIDE THE LIBRARY "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
LIBRARY IS WITH YOU. SHOULD THE LIBRARY PROVE DEFECTIVE, YOU ASSUME
THE COST OF ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
16. 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 LIBRARY 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
LIBRARY (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 LIBRARY TO OPERATE WITH ANY OTHER SOFTWARE), 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 Libraries
If you develop a new library, and you want it to be of the greatest
possible use to the public, we recommend making it free software that
everyone can redistribute and change. You can do so by permitting
redistribution under these terms (or, alternatively, under the terms of the
ordinary General Public License).
To apply these terms, attach the following notices to the library. 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 library's name and a brief idea of what it does.>
Copyright (C) <year> <name of author>
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; 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.
You should also get your employer (if you work as a programmer) or your
school, if any, to sign a "copyright disclaimer" for the library, if
necessary. Here is a sample; alter the names:
Yoyodyne, Inc., hereby disclaims all copyright interest in the
library `Frob' (a library for tweaking knobs) written by James Random Hacker.
<signature of Ty Coon>, 1 April 1990
Ty Coon, President of Vice
That's all there is to it!
*****************************************************************
For the file log4j-1.2.8.jar, the APL is relevent:
*****************************************************************
/* ====================================================================
*
* The Apache Software License, Version 1.1
*
* Copyright (c) 2003 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution, if
* any, must include the following acknowlegement:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowlegement may appear in the software itself,
* if and wherever such third-party acknowlegements normally appear.
*
* 4. The names "The Apache Logging Services Project", "log4j", and "Apache Software
* Foundation" must not be used to endorse or promote products derived
* from this software without prior written permission. For written
* permission, please contact apache@apache.org.
*
* 5. Products derived from this software may not be called "Apache"
* nor may "Apache" appear in their names without prior written
* permission of the Apache Group.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
* OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
* DISCLAIMED. IN NO EVENT SHALL THE APACHE SOFTWARE FOUNDATION OR
* ITS CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF
* USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
* ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT
* OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF
* SUCH DAMAGE.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
* [Additional notices, if required by prior licensing conditions]
*
*/

29
apps/jfreechart/build.xml Normal file
View File

@@ -0,0 +1,29 @@
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="all" name="jfreechart">
<target name="all">
<echo message="The code in the JFreeChart software contains LGPL and APL licensed software," />
<echo message="and is not necessary for using I2P. However, there is a seperate GUI for the " />
<echo message="heartbeat and netmonitor applications that uses this, so the retrieval of that " />
<echo message="code from the JFreeChart distribution is being made available (though we make no" />
<echo message="modifications to the code used here whatsoever - it is simply used by the public domain GUIs. " />
<echo message="If you would like to fetch the code, run the ant task 'fetchJfreechart'" />
<echo message="If you would like to build the code, run the ant task 'build'" />
<echo message="If you would like to delete the code, run the ant task 'clean'" />
</target>
<target name="build">
<ant dir="./jfreechart-0.9.17/" antfile="ant/build.xml" target="compile" />
</target>
<target name="fetchJfreechart">
<mkdir dir="./lib" />
<get src="http://www.jfree.org/jfreechart/jfreechart-0.9.17.zip" verbose="true" dest="jfreechart-0.9.17.zip" />
<unzip src="jfreechart-0.9.17.zip" dest="." />
</target>
<target name="builddep" />
<target name="compile" />
<target name="jar" />
<target name="clean">
<delete dir="./jfreechart-0.9.17/" />
</target>
<target name="cleandep" depends="clean" />
<target name="distclean" depends="clean" />
</project>

View File

@@ -1,5 +1,5 @@
ministreaming protocol:
*******************
ministreaming protocol
**********************
Each message looks like the following
@@ -15,9 +15,11 @@ These IDs may be any 3-byte values except 00 00 00, which is reserved.
All connections are created as PROP_RELIABILITY_GUARANTEED.
"actions" are the things a proper tunnel implementation SHOULD do
when it receives such a message.
"actions" are the things a proper ministreaming implementation SHOULD
do when it receives such a message.
A "ministreaming connection" is a connection where the user of the
library can send data into or receive from.
Client->Server:
===============
@@ -25,13 +27,13 @@ Client->Server:
0xA0 Send data
id: the server id
payload: the data to send
actions: send the data to the TCP connection
actions: send the data to the ministreaming connection
0xA1 SYN
id: the client id
payload: the public key dynamically created by the client
actions: create a server ID and create a TCP connection. When successful,
send an ACK back, otherwise a close.
actions: create a server ID and create a ministreaming connection. When
successful, send an ACK back, otherwise a close.
0xA2 Close
id: the server id
@@ -44,7 +46,7 @@ Server->Client
0x50 Send data
id: the client id
payload: the data to send
actions: send the data to the TCP connection
actions: send the data to the ministreaming connection
0x51 ACK
id: the client id
@@ -60,7 +62,7 @@ Server->Client
Sample conversations:
=====================
a) Service not available (e.g. the server on the TCP port is not running)
a) Service not available (e.g. the server is not accepting connections)
C->S A1 12 34 56 key... (SYN, client ID = 12 34 56)
S->C 52 12 34 56 (Close)

View File

@@ -6,154 +6,152 @@ public class ByteCollector {
int size;
public ByteCollector() {
contents=new byte[80];
size=0;
contents = new byte[80];
size = 0;
}
public ByteCollector(byte[] b) {
this();
append(b);
this();
append(b);
}
public ByteCollector(byte b) {
this();
append(b);
this();
append(b);
}
public ByteCollector append (byte b) {
ensureCapacity(size+1);
contents[size++]=b;
return this;
public ByteCollector append(byte b) {
ensureCapacity(size + 1);
contents[size++] = b;
return this;
}
public ByteCollector append (byte[] b) {
ensureCapacity(size+b.length);
System.arraycopy(b,0,contents,size,b.length);
size+=b.length;
return this;
public ByteCollector append(byte[] b) {
ensureCapacity(size + b.length);
System.arraycopy(b, 0, contents, size, b.length);
size += b.length;
return this;
}
public ByteCollector append(byte[] b, int len) {
return append(b,0,len);
return append(b, 0, len);
}
public ByteCollector append(byte[] b, int off, int len) {
ensureCapacity(size+len);
System.arraycopy(b,off,contents,size,len);
size+=len;
return this;
ensureCapacity(size + len);
System.arraycopy(b, off, contents, size, len);
size += len;
return this;
}
public ByteCollector append(ByteCollector bc) {
// optimieren?
return append(bc.toByteArray());
// optimieren?
return append(bc.toByteArray());
}
public byte[] toByteArray() {
byte[] result=new byte[size];
System.arraycopy(contents,0,result,0,size);
return result;
byte[] result = new byte[size];
System.arraycopy(contents, 0, result, 0, size);
return result;
}
public byte[] startToByteArray(int maxlen) {
if (size < maxlen) {
byte[] res = toByteArray();
clear();
return res;
} else {
byte[] result = new byte[maxlen];
System.arraycopy(contents,0,result,0,maxlen);
System.arraycopy(contents,maxlen,contents,0,size-maxlen);
size-=maxlen;
return result;
}
if (size < maxlen) {
byte[] res = toByteArray();
clear();
return res;
} else {
byte[] result = new byte[maxlen];
System.arraycopy(contents, 0, result, 0, maxlen);
System.arraycopy(contents, maxlen, contents, 0, size - maxlen);
size -= maxlen;
return result;
}
}
public int getCurrentSize() {
return size;
public int getCurrentSize() {
return size;
}
public boolean ensureCapacity(int cap) {
if (contents.length<cap) {
int l=contents.length;
while (l<cap) {
l=(l*3)/2+1;
}
byte[] newcont=new byte[l];
System.arraycopy(contents,0,newcont,0,size);
contents=newcont;
return true;
}
return false;
if (contents.length < cap) {
int l = contents.length;
while (l < cap) {
l = (l * 3) / 2 + 1;
}
byte[] newcont = new byte[l];
System.arraycopy(contents, 0, newcont, 0, size);
contents = newcont;
return true;
}
return false;
}
public boolean isEmpty() {
return size==0;
return size == 0;
}
public int indexOf(ByteCollector bc) {
// optimieren?
return indexOf(bc.toByteArray());
// optimieren?
return indexOf(bc.toByteArray());
}
public int indexOf(byte b) {
// optimieren?
return indexOf(new byte[] {b});
// optimieren?
return indexOf(new byte[] { b});
}
public int indexOf(byte[] ba) {
loop:
for (int i=0;i<size-ba.length+1;i++) {
for (int j=0;j<ba.length;j++) {
if (contents[i+j]!=ba[j]) continue loop;
}
return i;
}
return -1;
loop: for (int i = 0; i < size - ba.length + 1; i++) {
for (int j = 0; j < ba.length; j++) {
if (contents[i + j] != ba[j]) continue loop;
}
return i;
}
return -1;
}
public void clear() {
size=0;
size = 0;
}
public void clearAndShorten() {
size=0;
contents=new byte[80];
size = 0;
contents = new byte[80];
}
public String toString() {
return new String(toByteArray());
return new String(toByteArray());
}
public int hashCode() {
int h =0;
for (int i=0;i<size;i++) {
h+=contents[i]*contents[i];
}
return h;
int h = 0;
for (int i = 0; i < size; i++) {
h += contents[i] * contents[i];
}
return h;
}
public boolean equals(Object o) {
if (o instanceof ByteCollector) {
ByteCollector by=(ByteCollector)o;
if (size!=by.size) return false;
for (int i=0;i<size;i++) {
if (contents[i]!=by.contents[i]) return false;
}
return true;
} else {
return false;
}
if (o instanceof ByteCollector) {
ByteCollector by = (ByteCollector) o;
if (size != by.size) return false;
for (int i = 0; i < size; i++) {
if (contents[i] != by.contents[i]) return false;
}
return true;
} else {
return false;
}
}
public byte removeFirst() {
byte bb=contents[0];
if (size==0)
throw new IllegalArgumentException("ByteCollector is empty");
if(size>1)
System.arraycopy(contents,1,contents,0,--size);
else
size=0;
return bb;
byte bb = contents[0];
if (size == 0) throw new IllegalArgumentException("ByteCollector is empty");
if (size > 1)
System.arraycopy(contents, 1, contents, 0, --size);
else
size = 0;
return bb;
}
}
}

View File

@@ -1,5 +1,7 @@
package net.i2p.client.streaming;
import java.net.ConnectException;
import net.i2p.I2PException;
/**
@@ -11,16 +13,19 @@ public interface I2PServerSocket {
* Closes the socket.
*/
public void close() throws I2PException;
/**
* Waits for the next socket connecting. If a remote user tried to make a
* connection and the local application wasn't .accept()ing new connections,
* they should get refused (if .accept() doesnt occur in some small period)
*
* @return a connected I2PSocket
*
* @throws I2PException if there is a problem with reading a new socket
* from the data available (aka the I2PSession closed, etc)
* @throws ConnectException if the I2PServerSocket is closed
*/
public I2PSocket accept() throws I2PException;
public I2PSocket accept() throws I2PException, ConnectException;
/**
* Access the manager which is coordinating the server socket

View File

@@ -1,50 +1,151 @@
package net.i2p.client.streaming;
import java.net.ConnectException;
import net.i2p.I2PException;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import net.i2p.I2PAppContext;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
/**
* Initial stub implementation for the server socket
* Server socket implementation, allowing multiple threads to accept I2PSockets
* and pull from a queue populated by various threads (each of whom have their own
* timeout)
*
*/
class I2PServerSocketImpl implements I2PServerSocket {
private final static Log _log = new Log(I2PServerSocketImpl.class);
private I2PSocketManager mgr;
private I2PSocket cached=null; // buffer one socket here
/** list of sockets waiting for the client to accept them */
private List pendingSockets = Collections.synchronizedList(new ArrayList(4));
/** have we been closed */
private volatile boolean closing = false;
/** lock on this when accepting a pending socket, and wait on it for notification of acceptance */
private Object socketAcceptedLock = new Object();
/** lock on this when adding a new socket to the pending list, and wait on it accordingly */
private Object socketAddedLock = new Object();
public I2PServerSocketImpl(I2PSocketManager mgr) {
this.mgr = mgr;
this.mgr = mgr;
}
public synchronized I2PSocket accept() throws I2PException {
while(cached == null) {
myWait();
}
I2PSocket ret=cached;
cached=null;
notifyAll();
_log.debug("TIMING: handed out accept result "+ret.hashCode());
return ret;
/**
* Waits for the next socket connecting. If a remote user tried to make a
* connection and the local application wasn't .accept()ing new connections,
* they should get refused (if .accept() doesnt occur in some small period -
* currently 5 seconds)
*
* @return a connected I2PSocket
*
* @throws I2PException if there is a problem with reading a new socket
* from the data available (aka the I2PSession closed, etc)
* @throws ConnectException if the I2PServerSocket is closed
*/
public I2PSocket accept() throws I2PException, ConnectException {
if (_log.shouldLog(Log.DEBUG))
_log.debug("accept() called, pending: " + pendingSockets.size());
I2PSocket ret = null;
while ( (ret == null) && (!closing) ){
while (pendingSockets.size() <= 0) {
if (closing) throw new ConnectException("I2PServerSocket closed");
try {
synchronized(socketAddedLock) {
socketAddedLock.wait();
}
} catch (InterruptedException ie) {}
}
synchronized (pendingSockets) {
if (pendingSockets.size() > 0) {
ret = (I2PSocket)pendingSockets.remove(0);
}
}
if (ret != null) {
synchronized (socketAcceptedLock) {
socketAcceptedLock.notifyAll();
}
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("TIMING: handed out accept result " + ret.hashCode());
return ret;
}
public synchronized boolean getNewSocket(I2PSocket s){
while(cached != null) {
myWait();
}
cached=s;
notifyAll();
return true;
/**
* Make the socket available and wait until the client app accepts it, or until
* the given timeout elapses. This doesn't have any limits on the queue size -
* perhaps it should add some choking (e.g. after 5 waiting for accept, refuse)
*
* @param timeoutMs how long to wait until accept
* @return true if the socket was accepted, false if the timeout expired
* or the socket was closed
*/
public boolean addWaitForAccept(I2PSocket s, long timeoutMs) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("addWaitForAccept [new socket arrived, pending: " + pendingSockets.size());
if (closing) {
if (_log.shouldLog(Log.WARN))
_log.warn("Already closing the socket");
return false;
}
Clock clock = I2PAppContext.getGlobalContext().clock();
long start = clock.now();
long end = start + timeoutMs;
pendingSockets.add(s);
synchronized (socketAddedLock) {
socketAddedLock.notifyAll();
}
// keep looping until the socket has been grabbed by the accept()
// (or the expiration passes, or the socket is closed)
while (pendingSockets.contains(s)) {
long now = clock.now();
if (now >= end) {
if (_log.shouldLog(Log.INFO))
_log.info("Expired while waiting for accept (time elapsed =" + (now - start) + "ms");
pendingSockets.remove(s);
return false;
}
if (closing) {
if (_log.shouldLog(Log.WARN))
_log.warn("Server socket closed while waiting for accept");
pendingSockets.remove(s);
return false;
}
long remaining = end - now;
try {
synchronized (socketAcceptedLock) {
socketAcceptedLock.wait(remaining);
}
} catch (InterruptedException ie) {}
}
long now = clock.now();
if (_log.shouldLog(Log.DEBUG))
_log.info("Socket accepted after " + (now-start) + "ms");
return true;
}
public void close() throws I2PException {
//noop
public void close() {
closing = true;
// let anyone .accept()ing know to fsck off
synchronized (socketAddedLock) {
socketAddedLock.notifyAll();
}
// let anyone addWaitForAccept()ing know to fsck off
synchronized (socketAcceptedLock) {
socketAcceptedLock.notifyAll();
}
}
private void myWait() {
try{
wait();
} catch (InterruptedException ex) {}
}
public I2PSocketManager getManager() { return mgr; }
}

View File

@@ -1,10 +1,10 @@
package net.i2p.client.streaming;
import net.i2p.data.Destination;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.io.IOException;
import net.i2p.data.Destination;
/**
* Minimalistic adapter between the socket api and I2PTunnel's way.
@@ -32,6 +32,20 @@ public interface I2PSocket {
*/
public OutputStream getOutputStream() throws IOException;
/**
* How long we will wait blocked on a read() operation.
*
* @return milliseconds to wait, or -1 if we will wait indefinitely
*/
public long getReadTimeout();
/**
* Define how long we will wait blocked on a read() operation (-1 will make
* the socket wait forever).
*
*/
public void setReadTimeout(long ms);
/**
* Closes the socket if not closed yet
*/

View File

@@ -8,6 +8,7 @@ import java.io.OutputStream;
import net.i2p.I2PException;
import net.i2p.client.I2PSessionException;
import net.i2p.data.Destination;
import net.i2p.util.I2PThread;
import net.i2p.util.Log;
/**
@@ -17,9 +18,9 @@ import net.i2p.util.Log;
class I2PSocketImpl implements I2PSocket {
private final static Log _log = new Log(I2PSocketImpl.class);
public static final int MAX_PACKET_SIZE = 1024*32;
public static final int PACKET_DELAY=100;
public static final int MAX_PACKET_SIZE = 1024 * 32;
public static final int PACKET_DELAY = 100;
private I2PSocketManager manager;
private Destination local;
private Destination remote;
@@ -30,306 +31,436 @@ class I2PSocketImpl implements I2PSocket {
private I2POutputStream out;
private boolean outgoing;
private Object flagLock = new Object();
private boolean closed = false, sendClose=true, closed2=false;
public I2PSocketImpl(Destination peer, I2PSocketManager mgr,
boolean outgoing, String localID) {
this.outgoing=outgoing;
manager = mgr;
remote = peer;
local = mgr.getSession().getMyDestination();
in = new I2PInputStream();
I2PInputStream pin = new I2PInputStream();
out = new I2POutputStream(pin);
new I2PSocketRunner(pin);
this.localID = localID;
/**
* Whether the I2P socket has already been closed.
*/
private boolean closed = false;
/**
* Whether to send out a close packet when the socket is
* closed. (If the socket is closed because of an incoming close
* packet, we need not send one.)
*/
private boolean sendClose = true;
/**
* Whether the I2P socket has already been closed and all data
* (from I2P to the app, dunno whether to call this incoming or
* outgoing) has been processed.
*/
private boolean closed2 = false;
/**
* @param peer who this socket is (or should be) connected to
* @param mgr how we talk to the network
* @param outgoing did we initiate the connection (true) or did we receive it (false)?
* @param localID what is our half of the socket ID?
*/
public I2PSocketImpl(Destination peer, I2PSocketManager mgr, boolean outgoing, String localID) {
this.outgoing = outgoing;
manager = mgr;
remote = peer;
local = mgr.getSession().getMyDestination();
in = new I2PInputStream();
I2PInputStream pin = new I2PInputStream();
out = new I2POutputStream(pin);
new I2PSocketRunner(pin);
this.localID = localID;
}
/**
* Our half of the socket's unique ID
*
*/
public String getLocalID() {
return localID;
return localID;
}
/**
* We've received the other side's half of the socket's unique ID
*/
public void setRemoteID(String id) {
synchronized(remoteIDWaiter) {
remoteID=id;
remoteIDWaiter.notifyAll();
}
synchronized (remoteIDWaiter) {
remoteID = id;
remoteIDWaiter.notifyAll();
}
}
public String getRemoteID(boolean wait) throws InterruptedIOException {
return getRemoteID(wait, -1);
/**
* Retrieve the other side's half of the socket's unique ID, or null if it
* isn't known yet
*
* @param wait if true, we should wait until we receive it from the peer, otherwise
* return what we know immediately (which may be null)
*/
public String getRemoteID(boolean wait) {
try {
return getRemoteID(wait, -1);
} catch (InterruptedIOException iie) {
_log.error("wtf, we said we didn't want it to time out! you smell", iie);
return null;
}
}
/**
* Retrieve the other side's half of the socket's unique ID, or null if it isn't
* known yet and we were instructed not to wait
*
* @param wait should we wait for the peer to send us their half of the ID, or
* just return immediately?
* @param maxWait if we're going to wait, after how long should we timeout and fail?
* (if this value is < 0, we wait indefinitely)
* @throws InterruptedIOException when the max waiting period has been exceeded
*/
public String getRemoteID(boolean wait, long maxWait) throws InterruptedIOException {
long dieAfter = System.currentTimeMillis() + maxWait;
synchronized(remoteIDWaiter) {
while (wait && remoteID==null) {
try {
if (maxWait > 0)
remoteIDWaiter.wait(maxWait);
else
remoteIDWaiter.wait();
} catch (InterruptedException ex) {}
if ( (maxWait > 0) && (System.currentTimeMillis() > dieAfter) )
throw new InterruptedIOException("Timed out waiting for remote ID");
}
if (wait) {
_log.debug("TIMING: RemoteID set to " + I2PSocketManager.getReadableForm(remoteID) +" for "+this.hashCode());
}
return remoteID;
}
long dieAfter = System.currentTimeMillis() + maxWait;
synchronized (remoteIDWaiter) {
if (wait) {
try {
if (maxWait >= 0)
remoteIDWaiter.wait(maxWait);
else
remoteIDWaiter.wait();
} catch (InterruptedException ex) {
}
if ((maxWait >= 0) && (System.currentTimeMillis() >= dieAfter))
throw new InterruptedIOException("Timed out waiting for remote ID");
if (_log.shouldLog(Log.DEBUG))
_log.debug("TIMING: RemoteID set to "
+ I2PSocketManager.getReadableForm(remoteID) + " for "
+ this.hashCode());
}
return remoteID;
}
}
public String getRemoteID() throws InterruptedIOException {
return getRemoteID(false);
/**
* Retrieve the other side's half of the socket's unique ID, or null if it
* isn't known yet. This does not wait
*
*/
public String getRemoteID() {
return getRemoteID(false);
}
/**
* The other side has given us some data, so inject it into our socket's
* inputStream
*
* @param data the data to inject into our local inputStream
*/
public void queueData(byte[] data) {
in.queueData(data);
in.queueData(data);
}
/**
* Return the Destination of this side of the socket.
*/
public Destination getThisDestination() { return local; }
public Destination getThisDestination() {
return local;
}
/**
* Return the destination of the peer.
*/
public Destination getPeerDestination() { return remote; }
public Destination getPeerDestination() {
return remote;
}
/**
* Return an InputStream to read from the socket.
*/
public InputStream getInputStream() throws IOException {
if ( (in == null) )
throw new IOException("Not connected");
return in;
public InputStream getInputStream() throws IOException {
if ((in == null)) throw new IOException("Not connected");
return in;
}
/**
* Return an OutputStream to write into the socket.
*/
public OutputStream getOutputStream() throws IOException {
if ( (out == null) )
throw new IOException("Not connected");
return out;
if ((out == null)) throw new IOException("Not connected");
return out;
}
/**
* Closes the socket if not closed yet
* Closes the socket if not closed yet (from the Application
* side).
*/
public void close() throws IOException {
synchronized(flagLock) {
_log.debug("Closing connection");
closed=true;
}
out.close();
in.notifyClosed();
synchronized (flagLock) {
_log.debug("Closing connection");
closed = true;
}
out.close();
in.notifyClosed();
}
public void internalClose() {
synchronized(flagLock) {
closed=true;
closed2=true;
sendClose=false;
}
out.close();
in.notifyClosed();
/**
* Close the socket from the I2P side, e. g. by a close packet.
*/
protected void internalClose() {
synchronized (flagLock) {
closed = true;
closed2 = true;
sendClose = false;
}
out.close();
in.notifyClosed();
}
private byte getMask(int add) {
return (byte)((outgoing?(byte)0xA0:(byte)0x50)+(byte)add);
if (outgoing)
return (byte)(I2PSocketManager.DATA_IN + (byte)add);
else
return (byte)(I2PSocketManager.DATA_OUT + (byte)add);
}
/**
* What is the longest we'll block on the input stream while waiting
* for more data? If this value is exceeded, the read() throws
* InterruptedIOException
*/
public long getReadTimeout() {
return in.getReadTimeout();
}
public void setReadTimeout(long ms) {
in.setReadTimeout(ms);
}
//--------------------------------------------------
public class I2PInputStream extends InputStream {
private class I2PInputStream extends InputStream {
private ByteCollector bc = new ByteCollector();
private ByteCollector bc = new ByteCollector();
public int read() throws IOException {
byte[] b = new byte[1];
int res = read(b);
if (res == 1) return b[0] & 0xff;
if (res == -1) return -1;
throw new RuntimeException("Incorrect read() result");
}
private long readTimeout = -1;
public synchronized int read(byte[] b, int off, int len) throws IOException {
_log.debug("Read called: "+this.hashCode());
if (len==0) return 0;
byte[] read = bc.startToByteArray(len);
while (read.length==0) {
synchronized(flagLock) {
if (closed){
_log.debug("Closed is set, so closing stream: "+this.hashCode());
return -1;
}
}
try {
wait();
} catch (InterruptedException ex) {}
read = bc.startToByteArray(len);
}
if (read.length>len) throw new RuntimeException("BUG");
System.arraycopy(read,0,b,off,read.length);
public long getReadTimeout() {
return readTimeout;
}
public void setReadTimeout(long ms) {
readTimeout = ms;
}
public int read() throws IOException {
byte[] b = new byte[1];
int res = read(b);
if (res == 1) return b[0] & 0xff;
if (res == -1) return -1;
throw new RuntimeException("Incorrect read() result");
}
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Read from I2PInputStream " + this.hashCode()
+ " returned "+read.length+" bytes");
}
//if (_log.shouldLog(Log.DEBUG)) {
// _log.debug("Read from I2PInputStream " + this.hashCode()
// + " returned "+read.length+" bytes:\n"
// + HexDump.dump(read));
//}
return read.length;
}
public synchronized int read(byte[] b, int off, int len) throws IOException {
_log.debug("Read called: " + this.hashCode());
if (len == 0) return 0;
long dieAfter = System.currentTimeMillis() + readTimeout;
byte[] read = bc.startToByteArray(len);
boolean timedOut = false;
public int available() {
return bc.getCurrentSize();
}
while (read.length == 0) {
synchronized (flagLock) {
if (closed) {
_log.debug("Closed is set, so closing stream: " + hashCode());
return -1;
}
}
try {
if (readTimeout >= 0) {
wait(readTimeout);
} else {
wait();
}
} catch (InterruptedException ex) {}
public void queueData(byte[] data) {
queueData(data,0,data.length);
}
if ((readTimeout >= 0)
&& (System.currentTimeMillis() >= dieAfter)) {
throw new InterruptedIOException("Timeout reading from I2PSocket (" + readTimeout + " msecs)");
}
public synchronized void queueData(byte[] data, int off, int len) {
_log.debug("Insert "+len+" bytes into queue: "+this.hashCode());
bc.append(data, off, len);
notifyAll();
}
read = bc.startToByteArray(len);
}
if (read.length > len) throw new RuntimeException("BUG");
System.arraycopy(read, 0, b, off, read.length);
if (_log.shouldLog(Log.DEBUG)) {
_log.debug("Read from I2PInputStream " + hashCode() + " returned "
+ read.length + " bytes");
}
//if (_log.shouldLog(Log.DEBUG)) {
// _log.debug("Read from I2PInputStream " + this.hashCode()
// + " returned "+read.length+" bytes:\n"
// + HexDump.dump(read));
//}
return read.length;
}
public int available() {
return bc.getCurrentSize();
}
public void queueData(byte[] data) {
queueData(data, 0, data.length);
}
public synchronized void queueData(byte[] data, int off, int len) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Insert " + len + " bytes into queue: " + hashCode());
bc.append(data, off, len);
notifyAll();
}
public synchronized void notifyClosed() {
I2PInputStream.this.notifyAll();
}
public void close() throws IOException {
super.close();
notifyClosed();
}
public synchronized void notifyClosed() {
notifyAll();
}
}
public class I2POutputStream extends OutputStream {
private class I2POutputStream extends OutputStream {
public I2PInputStream sendTo;
public I2POutputStream(I2PInputStream sendTo) {
this.sendTo=sendTo;
}
public void write(int b) throws IOException {
write(new byte[] {(byte)b});
}
public I2PInputStream sendTo;
public void write (byte[] b, int off, int len) throws IOException {
sendTo.queueData(b,off,len);
}
public I2POutputStream(I2PInputStream sendTo) {
this.sendTo = sendTo;
}
public void close() {
sendTo.notifyClosed();
}
public void write(int b) throws IOException {
write(new byte[] { (byte) b});
}
public void write(byte[] b, int off, int len) throws IOException {
sendTo.queueData(b, off, len);
}
public void close() {
sendTo.notifyClosed();
}
}
public class I2PSocketRunner extends Thread {
private static volatile long __runnerId = 0;
private class I2PSocketRunner extends I2PThread {
public InputStream in;
public InputStream in;
public I2PSocketRunner(InputStream in) {
_log.debug("Runner's input stream is: "+in.hashCode());
this.in=in;
start();
}
public I2PSocketRunner(InputStream in) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Runner's input stream is: " + in.hashCode());
this.in = in;
String peer = I2PSocketImpl.this.remote.calculateHash().toBase64();
setName("SocketRunner " + (++__runnerId) + " " + peer.substring(0, 4));
start();
}
/**
* Pump some more data
*
* @return true if we should keep on handling, false otherwise
*/
private boolean handleNextPacket(ByteCollector bc, byte buffer[])
throws IOException, I2PSessionException {
int len = in.read(buffer);
int bcsize = bc.getCurrentSize();
if (len != -1) {
bc.append(buffer, len);
} else if (bcsize == 0) {
// nothing left in the buffer, and read(..) got EOF (-1).
// the bart the
return false;
}
if ((bcsize < MAX_PACKET_SIZE) && (in.available() == 0)) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Runner Point d: " + hashCode());
public void run() {
byte[] buffer = new byte[MAX_PACKET_SIZE];
ByteCollector bc = new ByteCollector();
boolean sent = true;
try {
int len, bcsize;
// try {
while (true) {
len = in.read(buffer);
bcsize = bc.getCurrentSize();
if (len != -1) {
bc.append(buffer,len);
} else if (bcsize == 0) {
break;
}
if ((bcsize < MAX_PACKET_SIZE)
&& (in.available()==0)) {
_log.debug("Runner Point d: "+this.hashCode());
try {
Thread.sleep(PACKET_DELAY);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
if ((bcsize >= MAX_PACKET_SIZE)
|| (in.available()==0) ) {
byte[] data = bc.startToByteArray(MAX_PACKET_SIZE);
if (data.length > 0) {
_log.debug("Message size is: "+data.length);
sent = sendBlock(data);
if (!sent) {
_log.error("Error sending message to peer. Killing socket runner");
break;
}
}
}
}
if ((bc.getCurrentSize() > 0) && sent) {
_log.error("A SCARY MONSTER HAS EATEN SOME DATA! "
+ "(input stream: " + in.hashCode() + "; "
+ "queue size: " + bc.getCurrentSize() + ")");
}
synchronized(flagLock) {
closed2=true;
}
// } catch (IOException ex) {
// if (_log.shouldLog(Log.INFO))
// _log.info("Error reading and writing", ex);
// }
boolean sc;
synchronized(flagLock) {
sc=sendClose;
} // FIXME: Race here?
if (sc) {
_log.info("Sending close packet: "+outgoing);
byte[] packet = I2PSocketManager.makePacket
((byte)(getMask(0x02)),remoteID, new byte[0]);
synchronized(manager.getSession()) {
sent = manager.getSession().sendMessage(remote, packet);
}
if (!sent) {
_log.error("Error sending close packet to peer");
}
}
manager.removeSocket(I2PSocketImpl.this);
} catch (IOException ex) {
// WHOEVER removes this event on inconsistent
// state before fixing the inconsistent state (a
// reference on the socket in the socket manager
// etc.) will get hanged by me personally -- mihi
_log.error("Error running - **INCONSISTENT STATE!!!**", ex);
} catch (I2PException ex) {
_log.error("Error running - **INCONSISTENT STATE!!!**" , ex);
}
}
private boolean sendBlock(byte data[]) throws I2PSessionException {
_log.debug("TIMING: Block to send for "+I2PSocketImpl.this.hashCode());
if (remoteID==null) {
_log.error("NULL REMOTEID");
return false;
}
byte[] packet = I2PSocketManager.makePacket(getMask(0x00), remoteID,
data);
boolean sent;
synchronized(flagLock) {
if (closed2) return false;
}
synchronized(manager.getSession()) {
sent = manager.getSession().sendMessage(remote, packet);
}
return sent;
}
try {
Thread.sleep(PACKET_DELAY);
} catch (InterruptedException e) {
_log.warn("wtf", e);
}
}
if ((bcsize >= MAX_PACKET_SIZE) || (in.available() == 0)) {
byte[] data = bc.startToByteArray(MAX_PACKET_SIZE);
if (data.length > 0) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Message size is: " + data.length);
boolean sent = sendBlock(data);
if (!sent) {
_log.error("Error sending message to peer. Killing socket runner");
return false;
}
}
}
return true;
}
public void run() {
byte[] buffer = new byte[MAX_PACKET_SIZE];
ByteCollector bc = new ByteCollector();
boolean keepHandling = true;
int packetsHandled = 0;
try {
// try {
while (keepHandling) {
keepHandling = handleNextPacket(bc, buffer);
packetsHandled++;
}
if ((bc.getCurrentSize() > 0) && (packetsHandled > 1)) {
_log.error("A SCARY MONSTER HAS EATEN SOME DATA! " + "(input stream: "
+ in.hashCode() + "; "
+ "queue size: " + bc.getCurrentSize() + ")");
}
synchronized (flagLock) {
closed2 = true;
}
boolean sc;
synchronized (flagLock) {
sc = sendClose;
} // FIXME: Race here?
if (sc) {
if (_log.shouldLog(Log.INFO))
_log.info("Sending close packet: " + outgoing);
byte[] packet = I2PSocketManager.makePacket(getMask(0x02), remoteID, new byte[0]);
boolean sent = manager.getSession().sendMessage(remote, packet);
if (!sent) {
_log.error("Error sending close packet to peer");
}
}
manager.removeSocket(I2PSocketImpl.this);
} catch (InterruptedIOException ex) {
_log.error("BUG! read() operations should not timeout!", ex);
} catch (IOException ex) {
// WHOEVER removes this event on inconsistent
// state before fixing the inconsistent state (a
// reference on the socket in the socket manager
// etc.) will get hanged by me personally -- mihi
_log.error("Error running - **INCONSISTENT STATE!!!**", ex);
} catch (I2PException ex) {
_log.error("Error running - **INCONSISTENT STATE!!!**", ex);
}
}
private boolean sendBlock(byte data[]) throws I2PSessionException {
if (_log.shouldLog(Log.DEBUG))
_log.debug("TIMING: Block to send for " + I2PSocketImpl.this.hashCode());
if (remoteID == null) {
_log.error("NULL REMOTEID");
return false;
}
byte[] packet = I2PSocketManager.makePacket(getMask(0x00), remoteID, data);
boolean sent;
synchronized (flagLock) {
if (closed2) return false;
}
sent = manager.getSession().sendMessage(remote, packet);
return sent;
}
}
}

View File

@@ -9,15 +9,20 @@ import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.io.UnsupportedEncodingException;
import java.net.ConnectException;
import java.net.NoRouteToHostException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import net.i2p.I2PException;
import net.i2p.client.I2PSession;
import net.i2p.client.I2PSessionException;
import net.i2p.client.I2PSessionListener;
import net.i2p.data.Base64;
import net.i2p.data.Destination;
import net.i2p.data.DataFormatException;
import net.i2p.util.Log;
/**
@@ -31,312 +36,559 @@ import net.i2p.util.Log;
public class I2PSocketManager implements I2PSessionListener {
private final static Log _log = new Log(I2PSocketManager.class);
private I2PSession _session;
private I2PServerSocketImpl _serverSocket;
private I2PServerSocketImpl _serverSocket = null;
private Object lock = new Object(); // for locking socket lists
private HashMap _outSockets;
private HashMap _inSockets;
private I2PSocketOptions _defaultOptions;
private long _acceptTimeout;
public static final short ACK = 0x51;
public static final short CLOSE_OUT = 0x52;
public static final short DATA_OUT = 0x50;
public static final short SYN = 0xA1;
public static final short CLOSE_IN = 0xA2;
public static final short DATA_IN = 0xA0;
public static final short CHAFF = 0xFF;
public static final int PUBKEY_LENGTH=387;
/**
* How long to wait for the client app to accept() before sending back CLOSE?
* This includes the time waiting in the queue. Currently set to 5 seconds.
*/
private static final long ACCEPT_TIMEOUT_DEFAULT = 5*1000;
public I2PSocketManager() {
_session=null;
_serverSocket = new I2PServerSocketImpl(this);
_inSockets = new HashMap(16);
_outSockets = new HashMap(16);
_session = null;
_inSockets = new HashMap(16);
_outSockets = new HashMap(16);
_acceptTimeout = ACCEPT_TIMEOUT_DEFAULT;
}
public I2PSession getSession() {
return _session;
}
public void setSession(I2PSession session) {
_session = session;
if (session != null)
session.setSessionListener(this);
return _session;
}
public void setSession(I2PSession session) {
_session = session;
if (session != null) session.setSessionListener(this);
}
/**
* How long should we wait for the client to .accept() a socket before
* sending back a NACK/Close?
*
* @param ms milliseconds to wait, maximum
*/
public void setAcceptTimeout(long ms) { _acceptTimeout = ms; }
public long getAcceptTimeout() { return _acceptTimeout; }
public void disconnected(I2PSession session) {
_log.error("Disconnected from the session");
_log.info("Disconnected from the session");
destroySocketManager();
}
public void errorOccurred(I2PSession session, String message, Throwable error) {
_log.error("Error occurred: [" + message + "]", error);
_log.error("Error occurred: [" + message + "]", error);
}
public void messageAvailable(I2PSession session, int msgId, long size) {
try {
I2PSocketImpl s;
byte msg[] = session.receiveMessage(msgId);
if (msg.length == 1 && msg[0] == -1) {
_log.debug("Ping received");
return;
}
if (msg.length <4) {
_log.error("==== packet too short ====");
return;
}
int type = msg[0] & 0xff;
String id = new String(new byte[] {msg[1], msg[2], msg[3]},
"ISO-8859-1");
byte[] payload = new byte[msg.length-4];
System.arraycopy(msg, 4, payload, 0, payload.length);
_log.debug("Message read: type = [" + Integer.toHexString(type) +
"] id = [" + getReadableForm(id)+
"] payload length: " + payload.length + "]");
synchronized(lock) {
switch(type) {
case 0x51: // ACK outgoing
s = (I2PSocketImpl) _outSockets.get(id);
if (s == null) {
_log.warn("No socket responsible for ACK packet");
return;
}
if (payload.length==3 && s.getRemoteID(false)==null) {
String newID = new String(payload,
"ISO-8859-1");
s.setRemoteID(newID);
return;
} else {
if (payload.length != 3)
_log.warn("Ack packet had " + payload.length + " bytes");
else
_log.warn("Remote ID already exists? " + s.getRemoteID());
return;
}
case 0x52: // disconnect outgoing
_log.debug("*Disconnect outgoing!");
try {
s = (I2PSocketImpl) _outSockets.get(id);
if (payload.length==0 && s != null) {
s.internalClose();
_outSockets.remove(id);
return;
} else {
if (payload.length > 0)
_log.warn("Disconnect packet had " + payload.length + " bytes");
return;
}
} catch (Exception t) {
_log.error("Ignoring error on disconnect", t);
}
case 0x50: // packet send outgoing
_log.debug("*Packet send outgoing [" + payload.length + "]");
s = (I2PSocketImpl) _outSockets.get(id);
if (s != null) {
s.queueData(payload);
return;
} else {
_log.error("Null socket with data available");
throw new IllegalStateException("Null socket with data available");
}
case 0xA1: // SYN incoming
_log.debug("*Syn!");
if (payload.length==PUBKEY_LENGTH) {
String newLocalID = makeID(_inSockets);
Destination d = new Destination();
d.readBytes(new ByteArrayInputStream(payload));
s = new I2PSocketImpl(d, this, false,
newLocalID);
s.setRemoteID(id);
if (_serverSocket.getNewSocket(s)) {
_inSockets.put(newLocalID, s);
byte[] packet = makePacket
((byte)0x51, id,
newLocalID.getBytes("ISO-8859-1"));
boolean replySentOk = false;
synchronized(_session) {
replySentOk = _session.sendMessage(d, packet);
}
if (!replySentOk) {
_log.error("Error sending reply to " +
d.calculateHash().toBase64() +
" in response to a new con message",
new Exception("Failed creation"));
s.internalClose();
}
} else {
byte[] packet =
(" "+id).getBytes("ISO-8859-1");
packet[0]=0x52;
boolean nackSent = session.sendMessage(d, packet);
if (!nackSent) {
_log.error("Error sending NACK for session creation");
}
s.internalClose();
}
return;
} else {
_log.error("Syn packet that has a payload not equal to the pubkey length (" + payload.length + " != " + PUBKEY_LENGTH + ")");
return;
}
case 0xA2: // disconnect incoming
_log.debug("*Disconnect incoming!");
try {
s = (I2PSocketImpl) _inSockets.get(id);
if (payload.length==0 && s != null) {
s.internalClose();
_inSockets.remove(id);
return;
} else {
if (payload.length > 0)
_log.warn("Disconnect packet had " + payload.length + " bytes");
return;
}
} catch (Exception t) {
_log.error("Ignoring error on disconnect", t);
return;
}
case 0xA0: // packet send incoming
_log.debug("*Packet send incoming [" + payload.length + "]");
s = (I2PSocketImpl) _inSockets.get(id);
if (s != null) {
s.queueData(payload);
return;
} else {
_log.error("Null socket with data available");
throw new IllegalStateException("Null socket with data available");
}
case 0xFF: // ignore
return;
}
_log.error("\n\n=============== Unknown packet! "+
"============"+
"\nType: "+(int)type+
"\nID: " + getReadableForm(id)+
"\nBase64'ed Data: "+Base64.encode(payload)+
"\n\n\n");
if (id != null) {
_inSockets.remove(id);
_outSockets.remove(id);
}
}
} catch (I2PException ise) {
_log.error("Error processing", ise);
} catch (IOException ioe) {
_log.error("Error processing", ioe);
} catch (IllegalStateException ise) {
_log.debug("Error processing", ise);
}
try {
I2PSocketImpl s;
byte msg[] = session.receiveMessage(msgId);
if (msg.length == 1 && msg[0] == -1) {
_log.debug("Ping received");
return;
}
if (msg.length < 4) {
_log.error("==== packet too short ====");
return;
}
int type = msg[0] & 0xff;
String id = toString(new byte[] { msg[1], msg[2], msg[3]});
byte[] payload = new byte[msg.length - 4];
System.arraycopy(msg, 4, payload, 0, payload.length);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Message read: type = [" + Integer.toHexString(type)
+ "] id = [" + getReadableForm(id)
+ "] payload length: [" + payload.length + "]");
switch (type) {
case ACK:
ackAvailable(id, payload);
return;
case CLOSE_OUT:
disconnectAvailable(id, payload);
return;
case DATA_OUT:
sendOutgoingAvailable(id, payload);
return;
case SYN:
synIncomingAvailable(id, payload, session);
return;
case CLOSE_IN:
disconnectIncoming(id, payload);
return;
case DATA_IN:
sendIncoming(id, payload);
case CHAFF:
// ignore
return;
default:
handleUnknown(type, id, payload);
return;
}
} catch (I2PException ise) {
_log.error("Error processing", ise);
} catch (IllegalStateException ise) {
_log.debug("Error processing", ise);
}
}
/**
* We've received an ACK packet (hopefully, in response to a SYN that we
* recently sent out). Notify the associated I2PSocket that we now have
* the remote stream ID (which should get things going, since the handshake
* is complete).
*
*/
private void ackAvailable(String id, byte payload[]) {
I2PSocketImpl s = null;
synchronized (lock) {
s = (I2PSocketImpl) _outSockets.get(id);
}
if (s == null) {
_log.warn("No socket responsible for ACK packet");
return;
}
String remoteId = null;
remoteId = s.getRemoteID(false);
if ( (payload.length == 3) && (remoteId == null) ) {
String newID = toString(payload);
s.setRemoteID(newID);
return;
} else {
// (payload.length != 3 || getRemoteId != null)
if (_log.shouldLog(Log.WARN)) {
if (payload.length != 3)
_log.warn("Ack packet had " + payload.length + " bytes");
else
_log.warn("Remote ID already exists? " + remoteId);
}
return;
}
}
/**
* We received a disconnect packet, telling us to tear down the specified
* stream.
*/
private void disconnectAvailable(String id, byte payload[]) {
I2PSocketImpl s = null;
synchronized (lock) {
s = (I2PSocketImpl) _outSockets.get(id);
}
_log.debug("*Disconnect outgoing!");
try {
if (s != null) {
if (payload.length > 0) {
_log.debug("Disconnect packet had "
+ payload.length + " bytes");
}
if (s.getRemoteID(false) == null) {
s.setRemoteID(null); // Just to wake up socket
return;
}
s.internalClose();
synchronized (lock) {
_outSockets.remove(id);
}
}
return;
} catch (Exception t) {
_log.error("Ignoring error on disconnect", t);
}
}
/**
* We've received data on a stream we created - toss the data onto
* the socket for handling.
*
* @throws IllegalStateException if the socket isn't open or isn't known
*/
private void sendOutgoingAvailable(String id, byte payload[]) throws IllegalStateException {
I2PSocketImpl s = null;
synchronized (lock) {
s = (I2PSocketImpl) _outSockets.get(id);
}
// packet send outgoing
if (_log.shouldLog(Log.DEBUG))
_log.debug("*Packet send outgoing [" + payload.length + "]");
if (s != null) {
s.queueData(payload);
return;
} else {
_log.error("Null socket with data available");
throw new IllegalStateException("Null socket with data available");
}
}
/**
* We've received a SYN packet (a request for a new stream). If the client has
* said they want incoming sockets (by retrieving the serverSocket), the stream
* will be ACKed, but if they have not, they'll be NACKed)
*
* @throws DataFormatException if the destination in the SYN was invalid
* @throws I2PSessionException if there was an I2P error sending the ACK or NACK
*/
private void synIncomingAvailable(String id, byte payload[], I2PSession session)
throws DataFormatException, I2PSessionException {
_log.debug("*Syn!");
Destination d = new Destination();
d.fromByteArray(payload);
I2PSocketImpl s = null;
boolean acceptConnections = (_serverSocket != null);
String newLocalID = null;
synchronized (lock) {
newLocalID = makeID(_inSockets);
if (acceptConnections) {
s = new I2PSocketImpl(d, this, false, newLocalID);
s.setRemoteID(id);
}
}
if (!acceptConnections) {
// The app did not instantiate an I2PServerSocket
byte[] packet = makePacket((byte) CLOSE_OUT, id, toBytes(newLocalID));
boolean replySentOk = false;
synchronized (_session) {
replySentOk = _session.sendMessage(d, packet);
}
if (!replySentOk) {
_log.error("Error sending close to " + d.calculateHash().toBase64()
+ " in response to a new con message",
new Exception("Failed creation"));
}
return;
}
if (_serverSocket.addWaitForAccept(s, _acceptTimeout)) {
_inSockets.put(newLocalID, s);
byte[] packet = makePacket((byte) ACK, id, toBytes(newLocalID));
boolean replySentOk = false;
replySentOk = _session.sendMessage(d, packet);
if (!replySentOk) {
if (_log.shouldLog(Log.WARN))
_log.warn("Error sending reply to " + d.calculateHash().toBase64()
+ " in response to a new con message",
new Exception("Failed creation"));
s.internalClose();
}
} else {
// timed out or serverSocket closed
byte[] packet = toBytes(" " + id);
packet[0] = CLOSE_OUT;
boolean nackSent = session.sendMessage(d, packet);
if (!nackSent) {
_log.warn("Error sending NACK for session creation");
}
s.internalClose();
}
return;
}
/**
* We've received a disconnect for a socket we didn't initiate, so kill
* the socket.
*
*/
private void disconnectIncoming(String id, byte payload[]) {
_log.debug("*Disconnect incoming!");
I2PSocketImpl s = null;
synchronized (lock) {
s = (I2PSocketImpl) _inSockets.get(id);
if (payload.length == 0 && s != null) {
_inSockets.remove(id);
}
}
try {
if (payload.length == 0 && s != null) {
s.internalClose();
return;
} else {
if ( (payload.length > 0) && (_log.shouldLog(Log.ERROR)) )
_log.error("Disconnect packet had " + payload.length + " bytes");
if (s != null)
s.internalClose();
return;
}
} catch (Exception t) {
_log.error("Ignoring error on disconnect", t);
return;
}
}
/**
* We've received data on a stream we received - toss the data onto
* the socket for handling.
*
* @throws IllegalStateException if the socket isn't open or isn't known
*/
private void sendIncoming(String id, byte payload[]) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("*Packet send incoming [" + payload.length + "]");
I2PSocketImpl s = null;
synchronized (lock) {
s = (I2PSocketImpl) _inSockets.get(id);
}
if (s != null) {
s.queueData(payload);
return;
} else {
_log.info("Null socket with data available");
throw new IllegalStateException("Null socket with data available");
}
}
/**
* Unknown packet. moo.
*
*/
private void handleUnknown(int type, String id, byte payload[]) {
_log.error("\n\n=============== Unknown packet! " + "============"
+ "\nType: " + (int) type
+ "\nID: " + getReadableForm(id)
+ "\nBase64'ed Data: " + Base64.encode(payload)
+ "\n\n\n");
if (id != null) {
synchronized (lock) {
_inSockets.remove(id);
_outSockets.remove(id);
}
}
}
public void reportAbuse(I2PSession session, int severity) {
_log.error("Abuse reported [" + severity + "]");
_log.error("Abuse reported [" + severity + "]");
}
public void setDefaultOptions(I2PSocketOptions options) {
_defaultOptions = options;
}
public I2PSocketOptions getDefaultOptions() {
return _defaultOptions;
}
public I2PServerSocket getServerSocket() {
if (_serverSocket == null) {
_serverSocket = new I2PServerSocketImpl(this);
}
return _serverSocket;
}
public void setDefaultOptions(I2PSocketOptions options) { _defaultOptions = options; }
public I2PSocketOptions getDefaultOptions() { return _defaultOptions ; }
public I2PServerSocket getServerSocket() { return _serverSocket; }
/**
* Create a new connected socket (block until the socket is created)
*
* @throws I2PException if there is a problem connecting
* @param peer Destination to connect to
* @param options I2P socket options to be used for connecting
*
* @throws ConnectException if the peer refuses the connection
* @throws NoRouteToHostException if the peer is not found or not reachable
* @throws InterruptedIOException if the connection timeouts
* @throws I2PException if there is some other I2P-related problem
*/
public I2PSocket connect(Destination peer, I2PSocketOptions options) throws I2PException {
public I2PSocket connect(Destination peer, I2PSocketOptions options)
throws I2PException, ConnectException,
NoRouteToHostException, InterruptedIOException {
String localID, lcID;
I2PSocketImpl s;
synchronized (lock) {
localID = makeID(_outSockets);
lcID = getReadableForm(localID);
s = new I2PSocketImpl(peer, this, true, localID);
_outSockets.put(localID, s);
}
try {
ByteArrayOutputStream pubkey = new ByteArrayOutputStream();
_session.getMyDestination().writeBytes(pubkey);
String remoteID;
byte[] packet = makePacket((byte) SYN, localID, pubkey.toByteArray());
boolean sent = false;
sent = _session.sendMessage(peer, packet);
if (!sent) {
_log.info("Unable to send & receive ack for SYN packet");
synchronized (lock) {
_outSockets.remove(s.getLocalID());
}
throw new I2PException("Error sending through I2P network");
}
remoteID = s.getRemoteID(true, options.getConnectTimeout());
if (remoteID == null)
throw new ConnectException("Connection refused by peer");
if ("".equals(remoteID))
throw new NoRouteToHostException("Unable to reach peer");
if (_log.shouldLog(Log.DEBUG))
_log.debug("TIMING: s given out for remoteID "
+ getReadableForm(remoteID));
return s;
} catch (InterruptedIOException ioe) {
if (_log.shouldLog(Log.ERROR))
_log.error("Timeout waiting for ack from syn for id "
+ getReadableForm(lcID), ioe);
synchronized (lock) {
_outSockets.remove(s.getLocalID());
}
s.internalClose();
throw new InterruptedIOException("Timeout waiting for ack");
} catch (ConnectException ex) {
s.internalClose();
throw ex;
} catch (NoRouteToHostException ex) {
s.internalClose();
throw ex;
} catch (IOException ex) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error sending syn on id " + getReadableForm(lcID), ex);
synchronized (lock) {
_outSockets.remove(s.getLocalID());
}
s.internalClose();
throw new I2PException("Unhandled IOException occurred");
} catch (I2PException ex) {
if (_log.shouldLog(Log.INFO))
_log.info("Error sending syn on id " + getReadableForm(lcID), ex);
synchronized (lock) {
_outSockets.remove(s.getLocalID());
}
s.internalClose();
throw ex;
} catch (Exception e) {
s.internalClose();
_log.error("Unhandled error connecting", e);
throw new ConnectException("Unhandled error connecting: " + e.getMessage());
}
}
String localID, lcID;
I2PSocketImpl s;
synchronized(lock) {
localID=makeID(_outSockets);
lcID=getReadableForm(localID);
s = new I2PSocketImpl(peer, this, true, localID);
_outSockets.put(s.getLocalID(),s);
}
try {
ByteArrayOutputStream pubkey = new ByteArrayOutputStream();
_session.getMyDestination().writeBytes(pubkey);
String remoteID;
byte[] packet = makePacket((byte)0xA1, localID,
pubkey.toByteArray());
boolean sent = false;
synchronized(_session) {
sent = _session.sendMessage(peer, packet);
}
if (!sent) {
_log.info("Unable to send & receive ack for SYN packet");
synchronized(lock) {
_outSockets.remove(s.getLocalID());
}
throw new I2PException("Unable to reach peer");
}
remoteID = s.getRemoteID(true, options.getConnectTimeout());
if ("".equals(remoteID)) {
throw new I2PException("Unable to reach peer");
}
_log.debug("TIMING: s given out for remoteID "+getReadableForm(remoteID));
return s;
} catch (InterruptedIOException ioe) {
_log.error("Timeout waiting for ack from syn for id " + getReadableForm(lcID), ioe);
synchronized(lock) {
_outSockets.remove(s.getLocalID());
}
throw new I2PException("Timeout waiting for ack");
} catch (IOException ex) {
_log.error("Error sending syn on id " + getReadableForm(lcID), ex);
synchronized(lock) {
_outSockets.remove(s.getLocalID());
}
throw new I2PException("IOException occurred");
} catch (I2PException ex) {
_log.info("Error sending syn on id " + getReadableForm(lcID), ex);
synchronized(lock) {
_outSockets.remove(s.getLocalID());
}
throw ex;
}
/**
* Create a new connected socket (block until the socket is created)
*
* @param peer Destination to connect to
*
* @throws ConnectException if the peer refuses the connection
* @throws NoRouteToHostException if the peer is not found or not reachable
* @throws InterruptedIOException if the connection timeouts
* @throws I2PException if there is some other I2P-related problem
*/
public I2PSocket connect(Destination peer) throws I2PException, ConnectException,
NoRouteToHostException, InterruptedIOException {
return connect(peer, null);
}
public I2PSocket connect(Destination peer) throws I2PException {
return connect(peer, null);
/**
* Destroy the socket manager, freeing all the associated resources. This
* method will block untill all the managed sockets are closed.
*
*/
public void destroySocketManager() {
if (_serverSocket != null) {
_serverSocket.close();
_serverSocket = null;
}
synchronized (lock) {
Iterator iter;
String id = null;
I2PSocketImpl sock;
iter = _inSockets.keySet().iterator();
while (iter.hasNext()) {
id = (String)iter.next();
sock = (I2PSocketImpl)_inSockets.get(id);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Closing inSocket \""
+ getReadableForm(sock.getLocalID()) + "\"");
sock.internalClose();
}
iter = _outSockets.keySet().iterator();
while (iter.hasNext()) {
id = (String)iter.next();
sock = (I2PSocketImpl)_outSockets.get(id);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Closing outSocket \""
+ getReadableForm(sock.getLocalID()) + "\"");
sock.internalClose();
}
}
_log.debug("Waiting for all open sockets to really close...");
synchronized (lock) {
while ((_inSockets.size() != 0) || (_outSockets.size() != 0)) {
try {
lock.wait();
} catch (InterruptedException e) {}
}
}
try {
_log.debug("Destroying I2P session...");
_session.destroySession();
_log.debug("I2P session destroyed");
} catch (I2PSessionException e) {
_log.error("Error destroying I2P session", e);
}
}
/**
/**
* Retrieve a set of currently connected I2PSockets, either initiated locally or remotely.
*
*/
public Set listSockets() {
Set sockets = new HashSet(8);
synchronized (lock) {
sockets.addAll(_inSockets.values());
sockets.addAll(_outSockets.values());
}
return sockets;
Set sockets = new HashSet(8);
synchronized (lock) {
sockets.addAll(_inSockets.values());
sockets.addAll(_outSockets.values());
}
return sockets;
}
/**
* Ping the specified peer, returning true if they replied to the ping within
* the timeout specified, false otherwise. This call blocks.
*
*/
public boolean ping(Destination peer, long timeoutMs) {
try {
return _session.sendMessage(peer, new byte[] {(byte)0xFF});
} catch (I2PException ex) {
_log.error("I2PException:",ex);
return false;
}
try {
return _session.sendMessage(peer, new byte[] { (byte) CHAFF});
} catch (I2PException ex) {
_log.error("I2PException:", ex);
return false;
}
}
public void removeSocket(I2PSocketImpl sock) {
synchronized(lock) {
_inSockets.remove(sock.getLocalID());
_outSockets.remove(sock.getLocalID());
}
synchronized (lock) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("Removing socket \"" + getReadableForm(sock.getLocalID()) + "\"");
_inSockets.remove(sock.getLocalID());
_outSockets.remove(sock.getLocalID());
lock.notify();
}
}
public static String getReadableForm(String id) {
try {
if (id.length() != 3) return "Bogus";
return Base64.encode(id.getBytes("ISO-8859-1"));
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
return null;
}
if (id == null) return "(null)";
if (id.length() != 3) return "Bogus";
return Base64.encode(toBytes(id));
}
/**
@@ -344,22 +596,17 @@ public class I2PSocketManager implements I2PSessionListener {
*
* @param uniqueIn map of already known local IDs so we don't collide. WARNING - NOT THREADSAFE!
*/
public static String makeID(HashMap uniqueIn) {
String newID;
try {
do {
int id = (int)(Math.random()*16777215+1);
byte[] nid = new byte[3];
nid[0]=(byte)(id / 65536);
nid[1] = (byte)((id/256) % 256);
nid[2]= (byte)(id %256);
newID = new String(nid, "ISO-8859-1");
} while (uniqueIn.get(newID) != null);
return newID;
} catch (UnsupportedEncodingException ex) {
ex.printStackTrace();
return null;
}
private static String makeID(HashMap uniqueIn) {
String newID;
do {
int id = (int) (Math.random() * 16777215 + 1);
byte[] nid = new byte[3];
nid[0] = (byte) (id / 65536);
nid[1] = (byte) ((id / 256) % 256);
nid[2] = (byte) (id % 256);
newID = toString(nid);
} while (uniqueIn.get(newID) != null);
return newID;
}
/**
@@ -367,20 +614,28 @@ public class I2PSocketManager implements I2PSessionListener {
* the given payload
*/
public static byte[] makePacket(byte type, String id, byte[] payload) {
try {
byte[] packet = new byte[payload.length+4];
packet[0]=type;
byte[] temp = id.getBytes("ISO-8859-1");
if (temp.length != 3)
throw new RuntimeException("Incorrect ID length: "+
temp.length);
System.arraycopy(temp,0,packet,1,3);
System.arraycopy(payload,0,packet,4,payload.length);
return packet;
} catch (UnsupportedEncodingException ex) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error building the packet", ex);
return new byte[0];
}
byte[] packet = new byte[payload.length + 4];
packet[0] = type;
byte[] temp = toBytes(id);
if (temp.length != 3) throw new RuntimeException("Incorrect ID length: " + temp.length);
System.arraycopy(temp, 0, packet, 1, 3);
System.arraycopy(payload, 0, packet, 4, payload.length);
return packet;
}
private static final String toString(byte data[]) {
try {
return new String(data, "ISO-8859-1");
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("WTF! iso-8859-1 isn't supported?");
}
}
private static final byte[] toBytes(String str) {
try {
return str.getBytes("ISO-8859-1");
} catch (UnsupportedEncodingException uee) {
throw new RuntimeException("WTF! iso-8859-1 isn't supported?");
}
}
}

View File

@@ -1,20 +1,19 @@
package net.i2p.client.streaming;
import net.i2p.client.I2PSession;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.I2PSessionException;
import net.i2p.I2PException;
import net.i2p.data.Destination;
import net.i2p.util.Log;
import java.io.InputStream;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
import net.i2p.I2PException;
import net.i2p.client.I2PClient;
import net.i2p.client.I2PClientFactory;
import net.i2p.client.I2PSession;
import net.i2p.client.I2PSessionException;
import net.i2p.data.Destination;
import net.i2p.util.Log;
/**
* Simplify the creation of I2PSession and transient I2P Destination objects if
* necessary to create a socket manager. This class is most likely how classes
@@ -23,7 +22,7 @@ import java.util.Properties;
*/
public class I2PSocketManagerFactory {
private final static Log _log = new Log(I2PSocketManagerFactory.class);
/**
* Create a socket manager using a brand new destination connected to the
* I2CP router on the local machine on the default port (7654).
@@ -31,9 +30,9 @@ public class I2PSocketManagerFactory {
* @return the newly created socket manager, or null if there were errors
*/
public static I2PSocketManager createManager() {
return createManager("localhost", 7654, new Properties());
return createManager("localhost", 7654, new Properties());
}
/**
* Create a socket manager using a brand new destination connected to the
* I2CP router on the given machine reachable through the given port.
@@ -41,21 +40,21 @@ public class I2PSocketManagerFactory {
* @return the newly created socket manager, or null if there were errors
*/
public static I2PSocketManager createManager(String i2cpHost, int i2cpPort, Properties opts) {
I2PClient client = I2PClientFactory.createClient();
ByteArrayOutputStream keyStream = new ByteArrayOutputStream(512);
try {
Destination dest = client.createDestination(keyStream);
ByteArrayInputStream in = new ByteArrayInputStream(keyStream.toByteArray());
return createManager(in, i2cpHost, i2cpPort, opts);
} catch (IOException ioe) {
_log.error("Error creating the destination for socket manager", ioe);
return null;
} catch (I2PException ie) {
_log.error("Error creating the destination for socket manager", ie);
return null;
}
I2PClient client = I2PClientFactory.createClient();
ByteArrayOutputStream keyStream = new ByteArrayOutputStream(512);
try {
Destination dest = client.createDestination(keyStream);
ByteArrayInputStream in = new ByteArrayInputStream(keyStream.toByteArray());
return createManager(in, i2cpHost, i2cpPort, opts);
} catch (IOException ioe) {
_log.error("Error creating the destination for socket manager", ioe);
return null;
} catch (I2PException ie) {
_log.error("Error creating the destination for socket manager", ie);
return null;
}
}
/**
* Create a socket manager using the destination loaded from the given private key
* stream and connected to the I2CP router on the specified machine on the given
@@ -63,24 +62,25 @@ public class I2PSocketManagerFactory {
*
* @return the newly created socket manager, or null if there were errors
*/
public static I2PSocketManager createManager(InputStream myPrivateKeyStream, String i2cpHost, int i2cpPort, Properties opts) {
I2PClient client = I2PClientFactory.createClient();
opts.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_GUARANTEED);
opts.setProperty(I2PClient.PROP_TCP_HOST, i2cpHost);
opts.setProperty(I2PClient.PROP_TCP_PORT, ""+i2cpPort);
try {
I2PSession session = client.createSession(myPrivateKeyStream, opts);
session.connect();
return createManager(session);
} catch (I2PSessionException ise) {
_log.error("Error creating session for socket manager", ise);
return null;
}
public static I2PSocketManager createManager(InputStream myPrivateKeyStream, String i2cpHost, int i2cpPort,
Properties opts) {
I2PClient client = I2PClientFactory.createClient();
opts.setProperty(I2PClient.PROP_RELIABILITY, I2PClient.PROP_RELIABILITY_GUARANTEED);
opts.setProperty(I2PClient.PROP_TCP_HOST, i2cpHost);
opts.setProperty(I2PClient.PROP_TCP_PORT, "" + i2cpPort);
try {
I2PSession session = client.createSession(myPrivateKeyStream, opts);
session.connect();
return createManager(session);
} catch (I2PSessionException ise) {
_log.error("Error creating session for socket manager", ise);
return null;
}
}
private static I2PSocketManager createManager(I2PSession session) {
I2PSocketManager mgr = new I2PSocketManager();
mgr.setSession(session);
return mgr;
I2PSocketManager mgr = new I2PSocketManager();
mgr.setSession(session);
return mgr;
}
}
}

View File

@@ -2,20 +2,29 @@ package net.i2p.client.streaming;
/**
* Define the configuration for streaming and verifying data on the socket.
* No options available...
*
*/
public class I2PSocketOptions {
private long _connectTimeout;
public I2PSocketOptions() {
_connectTimeout = -1;
_connectTimeout = -1;
}
/**
* How long we will wait for the ACK from a SYN, in milliseconds.
*
* @return milliseconds to wait, or -1 if we will wait indefinitely
*/
public long getConnectTimeout() { return _connectTimeout; }
public void setConnectTimeout(long ms) { _connectTimeout = ms; }
public long getConnectTimeout() {
return _connectTimeout;
}
/**
* Define how long we will wait for the ACK from a SYN, in milliseconds.
*
*/
public void setConnectTimeout(long ms) {
_connectTimeout = ms;
}
}

View File

@@ -0,0 +1,130 @@
# dropped jobs
statGroup.0.name=droppedJobs
statGroup.0.detail.0.name=num dropped jobs (minute)
statGroup.0.detail.0.option=stat_jobQueue.droppedJobs.60m
statGroup.0.detail.0.field=3
statGroup.0.detail.1.name=num dropped jobs (hour)
statGroup.0.detail.1.option=stat_jobQueue.droppedJobs.60h
statGroup.0.detail.1.field=3
#
statGroup.1.name=encryptTime
statGroup.1.detail.0.name=encryption time avg ms (minute)
statGroup.1.detail.0.option=stat_crypto.elGamal.encrypt.60s
statGroup.1.detail.0.field=0
statGroup.1.detail.1.name=num encryptions (minute)
statGroup.1.detail.1.option=stat_crypto.elGamal.encrypt.60s
statGroup.1.detail.1.field=7
statGroup.1.detail.2.name=encryption time avg ms (hour)
statGroup.1.detail.2.option=stat_crypto.elGamal.encrypt.60s
statGroup.1.detail.2.field=0
statGroup.1.detail.3.name=num encryptions (hour)
statGroup.1.detail.3.option=stat_crypto.elGamal.encrypt.60s
statGroup.1.detail.3.field=7
#
statGroup.2.name=processingTime
statGroup.2.detail.0.name=process time avg ms (minute)
statGroup.2.detail.0.option=stat_transport.sendProcessingTime.60s
statGroup.2.detail.0.field=0
statGroup.2.detail.1.name=process events (minute)
statGroup.2.detail.1.option=stat_transport.sendProcessingTime.60s
statGroup.2.detail.1.field=7
statGroup.2.detail.2.name=process time avg ms (hour)
statGroup.2.detail.2.option=stat_transport.sendProcessingTime.60m
statGroup.2.detail.2.field=0
statGroup.2.detail.3.name=process events(hour)
statGroup.2.detail.3.option=stat_transport.sendProcessingTime.60m
statGroup.2.detail.3.field=7
#
statGroup.3.name=jobInfo
statGroup.3.detail.0.name=job run avg ms (minute)
statGroup.3.detail.0.option=stat_jobQueue.jobRun.60s
statGroup.3.detail.0.field=0
statGroup.3.detail.1.name=job lag avg ms (minute)
statGroup.3.detail.1.option=stat_jobQueue.jobLag.60s
statGroup.3.detail.1.field=0
statGroup.3.detail.2.name=job count (minute)
statGroup.3.detail.2.option=stat_jobQueue.jobRun.60s
statGroup.3.detail.2.field=7
statGroup.3.detail.3.name=job run avg ms (hour)
statGroup.3.detail.3.option=stat_jobQueue.jobRun.60m
statGroup.3.detail.3.field=0
statGroup.3.detail.4.name=job lag avg ms (hour)
statGroup.3.detail.4.option=stat_jobQueue.jobLag.60m
statGroup.3.detail.4.field=0
statGroup.3.detail.5.name=job count (hour)
statGroup.3.detail.5.option=stat_jobQueue.jobRun.60m
statGroup.3.detail.5.field=7
#
statGroup.4.name=tunnels
statGroup.4.detail.0.name=participating tunnels count (5 minutes)
statGroup.4.detail.0.option=stat_tunnel.participatingTunnels.5m
statGroup.4.detail.0.field=0
statGroup.4.detail.1.name=participating tunnels joined (5 minutes)
statGroup.4.detail.1.option=stat_tunnel.participatingTunnels.5m
statGroup.4.detail.1.field=3
statGroup.4.detail.2.name=participating tunnels count (hour)
statGroup.4.detail.2.option=stat_tunnel.participatingTunnels.60m
statGroup.4.detail.2.field=0
statGroup.4.detail.3.name=participating tunnels joined (hour)
statGroup.4.detail.3.option=stat_tunnel.participatingTunnels.60m
statGroup.4.detail.3.field=3
#
statGroup.5.name=transfer
statGroup.5.detail.0.name=messages sent (5 minutes)
statGroup.5.detail.0.option=stat_transport.sendMessageSize.5m
statGroup.5.detail.0.field=7
statGroup.5.detail.1.name=send message size avg (5 minutes)
statGroup.5.detail.1.option=stat_transport.sendMessageSize.5m
statGroup.5.detail.1.field=0
statGroup.5.detail.2.name=messages sent (hour)
statGroup.5.detail.2.option=stat_transport.sendMessageSize.60m
statGroup.5.detail.2.field=7
statGroup.5.detail.3.name=send message size avg (hour)
statGroup.5.detail.3.option=stat_transport.sendMessageSize.60m
statGroup.5.detail.3.field=0
statGroup.5.detail.4.name=messages received (5 minutes)
statGroup.5.detail.4.option=stat_transport.receiveMessageSize.5m
statGroup.5.detail.4.field=7
statGroup.5.detail.5.name=receive message size avg (5 minutes)
statGroup.5.detail.5.option=stat_transport.receiveMessageSize.5m
statGroup.5.detail.5.field=0
statGroup.5.detail.6.name=messages received (hour)
statGroup.5.detail.6.option=stat_transport.receiveMessageSize.60m
statGroup.5.detail.6.field=7
statGroup.5.detail.7.name=receive message size avg (hour)
statGroup.5.detail.7.option=stat_transport.receiveMessageSize.60m
statGroup.5.detail.7.field=0
#
statGroup.6.name=networkDbHandling
statGroup.6.detail.0.name=lookups received (5 minutes)
statGroup.6.detail.0.option=stat_netDb.lookupsReceived.5m
statGroup.6.detail.0.field=3
statGroup.6.detail.1.name=lookups handled (5 minutes)
statGroup.6.detail.1.option=stat_netDb.lookupsHandled.5m
statGroup.6.detail.1.field=3
statGroup.6.detail.2.name=lookups matched (5 minutes)
statGroup.6.detail.2.option=stat_netDb.lookupsReceived.5m
statGroup.6.detail.2.field=3
statGroup.6.detail.3.name=lookups received (hour)
statGroup.6.detail.3.option=stat_netDb.lookupsReceived.60m
statGroup.6.detail.3.field=3
statGroup.6.detail.4.name=lookups handled (hour)
statGroup.6.detail.4.option=stat_netDb.lookupsHandled.60m
statGroup.6.detail.4.field=3
statGroup.6.detail.5.name=lookups matched (hour)
statGroup.6.detail.5.option=stat_netDb.lookupsReceived.60m
statGroup.6.detail.5.field=3
#
statGroup.7.name=networkDbActivity
statGroup.7.detail.0.name=lookups sent (hour)
statGroup.7.detail.0.option=stat_netDb.successPeers.60m
statGroup.7.detail.0.field=3
statGroup.7.detail.1.name=lookup peers (hour)
statGroup.7.detail.1.option=stat_netDb.successPeers.60m
statGroup.7.detail.1.field=0
statGroup.7.detail.2.name=db store sent (5 minutes)
statGroup.7.detail.2.option=stat_netDb.storeSent.5m
statGroup.7.detail.2.field=3
statGroup.7.detail.3.name=db store sent (hour)
statGroup.7.detail.3.option=stat_netDb.storeSent.60m
statGroup.7.detail.3.field=3

View File

@@ -0,0 +1,69 @@
<?xml version="1.0" encoding="UTF-8"?>
<project basedir="." default="all" name="netmonitor">
<target name="all" depends="clean, build" />
<target name="build" depends="builddep, jar" />
<target name="builddep">
<ant dir="../../../core/java/" target="build" />
</target>
<target name="buildGUI" depends="build, jarGUI" />
<target name="compile">
<mkdir dir="./build" />
<mkdir dir="./build/obj" />
<javac srcdir="./src" debug="true" destdir="./build/obj" includes="net/**/*.java" excludes="net/i2p/netmonitor/gui/**" classpath="../../../core/java/build/i2p.jar" />
</target>
<target name="compileGUI" depends="builddep">
<mkdir dir="./build" />
<mkdir dir="./build/obj" />
<javac debug="true" destdir="./build/obj">
<src path="src/" />
<classpath path="../../../core/java/build/i2p.jar" />
<classpath path="../../jfreechart/jfreechart-0.9.17/lib/jcommon-0.9.2.jar" />
<classpath path="../../jfreechart/jfreechart-0.9.17/lib/log4j-1.2.8.jar" />
<classpath path="../../jfreechart/jfreechart-0.9.17/jfreechart-0.9.17.jar" />
</javac>
</target>
<target name="jarGUI" depends="compileGUI">
<copy file="../../jfreechart/jfreechart-0.9.17/jfreechart-0.9.17.jar" todir="build/" />
<copy file="../../jfreechart/jfreechart-0.9.17/lib/log4j-1.2.8.jar" todir="build/" />
<copy file="../../jfreechart/jfreechart-0.9.17/lib/jcommon-0.9.2.jar" todir="build/" />
<jar destfile="./build/netviewer.jar" basedir="./build/obj" includes="**">
<manifest>
<attribute name="Main-Class" value="net.i2p.netmonitor.gui.NetViewer" />
<attribute name="Class-Path" value="log4j-1.2.8.jar jcommon-0.9.2.jar jfreechart-0.9.17.jar netviewer.jar i2p.jar" />
</manifest>
</jar>
<echo message="You will need to copy the log4j, jcommon, and jfreechart jar files into your lib dir" />
</target>
<target name="jar" depends="compile">
<jar destfile="./build/netmonitor.jar" basedir="./build/obj" includes="**/*.class">
<manifest>
<attribute name="Main-Class" value="net.i2p.netmonitor.NetMonitor" />
<attribute name="Class-Path" value="i2p.jar netmonitor.jar" />
</manifest>
</jar>
</target>
<target name="javadoc">
<mkdir dir="./build" />
<mkdir dir="./build/javadoc" />
<javadoc
sourcepath="./src:../../../core/java/src:../../../core/java/test" destdir="./build/javadoc"
packagenames="*"
use="true"
access="package"
splitindex="true"
windowtitle="I2P netmonitor" />
</target>
<target name="clean">
<delete dir="./build" />
</target>
<target name="cleandep" depends="clean">
<ant dir="../../../core/java/" target="cleandep" />
</target>
<target name="distclean" depends="clean">
<ant dir="../../../core/java/" target="distclean" />
<delete dir="./lib/" />
</target>
</project>

View File

@@ -0,0 +1,245 @@
package net.i2p.netmonitor;
import net.i2p.data.RouterInfo;
import net.i2p.util.Log;
import net.i2p.util.Clock;
import java.util.Properties;
import java.util.Iterator;
import java.util.ArrayList;
import java.util.List;
import java.util.StringTokenizer;
import java.util.Locale;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.ParseException;
/**
* Pull out important data from the published routerInfo and stash it away
* in the netMonitor
*
*/
class DataHarvester {
private static final Log _log = new Log(DataHarvester.class);
private static final DataHarvester _instance = new DataHarvester();
public static final DataHarvester getInstance() { return _instance; }
/**
* Contains the list of StatGroup objects loaded from the harvest.config file
* {@see StatGroupLoader} where each statGroup defines a set of stats to pull
* from each router's options.
*
*/
private List _statGroups;
/**
* Where are we reading the stat groups from? For now, "harvester.config".
*/
private static final String STAT_GROUP_CONFIG_FILENAME = "harvester.config";
protected DataHarvester() {
_statGroups = StatGroupLoader.loadStatGroups(STAT_GROUP_CONFIG_FILENAME);
}
/**
* Harvest all of the data from the peers and store it in the monitor.
*
* @param peers list of RouterInfo structures to harvest from
*/
public void harvestData(NetMonitor monitor, List peers) {
for (int i = 0; i < peers.size(); i++) {
harvestData(monitor, (RouterInfo)peers.get(i), peers);
}
}
/**
* Pull out all the data we can for the specified peer
*
* @param peer who are we focusing on in this pass
* @param peers everyone on the network, to co
*/
private void harvestData(NetMonitor monitor, RouterInfo peer, List peers) {
_log.info("Harvest the data from " + peer.getIdentity().getHash().toBase64());
harvestRank(monitor, peer, peers);
harvestRankAs(monitor, peer);
harvestGroups(monitor, peer);
}
/**
* How does the peer rank other routers? Stored in the peer summary as
* "rankAs", containing 4 longs (numFast, numReliable, numNotFailing, numFailing)
*
* @param peer who is doing the ranking
*/
private void harvestRankAs(NetMonitor monitor, RouterInfo peer) {
int numFast = 0;
int numReliable = 0;
int numNotFailing = 0;
int numFailing = 0;
Properties props = peer.getOptions();
for (Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
String key = (String)iter.next();
if (key.startsWith("profile.")) {
String val = (String)props.get(key);
if (val.indexOf("fastReliable") != -1)
numFast++;
else if (val.indexOf("reliable") != -1)
numReliable++;
else if (val.indexOf("notFailing") != -1)
numNotFailing++;
else if (val.indexOf("failing") != -1)
numFailing++;
}
}
long rankAs[] = new long[4];
rankAs[0] = numFast;
rankAs[1] = numReliable;
rankAs[2] = numNotFailing;
rankAs[3] = numFailing;
String description = "how we rank peers";
String valDescr[] = new String[4];
valDescr[0] = "# peers we rank as fast";
valDescr[1] = "# peers we rank as reliable";
valDescr[2] = "# peers we rank as not failing";
valDescr[3] = "# peers we rank as failing";
monitor.addData(peer.getIdentity().getHash().toBase64(), "rankAs", description, valDescr, peer.getPublished(), rankAs);
}
/**
* How do other peers rank the current peer? Stored in the peer summary as
* "rank", containing 4 longs (numFast, numReliable, numNotFailing, numFailing)
*
* @param peer who do we want to check the network's perception of
* @param peers peers whose rankings we will use
*/
private void harvestRank(NetMonitor monitor, RouterInfo peer, List peers) {
int numFast = 0;
int numReliable = 0;
int numNotFailing = 0;
int numFailing = 0;
// now count 'em
for (int i = 0; i < peers.size(); i++) {
RouterInfo cur = (RouterInfo)peers.get(i);
if (peer == cur) continue;
String prop = "profile." + peer.getIdentity().getHash().toBase64().replace('=', '_');
String val = cur.getOptions().getProperty(prop);
if ( (val == null) || (val.length() <= 0) ) continue;
if (val.indexOf("fastReliable") != -1)
numFast++;
else if (val.indexOf("reliable") != -1)
numReliable++;
else if (val.indexOf("notFailing") != -1)
numNotFailing++;
else if (val.indexOf("failing") != -1)
numFailing++;
}
long rank[] = new long[4];
rank[0] = numFast;
rank[1] = numReliable;
rank[2] = numNotFailing;
rank[3] = numFailing;
String description = "how peers rank us";
String valDescr[] = new String[4];
valDescr[0] = "# peers ranking us as fast";
valDescr[1] = "# peers ranking us as reliable";
valDescr[2] = "# peers ranking us as not failing";
valDescr[3] = "# peers ranking us as failing";
// we use the current date, not the published date, since this sample doesnt come from them
monitor.addData(peer.getIdentity().getHash().toBase64(), "rank", description, valDescr, Clock.getInstance().now(), rank);
}
/**
* Harvest all data points from the peer
*
*/
private void harvestGroups(NetMonitor monitor, RouterInfo peer) {
_log.debug("Harvesting group data for " + peer.getIdentity().getHash().toBase64());
for (int i = 0; i < _statGroups.size(); i++) {
StatGroup group = (StatGroup)_statGroups.get(i);
harvestGroup(monitor, peer, group);
}
}
/**
* Harvest the data points for the given group from the peer and toss them
* into the monitor
*
*/
private void harvestGroup(NetMonitor monitor, RouterInfo peer, StatGroup group) {
_log.debug("Harvesting group data for " + peer.getIdentity().getHash().toBase64() + " / " + group.getDescription());
double values[] = harvestGroupValues(peer, group);
if (values == null) return;
String description = "how long it takes to do an ElGamal encryption";
String valDescr[] = new String[group.getStatCount()];
for (int i = 0; i < group.getStatCount(); i++)
valDescr[i] = group.getStat(i).getStatDescription();
monitor.addData(peer.getIdentity().getHash().toBase64(), group.getDescription(), group.getDescription(), valDescr, peer.getPublished(), values);
}
/**
* Pull up a list of all values associated with the group (in the order that the
* group specifies).
*
* @return values or null on error
*/
private double[] harvestGroupValues(RouterInfo peer, StatGroup group) {
List values = new ArrayList(8);
for (int i = 0; i < group.getStatCount(); i++) {
StatGroup.StatDescription stat = group.getStat(i);
double val = getDouble(peer, stat.getOptionName(), stat.getOptionField());
if (val == -1)
return null;
else
values.add(new Double(val));
}
double rv[] = new double[values.size()];
for (int i = 0; i < values.size(); i++)
rv[i] = ((Double)values.get(i)).doubleValue();
return rv;
}
/**
* Pull a value from the peer's option as a double, assuming the standard semicolon
* delimited formatting
*
* @param peer peer to query
* @param key peer option to check
* @param index 0-based index into the semicolon delimited values to pull out
* @return value, or -1 if there was an error
*/
private static final double getDouble(RouterInfo peer, String key, int index) {
String val = peer.getOptions().getProperty(key);
if (val == null) return -1;
StringTokenizer tok = new StringTokenizer(val, ";");
for (int i = 0; i < index; i++) {
if (!tok.hasMoreTokens()) return -1;
tok.nextToken(); // ignore
}
if (!tok.hasMoreTokens()) return -1;
String cur = tok.nextToken();
try {
return getDoubleValue(cur);
} catch (ParseException pe) {
_log.warn("Unable to parse out the double from field " + index + " out of " + val + " for " + key, pe);
return -1;
}
}
/** this mimics the format used in the router's StatisticsManager */
private static final DecimalFormat _numFmt = new DecimalFormat("###,###,###,###,##0.00", new DecimalFormatSymbols(Locale.UK));
/**
* Converts a number (double) to text
* @param val the number to convert
* @return the textual representation
*/
private static final double getDoubleValue(String val) throws ParseException {
synchronized (_numFmt) {
Number n = _numFmt.parse(val);
return n.doubleValue();
}
}
}

View File

@@ -0,0 +1,212 @@
package net.i2p.netmonitor;
import net.i2p.util.Log;
import net.i2p.util.I2PThread;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Properties;
import java.util.Map;
import java.util.HashMap;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.FilenameFilter;
import java.io.File;
/**
* Main driver for the app that harvests data about the performance of the network,
* building summaries for each peer that change over time. <p />
*
* Usage: <code>NetMonitor [configFilename]</code> <p />
*
*
*
*/
public class NetMonitor {
private static final Log _log = new Log(NetMonitor.class);
public static final String CONFIG_LOCATION_DEFAULT = "netmonitor.config";
public static final String HARVEST_DELAY_PROP = "harvestDelaySeconds";
public static final int HARVEST_DELAY_DEFAULT = 60;
public static final String EXPORT_DELAY_PROP = "exportDelaySeconds";
public static final int EXPORT_DELAY_DEFAULT = 120;
public static final String SUMMARY_DURATION_PROP = "summaryDurationHours";
public static final int SUMMARY_DURATION_DEFAULT = 72;
public static final String NETDB_DIR_PROP = "netDbDir";
public static final String NETDB_DIR_DEFAULT = "netDb";
public static final String EXPORT_DIR_PROP = "exportDir";
public static final String EXPORT_DIR_DEFAULT = "monitorData";
private String _configLocation;
private int _harvestDelay;
private int _exportDelay;
private String _exportDir;
private String _netDbDir;
private int _summaryDurationHours;
private boolean _isRunning;
private Map _peerSummaries;
public NetMonitor() {
this(CONFIG_LOCATION_DEFAULT);
}
public NetMonitor(String configLocation) {
_configLocation = configLocation;
_peerSummaries = new HashMap(32);
loadConfig();
}
/** read and call parse */
private void loadConfig() {
Properties props = new Properties();
FileInputStream fis = null;
try {
fis = new FileInputStream(_configLocation);
props.load(fis);
} catch (IOException ioe) {
_log.warn("Error loading the net monitor config", ioe);
} finally {
if (fis != null) try { fis.close(); } catch (IOException ioe) {}
}
parseConfig(props);
}
/** interpret the config elements and shove 'em in the vars */
private void parseConfig(Properties props) {
String val = props.getProperty(HARVEST_DELAY_PROP, ""+HARVEST_DELAY_DEFAULT);
try {
_harvestDelay = Integer.parseInt(val);
} catch (NumberFormatException nfe) {
_log.warn("Error parsing the harvest delay [" + val + "]", nfe);
_harvestDelay = HARVEST_DELAY_DEFAULT;
}
val = props.getProperty(EXPORT_DELAY_PROP, ""+EXPORT_DELAY_DEFAULT);
try {
_exportDelay = Integer.parseInt(val);
} catch (NumberFormatException nfe) {
_log.warn("Error parsing the export delay [" + val + "]", nfe);
_exportDelay = EXPORT_DELAY_DEFAULT;
}
val = props.getProperty(SUMMARY_DURATION_PROP, ""+SUMMARY_DURATION_DEFAULT);
try {
_summaryDurationHours = Integer.parseInt(val);
} catch (NumberFormatException nfe) {
_log.warn("Error parsing the summary duration [" + val + "]", nfe);
_summaryDurationHours = SUMMARY_DURATION_DEFAULT;
}
_netDbDir = props.getProperty(NETDB_DIR_PROP, NETDB_DIR_DEFAULT);
_exportDir = props.getProperty(EXPORT_DIR_PROP, EXPORT_DIR_DEFAULT);
}
public void startMonitor() {
_isRunning = true;
I2PThread t = new I2PThread(new NetMonitorRunner(this));
t.setName("DataHarvester");
t.setPriority(I2PThread.MIN_PRIORITY);
t.setDaemon(false);
t.start();
}
public void stopMonitor() { _isRunning = false; }
public boolean isRunning() { return _isRunning; }
/** how many seconds should we wait between harvestings? */
public int getHarvestDelay() { return _harvestDelay; }
/** how many seconds should we wait between exporting the data? */
public int getExportDelay() { return _exportDelay; }
/** where should we export the data? */
public String getExportDir() { return _exportDir; }
public void setExportDir(String dir) { _exportDir = dir; }
public int getSummaryDurationHours() { return _summaryDurationHours; }
/** where should we read the data from? */
public String getNetDbDir() { return _netDbDir; }
/**
* what peers are we keeping track of?
*
* @return list of peer names (H(routerIdentity).toBase64())
*/
public List getPeers() {
synchronized (_peerSummaries) {
return new ArrayList(_peerSummaries.keySet());
}
}
/** what data do we have for the peer? */
public PeerSummary getSummary(String peer) {
synchronized (_peerSummaries) {
return (PeerSummary)_peerSummaries.get(peer);
}
}
/** keep track of the given stat on the given peer */
public void addData(String peer, String stat, String descr, String valDescr[], long sampleDate, double val[]) {
synchronized (_peerSummaries) {
if (!_peerSummaries.containsKey(peer))
_peerSummaries.put(peer, new PeerSummary(peer));
PeerSummary summary = (PeerSummary)_peerSummaries.get(peer);
summary.addData(stat, descr, valDescr, sampleDate, val);
}
}
/** keep track of the given stat on the given peer */
public void addData(String peer, String stat, String descr, String valDescr[], long sampleDate, long val[]) {
synchronized (_peerSummaries) {
if (!_peerSummaries.containsKey(peer))
_peerSummaries.put(peer, new PeerSummary(peer));
PeerSummary summary = (PeerSummary)_peerSummaries.get(peer);
summary.addData(stat, descr, valDescr, sampleDate, val);
}
}
/** keep track of the loaded summary, overwriting any existing summary for the specified peer */
public void addSummary(PeerSummary summary) {
synchronized (_peerSummaries) {
Object rv = _peerSummaries.put(summary.getPeer(), summary);
if (rv != summary) _log.error("Updating the peer summary changed objects! old = " + rv + " new = " + summary);
}
}
public void importData() {
_log.debug("Running import");
File dataDir = new File(getExportDir());
if (!dataDir.exists()) return;
File dataFiles[] = dataDir.listFiles(new FilenameFilter() {
public boolean accept(File f, String name) {
return name.endsWith(".txt");
}
});
if (dataFiles == null) return;
for (int i = 0; i < dataFiles.length; i++) {
FileInputStream fis = null;
boolean delete = false;
try {
fis = new FileInputStream(dataFiles[i]);
PeerSummaryReader.getInstance().read(this, fis);
} catch (IOException ioe) {
_log.error("Error reading the data file " + dataFiles[i].getAbsolutePath(), ioe);
delete = true;
} finally {
if (fis != null) try { fis.close(); } catch (IOException ioe) {}
if (delete) dataFiles[i].delete();
}
}
_log.debug(dataFiles.length + " summaries imported");
}
/** drop all the old summary data */
public void coallesceData() {
synchronized (_peerSummaries) {
for (Iterator iter = _peerSummaries.values().iterator(); iter.hasNext(); ) {
PeerSummary summary = (PeerSummary)iter.next();
summary.coallesceData(_summaryDurationHours * 60*60*1000);
}
}
}
public static final void main(String args[]) {
if (args.length == 1)
new NetMonitor(args[0]).startMonitor();
else
new NetMonitor(CONFIG_LOCATION_DEFAULT).startMonitor();
}
}

View File

@@ -0,0 +1,151 @@
package net.i2p.netmonitor;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FilenameFilter;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import net.i2p.data.DataFormatException;
import net.i2p.data.RouterInfo;
/**
* Active process that drives the monitoring by periodically rading the
* netDb dir, pumping the router data throug the data harvester, updating
* the state, and coordinating the export.
*
*/
class NetMonitorRunner implements Runnable {
private static final Log _log = new Log(NetMonitorRunner.class);
private NetMonitor _monitor;
/**
* @param monitor who do we give our data to?
*/
public NetMonitorRunner(NetMonitor monitor) {
_monitor = monitor;
}
public void run() {
runImport();
long now = Clock.getInstance().now();
long nextHarvest = now;
long nextExport = now + _monitor.getExportDelay() * 1000;
while (_monitor.isRunning()) {
now = Clock.getInstance().now();
_monitor.coallesceData();
if (now >= nextHarvest) {
runHarvest();
nextHarvest = now + _monitor.getHarvestDelay() * 1000;
}
if (now >= nextExport) {
runExport();
nextExport = now + _monitor.getExportDelay() * 1000;
}
pauseHarvesting();
}
}
private void runHarvest() {
try {
List routers = getRouters();
DataHarvester.getInstance().harvestData(_monitor, routers);
} catch (Throwable t) {
_log.error("Unhandled exception harvesting the data", t);
}
}
/**
* Fetch all of the available RouterInfo structures
*
*/
private List getRouters() {
File routers[] = listRouters();
List rv = new ArrayList(64);
if (routers != null) {
for (int i = 0; i < routers.length; i++) {
FileInputStream fis = null;
try {
fis = new FileInputStream(routers[i]);
RouterInfo ri = new RouterInfo();
ri.readBytes(fis);
rv.add(ri);
} catch (DataFormatException dfe) {
_log.warn("Unable to parse the routerInfo from " + routers[i].getAbsolutePath(), dfe);
} catch (IOException ioe) {
_log.warn("Unable to read the routerInfo from " + routers[i].getAbsolutePath(), ioe);
} finally {
if (fis != null) try { fis.close(); } catch (IOException ioe) {}
}
}
}
return rv;
}
/**
* dump the data to the filesystem
*/
private void runExport() {
_log.info("Export");
List peers = _monitor.getPeers();
File exportDir = new File(_monitor.getExportDir());
if (!exportDir.exists())
exportDir.mkdirs();
for (int i = 0; i < peers.size(); i++) {
String peerName = (String)peers.get(i);
PeerSummary summary = (PeerSummary)_monitor.getSummary(peerName);
FileOutputStream fos = null;
try {
File summaryFile = new File(exportDir, peerName + ".txt");
fos = new FileOutputStream(summaryFile);
PeerSummaryWriter.getInstance().write(summary, fos);
_log.debug("Peer summary written to " + summaryFile.getAbsolutePath());
} catch (IOException ioe) {
_log.error("Error exporting the peer summary for " + peerName, ioe);
} catch (Throwable t) {
_log.error("Unhandled exception exporting the data", t);
} finally {
if (fos != null) try { fos.close(); } catch (IOException ioe) {}
}
}
}
/**
* Read in all the peer summaries we had previously exported, overwriting any
* existing ones in memory
*
*/
private void runImport() {
_monitor.importData();
}
/**
* Find all of the routers to load
*
* @return list of File objects pointing at the routers around
*/
private File[] listRouters() {
File dbDir = new File(_monitor.getNetDbDir());
File files[] = dbDir.listFiles(new FilenameFilter() {
public boolean accept(File f, String name) {
return name.startsWith("routerInfo-");
}
});
return files;
}
/**
* Wait the correct amount of time before harvesting again
*
*/
private void pauseHarvesting() {
try {
Thread.sleep(_monitor.getHarvestDelay());
} catch (InterruptedException ie) {}
}
}

View File

@@ -0,0 +1,46 @@
package net.i2p.netmonitor;
/**
* Actual data point (though its not fully normalized, but KISS)
*
*/
public class PeerStat {
private String _statName;
private String _description;
private String _valueDescriptions[];
private long _sampleDate;
private long _lvalues[];
private double _dvalues[];
public PeerStat(String name, String description, String valueDescriptions[], long sampleDate, double values[]) {
this(name, description, valueDescriptions, sampleDate, null, values);
}
public PeerStat(String name, String description, String valueDescriptions[], long sampleDate, long values[]) {
this(name, description, valueDescriptions, sampleDate, values, null);
}
private PeerStat(String name, String description, String valueDescriptions[], long sampleDate, long lvalues[], double dvalues[]) {
_statName = name;
_description = description;
_valueDescriptions = valueDescriptions;
_sampleDate = sampleDate;
_lvalues = lvalues;
_dvalues = dvalues;
}
/** unique name of the stat */
public String getStatName() { return _statName; }
/** one line summary of the stat */
public String getDescription() { return _description; }
/** description of each value */
public String getValueDescription(int index) { return _valueDescriptions[index]; }
/** description of all values */
public String[] getValueDescriptions() { return _valueDescriptions; }
/** when did the router publish the info being sampled? */
public long getSampleDate() { return _sampleDate; }
/** if the values are integers, this contains their values */
public long[] getLongValues() { return _lvalues; }
/** if the values are floating point numbers, this contains their values */
public double[] getDoubleValues() { return _dvalues; }
/** are the values floating poing numbers? */
public boolean getIsDouble() { return _dvalues != null; }
}

View File

@@ -0,0 +1,119 @@
package net.i2p.netmonitor;
import net.i2p.util.Clock;
import net.i2p.util.Log;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;
import java.util.Set;
/**
* coordinate the data points summarizing the performance of a particular peer
* within the network
*/
public class PeerSummary {
private static final Log _log = new Log(PeerSummary.class);
private String _peer;
/** statName to a List of PeerStat elements (sorted by sample date, earliest first) */
private Map _stats;
/** lock on this when accessing stat data */
private Object _coallesceLock = new Object();
public PeerSummary(String peer) {
_peer = peer;
_stats = new HashMap(16);
}
/**
* Track a data point
*
* @param stat what data are we tracking?
* @param description what does this data mean? (and what are the values?)
* @param when what data set is this sample based off?
* @param val actual data harvested
*/
public void addData(String stat, String description, String valueDescriptions[], long when, double val[]) {
synchronized (_coallesceLock) {
TreeMap stats = locked_getData(stat);
stats.put(new Long(when), new PeerStat(stat, description, valueDescriptions, when, val));
}
}
/**
* Track a data point
*
* @param stat what data are we tracking?
* @param description what does this data mean? (and what are the values?)
* @param when what data set is this sample based off?
* @param val actual data harvested
*/
public void addData(String stat, String description, String valueDescriptions[], long when, long val[]) {
synchronized (_coallesceLock) {
TreeMap stats = locked_getData(stat);
stats.put(new Long(when), new PeerStat(stat, description, valueDescriptions, when, val));
}
}
/** get the peer's name (H(routerIdentity).toBase64()) */
public String getPeer() { return _peer; }
/**
* fetch the ordered list of PeerStat objects for the given stat (or null if
* isn't being tracked or has no data)
*
*/
public List getData(String statName) {
synchronized (_coallesceLock) {
return new ArrayList(((TreeMap)_stats.get(statName)).values());
}
}
/**
* Get the names of all of the stats that are being tracked
*
*/
public Set getStatNames() {
synchronized (_coallesceLock) {
return new HashSet(_stats.keySet());
}
}
/** drop old data points */
public void coallesceData(long summaryDurationMs) {
long earliest = Clock.getInstance().now() - summaryDurationMs;
synchronized (_coallesceLock) {
locked_coallesce(earliest);
}
}
/** go through all the stats and remove ones from before the given date */
private void locked_coallesce(long earliestSampleDate) {
if (true) return;
for (Iterator iter = _stats.keySet().iterator(); iter.hasNext(); ) {
String statName = (String)iter.next();
TreeMap stats = (TreeMap)_stats.get(statName);
while (stats.size() > 0) {
Long when = (Long)stats.keySet().iterator().next();
if (when.longValue() < earliestSampleDate) {
stats.remove(when);
} else {
break;
}
}
}
}
/**
* @return PeerStat elements, ordered by sample date (earliest first)
*/
private TreeMap locked_getData(String statName) {
if (!_stats.containsKey(statName))
_stats.put(statName, new TreeMap());
return (TreeMap)_stats.get(statName);
}
}

View File

@@ -0,0 +1,109 @@
package net.i2p.netmonitor;
import net.i2p.util.Log;
import java.io.IOException;
import java.io.InputStream;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.Iterator;
import java.util.List;
import java.util.ArrayList;
import java.util.TreeSet;
import java.util.Set;
import java.util.Locale;
import java.util.Date;
import java.util.StringTokenizer;
import java.text.SimpleDateFormat;
import java.text.ParseException;
/**
* Load up the peer summary
*
*/
class PeerSummaryReader {
private static final Log _log = new Log(PeerSummaryReader.class);
private static final PeerSummaryReader _instance = new PeerSummaryReader();
public static final PeerSummaryReader getInstance() { return _instance; }
private PeerSummaryReader() {}
/** */
public void read(NetMonitor monitor, InputStream in) throws IOException {
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
String line = null;
PeerSummary summary = null;
String curDescription = null;
List curArgs = null;
try {
while ((line = reader.readLine()) != null) {
if (line.startsWith("peer\t")) {
String name = line.substring("peer\t".length()).trim();
summary = monitor.getSummary(name);
if (summary == null)
summary = new PeerSummary(name);
} else if (line.startsWith("## ")) {
curDescription = line.substring("## ".length()).trim();
curArgs = new ArrayList(4);
} else if (line.startsWith("# param ")) {
int start = line.indexOf(':');
String arg = line.substring(start+1).trim();
curArgs.add(arg);
} else {
StringTokenizer tok = new StringTokenizer(line);
String name = tok.nextToken();
try {
long when = getTime(tok.nextToken());
boolean isDouble = false;
List argVals = new ArrayList(curArgs.size());
while (tok.hasMoreTokens()) {
String val = (String)tok.nextToken();
if (val.indexOf('.') >= 0) {
argVals.add(new Double(val));
isDouble = true;
} else {
argVals.add(new Long(val));
}
}
String valDescriptions[] = new String[curArgs.size()];
for (int i = 0; i < curArgs.size(); i++)
valDescriptions[i] = (String)curArgs.get(i);
if (isDouble) {
double values[] = new double[argVals.size()];
for (int i = 0; i < argVals.size(); i++)
values[i] = ((Double)argVals.get(i)).doubleValue();
summary.addData(name, curDescription, valDescriptions, when, values);
} else {
long values[] = new long[argVals.size()];
for (int i = 0; i < argVals.size(); i++)
values[i] = ((Long)argVals.get(i)).longValue();
summary.addData(name, curDescription, valDescriptions, when, values);
}
} catch (ParseException pe) {
_log.error("Error parsing the data line [" + line + "]", pe);
} catch (NumberFormatException nfe) {
_log.error("Error parsing the data line [" + line + "]", nfe);
}
}
}
} catch (Exception e) {
_log.error("Error handling the data", e);
throw new IOException("Error parsing the data");
}
if (summary == null)
return;
summary.coallesceData(monitor.getSummaryDurationHours() * 60*60*1000);
monitor.addSummary(summary);
}
private static final SimpleDateFormat _fmt = new SimpleDateFormat("yyyyMMdd.HH:mm:ss.SSS", Locale.UK);
/**
* Converts a time (long) to text
* @param when the time to convert
* @return the textual representation
*/
public long getTime(String when) throws ParseException {
synchronized (_fmt) {
return _fmt.parse(when).getTime();
}
}
}

View File

@@ -0,0 +1,80 @@
package net.i2p.netmonitor;
import net.i2p.util.Log;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Iterator;
import java.util.List;
import java.util.TreeSet;
import java.util.Set;
import java.util.Locale;
import java.util.Date;
import java.text.SimpleDateFormat;
/**
* Dump various peer summaries to disk (so external apps (or good ol' vi) can
* peek into what we're harvesting
*
*/
class PeerSummaryWriter {
private static final Log _log = new Log(PeerSummaryWriter.class);
private static final PeerSummaryWriter _instance = new PeerSummaryWriter();
public static final PeerSummaryWriter getInstance() { return _instance; }
private PeerSummaryWriter() {}
/** write out the peer summary to the stream specified */
public void write(PeerSummary summary, OutputStream out) throws IOException {
StringBuffer buf = new StringBuffer(4*1024);
buf.append("peer\t").append(summary.getPeer()).append('\n');
TreeSet names = new TreeSet(summary.getStatNames());
for (Iterator iter = names.iterator(); iter.hasNext(); ) {
String statName = (String)iter.next();
List stats = summary.getData(statName);
for (int i = 0; i < stats.size(); i++) {
PeerStat stat = (PeerStat)stats.get(i);
if (i == 0) {
buf.append("## ").append(stat.getDescription()).append('\n');
String descr[] = stat.getValueDescriptions();
if (descr != null) {
for (int j = 0; j < descr.length; j++)
buf.append("# param ").append(j).append(": ").append(descr[j]).append('\n');
}
}
buf.append(statName).append('\t');
buf.append(getTime(stat.getSampleDate())).append('\t');
if (stat.getIsDouble()) {
double vals[] = stat.getDoubleValues();
if (vals != null) {
for (int j = 0; j < vals.length; j++)
buf.append(vals[j]).append('\t');
}
} else {
long vals[] = stat.getLongValues();
if (vals != null) {
for (int j = 0; j < vals.length; j++)
buf.append(vals[j]).append('\t');
}
}
buf.append('\n');
}
}
String data = buf.toString();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Stat: \n" + data);
out.write(data.getBytes());
}
private static final SimpleDateFormat _fmt = new SimpleDateFormat("yyyyMMdd.HH:mm:ss.SSS", Locale.UK);
/**
* Converts a time (long) to text
* @param when the time to convert
* @return the textual representation
*/
public String getTime(long when) {
synchronized (_fmt) {
return _fmt.format(new Date(when));
}
}
}

View File

@@ -0,0 +1,53 @@
package net.i2p.netmonitor;
import java.util.ArrayList;
import java.util.List;
/**
* Stupid little structure to configure the DataHarvester's gathering of statistics.
*
*/
public class StatGroup {
private String _groupDescription;
private List _stats;
public StatGroup(String description) {
_groupDescription = description;
_stats = new ArrayList();
}
public String getDescription() { return _groupDescription; }
public int getStatCount() { return _stats.size(); }
public StatDescription getStat(int index) { return (StatDescription)_stats.get(index); }
public void addStat(String description, String optionName, int optionField) {
StatDescription descr = new StatDescription(description, optionName, optionField);
_stats.add(descr);
}
public class StatDescription {
private String _statDescription;
private String _optionName;
private int _optionField;
public StatDescription(String descr, String optionName, int optionField) {
_statDescription = descr;
_optionName = optionName;
_optionField = optionField;
}
/** brief description of this data point */
public String getStatDescription() { return _statDescription; }
/**
* if this is harvested from the RouterInfo's options, this specifies
* which key in that map to pull from (or null if it isn't harvested
* from there)
*/
public String getOptionName() { return _optionName; }
/**
* if this is harvested from the RouterInfo's options, this specifies
* which field in value of that map to pull from (or -1 if it isn't harvested
* from there)
*/
public int getOptionField() { return _optionField; }
}
}

View File

@@ -0,0 +1,92 @@
package net.i2p.netmonitor;
import net.i2p.util.Log;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.util.List;
import java.util.ArrayList;
import java.util.Properties;
/**
* Load up the StatGroups from the location specified to configure the data harvester.
* The stat groups are formatted in a simple properties file style, e.g.: <pre>
* # dropped jobs
* statGroup.0.name=droppedJobs
* statGroup.0.detail.0.name=num dropped jobs (minute)
* statGroup.0.detail.0.option=stat_jobQueue.droppedJobs.60m
* statGroup.0.detail.0.field=3
* statGroup.0.detail.1.name=num dropped jobs (hour)
* statGroup.0.detail.1.option=stat_jobQueue.droppedJobs.60h
* statGroup.0.detail.1.field=3
* #
* statGroup.1.name=encryptTime
* statGroup.1.detail.0.name=encryption time avg ms (minute)
* statGroup.1.detail.0.option=stat_crypto.elGamal.encrypt.60s
* statGroup.1.detail.0.field=0
* statGroup.1.detail.1.name=num encryptions (minute)
* statGroup.1.detail.1.option=stat_crypto.elGamal.encrypt.60s
* statGroup.1.detail.1.field=7
* statGroup.1.detail.2.name=encryption time avg ms (hour)
* statGroup.1.detail.2.option=stat_crypto.elGamal.encrypt.60s
* statGroup.1.detail.2.field=0
* statGroup.1.detail.3.name=num encryptions (hour)
* statGroup.1.detail.3.option=stat_crypto.elGamal.encrypt.60s
* statGroup.1.detail.3.field=7
* </pre>
*/
class StatGroupLoader {
private static final Log _log = new Log(StatGroupLoader.class);
/**
* Load a list of stat groups from the file specified
*
* @return list of StatGroup objects
*/
public static List loadStatGroups(String filename) {
_log.debug("Loading stat groups from " + filename);
FileInputStream fis = null;
File f = new File(filename);
try {
fis = new FileInputStream(f);
Properties p = new Properties();
p.load(fis);
_log.debug("Config loaded from " + filename);
return loadStatGroups(p);
} catch (IOException ioe) {
_log.error("Error loading the stat groups from " + f.getAbsolutePath(), ioe);
return new ArrayList();
}
}
private static List loadStatGroups(Properties props) {
List rv = new ArrayList(8);
int groupNum = 0;
while (true) {
String description = props.getProperty("statGroup." + groupNum + ".name");
if (description == null) break;
int detailNum = 0;
StatGroup group = new StatGroup(description);
while (true) {
String detailPrefix = "statGroup." + groupNum + ".detail." + detailNum + '.';
String name = props.getProperty(detailPrefix + "name");
if (name == null) break;
String option = props.getProperty(detailPrefix + "option");
if (option == null) break;
String field = props.getProperty(detailPrefix + "field");
if (field == null) break;
try {
int fieldNum = Integer.parseInt(field);
group.addStat(name, option, fieldNum);
} catch (NumberFormatException nfe) {
_log.warn("Unable to parse the field number from [" + field + "]", nfe);
break;
}
detailNum++;
}
rv.add(group);
groupNum++;
}
return rv;
}
}

View File

@@ -0,0 +1,113 @@
package net.i2p.netmonitor.gui;
import net.i2p.netmonitor.PeerSummary;
import net.i2p.netmonitor.PeerStat;
import net.i2p.util.Log;
import org.jfree.data.XYSeries;
import org.jfree.data.XYSeriesCollection;
import org.jfree.data.MovingAverage;
import org.jfree.chart.JFreeChart;
import org.jfree.chart.ChartPanel;
import org.jfree.chart.plot.Plot;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.axis.DateAxis;
import org.jfree.chart.axis.NumberAxis;
import org.jfree.chart.renderer.XYLineAndShapeRenderer;
import org.jfree.chart.renderer.XYItemRenderer;
import org.jfree.chart.renderer.XYDotRenderer;
import java.util.List;
import java.util.Set;
import java.util.Iterator;
import javax.swing.JPanel;
import java.awt.Font;
import java.awt.Color;
class JFreeChartAdapter {
private final static Log _log = new Log(JFreeChartAdapter.class);
private final static Color WHITE = new Color(255, 255, 255);
ChartPanel createPanel(NetViewer state) {
ChartPanel panel = new ChartPanel(createChart(state));
panel.setDisplayToolTips(true);
panel.setEnforceFileExtensions(true);
panel.setHorizontalZoom(true);
panel.setVerticalZoom(true);
panel.setMouseZoomable(true, true);
panel.getChart().setBackgroundPaint(WHITE);
return panel;
}
JFreeChart createChart(NetViewer state) {
Plot plot = createPlot(state);
JFreeChart chart = new JFreeChart("I2P network performance", Font.getFont("arial"), plot, true);
return chart;
}
void updateChart(ChartPanel panel, NetViewer state) {
XYPlot plot = (XYPlot)panel.getChart().getPlot();
plot.setDataset(getCollection(state));
}
Plot createPlot(NetViewer state) {
XYItemRenderer renderer = new XYLineAndShapeRenderer(); // new XYDotRenderer(); //
XYPlot plot = new XYPlot(getCollection(state), new DateAxis(), new NumberAxis("val"), renderer);
return plot;
}
XYSeriesCollection getCollection(NetViewer state) {
XYSeriesCollection col = new XYSeriesCollection();
if (state != null) {
List names = state.getConfigNames();
for (int i = 0; i < names.size(); i++) {
addPeer(col, state.getConfig((String)names.get(i)));
}
} else {
XYSeries series = new XYSeries("latency", false, false);
series.add(System.currentTimeMillis(), 0);
col.addSeries(series);
}
return col;
}
void addPeer(XYSeriesCollection col, PeerPlotConfig config) {
Set statNames = config.getSummary().getStatNames();
for (Iterator iter = statNames.iterator(); iter.hasNext(); ) {
String statName = (String)iter.next();
List statData = config.getSummary().getData(statName);
if (statData.size() > 0) {
PeerStat data = (PeerStat)statData.get(0);
String args[] = data.getValueDescriptions();
if (args != null) {
for (int i = 0; i < args.length; i++) {
if (config.getSeriesConfig().getShouldPlotValue(statName, args[i], false))
addLine(col, config.getPeerName(), statName, args[i], statData);
}
}
}
}
}
/**
*/
void addLine(XYSeriesCollection col, String peer, String statName, String argName, List dataPoints) {
XYSeries series = new XYSeries(peer.substring(0, 4) + ": " + argName, false, false);
for (int i = 0; i < dataPoints.size(); i++) {
PeerStat data = (PeerStat)dataPoints.get(i);
String argNames[] = data.getValueDescriptions();
int argIndex = -1;
for (int j = 0; j < argNames.length; j++) {
if (argNames[j].equals(argName)) {
argIndex = j;
break;
}
}
if (data.getIsDouble())
series.add(data.getSampleDate(), data.getDoubleValues()[argIndex]);
else
series.add(data.getSampleDate(), data.getLongValues()[argIndex]);
}
col.addSeries(series);
}
}

View File

@@ -0,0 +1,58 @@
package net.i2p.netmonitor.gui;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import javax.swing.JScrollPane;
import javax.swing.JLabel;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Dimension;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import net.i2p.util.Log;
import org.jfree.chart.ChartPanel;
/**
* Render the graph and legend
*
*/
class JFreeChartHeartbeatPlotPane extends NetViewerPlotPane {
private final static Log _log = new Log(JFreeChartHeartbeatPlotPane.class);
private ChartPanel _panel;
private JFreeChartAdapter _adapter;
public JFreeChartHeartbeatPlotPane(NetViewerGUI gui) {
super(gui);
}
public void stateUpdated() {
if (_panel == null) {
remove(0); // remove the dummy
_adapter = new JFreeChartAdapter();
_panel = _adapter.createPanel(_gui.getViewer());
_panel.setBackground(_gui.getBackground());
JScrollPane pane = new JScrollPane(_panel);
pane.setBackground(_gui.getBackground());
add(pane, BorderLayout.CENTER);
} else {
_adapter.updateChart(_panel, _gui.getViewer());
//_gui.pack();
}
}
protected void initializeComponents() {
// noop
setLayout(new BorderLayout());
add(new JLabel(), BorderLayout.CENTER);
//dummy.setBackground(_gui.getBackground());
//dummy.setPreferredSize(new Dimension(800,600));
//add(dummy);
setPreferredSize(new Dimension(800,600));
//add(_panel);
}
}

View File

@@ -0,0 +1,86 @@
package net.i2p.netmonitor.gui;
import net.i2p.netmonitor.NetMonitor;
import net.i2p.netmonitor.PeerSummary;
import net.i2p.netmonitor.PeerStat;
import net.i2p.util.Log;
import net.i2p.util.I2PThread;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.HashMap;
/**
* Coordinate the visualization of the network monitor. <p />
*
* <b>Usage: <code>NetViewer [exportDir]</code></b> <br />
* (exportDir is where the NetMonitor exports its state, "monitorData" by default)
*/
public class NetViewer {
private static final Log _log = new Log(NetViewer.class);
private NetMonitor _monitor;
private NetViewerGUI _gui;
private Map _plotConfigs;
private boolean _isClosed;
public NetViewer() {
this(NetMonitor.EXPORT_DIR_DEFAULT);
}
public NetViewer(String dataDir) {
_monitor = new NetMonitor();
_monitor.setExportDir(dataDir);
_isClosed = false;
_gui = new NetViewerGUI(this);
_plotConfigs = new HashMap();
}
public void runViewer() {
I2PThread t = new I2PThread(new NetViewerRunner(this));
t.setName("NetViewer");
t.setDaemon(false);
t.start();
}
void refreshGUI() {
_gui.stateUpdated();
}
void reloadData() {
_log.debug("Reloading data");
_monitor.importData();
refreshGUI();
}
public void addConfig(String peerName, PeerPlotConfig config) {
synchronized (_plotConfigs) {
_plotConfigs.put(peerName, config);
}
}
public PeerPlotConfig getConfig(String peerName) {
synchronized (_plotConfigs) {
return (PeerPlotConfig)_plotConfigs.get(peerName);
}
}
public List getConfigNames() {
synchronized (_plotConfigs) {
return new ArrayList(_plotConfigs.keySet());
}
}
public NetMonitor getMonitor() { return _monitor; }
long getDataLoadDelay() { return _monitor.getExportDelay(); }
/** has the viewer been closed? */
public boolean getIsClosed() { return _isClosed; }
public void setIsClosed(boolean closed) { _isClosed = closed; }
public static final void main(String args[]) {
if (args.length == 1)
new NetViewer(args[0]).runViewer();
else
new NetViewer().runViewer();
}
}

View File

@@ -0,0 +1,70 @@
package net.i2p.netmonitor.gui;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
class NetViewerCommandBar extends JPanel {
private NetViewerGUI _gui;
private JComboBox _refreshRate;
private JTextField _location;
/**
* Constructs a command bar onto the gui
* @param gui the gui the command bar is associated with
*/
public NetViewerCommandBar(NetViewerGUI gui) {
_gui = gui;
initializeComponents();
}
private void refreshChanged(ItemEvent evt) {}
private void loadCalled() {
//_gui.getMonitor().load(_location.getText());
}
private void browseCalled() {
JFileChooser chooser = new JFileChooser(_location.getText());
chooser.setBackground(_gui.getBackground());
chooser.setMultiSelectionEnabled(false);
int rv = chooser.showDialog(this, "Load");
//if (rv == JFileChooser.APPROVE_OPTION)
// _gui.getMonitor().load(chooser.getSelectedFile().getAbsolutePath());
}
private void initializeComponents() {
_refreshRate = new JComboBox(new DefaultComboBoxModel(new Object[] {"10 second refresh", "30 second refresh", "1 minute refresh", "5 minute refresh"}));
_refreshRate.addItemListener(new ItemListener() { public void itemStateChanged(ItemEvent evt) { refreshChanged(evt); } });
_refreshRate.setEnabled(false);
_refreshRate.setBackground(_gui.getBackground());
//add(_refreshRate);
JLabel loadLabel = new JLabel("Load from: ");
loadLabel.setBackground(_gui.getBackground());
add(loadLabel);
_location = new JTextField(20);
_location.setToolTipText("Either specify a local filename or a fully qualified URL");
_location.setBackground(_gui.getBackground());
_location.setEnabled(false);
add(_location);
JButton browse = new JButton("Browse...");
browse.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { browseCalled(); } });
browse.setBackground(_gui.getBackground());
browse.setEnabled(false);
add(browse);
JButton load = new JButton("Load");
load.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { loadCalled(); } });
load.setBackground(_gui.getBackground());
load.setEnabled(false);
add(load);
setBackground(_gui.getBackground());
}
}

View File

@@ -0,0 +1,107 @@
package net.i2p.netmonitor.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.util.ArrayList;
import java.util.List;
import java.awt.Dimension;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTabbedPane;
import net.i2p.util.Log;
/**
* Render the control widgets (refresh/load/snapshot and the
* tabbed panel with the plot config data)
*
*/
class NetViewerControlPane extends JPanel {
private final static Log _log = new Log(NetViewerControlPane.class);
private NetViewerGUI _gui;
private JTabbedPane _configPane;
private final static Color WHITE = new Color(255, 255, 255);
private final static Color LIGHT_BLUE = new Color(180, 180, 255);
private final static Color BLACK = new Color(0, 0, 0);
private Color _background = WHITE;
private Color _foreground = BLACK;
/**
* Constructs a control panel onto the gui
* @param gui the gui the panel is associated with
*/
public NetViewerControlPane(NetViewerGUI gui) {
_gui = gui;
initializeComponents();
}
/** the settings have changed - revise */
void refreshView() {
_gui.refreshView();
}
/**
* Callback: when tests have changed
*/
public synchronized void stateUpdated() {
List knownNames = new ArrayList(8);
List peers = _gui.getViewer().getMonitor().getPeers();
_log.debug("GUI updated with peers: " + peers);
for (int i = 0; i < peers.size(); i++) {
String name = (String)peers.get(i);
String shortName = name.substring(0,4);
knownNames.add(shortName);
if (_configPane.indexOfTab(shortName) >= 0) {
JScrollPane pane = (JScrollPane)_configPane.getComponentAt(_configPane.indexOfTab(shortName));
PeerPlotConfigPane cfgPane = (PeerPlotConfigPane)pane.getViewport().getView();
cfgPane.stateUpdated();
_log.debug("We already know about [" + name + "]");
} else {
_log.info("The peer [" + name + "] is new to us");
PeerPlotConfig cfg = new PeerPlotConfig(_gui.getViewer().getMonitor().getSummary(name));
_gui.getViewer().addConfig(name, cfg);
PeerPlotConfigPane pane = new PeerPlotConfigPane(cfg, this);
JScrollPane p = new JScrollPane(pane);
p.setBackground(_background);
_configPane.addTab(shortName, null, p, "Peer " + name);
_configPane.setBackgroundAt(_configPane.getTabCount()-1, _background);
_configPane.setForegroundAt(_configPane.getTabCount()-1, _foreground);
}
}
List toRemove = new ArrayList(4);
for (int i = 0; i < _configPane.getTabCount(); i++) {
if (knownNames.contains(_configPane.getTitleAt(i))) {
// noop
} else {
toRemove.add(_configPane.getTitleAt(i));
}
}
for (int i = 0; i < toRemove.size(); i++) {
String title = (String)toRemove.get(i);
_log.info("Removing peer [" + title + "]");
_configPane.removeTabAt(_configPane.indexOfTab(title));
}
}
private void initializeComponents() {
if (_gui != null)
setBackground(_gui.getBackground());
else
setBackground(_background);
setLayout(new BorderLayout());
NetViewerCommandBar bar = new NetViewerCommandBar(_gui);
bar.setBackground(getBackground());
add(bar, BorderLayout.NORTH);
_configPane = new JTabbedPane(JTabbedPane.LEFT);
_configPane.setBackground(_background);
JScrollPane pane = new JScrollPane(_configPane);
pane.setBackground(_background);
add(pane, BorderLayout.CENTER);
//setPreferredSize(new Dimension(800, 400));
//setMinimumSize(new Dimension(800, 400));
//setMaximumSize(new Dimension(800, 400));
}
NetViewer getViewer() { return _gui.getViewer(); }
}

View File

@@ -0,0 +1,105 @@
package net.i2p.netmonitor.gui;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JScrollPane;
import javax.swing.JSplitPane;
class NetViewerGUI extends JFrame {
private NetViewer _viewer;
private NetViewerPlotPane _plotPane;
private NetViewerControlPane _controlPane;
private final static Color WHITE = new Color(255, 255, 255);
private Color _background = WHITE;
/**
* Creates the GUI for all youz who be too shoopid for text based shitz
* @param monitor the monitor the gui operates over
*/
public NetViewerGUI(NetViewer viewer) {
super("Network Viewer");
_viewer = viewer;
initializeComponents();
pack();
//setResizable(false);
setVisible(true);
}
NetViewer getViewer() { return _viewer; }
/** build up all our widgets */
private void initializeComponents() {
getContentPane().setLayout(new BorderLayout());
setBackground(_background);
_plotPane = new JFreeChartHeartbeatPlotPane(this); // // new NetViewerPlotPane(this); //
_plotPane.setBackground(_background);
JScrollPane pane = new JScrollPane(_plotPane);
pane.setBackground(_background);
//getContentPane().add(pane, BorderLayout.CENTER);
_controlPane = new NetViewerControlPane(this);
_controlPane.setBackground(_background);
//getContentPane().add(_controlPane, BorderLayout.SOUTH);
JSplitPane split = new JSplitPane(JSplitPane.VERTICAL_SPLIT, _plotPane, _controlPane);
//split.setDividerLocation(0.3d);
getContentPane().add(split, BorderLayout.CENTER);
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
initializeMenus();
}
/**
* Callback: when the state of the world changes . . .
*/
public void stateUpdated() {
_controlPane.stateUpdated();
_plotPane.stateUpdated();
//pack();
}
public void refreshView() {
_plotPane.stateUpdated();
}
private void exitCalled() {
_viewer.setIsClosed(true);
setVisible(false);
System.exit(0);
}
private void loadConfigCalled() {}
private void saveConfigCalled() {}
private void loadSnapshotCalled() {}
private void saveSnapshotCalled() {}
private void initializeMenus() {
JMenuBar bar = new JMenuBar();
JMenu fileMenu = new JMenu("File");
JMenuItem loadConfig = new JMenuItem("Load config");
loadConfig.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { loadConfigCalled(); } });
JMenuItem saveConfig = new JMenuItem("Save config");
saveConfig.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveConfigCalled(); } });
JMenuItem saveSnapshot = new JMenuItem("Save snapshot");
saveSnapshot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { saveSnapshotCalled(); } });
JMenuItem loadSnapshot = new JMenuItem("Load snapshot");
loadSnapshot.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { loadSnapshotCalled(); } });
JMenuItem exit = new JMenuItem("Exit");
exit.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent evt) { exitCalled(); } });
fileMenu.add(loadConfig);
fileMenu.add(saveConfig);
fileMenu.add(loadSnapshot);
fileMenu.add(saveSnapshot);
fileMenu.add(exit);
bar.add(fileMenu);
setJMenuBar(bar);
}
}

View File

@@ -0,0 +1,50 @@
package net.i2p.netmonitor.gui;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import javax.swing.JPanel;
import javax.swing.JTextArea;
import net.i2p.util.Log;
/**
* Render the graph and legend
*/
class NetViewerPlotPane extends JPanel {
private final static Log _log = new Log(NetViewerPlotPane.class);
protected NetViewerGUI _gui;
private JTextArea _text;
/**
* Constructs the plot pane
* @param gui the gui the pane is attached to
*/
public NetViewerPlotPane(NetViewerGUI gui) {
_gui = gui;
initializeComponents();
}
/**
* Callback: when things change . . .
*/
public void stateUpdated() {
StringBuffer buf = new StringBuffer(32*1024);
buf.append("moo");
_text.setText(buf.toString());
}
protected void initializeComponents() {
setBackground(_gui.getBackground());
//Dimension size = new Dimension(800, 600);
_text = new JTextArea("",30,80); // 16, 60);
_text.setAutoscrolls(true);
_text.setEditable(false);
// _text.setLineWrap(true);
// add(new JScrollPane(_text));
add(_text);
// add(new JScrollPane(_text, JScrollPane.VERTICAL_SCROLLBAR_ALWAYS, JScrollPane.HORIZONTAL_SCROLLBAR_ALWAYS));
// setPreferredSize(size);
}
}

View File

@@ -0,0 +1,16 @@
package net.i2p.netmonitor.gui;
class NetViewerRunner implements Runnable {
private NetViewer _viewer;
public NetViewerRunner(NetViewer viewer) {
_viewer = viewer;
}
public void run() {
while (!_viewer.getIsClosed()) {
_viewer.reloadData();
try { Thread.sleep(_viewer.getDataLoadDelay()*1000); } catch (InterruptedException ie) {}
}
}
}

View File

@@ -0,0 +1,218 @@
package net.i2p.netmonitor.gui;
import java.awt.Color;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeMap;
import java.util.Map;
import java.util.HashMap;
import net.i2p.data.Destination;
import net.i2p.util.Log;
import net.i2p.netmonitor.PeerSummary;
/**
* Configure how we want to render a particular peerSummary in the GUI
*/
class PeerPlotConfig {
private final static Log _log = new Log(PeerPlotConfig.class);
/** where can we find the current state/data (either as a filename or a URL)? */
private String _location;
/** what test are we defining the plot data for? */
private PeerSummary _summary;
/** how should we render the current data set? */
private PlotSeriesConfig _seriesConfig;
private Set _listeners;
private boolean _disabled;
/**
* Delegating constructor . . .
* @param location the name of the file/URL to get the data from
*/
public PeerPlotConfig(String location) {
this(location, null, null);
}
/**
* Delegating constructor . . .
* @param location the name of the file/URL to get the data from
*/
public PeerPlotConfig(PeerSummary summary) {
this(null, summary, null);
}
/**
* Constructs a config =)
* @param location the location of the file/URL to get the data from
* @param config the client's configuration
* @param seriesConfig the series config
*/
public PeerPlotConfig(String location, PeerSummary summary, PlotSeriesConfig seriesConfig) {
_location = location;
_summary = summary;
if (seriesConfig != null)
_seriesConfig = seriesConfig;
else
_seriesConfig = new PlotSeriesConfig();
_listeners = Collections.synchronizedSet(new HashSet(2));
_disabled = false;
}
/**
* Where is the current state data supposed to be found? This must either be a
* local file path or a URL
* @return the current location
*/
public String getLocation() { return _location; }
/**
* The location the current state data is supposed to be found. This must either be
* a local file path or a URL
* @param location the location
*/
public void setLocation(String location) {
_location = location;
fireUpdate();
}
/**
* What are we configuring?
* @return the client configuration
*/
public PeerSummary getSummary() { return _summary; }
/**
* Sets what we are currently configuring
* @param config the new config
*/
public void setPeerSummary(PeerSummary summary) {
_summary = summary;
fireUpdate();
}
/**
* How do we want to render the current data set?
* @return the way we currently render the data
*/
public PlotSeriesConfig getSeriesConfig() { return _seriesConfig; }
/**
* Sets how we want to render the current data set.
* @param config the new config
*/
public void setSeriesConfig(PlotSeriesConfig config) {
_seriesConfig = config;
fireUpdate();
}
/**
* four char description of the peer
* @return the name
*/
public String getPeerName() { return _summary.getPeer(); }
/**
* we've got someone who wants to be notified of changes to the plot config
* @param lsnr the listener to be added
*/
public void addListener(UpdateListener lsnr) { _listeners.add(lsnr); }
/**
* remove a listener
* @param lsnr the listener to remove
*/
public void removeListener(UpdateListener lsnr) { _listeners.remove(lsnr); }
void fireUpdate() {
if (_disabled) return;
for (Iterator iter = _listeners.iterator(); iter.hasNext(); ) {
((UpdateListener)iter.next()).configUpdated(this);
}
}
/**
* Disables notification of events listeners
* @see PeerPlotConfig#fireUpdate()
*/
public void disableEvents() { _disabled = true; }
/**
* Enables notification of events listeners
* @see PeerPlotConfig#fireUpdate()
*/
public void enableEvents() { _disabled = false; }
/**
* How do we want to render a particular dataset (either the current or the averaged values)?
*/
public class PlotSeriesConfig {
private Map _shouldPlot;
private Map _plotColors;
/**
* Creates a config for the rendering of a particular dataset)
* @param plotLost do we plot lost packets?
* @param plotColor in what color?
*/
public PlotSeriesConfig() {
_shouldPlot = new HashMap(16);
_plotColors = new HashMap(16);
}
/**
* Retrieves the plot config this plot series config is a part of
* @return the plot config
*/
public PeerPlotConfig getPlotConfig() { return PeerPlotConfig.this; }
public boolean getShouldPlotValue(String statName, String argName, boolean defaultVal) {
Boolean val = (Boolean)_shouldPlot.get(statName + argName);
if (val == null)
return defaultVal;
else
return val.booleanValue();
}
public void setShouldPlotValue(String statName, String argName, boolean shouldPlot) {
_shouldPlot.put(statName + argName, new Boolean(shouldPlot));
fireUpdate();
}
/**
* What color should we plot the data with?
* @return the color
*/
public Color getPlotLineColor(String statName, String argName) {
return (Color)_plotColors.get(statName + argName);
}
/**
* Sets the color we should plot the data with
* @param color the color to use
*/
public void setPlotLineColor(String statName, String argName, Color color) {
if (color == null)
_plotColors.remove(statName + argName);
else
_plotColors.put(statName + argName, color);
fireUpdate();
}
}
/**
* An interface for listening to updates . . .
*/
public interface UpdateListener {
/**
* @param config the peer plot config that changes
* @see PeerPlotConfig#fireUpdate()
*/
void configUpdated(PeerPlotConfig config);
}
}

View File

@@ -0,0 +1,280 @@
package net.i2p.netmonitor.gui;
import java.awt.Color;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.TreeMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Set;
import java.util.Iterator;
import java.util.Random;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JColorChooser;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JTextField;
import net.i2p.util.Log;
import net.i2p.netmonitor.PeerStat;
import net.i2p.netmonitor.PeerSummary;
class PeerPlotConfigPane extends JPanel implements PeerPlotConfig.UpdateListener {
private final static Log _log = new Log(PeerPlotConfigPane.class);
private PeerPlotConfig _config;
private NetViewerControlPane _parent;
private JLabel _peer;
private JButton _toggleAll;
private OptionGroup _options[];
private Random _rnd = new Random();
private final static Color WHITE = new Color(255, 255, 255);
private Color _background = WHITE;
/**
* Constructs a pane
* @param config the plot config it represents
* @param pane the pane this one is attached to
*/
public PeerPlotConfigPane(PeerPlotConfig config, NetViewerControlPane pane) {
_config = config;
_parent = pane;
if (_parent != null)
_background = _parent.getBackground();
_config.addListener(this);
initializeComponents();
}
private void initializeComponents() {
buildComponents();
placeComponents(this);
refreshView();
//setBorder(new BevelBorder(BevelBorder.RAISED));
setBackground(_background);
}
/**
* place all the gui components onto the given panel
* @param body the panel to place the components on
*/
private void placeComponents(JPanel body) {
body.setLayout(new GridBagLayout());
GridBagConstraints cts = new GridBagConstraints();
// row 0: peer name + toggle All
cts.gridx = 0;
cts.gridy = 0;
cts.gridwidth = 2;
cts.anchor = GridBagConstraints.WEST;
cts.fill = GridBagConstraints.NONE;
body.add(_peer, cts);
cts.gridx = 2;
cts.gridy = 0;
cts.gridwidth = 1;
cts.anchor = GridBagConstraints.EAST;
cts.fill = GridBagConstraints.NONE;
body.add(_toggleAll, cts);
int row = 0;
for (int i = 0; i < _options.length; i++) {
row++;
cts.gridx = 0;
cts.gridy = row;
cts.gridwidth = 3;
cts.weightx = 5;
cts.fill = GridBagConstraints.BOTH;
cts.anchor = GridBagConstraints.WEST;
body.add(_options[i]._statName, cts);
for (int j = 0; j < _options[i]._statAttributes.size(); j++) {
row++;
cts.gridx = 0;
cts.gridy = row;
cts.gridwidth = 1;
cts.weightx = 1;
cts.fill = GridBagConstraints.NONE;
body.add(new JLabel(" "), cts);
cts.gridx = 1;
cts.gridy = row;
cts.gridwidth = 1;
cts.weightx = 5;
cts.fill = GridBagConstraints.BOTH;
JCheckBox box = (JCheckBox)_options[i]._statAttributes.get(j);
box.setBackground(_background);
body.add(box, cts);
cts.gridx = 2;
cts.fill = GridBagConstraints.NONE;
cts.anchor = GridBagConstraints.EAST;
JButton toggleAttr = new JButton("Toggle all");
toggleAttr.setBackground(_background);
toggleAttr.addActionListener(new ToggleAttribute(_options[i].getStatName(), box.getText(), box));
body.add(toggleAttr, cts);
}
}
}
private class ToggleAttribute implements ActionListener {
private String _statName;
private String _attrName;
private JCheckBox _box;
public ToggleAttribute(String statName, String attrName, JCheckBox box) {
_statName = statName;
_attrName = attrName;
_box = box;
}
public void actionPerformed(ActionEvent evt) {
boolean setActive = true;
if (_box.isSelected()) {
setActive = false;
}
List names = _parent.getViewer().getConfigNames();
for (int i = 0; i < names.size(); i++) {
String name = (String)names.get(i);
PeerPlotConfig cfg = _parent.getViewer().getConfig(name);
cfg.getSeriesConfig().setShouldPlotValue(_statName, _attrName, setActive);
_log.debug("Setting " + _statName + "." + _attrName + " to " + setActive + " for " + name);
}
_parent.stateUpdated();
_parent.refreshView();
}
}
/** build all of the gui components */
private void buildComponents() {
_peer = new JLabel("Router: " + _config.getPeerName());
_toggleAll = new JButton("Show all");
_toggleAll.setBackground(_background);
_toggleAll.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
_config.disableEvents();
for (int i = 0; i < _options.length; i++) {
for (int j = 0; j < _options[i]._statAttributes.size(); j++) {
JCheckBox box = (JCheckBox)_options[i]._statAttributes.get(j);
String statName = _options[i].getStatName();
String attrName = box.getText();
if (_toggleAll.getText().equals("Show all")) {
box.setSelected(true);
_config.getSeriesConfig().setShouldPlotValue(statName, attrName, true);
} else {
box.setSelected(false);
_config.getSeriesConfig().setShouldPlotValue(statName, attrName, false);
}
}
}
if (_toggleAll.getText().equals("Show all"))
_toggleAll.setText("Hide all");
else
_toggleAll.setText("Show all");
_config.enableEvents();
_config.fireUpdate();
}
});
Set statNames = _config.getSummary().getStatNames();
List options = new ArrayList(statNames.size());
for (Iterator iter = statNames.iterator(); iter.hasNext(); ) {
String statName = (String)iter.next();
List data = _config.getSummary().getData(statName);
if ( (data != null) && (data.size() > 0) ) {
PeerStat stat = (PeerStat)data.get(0);
String attributes[] = stat.getValueDescriptions();
OptionGroup group = new OptionGroup(statName, attributes);
options.add(group);
}
}
TreeMap orderedOptions = new TreeMap();
for (int i = 0; i < options.size(); i++) {
OptionGroup grp = (OptionGroup)options.get(i);
orderedOptions.put(grp.getStatName(), grp);
}
_options = new OptionGroup[options.size()];
int i = 0;
for (Iterator iter = orderedOptions.values().iterator(); iter.hasNext(); ) {
OptionGroup grp = (OptionGroup)iter.next();
_options[i] = grp;
i++;
}
}
/** the settings have changed - revise */
private void refreshView() {
_parent.refreshView();
}
/**
* notified that the config has been updated
* @param config the config that was been updated
*/
public void configUpdated(PeerPlotConfig config) { refreshView(); }
public void stateUpdated() {
for (int i = 0; i < _options.length; i++) {
for (int j = 0; j < _options[i]._statAttributes.size(); j++) {
JCheckBox box = (JCheckBox)_options[i]._statAttributes.get(j);
if (_config.getSeriesConfig().getShouldPlotValue(_options[i].getStatName(), box.getText(), false))
box.setSelected(true);
else
box.setSelected(false);
}
}
}
private class OptionGroup {
JTextField _statName;
List _statAttributes;
public String getStatName() { return _statName.getText(); }
/**
* Creates an OptionLine.
* @param statName statistic group in question
* @param statAttributes list of attributes we keep about this stat
*/
public OptionGroup(String statName, String statAttributes[]) {
_statName = new JTextField(statName);
_statName.setEditable(false);
_statName.setBackground(_background);
_statAttributes = new ArrayList(4);
if (statAttributes != null) {
for (int i = 0; i < statAttributes.length; i++) {
JCheckBox box = new JCheckBox(statAttributes[i]);
box.addActionListener(new UpdateListener(OptionGroup.this));
_statAttributes.add(box);
}
}
}
}
private class UpdateListener implements ActionListener {
private OptionGroup _group;
/**
* Update Listener constructor . . .
* @param group the group of stats to watch
*/
public UpdateListener(OptionGroup group) {
_group = group;
}
/* (non-Javadoc)
* @see java.awt.event.ActionListener#actionPerformed(java.awt.event.ActionEvent)
*/
public void actionPerformed(ActionEvent evt) {
_config.disableEvents();
for (int i = 0; i < _group._statAttributes.size(); i++) {
JCheckBox box = (JCheckBox)_group._statAttributes.get(i);
_config.getSeriesConfig().setShouldPlotValue(_group.getStatName(), box.getText(), box.isSelected());
}
_config.enableEvents();
_config.fireUpdate();
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -44,70 +45,70 @@ import javax.servlet.http.HttpServletResponse;
*/
public class CheckSendStatusServlet extends PHTTPRelayServlet {
/* URL parameters on the check */
/** H(routerIdent).toBase64() of the target to receive the message */
public final static String PARAM_SEND_TARGET = "target";
public final static String PARAM_SEND_TARGET = "target";
/** msgId parameter */
public final static String PARAM_MSG_ID = "msgId";
public final static String PROP_STATUS = "status";
public final static String STATUS_PENDING = "pending";
public final static String STATUS_UNKNOWN = "unknown";
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String target = req.getParameter(PARAM_SEND_TARGET);
String msgIdStr = req.getParameter(PARAM_MSG_ID);
log("Checking status of [" + target + "] message [" + msgIdStr + "]");
if (!isKnownMessage(target, msgIdStr)) {
log("Not known - its not pending");
notPending(req, resp);
return;
} else {
log("Known - its still pending");
pending(req, resp);
return;
}
String target = req.getParameter(PARAM_SEND_TARGET);
String msgIdStr = req.getParameter(PARAM_MSG_ID);
log("Checking status of [" + target + "] message [" + msgIdStr + "]");
if (!isKnownMessage(target, msgIdStr)) {
log("Not known - its not pending");
notPending(req, resp);
return;
} else {
log("Known - its still pending");
pending(req, resp);
return;
}
}
private boolean isKnownMessage(String target, String msgId) throws IOException {
if ( (target == null) || (target.trim().length() <= 0) ) return false;
if ( (msgId == null) || (msgId.trim().length() <= 0) ) return false;
File identDir = getIdentDir(target);
if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat");
if (identFile.exists()) {
// known and valid (maybe we need to check the file format... naw, fuck it
File msgFile = new File(identDir, "msg" + msgId + ".dat");
if (msgFile.exists())
return true;
else
return false;
} else {
return false;
}
} else {
return false;
}
if ((target == null) || (target.trim().length() <= 0)) return false;
if ((msgId == null) || (msgId.trim().length() <= 0)) return false;
File identDir = getIdentDir(target);
if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat");
if (identFile.exists()) {
// known and valid (maybe we need to check the file format... naw, fuck it
File msgFile = new File(identDir, "msg" + msgId + ".dat");
if (msgFile.exists())
return true;
else
return false;
} else {
return false;
}
} else {
return false;
}
}
private void pending(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_PENDING).append('\n');
out.write(buf.toString().getBytes());
out.flush();
out.close();
resp.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_PENDING).append('\n');
out.write(buf.toString().getBytes());
out.flush();
out.close();
}
private void notPending(HttpServletRequest req, HttpServletResponse resp) throws IOException {
resp.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_UNKNOWN).append('\n');
out.write(buf.toString().getBytes());
out.flush();
out.close();
resp.setStatus(HttpServletResponse.SC_OK);
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_UNKNOWN).append('\n');
out.write(buf.toString().getBytes());
out.flush();
out.close();
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -18,23 +19,26 @@ import java.util.Set;
*/
class LockManager {
private volatile static Set _locks = new HashSet(); // target
public static void lockIdent(String target) {
while (true) {
synchronized (_locks) {
if (!_locks.contains(target)) {
_locks.add(target);
return;
}
try { _locks.wait(1000); } catch (InterruptedException ie) {}
}
}
while (true) {
synchronized (_locks) {
if (!_locks.contains(target)) {
_locks.add(target);
return;
}
try {
_locks.wait(1000);
} catch (InterruptedException ie) {
}
}
}
}
public static void unlockIdent(String target) {
synchronized (_locks) {
_locks.remove(target);
_locks.notifyAll();
}
synchronized (_locks) {
_locks.remove(target);
_locks.notifyAll();
}
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -8,16 +9,16 @@ package net.i2p.phttprelay;
*
*/
import net.i2p.util.Log;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import java.io.File;
import java.io.IOException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import net.i2p.util.Log;
abstract class PHTTPRelayServlet extends HttpServlet {
private Log _log = new Log(getClass());
protected String _baseDir;
@@ -25,49 +26,50 @@ abstract class PHTTPRelayServlet extends HttpServlet {
/* config params */
/*public final static String PARAM_BASEDIR = "baseDir";*/
public final static String ENV_BASEDIR = "phttpRelay.baseDir";
/** match the clock fudge factor on the router, rather than importing the entire router cvs module */
public final static long CLOCK_FUDGE_FACTOR = 1*60*1000;
public final static long CLOCK_FUDGE_FACTOR = 1 * 60 * 1000;
protected String buildURL(HttpServletRequest req, String path) {
StringBuffer buf = new StringBuffer();
buf.append(req.getScheme()).append("://");
buf.append(req.getServerName()).append(":").append(req.getServerPort());
buf.append(req.getContextPath());
buf.append(path);
log("URL built: " + buf.toString());
return buf.toString();
StringBuffer buf = new StringBuffer();
buf.append(req.getScheme()).append("://");
buf.append(req.getServerName()).append(":").append(req.getServerPort());
buf.append(req.getContextPath());
buf.append(path);
log("URL built: " + buf.toString());
return buf.toString();
}
protected File getIdentDir(String target) throws IOException {
if ( (_baseDir == null) || (target == null) ) throw new IOException("dir not specified to deal with");
File baseDir = new File(_baseDir);
if (!baseDir.exists()) {
boolean created = baseDir.mkdirs();
log("Creating PHTTP Relay Base Directory: " + baseDir.getAbsolutePath() + " - ok? " + created);
}
File identDir = new File(baseDir, target);
log("Ident dir: " + identDir.getAbsolutePath());
return identDir;
if ((_baseDir == null) || (target == null)) throw new IOException("dir not specified to deal with");
File baseDir = new File(_baseDir);
if (!baseDir.exists()) {
boolean created = baseDir.mkdirs();
log("Creating PHTTP Relay Base Directory: " + baseDir.getAbsolutePath() + " - ok? " + created);
}
File identDir = new File(baseDir, target);
log("Ident dir: " + identDir.getAbsolutePath());
return identDir;
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
String dir = System.getProperty(ENV_BASEDIR);
if (dir == null) {
_log.warn("Base directory for the polling http relay system not in the environment [" + ENV_BASEDIR +"]");
_log.warn("Setting the base directory to ./relayDir for " + getServletName());
_baseDir = ".relayDir";
} else {
_baseDir = dir;
log("Loaded up " + getServletName() + " with base directory " + _baseDir);
}
super.init(config);
String dir = System.getProperty(ENV_BASEDIR);
if (dir == null) {
_log.warn("Base directory for the polling http relay system not in the environment [" + ENV_BASEDIR + "]");
_log.warn("Setting the base directory to ./relayDir for " + getServletName());
_baseDir = ".relayDir";
} else {
_baseDir = dir;
log("Loaded up " + getServletName() + " with base directory " + _baseDir);
}
}
public void log(String msg) {
_log.debug(msg);
_log.debug(msg);
}
public void log(String msg, Throwable t) {
_log.debug(msg, t);
_log.debug(msg, t);
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -55,209 +56,208 @@ import net.i2p.util.Clock;
* baseDir is the directory under which registrants and their pending messages are stored
*
*/
public class PollServlet extends PHTTPRelayServlet {
public class PollServlet extends PHTTPRelayServlet {
/* URL parameters on the check */
/** H(routerIdent).toBase64() of the target to receive the message */
public final static String PARAM_SEND_TARGET = "target";
public final static String PARAM_SEND_TARGET = "target";
/** HTTP error code if the target is not known*/
public final static int CODE_UNKNOWN = HttpServletResponse.SC_NOT_FOUND;
/** HTTP error code if the signature failed */
public final static int CODE_UNAUTHORIZED = HttpServletResponse.SC_UNAUTHORIZED;
/** HTTP error code if everything is ok */
public final static int CODE_OK = HttpServletResponse.SC_OK;
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
byte data[] = getData(req);
if (data == null) return;
ByteArrayInputStream bais = new ByteArrayInputStream(data);
String target = getTarget(bais);
if (target == null) {
log("Target not specified");
resp.sendError(CODE_UNKNOWN);
return;
}
if (!isKnown(target)) {
resp.sendError(CODE_UNKNOWN);
return;
}
if (!isAuthorized(target, bais)) {
resp.sendError(CODE_UNAUTHORIZED);
return;
} else {
log("Authorized access for target " + target);
}
sendMessages(resp, target);
byte data[] = getData(req);
if (data == null) return;
ByteArrayInputStream bais = new ByteArrayInputStream(data);
String target = getTarget(bais);
if (target == null) {
log("Target not specified");
resp.sendError(CODE_UNKNOWN);
return;
}
if (!isKnown(target)) {
resp.sendError(CODE_UNKNOWN);
return;
}
if (!isAuthorized(target, bais)) {
resp.sendError(CODE_UNAUTHORIZED);
return;
} else {
log("Authorized access for target " + target);
}
sendMessages(resp, target);
}
private byte[] getData(HttpServletRequest req) throws ServletException, IOException {
ServletInputStream in = req.getInputStream();
int len = req.getContentLength();
byte data[] = new byte[len];
int cur = 0;
int read = DataHelper.read(in, data);
if (read != len) {
log("Size read is incorrect [" + read + " instead of expected " + len + "]");
return null;
} else {
log("Read data length: " + data.length + " in base64: " + Base64.encode(data));
return data;
}
ServletInputStream in = req.getInputStream();
int len = req.getContentLength();
byte data[] = new byte[len];
int cur = 0;
int read = DataHelper.read(in, data);
if (read != len) {
log("Size read is incorrect [" + read + " instead of expected " + len + "]");
return null;
} else {
log("Read data length: " + data.length + " in base64: " + Base64.encode(data));
return data;
}
}
private String getTarget(InputStream in) throws IOException {
StringBuffer buf = new StringBuffer(64);
int numBytes = 0;
int c = 0;
while ( (c = in.read()) != -1) {
if (c == (int)'&') break;
buf.append((char)c);
numBytes++;
if (numBytes > 128) {
log("Target didn't find the & after 128 bytes [" + buf.toString() + "]");
return null;
}
}
if (buf.toString().indexOf("target=") != 0) {
log("Did not start with target= [" + buf.toString() + "]");
return null;
}
return buf.substring("target=".length());
StringBuffer buf = new StringBuffer(64);
int numBytes = 0;
int c = 0;
while ((c = in.read()) != -1) {
if (c == (int) '&') break;
buf.append((char) c);
numBytes++;
if (numBytes > 128) {
log("Target didn't find the & after 128 bytes [" + buf.toString() + "]");
return null;
}
}
if (buf.toString().indexOf("target=") != 0) {
log("Did not start with target= [" + buf.toString() + "]");
return null;
}
return buf.substring("target=".length());
}
private void sendMessages(HttpServletResponse resp, String target) throws IOException {
log("Before lock " + target);
LockManager.lockIdent(target);
log("Locked " + target);
try {
File identDir = getIdentDir(target);
expire(identDir);
File messageFiles[] = identDir.listFiles();
resp.setStatus(CODE_OK);
log("Sending back " + (messageFiles.length -1) + " messages");
ServletOutputStream out = resp.getOutputStream();
DataHelper.writeDate(out, new Date(Clock.getInstance().now()));
DataHelper.writeLong(out, 2, messageFiles.length -1);
for (int i = 0; i < messageFiles.length; i++) {
if ("identity.dat".equals(messageFiles[i].getName())) {
// skip
} else {
log("Message file " + messageFiles[i].getName() + " is " + messageFiles[i].length() + " bytes");
DataHelper.writeLong(out, 4, messageFiles[i].length());
writeFile(out, messageFiles[i]);
boolean deleted = messageFiles[i].delete();
if (!deleted) {
log("!!!Error removing message file " + messageFiles[i].getAbsolutePath() + " - please delete!");
}
}
}
out.flush();
out.close();
} catch (DataFormatException dfe) {
log("Error sending message", dfe);
} finally {
LockManager.unlockIdent(target);
log("Unlocked " + target);
}
log("Before lock " + target);
LockManager.lockIdent(target);
log("Locked " + target);
try {
File identDir = getIdentDir(target);
expire(identDir);
File messageFiles[] = identDir.listFiles();
resp.setStatus(CODE_OK);
log("Sending back " + (messageFiles.length - 1) + " messages");
ServletOutputStream out = resp.getOutputStream();
DataHelper.writeDate(out, new Date(Clock.getInstance().now()));
DataHelper.writeLong(out, 2, messageFiles.length - 1);
for (int i = 0; i < messageFiles.length; i++) {
if ("identity.dat".equals(messageFiles[i].getName())) {
// skip
} else {
log("Message file " + messageFiles[i].getName() + " is " + messageFiles[i].length() + " bytes");
DataHelper.writeLong(out, 4, messageFiles[i].length());
writeFile(out, messageFiles[i]);
boolean deleted = messageFiles[i].delete();
if (!deleted) {
log("!!!Error removing message file " + messageFiles[i].getAbsolutePath() + " - please delete!");
}
}
}
out.flush();
out.close();
} catch (DataFormatException dfe) {
log("Error sending message", dfe);
} finally {
LockManager.unlockIdent(target);
log("Unlocked " + target);
}
}
private final static long EXPIRE_DELAY = 60*1000; // expire messages every minute
private final static long EXPIRE_DELAY = 60 * 1000; // expire messages every minute
private void expire(File identDir) throws IOException {
File files[] = identDir.listFiles();
long now = System.currentTimeMillis();
for (int i = 0 ; i < files.length; i++) {
if ("identity.dat".equals(files[i].getName())) {
continue;
}
if (files[i].lastModified() + EXPIRE_DELAY < now) {
log("Expiring " + files[i].getAbsolutePath());
files[i].delete();
}
}
File files[] = identDir.listFiles();
long now = System.currentTimeMillis();
for (int i = 0; i < files.length; i++) {
if ("identity.dat".equals(files[i].getName())) {
continue;
}
if (files[i].lastModified() + EXPIRE_DELAY < now) {
log("Expiring " + files[i].getAbsolutePath());
files[i].delete();
}
}
}
private void writeFile(ServletOutputStream out, File file) throws IOException {
FileInputStream fis = new FileInputStream(file);
try {
byte buf[] = new byte[4096];
while (true) {
int read = DataHelper.read(fis, buf);
if (read > 0)
out.write(buf, 0, read);
else
break;
}
} finally {
fis.close();
}
FileInputStream fis = new FileInputStream(file);
try {
byte buf[] = new byte[4096];
while (true) {
int read = DataHelper.read(fis, buf);
if (read > 0)
out.write(buf, 0, read);
else
break;
}
} finally {
fis.close();
}
}
private boolean isKnown(String target) throws IOException {
File identDir = getIdentDir(target);
if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat");
if (identFile.exists()) {
// known and valid (maybe we need to check the file format... naw, fuck it
return true;
} else {
return false;
}
} else {
return false;
}
File identDir = getIdentDir(target);
if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat");
if (identFile.exists()) {
// known and valid (maybe we need to check the file format... naw, fuck it
return true;
} else {
return false;
}
} else {
return false;
}
}
private boolean isAuthorized(String target, InputStream in) throws IOException {
RouterIdentity ident = null;
try {
ident = getRouterIdentity(target);
} catch (DataFormatException dfe) {
log("Identity was not valid", dfe);
}
if (ident == null) {
log("Identity not registered");
return false;
}
try {
long val = DataHelper.readLong(in, 4);
Signature sig = new Signature();
sig.readBytes(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataHelper.writeLong(baos, 4, val);
if (DSAEngine.getInstance().verifySignature(sig, baos.toByteArray(), ident.getSigningPublicKey())) {
return true;
} else {
log("Signature does NOT match");
return false;
}
} catch (DataFormatException dfe) {
log("Format error reading the nonce and signature", dfe);
return false;
}
RouterIdentity ident = null;
try {
ident = getRouterIdentity(target);
} catch (DataFormatException dfe) {
log("Identity was not valid", dfe);
}
if (ident == null) {
log("Identity not registered");
return false;
}
try {
long val = DataHelper.readLong(in, 4);
Signature sig = new Signature();
sig.readBytes(in);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
DataHelper.writeLong(baos, 4, val);
if (DSAEngine.getInstance().verifySignature(sig, baos.toByteArray(), ident.getSigningPublicKey())) {
return true;
} else {
log("Signature does NOT match");
return false;
}
} catch (DataFormatException dfe) {
log("Format error reading the nonce and signature", dfe);
return false;
}
}
private RouterIdentity getRouterIdentity(String target) throws IOException, DataFormatException {
File identDir = getIdentDir(target);
if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat");
if (identFile.exists()) {
// known and valid (maybe we need to check the file format... naw, fuck it
RouterIdentity ident = new RouterIdentity();
ident.readBytes(new FileInputStream(identFile));
return ident;
} else {
return null;
}
} else {
return null;
}
File identDir = getIdentDir(target);
if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat");
if (identFile.exists()) {
// known and valid (maybe we need to check the file format... naw, fuck it
RouterIdentity ident = new RouterIdentity();
ident.readBytes(new FileInputStream(identFile));
return ident;
} else {
return null;
}
} else {
return null;
}
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -66,89 +67,92 @@ public class RegisterServlet extends PHTTPRelayServlet {
/* config params */
public final static String PARAM_POLL_PATH = "pollPath";
public final static String PARAM_SEND_PATH = "sendPath";
/* key=val keys sent back on registration */
public final static String PROP_STATUS = "status";
public final static String PROP_STATUS = "status";
public final static String PROP_POLL_URL = "pollURL";
public final static String PROP_SEND_URL = "sendURL";
public final static String PROP_TIME_OFFSET = "timeOffset"; // ms (local-remote)
/* values for the PROP_STATUS */
public final static String STATUS_FAILED = "failed";
public final static String STATUS_FAILED = "failed";
public final static String STATUS_REGISTERED = "registered";
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream in = req.getInputStream();
RouterIdentity ident = new RouterIdentity();
try {
Date remoteTime = DataHelper.readDate(in);
long skew = getSkew(remoteTime);
ident.readBytes(in);
boolean ok = registerIdent(ident);
sendURLs(req, resp, skew, ok);
} catch (DataFormatException dfe) {
log("Invalid format for router identity posted", dfe);
} finally {
in.close();
}
}
private long getSkew(Date remoteDate) {
if (remoteDate == null) {
log("*ERROR: remote date was null");
return Long.MAX_VALUE;
} else {
long diff = Clock.getInstance().now() - remoteDate.getTime();
return diff;
}
}
private boolean registerIdent(RouterIdentity ident) throws DataFormatException, IOException {
File identDir = getIdentDir(ident.getHash().toBase64());
boolean created = identDir.mkdirs();
File identFile = new File(identDir, "identity.dat");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(identFile);
ident.writeBytes(fos);
} finally {
if (fos != null) try { fos.close(); } catch (IOException ioe) {}
}
log("Identity registered into " + identFile.getAbsolutePath());
return true;
}
private void sendURLs(HttpServletRequest req, HttpServletResponse resp, long skew, boolean ok) throws IOException {
ServletOutputStream out = resp.getOutputStream();
log("*Debug: clock skew of " + skew + "ms (local-remote)");
StringBuffer buf = new StringBuffer();
if (ok) {
buf.append(PROP_POLL_URL).append("=").append(buildURL(req, _pollPath)).append("\n");
buf.append(PROP_SEND_URL).append("=").append(buildURL(req, _sendPath)).append("\n");
buf.append(PROP_TIME_OFFSET).append("=").append(skew).append("\n");
buf.append(PROP_STATUS).append("=").append(STATUS_REGISTERED).append("\n");
} else {
buf.append(PROP_TIME_OFFSET).append("=").append(skew).append("\n");
buf.append(PROP_STATUS).append("=").append(STATUS_FAILED).append("\n");
}
out.write(buf.toString().getBytes());
out.close();
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream in = req.getInputStream();
RouterIdentity ident = new RouterIdentity();
try {
Date remoteTime = DataHelper.readDate(in);
long skew = getSkew(remoteTime);
ident.readBytes(in);
boolean ok = registerIdent(ident);
sendURLs(req, resp, skew, ok);
} catch (DataFormatException dfe) {
log("Invalid format for router identity posted", dfe);
} finally {
in.close();
}
}
private long getSkew(Date remoteDate) {
if (remoteDate == null) {
log("*ERROR: remote date was null");
return Long.MAX_VALUE;
} else {
long diff = Clock.getInstance().now() - remoteDate.getTime();
return diff;
}
}
private boolean registerIdent(RouterIdentity ident) throws DataFormatException, IOException {
File identDir = getIdentDir(ident.getHash().toBase64());
boolean created = identDir.mkdirs();
File identFile = new File(identDir, "identity.dat");
FileOutputStream fos = null;
try {
fos = new FileOutputStream(identFile);
ident.writeBytes(fos);
} finally {
if (fos != null) try {
fos.close();
} catch (IOException ioe) {
}
}
log("Identity registered into " + identFile.getAbsolutePath());
return true;
}
private void sendURLs(HttpServletRequest req, HttpServletResponse resp, long skew, boolean ok) throws IOException {
ServletOutputStream out = resp.getOutputStream();
log("*Debug: clock skew of " + skew + "ms (local-remote)");
StringBuffer buf = new StringBuffer();
if (ok) {
buf.append(PROP_POLL_URL).append("=").append(buildURL(req, _pollPath)).append("\n");
buf.append(PROP_SEND_URL).append("=").append(buildURL(req, _sendPath)).append("\n");
buf.append(PROP_TIME_OFFSET).append("=").append(skew).append("\n");
buf.append(PROP_STATUS).append("=").append(STATUS_REGISTERED).append("\n");
} else {
buf.append(PROP_TIME_OFFSET).append("=").append(skew).append("\n");
buf.append(PROP_STATUS).append("=").append(STATUS_FAILED).append("\n");
}
out.write(buf.toString().getBytes());
out.close();
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
String pollPath = config.getInitParameter(PARAM_POLL_PATH);
if (pollPath == null)
throw new ServletException("Polling path for the registration servlet required [" + PARAM_POLL_PATH + "]");
else
_pollPath = pollPath;
String sendPath = config.getInitParameter(PARAM_SEND_PATH);
if (sendPath == null)
throw new ServletException("Sending path for the registration servlet required [" + PARAM_SEND_PATH + "]");
else
_sendPath = sendPath;
super.init(config);
String pollPath = config.getInitParameter(PARAM_POLL_PATH);
if (pollPath == null)
throw new ServletException("Polling path for the registration servlet required [" + PARAM_POLL_PATH + "]");
else
_pollPath = pollPath;
String sendPath = config.getInitParameter(PARAM_SEND_PATH);
if (sendPath == null)
throw new ServletException("Sending path for the registration servlet required [" + PARAM_SEND_PATH + "]");
else
_sendPath = sendPath;
}
}
}

View File

@@ -1,4 +1,5 @@
package net.i2p.phttprelay;
/*
* free (adj.): unencumbered; not under the control of others
* Written by jrandom in 2003 and released into the public domain
@@ -63,256 +64,261 @@ import javax.servlet.http.HttpServletResponse;
public class SendServlet extends PHTTPRelayServlet {
private String _checkPath;
private int _maxMessagesPerIdent;
/* config params */
public final static String PARAM_CHECK_PATH = "checkPath";
public final static String PARAM_MAX_MESSAGES_PER_IDENT = "maxMessagesPerIdent";
/* URL parameters on the send */
/** H(routerIdent).toBase64() of the target to receive the message */
public final static String PARAM_SEND_TARGET = "target";
public final static String PARAM_SEND_TARGET = "target";
/** # ms to wait for the message to be delivered before failing it */
public final static String PARAM_SEND_TIMEOUTMS = "timeoutMs";
/** # bytes to be sent in the message */
public final static String PARAM_SEND_DATA_LENGTH = "dataLength";
/** sending router's time in ms */
public final static String PARAM_SEND_TIME = "localTime";
/** msgId parameter to access the check path servlet with (along side PARAM_SEND_TARGET) */
public final static String PARAM_MSG_ID = "msgId";
/* key=val keys sent back on registration */
public final static String PROP_CHECK_URL = "statusCheckURL";
public final static String PROP_STATUS = "status";
public final static String STATUS_OK = "accepted";
public final static String STATUS_UNKNOWN = "unknown";
private final static String STATUS_CLOCKSKEW = "clockSkew_"; /** prefix for (local-remote) */
private final static String STATUS_CLOCKSKEW = "clockSkew_";
/** prefix for (local-remote) */
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletInputStream in = req.getInputStream();
try {
int contentLen = req.getContentLength();
String firstLine = getFirstLine(in, contentLen);
if (firstLine == null) {
return;
}
Map params = getParameters(firstLine);
String target = (String)params.get(PARAM_SEND_TARGET);
String timeoutStr = (String)params.get(PARAM_SEND_TIMEOUTMS);
String lenStr = (String)params.get(PARAM_SEND_DATA_LENGTH);
String remoteTimeStr = (String)params.get(PARAM_SEND_TIME);
long skew = 0;
try {
long remTime = Long.parseLong(remoteTimeStr);
skew = System.currentTimeMillis() - remTime;
} catch (Throwable t) {
skew = Long.MAX_VALUE;
log("*ERROR could not parse the remote time from [" + remoteTimeStr + "]");
}
ServletInputStream in = req.getInputStream();
try {
int contentLen = req.getContentLength();
String firstLine = getFirstLine(in, contentLen);
if (firstLine == null) { return; }
Map params = getParameters(firstLine);
String target = (String) params.get(PARAM_SEND_TARGET);
String timeoutStr = (String) params.get(PARAM_SEND_TIMEOUTMS);
String lenStr = (String) params.get(PARAM_SEND_DATA_LENGTH);
String remoteTimeStr = (String) params.get(PARAM_SEND_TIME);
long skew = 0;
try {
long remTime = Long.parseLong(remoteTimeStr);
skew = System.currentTimeMillis() - remTime;
} catch (Throwable t) {
skew = Long.MAX_VALUE;
log("*ERROR could not parse the remote time from [" + remoteTimeStr + "]");
}
log("Target [" + target + "] timeout [" + timeoutStr + "] length [" + lenStr + "] skew [" + skew + "]");
log("Target [" + target + "] timeout [" + timeoutStr + "] length [" + lenStr + "] skew [" + skew + "]");
if ( (skew > CLOCK_FUDGE_FACTOR) || (skew < 0 - CLOCK_FUDGE_FACTOR) ) {
log("Attempt to send by a skewed router: skew = " + skew + "ms (local-remote)");
failSkewed(req, resp, skew);
}
if (!isValidTarget(target)) {
log("Attempt to send to an invalid target [" + target + "]");
fail(req, resp, "Unknown or invalid target");
return;
}
if ((skew > CLOCK_FUDGE_FACTOR) || (skew < 0 - CLOCK_FUDGE_FACTOR)) {
log("Attempt to send by a skewed router: skew = " + skew + "ms (local-remote)");
failSkewed(req, resp, skew);
}
long len = -1;
try {
len = Long.parseLong(lenStr);
} catch (Throwable t) {
log("Unable to parse length parameter [" + PARAM_SEND_DATA_LENGTH + "] (" + lenStr + ")");
fail(req, resp, "Invalid length parameter");
return;
}
if (!isValidTarget(target)) {
log("Attempt to send to an invalid target [" + target + "]");
fail(req, resp, "Unknown or invalid target");
return;
}
int msgId = saveFile(in, resp, target, len);
if (msgId >= 0) {
sendSuccess(req, resp, target, msgId);
} else {
fail(req, resp, "Unable to queue up the message for delivery");
}
} finally {
try { in.close(); } catch (IOException ioe) {}
}
long len = -1;
try {
len = Long.parseLong(lenStr);
} catch (Throwable t) {
log("Unable to parse length parameter [" + PARAM_SEND_DATA_LENGTH + "] (" + lenStr + ")");
fail(req, resp, "Invalid length parameter");
return;
}
int msgId = saveFile(in, resp, target, len);
if (msgId >= 0) {
sendSuccess(req, resp, target, msgId);
} else {
fail(req, resp, "Unable to queue up the message for delivery");
}
} finally {
try {
in.close();
} catch (IOException ioe) {
}
}
}
private String getFirstLine(ServletInputStream in, int len) throws ServletException, IOException {
StringBuffer buf = new StringBuffer(128);
int numBytes = 0;
int c = 0;
while ( (c = in.read()) != -1) {
if (c == (int)'\n') break;
buf.append((char)c);
numBytes++;
if (numBytes > 512) {
log("First line is > 512 bytes [" + buf.toString() + "]");
return null;
}
}
log("First line: " + buf.toString());
return buf.toString();
StringBuffer buf = new StringBuffer(128);
int numBytes = 0;
int c = 0;
while ((c = in.read()) != -1) {
if (c == (int) '\n') break;
buf.append((char) c);
numBytes++;
if (numBytes > 512) {
log("First line is > 512 bytes [" + buf.toString() + "]");
return null;
}
}
log("First line: " + buf.toString());
return buf.toString();
}
private static Map getParameters(String line) {
//StringTokenizer tok = new StringTokenizer(line, "&=", true);
Map params = new HashMap();
while (line != null) {
String key = null;
String val = null;
int firstAmp = line.indexOf('&');
int firstEq = line.indexOf('=');
if (firstAmp > 0) {
key = line.substring(0, firstEq);
val = line.substring(firstEq+1, firstAmp);
line = line.substring(firstAmp+1);
params.put(key, val);
} else {
line = null;
}
}
return params;
//StringTokenizer tok = new StringTokenizer(line, "&=", true);
Map params = new HashMap();
while (line != null) {
String key = null;
String val = null;
int firstAmp = line.indexOf('&');
int firstEq = line.indexOf('=');
if (firstAmp > 0) {
key = line.substring(0, firstEq);
val = line.substring(firstEq + 1, firstAmp);
line = line.substring(firstAmp + 1);
params.put(key, val);
} else {
line = null;
}
}
return params;
}
private boolean isValidTarget(String target) throws IOException {
File identDir = getIdentDir(target);
if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat");
if (identFile.exists()) {
// known and valid (maybe we need to check the file format... naw, fuck it
String files[] = identDir.list();
// we skip 1 because of identity.dat
if (files.length -1 > _maxMessagesPerIdent) {
log("Too many messages pending for " + target + ": " + (files.length-1));
return false;
} else {
return true;
}
} else {
log("Ident directory exists, but identity does not... corrupt for " + target);
return false;
}
} else {
log("Unknown ident " + target);
return false;
}
File identDir = getIdentDir(target);
if (identDir.exists()) {
File identFile = new File(identDir, "identity.dat");
if (identFile.exists()) {
// known and valid (maybe we need to check the file format... naw, fuck it
String files[] = identDir.list();
// we skip 1 because of identity.dat
if (files.length - 1 > _maxMessagesPerIdent) {
log("Too many messages pending for " + target + ": " + (files.length - 1));
return false;
} else {
return true;
}
} else {
log("Ident directory exists, but identity does not... corrupt for " + target);
return false;
}
} else {
log("Unknown ident " + target);
return false;
}
}
private int saveFile(InputStream in, HttpServletResponse resp, String target, long len) throws IOException {
File identDir = getIdentDir(target);
if (!identDir.exists()) return -1;
try {
LockManager.lockIdent(target);
int i = 0;
while (true) {
File curFile = new File(identDir, "msg" + i + ".dat");
if (!curFile.exists()) {
boolean ok = writeFile(curFile, in, len);
if (ok)
return i;
else
return -1;
}
i++;
continue;
}
} finally {
LockManager.unlockIdent(target);
}
File identDir = getIdentDir(target);
if (!identDir.exists()) return -1;
try {
LockManager.lockIdent(target);
int i = 0;
while (true) {
File curFile = new File(identDir, "msg" + i + ".dat");
if (!curFile.exists()) {
boolean ok = writeFile(curFile, in, len);
if (ok)
return i;
else
return -1;
}
i++;
continue;
}
} finally {
LockManager.unlockIdent(target);
}
}
private boolean writeFile(File file, InputStream in, long len) throws IOException {
long remaining = len;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
byte buf[] = new byte[4096];
while (remaining > 0) {
int read = in.read(buf);
if (read == -1)
break;
remaining -= read;
if (read > 0)
fos.write(buf, 0, read);
}
} finally {
if (fos != null) {
try { fos.close(); } catch (IOException ioe) {}
}
if (remaining != 0) {
log("Invalid remaining bytes [" + remaining + " out of " + len + "] - perhaps message was cancelled partway through delivery? deleting " + file.getAbsolutePath());
boolean deleted = file.delete();
if (!deleted)
log("!!!Error deleting temporary file " + file.getAbsolutePath());
return false;
}
}
return true;
long remaining = len;
FileOutputStream fos = null;
try {
fos = new FileOutputStream(file);
byte buf[] = new byte[4096];
while (remaining > 0) {
int read = in.read(buf);
if (read == -1) break;
remaining -= read;
if (read > 0) fos.write(buf, 0, read);
}
} finally {
if (fos != null) {
try {
fos.close();
} catch (IOException ioe) {
}
}
if (remaining != 0) {
log("Invalid remaining bytes [" + remaining + " out of " + len
+ "] - perhaps message was cancelled partway through delivery? deleting " + file.getAbsolutePath());
boolean deleted = file.delete();
if (!deleted) log("!!!Error deleting temporary file " + file.getAbsolutePath());
return false;
}
}
return true;
}
private void sendSuccess(HttpServletRequest req, HttpServletResponse resp, String target, int msgId) throws IOException {
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_OK).append('\n');
buf.append(PROP_CHECK_URL).append('=').append(buildURL(req, _checkPath));
buf.append('?');
buf.append(PARAM_SEND_TARGET).append('=').append(target).append("&");
buf.append(PARAM_MSG_ID).append('=').append(msgId).append("\n");
out.write(buf.toString().getBytes());
out.flush();
private void sendSuccess(HttpServletRequest req, HttpServletResponse resp, String target, int msgId)
throws IOException {
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_OK).append('\n');
buf.append(PROP_CHECK_URL).append('=').append(buildURL(req, _checkPath));
buf.append('?');
buf.append(PARAM_SEND_TARGET).append('=').append(target).append("&");
buf.append(PARAM_MSG_ID).append('=').append(msgId).append("\n");
out.write(buf.toString().getBytes());
out.flush();
}
private void fail(HttpServletRequest req, HttpServletResponse resp, String err) throws IOException {
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_UNKNOWN).append('\n');
out.write(buf.toString().getBytes());
out.flush();
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_UNKNOWN).append('\n');
out.write(buf.toString().getBytes());
out.flush();
}
private void failSkewed(HttpServletRequest req, HttpServletResponse resp, long skew) throws IOException {
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_CLOCKSKEW).append(skew).append('\n');
out.write(buf.toString().getBytes());
out.flush();
ServletOutputStream out = resp.getOutputStream();
StringBuffer buf = new StringBuffer();
buf.append(PROP_STATUS).append('=').append(STATUS_CLOCKSKEW).append(skew).append('\n');
out.write(buf.toString().getBytes());
out.flush();
}
public void init(ServletConfig config) throws ServletException {
super.init(config);
String checkPath = config.getInitParameter(PARAM_CHECK_PATH);
if (checkPath == null)
throw new ServletException("Check status path for the sending servlet required [" + PARAM_CHECK_PATH + "]");
else
_checkPath = checkPath;
String maxMessagesPerIdentStr = config.getInitParameter(PARAM_MAX_MESSAGES_PER_IDENT);
if (maxMessagesPerIdentStr == null)
throw new ServletException("Max messages per ident for the sending servlet required [" + PARAM_MAX_MESSAGES_PER_IDENT + "]");
try {
_maxMessagesPerIdent = Integer.parseInt(maxMessagesPerIdentStr);
} catch (Throwable t) {
throw new ServletException("Valid max messages per ident for the sending servlet required [" + PARAM_MAX_MESSAGES_PER_IDENT + "]");
}
super.init(config);
String checkPath = config.getInitParameter(PARAM_CHECK_PATH);
if (checkPath == null)
throw new ServletException("Check status path for the sending servlet required [" + PARAM_CHECK_PATH + "]");
else
_checkPath = checkPath;
String maxMessagesPerIdentStr = config.getInitParameter(PARAM_MAX_MESSAGES_PER_IDENT);
if (maxMessagesPerIdentStr == null)
throw new ServletException("Max messages per ident for the sending servlet required ["
+ PARAM_MAX_MESSAGES_PER_IDENT + "]");
try {
_maxMessagesPerIdent = Integer.parseInt(maxMessagesPerIdentStr);
} catch (Throwable t) {
throw new ServletException("Valid max messages per ident for the sending servlet required ["
+ PARAM_MAX_MESSAGES_PER_IDENT + "]");
}
}
public static void main(String args[]) {
String line = "target=pp0ARjQiB~IKC-0FsMUsPEMrwR3gxVBZGRYfEr1IzHI=&timeoutMs=52068&dataLength=2691&";
Map props = getParameters(line);
for (java.util.Iterator iter = props.keySet().iterator(); iter.hasNext(); ) {
String key = (String)iter.next();
String val = (String)props.get(key);
System.out.println("[" + key + "] = [" + val + "]");
}
String line = "target=pp0ARjQiB~IKC-0FsMUsPEMrwR3gxVBZGRYfEr1IzHI=&timeoutMs=52068&dataLength=2691&";
Map props = getParameters(line);
for (java.util.Iterator iter = props.keySet().iterator(); iter.hasNext();) {
String key = (String) iter.next();
String val = (String) props.get(key);
System.out.println("[" + key + "] = [" + val + "]");
}
}
}
}

3957
apps/sam/code.leo Normal file

File diff suppressed because it is too large Load Diff

View File

@@ -0,0 +1,58 @@
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]

View File

@@ -0,0 +1,50 @@
using System;
using System.Net;
using System.Threading;
using System.Text;
using System.Collections;
namespace SAM.NET
{
class SAMTester
{
[STAThread]
static void Main(string[] args)
{
new SAMTester();
}
public SAMTester ()
{
SAMConnection connection1 = new SAMConnection(IPAddress.Parse("127.0.0.1"),7656);
SAMSession session1 = new SAMSession(connection1,SAM.NET.SamSocketType.Stream,"alice");
SAMConnection connection2 = new SAMConnection(IPAddress.Parse("127.0.0.1"),7656);
SAMSession session2 = new SAMSession(connection2,SAM.NET.SamSocketType.Stream,"bob");
SAMStream stream1 = new SAMStream(connection1,session1,233);
stream1.Connect(session2.getKey());
//Wait till we are connected to destination
while (!stream1.isConnected)
Thread.Sleep(1000);
//Send some bytes
stream1.Write(Encoding.ASCII.GetBytes(DateTime.Now.ToLongTimeString() + "Hi!!!!!!"));
//Wait till a stream magically appears on the other side
while (session2.getStreams().Count == 0) Thread.Sleep(1000);
Thread.Sleep(1000);
foreach (SAMStream stream in session2.getStreams().Values)
{
Console.WriteLine("Text received on " + stream.getID() + " at " + DateTime.Now.ToLongTimeString());
Console.WriteLine(Encoding.ASCII.GetString(stream.ReadToEnd()));
stream.Close();
}
stream1.Close();
connection1.Close();
connection2.Close();
}
}
}

View File

@@ -0,0 +1,58 @@
using System.Reflection;
using System.Runtime.CompilerServices;
//
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
//
[assembly: AssemblyTitle("")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("")]
[assembly: AssemblyCopyright("")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
//
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.*")]
//
// In order to sign your assembly you must specify a key to use. Refer to the
// Microsoft .NET Framework documentation for more information on assembly signing.
//
// Use the attributes below to control which key is used for signing.
//
// Notes:
// (*) If no key is specified, the assembly is not signed.
// (*) KeyName refers to a key that has been installed in the Crypto Service
// Provider (CSP) on your machine. KeyFile refers to a file which contains
// a key.
// (*) If the KeyFile and the KeyName values are both specified, the
// following processing occurs:
// (1) If the KeyName can be found in the CSP, that key is used.
// (2) If the KeyName does not exist and the KeyFile does exist, the key
// in the KeyFile is installed into the CSP and used.
// (*) In order to create a KeyFile, you can use the sn.exe (Strong Name) utility.
// When specifying the KeyFile, the location of the KeyFile should be
// relative to the project output directory which is
// %Project Directory%\obj\<configuration>. For example, if your KeyFile is
// located in the project directory, you would specify the AssemblyKeyFile
// attribute as [assembly: AssemblyKeyFile("..\\..\\mykey.snk")]
// (*) Delay Signing is an advanced option - see the Microsoft .NET Framework
// documentation for more information on this.
//
[assembly: AssemblyDelaySign(false)]
[assembly: AssemblyKeyFile("")]
[assembly: AssemblyKeyName("")]

View File

@@ -0,0 +1,271 @@
using System;
using System.Net.Sockets;
using System.Text;
using System.Net;
using System.IO;
using System.Collections;
using System.Threading;
namespace SAM.NET
{
public enum SamSocketType
{
Stream,
Datagram,
Raw
}
public class SAMConnection
{
private const string propertyMinVersion = "1.0";
private const string propertyMaxVersion = "1.0";
private Socket _sock;
private NetworkStream _sockStream;
private StreamReader _sockStreamIn;
private StreamWriter _sockStreamOut;
public SAMConnection(IPAddress routerIP, int port)
{
_sock = new Socket(AddressFamily.InterNetwork,SocketType.Stream,ProtocolType.Tcp);
IPEndPoint rEP = new IPEndPoint(routerIP,port);
_sock.Connect(rEP);
_sockStream = new NetworkStream(_sock);
_sockStreamIn = new StreamReader(_sockStream);
_sockStreamOut = new StreamWriter(_sockStream);
try
{
sendVersion(propertyMinVersion,propertyMinVersion);
}
catch (Exception e)
{
_sock.Close();
throw (new Exception("No SAM for you :("));
}
}
private void sendVersion(string min, string max)
{
_sockStreamOut.WriteLine("HELLO VERSION MIN=" + propertyMinVersion + " MAX=" + propertyMaxVersion);
_sockStreamOut.Flush();
Hashtable response = SAMUtil.parseKeyValues(_sockStreamIn.ReadLine(),2);
if (response["RESULT"].ToString() != "OK") throw (new Exception("Version mismatch"));
}
public StreamWriter getOutputStream()
{
return _sockStreamOut;
}
public StreamReader getInputStream()
{
return _sockStreamIn;
}
public NetworkStream getStream()
{
return _sockStream;
}
public void Close()
{
_sock.Close();
}
}
/*
* Creating a SAMSession object will automatically:
* 1) create a sesion on SAM
* 1) query for the base64key
* 2) start a listening thread to catch all stream commands
*/
public class SAMSession
{
private Hashtable _streams;
private string _sessionKey;
public SAMSession (SAMConnection connection, SamSocketType type, string destination)
{
_streams = new Hashtable();
StreamWriter writer = connection.getOutputStream();
StreamReader reader = connection.getInputStream();
writer.WriteLine("SESSION CREATE STYLE=STREAM DESTINATION=" + destination);
writer.Flush();
Hashtable response = SAMUtil.parseKeyValues(reader.ReadLine(),2);
if (response["RESULT"].ToString() != "OK")
{
throw (new Exception(response["MESSAGE"].ToString()));
}
else
{
writer.WriteLine("NAMING LOOKUP NAME=ME");
writer.Flush();
response = SAMUtil.parseKeyValues(reader.ReadLine(),2);
_sessionKey = response["VALUE"].ToString();
SAMSessionListener listener = new SAMSessionListener(connection,this,_streams);
new Thread(new ThreadStart(listener.startListening)).Start();
}
}
public void addStream(SAMStream stream)
{
_streams.Add(stream.getID(),stream);
}
public string getKey()
{
return _sessionKey;
}
public Hashtable getStreams()
{
return _streams;
}
}
public class SAMSessionListener
{
private Hashtable _streams;
private SAMConnection _connection;
private SAMSession _session;
private bool stayAlive = true;
public SAMSessionListener(SAMConnection connection,SAMSession session, Hashtable streams)
{
_streams = streams;
_connection = connection;
_session = session;
}
public void startListening()
{
StreamReader reader = _connection.getInputStream();
while (stayAlive)
{
string response = reader.ReadLine();
if (response.StartsWith("STREAM STATUS"))
{
Hashtable values = SAMUtil.parseKeyValues(response,2);
SAMStream theStream = (SAMStream)_streams[int.Parse(values["ID"].ToString())];
if (theStream != null) theStream.ReceivedStatus(values);
}
if (response.StartsWith("STREAM CONNECTED"))
{
Hashtable values = SAMUtil.parseKeyValues(response,2);
SAMStream theStream = (SAMStream)_streams[int.Parse(values["ID"].ToString())];
if (theStream != null) theStream.isConnected = true;
}
if (response.StartsWith("STREAM RECEIVED"))
{
Hashtable values = SAMUtil.parseKeyValues(response,2);
int streamID = int.Parse(values["ID"].ToString());
SAMStream theStream = (SAMStream)_streams[streamID];
if (theStream == null) new SAMStream(_connection,_session,streamID);
theStream = (SAMStream)_streams[streamID];
theStream.ReceivedData(int.Parse(values["SIZE"].ToString()));
}
if (response.StartsWith("STREAM CLOSE"))
{
Hashtable values = SAMUtil.parseKeyValues(response,2);
SAMStream theStream = (SAMStream)_streams[int.Parse(values["ID"].ToString())];
if (theStream != null) theStream.isConnected = false;
}
}
}
}
public class SAMStream
{
private int _ID;
private byte[] _data;
private int _position=0;
private int _size=0;
private SAMSession _session;
private SAMConnection _connection;
public bool isConnected=false;
public SAMStream (SAMConnection connection,SAMSession session, int ID)
{
_data = new byte[100000]; //FIXME: change to non-static structure for storing stream data
_ID = ID;
_connection = connection;
_session = session;
_session.addStream(this);
}
public void Connect(string destination)
{
StreamWriter writer = _connection.getOutputStream();
writer.WriteLine("STREAM CONNECT ID=" + _ID.ToString() + " DESTINATION=" + destination);
writer.Flush();
}
public void ReceivedData(int size) //FIXME: WTF is going on when reading the payload here? All zeros and way too many of them.
{
NetworkStream stream = _connection.getStream();
int bytesRead = stream.Read(_data,_size,size);
_size = _size + bytes;
}
public void ReceivedStatus(Hashtable response)
{
if (response["RESULT"].ToString() != "OK")
{
throw (new Exception(response["RESULT"].ToString()));
}
else
{
isConnected = true;
}
}
public int getID() {return _ID;}
public bool DataAvailable()
{
return _position != _size;
}
public void Write(byte[] buf)
{
NetworkStream stream = _connection.getStream();
int sent = 0;
while (sent < buf.Length)
{
int toSend = Math.Min(buf.Length - sent,32768);
string header = "STREAM SEND ID=" + _ID.ToString() + " SIZE=" + toSend.ToString() + "\n";
byte[] headerbytes = Encoding.ASCII.GetBytes(header);
stream.Write(headerbytes,0,headerbytes.Length);
stream.Write(buf,sent,toSend);
sent = sent + toSend;
}
}
public byte[] ReadToEnd()
{
byte[] ret = new byte[_size - _position];
Array.Copy(_data,_position,ret,0,_size - _position);
_position = _size;
return ret;
}
public void Close()
{
StreamWriter writer = _connection.getOutputStream();
writer.WriteLine("STREAM CLOSE " + _ID.ToString());
writer.Flush();
}
}
public class SAMUtil
{
public static Hashtable parseKeyValues(string str, int startingWord)
{
Hashtable hash = new Hashtable();
string strTruncated = string.Join(" ",str.Split(' '),startingWord,str.Split(' ').Length - startingWord);
string[] sets = strTruncated.Split('=',' ');
for (int i=0; i<sets.Length; i=i+2)
{
hash.Add(sets[i],sets[i+1]);
}
return hash;
}
}
}

27
apps/sam/doc/README Normal file
View File

@@ -0,0 +1,27 @@
SAM - Simple Anonymous Messaging - is a protocol which allows
I2P applications to access the I2P network via an unencrypted
TCP socket connection.
Interim SAM protocol specification can be found at:
http://drupal.i2p.net/node/view/144
At time of first writing this README, an implementation of the SAM
server has been implemented in Jython (www.jython.org).
You can find the server code, and build files, in the ../jython
directory.
A python client implementation, containing demo functions,
can be found in the ../python directory.
I2P developers are strongly encouraged to create SAM
client implementations in other languages, most importantly,
popular portable languages like C/C++, Perl and Ruby.
The 'code.leo' file in this directory is used by the Leo
code editor (http://leo.sf.net), to manage the source in a
flexible tree format. While I can't insist on it, I'd
massively appreciate it if you could use this editor when
making additions and changes to the files herein, because
it will save me a lot of maintenance effort.

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