use of net.i2p.data.Destination in project i2p.i2p by i2p.
the class StreamSinkClient method runClient.
/**
* Actually connect and run the client - this call blocks until completion.
*/
public void runClient() {
I2PSocketManager mgr = null;
if (_i2cpHost != null)
mgr = I2PSocketManagerFactory.createManager(_i2cpHost, _i2cpPort, new Properties());
else
mgr = I2PSocketManagerFactory.createManager();
Destination peer = null;
FileInputStream fis = null;
try {
fis = new FileInputStream(_peerDestFile);
peer = new Destination();
peer.readBytes(fis);
} catch (IOException ioe) {
_log.error("Error finding the peer destination to contact in " + _peerDestFile, ioe);
return;
} catch (DataFormatException dfe) {
_log.error("Peer destination is not valid in " + _peerDestFile, dfe);
return;
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ioe) {
}
}
if (_log.shouldLog(Log.DEBUG))
_log.debug("Send " + _sendSize + "KB to " + peer.calculateHash().toBase64());
while (true) {
try {
I2PSocket sock = mgr.connect(peer);
byte[] buf = new byte[Math.min(32 * 1024, _sendSize * 1024)];
Random rand = new Random();
OutputStream out = sock.getOutputStream();
long beforeSending = System.currentTimeMillis();
for (int i = 0; (_sendSize < 0) || (i < _sendSize); i += buf.length / 1024) {
rand.nextBytes(buf);
out.write(buf);
if (_log.shouldLog(Log.DEBUG))
_log.debug("Wrote " + ((1 + i * buf.length) / 1024) + "/" + _sendSize + "KB");
if (_writeDelay > 0) {
try {
Thread.sleep(_writeDelay);
} catch (InterruptedException ie) {
}
}
}
sock.close();
long afterSending = System.currentTimeMillis();
if (_log.shouldLog(Log.DEBUG))
_log.debug("Sent " + _sendSize + "KB in " + (afterSending - beforeSending) + "ms");
} catch (InterruptedIOException iie) {
_log.error("Timeout connecting to the peer", iie);
// return;
} catch (NoRouteToHostException nrthe) {
_log.error("Unable to connect to the peer", nrthe);
// return;
} catch (ConnectException ce) {
_log.error("Connection already dropped", ce);
// return;
} catch (I2PException ie) {
_log.error("Error connecting to the peer", ie);
return;
} catch (IOException ioe) {
_log.error("IO error sending", ioe);
return;
}
}
}
use of net.i2p.data.Destination in project i2p.i2p by i2p.
the class TestSwarm method connectWithPeers.
private void connectWithPeers() {
if (_peerDestFiles != null) {
for (int i = 0; i < _peerDestFiles.length; i++) {
try {
FileInputStream fin = new FileInputStream(_peerDestFiles[i]);
Destination dest = new Destination();
dest.readBytes(fin);
I2PThread flooder = new I2PThread(new Flooder(dest), "Flooder+" + dest.calculateHash().toBase64().substring(0, 4));
flooder.start();
} catch (Exception e) {
_log.error("Unable to read the peer from " + _peerDestFiles[i], e);
}
}
}
}
use of net.i2p.data.Destination in project i2p.i2p by i2p.
the class GeneralHelper method getDestination.
/**
* Works even if tunnel is not running.
* @return Destination or null
*/
public Destination getDestination(int tunnel) {
TunnelController tun = getController(tunnel);
if (tun != null) {
Destination rv = tun.getDestination();
if (rv != null)
return rv;
// if not running, do this the hard way
File keyFile = tun.getPrivateKeyFile();
if (keyFile != null) {
PrivateKeyFile pkf = new PrivateKeyFile(keyFile);
try {
rv = pkf.getDestination();
if (rv != null)
return rv;
} catch (I2PException e) {
} catch (IOException e) {
}
}
}
return null;
}
use of net.i2p.data.Destination in project i2p.i2p by i2p.
the class LocalHTTPServer method serveLocalFile.
/**
* Very simple web server.
*
* Serve local files in the docs/ directory, for CSS and images in
* error pages, using the reserved address proxy.i2p
* (similar to p.p in privoxy).
* This solves the problems with including links to the router console,
* as assuming the router console is at 127.0.0.1 leads to broken
* links if it isn't.
*
* Ignore all request headers (If-Modified-Since, etc.)
*
* There is basic protection here -
* FileUtil.readFile() prevents traversal above the base directory -
* but inproxy/gateway ops would be wise to block proxy.i2p to prevent
* exposing the docs/ directory or perhaps other issues through
* uncaught vulnerabilities.
* Restrict to the /themes/ directory for now.
*
* @param targetRequest decoded path only, non-null
* @param query raw (encoded), may be null
*/
public static void serveLocalFile(OutputStream out, String method, String targetRequest, String query, String proxyNonce) throws IOException {
// a home page message for the curious...
if (targetRequest.equals("/")) {
out.write(OK.getBytes("UTF-8"));
out.flush();
return;
}
if ((method.equals("GET") || method.equals("HEAD")) && targetRequest.startsWith("/themes/") && !targetRequest.contains("..")) {
String filename = null;
try {
// "/themes/".length
filename = targetRequest.substring(8);
} catch (IndexOutOfBoundsException ioobe) {
return;
}
// theme hack
if (filename.startsWith("console/default/"))
filename = filename.replaceFirst("default", I2PAppContext.getGlobalContext().getProperty("routerconsole.theme", "light"));
File themesDir = new File(I2PAppContext.getGlobalContext().getBaseDir(), "docs/themes");
File file = new File(themesDir, filename);
if (file.exists() && !file.isDirectory()) {
String type;
if (filename.endsWith(".css"))
type = "text/css";
else if (filename.endsWith(".ico"))
type = "image/x-icon";
else if (filename.endsWith(".png"))
type = "image/png";
else if (filename.endsWith(".jpg"))
type = "image/jpeg";
else
type = "text/html";
out.write("HTTP/1.1 200 OK\r\nContent-Type: ".getBytes("UTF-8"));
out.write(type.getBytes("UTF-8"));
out.write("\r\nCache-Control: max-age=86400\r\nConnection: close\r\nProxy-Connection: close\r\n\r\n".getBytes("UTF-8"));
FileUtil.readFile(filename, themesDir.getAbsolutePath(), out);
return;
}
}
// Do the add and redirect.
if (targetRequest.equals("/add")) {
if (query == null) {
out.write(ERR_ADD.getBytes("UTF-8"));
return;
}
Map<String, String> opts = new HashMap<String, String>(8);
// this only works if all keys are followed by =value
StringTokenizer tok = new StringTokenizer(query, "=&;");
while (tok.hasMoreTokens()) {
String k = tok.nextToken();
if (!tok.hasMoreTokens())
break;
String v = tok.nextToken();
opts.put(decode(k), decode(v));
}
String url = opts.get("url");
String host = opts.get("host");
String b64Dest = opts.get("dest");
String nonce = opts.get("nonce");
String referer = opts.get("referer");
String book = "privatehosts.txt";
if (opts.get("master") != null)
book = "userhosts.txt";
else if (opts.get("router") != null)
book = "hosts.txt";
Destination dest = null;
if (b64Dest != null) {
try {
dest = new Destination(b64Dest);
} catch (DataFormatException dfe) {
System.err.println("Bad dest to save?" + b64Dest);
}
}
// System.err.println("nonce : \"" + nonce + "\"");
if (proxyNonce.equals(nonce) && url != null && host != null && dest != null) {
NamingService ns = I2PAppContext.getGlobalContext().namingService();
Properties nsOptions = new Properties();
nsOptions.setProperty("list", book);
if (referer != null && referer.startsWith("http")) {
String ref = DataHelper.escapeHTML(referer);
String from = "<a href=\"" + ref + "\">" + ref + "</a>";
nsOptions.setProperty("s", _t("Added via address helper from {0}", from));
} else {
nsOptions.setProperty("s", _t("Added via address helper"));
}
boolean success = ns.put(host, dest, nsOptions);
writeRedirectPage(out, success, host, book, url);
return;
}
out.write(ERR_ADD.getBytes("UTF-8"));
} else {
out.write(ERR_404.getBytes("UTF-8"));
}
out.flush();
}
use of net.i2p.data.Destination in project i2p.i2p by i2p.
the class SOCKS5Server method getDestinationI2PSocket.
/**
* Get an I2PSocket that can be used to send/receive 8-bit clean data
* to/from the destination of the SOCKS connection.
*
* @return an I2PSocket connected with the destination
*/
public I2PSocket getDestinationI2PSocket(I2PSOCKSTunnel t) throws SOCKSException {
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!");
}
// for errors
DataOutputStream out;
try {
out = new DataOutputStream(clientSock.getOutputStream());
} catch (IOException e) {
throw new SOCKSException("Connection error", e);
}
// 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(Locale.US).endsWith(".i2p")) {
// Let's not do a new Dest for every request, huh?
// I2PSocketManager sm = I2PSocketManagerFactory.createManager();
// destSock = sm.connect(I2PTunnel.destFromName(connHostName), null);
Destination dest = _context.namingService().lookup(connHostName);
if (dest == null) {
try {
sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
} catch (IOException ioe) {
}
throw new SOCKSException("Host not found");
}
if (_log.shouldDebug())
_log.debug("connecting to " + connHostName + "...");
Properties overrides = new Properties();
I2PSocketOptions sktOpts = t.buildOptions(overrides);
sktOpts.setPort(connPort);
destSock = t.createI2PSocket(dest, sktOpts);
} else if ("localhost".equals(connHostName) || "127.0.0.1".equals(connHostName)) {
String err = "No localhost accesses allowed through the Socks Proxy";
_log.error(err);
try {
sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
} catch (IOException ioe) {
}
throw new SOCKSException(err);
/**
**
* } else if (connPort == 80) {
* // rewrite GET line to include hostname??? or add Host: line???
* // or forward to local eepProxy (but that's a Socket not an I2PSocket)
* // use eepProxy configured outproxies?
* String err = "No handler for HTTP outproxy implemented";
* _log.error(err);
* try {
* sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
* } catch (IOException ioe) {}
* throw new SOCKSException(err);
***
*/
} else {
Outproxy outproxy = getOutproxyPlugin();
if (outproxy != null) {
// but here, we wrap a Socket in a I2PSocket and use the regular Runner.
try {
destSock = new SocketWrapper(outproxy.connect(connHostName, connPort));
} catch (IOException ioe) {
try {
sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
} catch (IOException ioe2) {
}
throw new SOCKSException("connect failed via outproxy plugin", ioe);
}
} else {
List<String> proxies = t.getProxies(connPort);
if (proxies == null || proxies.isEmpty()) {
String err = "No outproxy configured for port " + connPort + " and no default configured either";
_log.error(err);
try {
sendRequestReply(Reply.CONNECTION_NOT_ALLOWED_BY_RULESET, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
} catch (IOException ioe) {
}
throw new SOCKSException(err);
}
int p = _context.random().nextInt(proxies.size());
String proxy = proxies.get(p);
if (_log.shouldLog(Log.DEBUG))
_log.debug("connecting to proxy " + proxy + " for " + connHostName + " port " + connPort);
try {
destSock = outproxyConnect(t, proxy);
} catch (SOCKSException se) {
try {
sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
} catch (IOException ioe) {
}
throw se;
}
}
}
confirmConnection();
_log.debug("connection confirmed - exchanging data...");
} catch (DataFormatException e) {
if (_log.shouldLog(Log.WARN))
_log.warn("socks error", e);
try {
sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
} catch (IOException ioe) {
}
throw new SOCKSException("Error in destination format");
} catch (IOException e) {
if (_log.shouldLog(Log.WARN))
_log.warn("socks error", e);
try {
sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
} catch (IOException ioe) {
}
throw new SOCKSException("Connection error", e);
} catch (I2PException e) {
if (_log.shouldLog(Log.WARN))
_log.warn("socks error", e);
try {
sendRequestReply(Reply.HOST_UNREACHABLE, AddressType.DOMAINNAME, null, "0.0.0.0", 0, out);
} catch (IOException ioe) {
}
throw new SOCKSException("Connection error", e);
}
return destSock;
}
Aggregations