use of net.i2p.I2PException in project i2p.i2p by i2p.
the class TunnelController method createPrivateKey.
/**
* @return success
*/
private boolean createPrivateKey() {
I2PClient client = I2PClientFactory.createClient();
File keyFile = getPrivateKeyFile();
if (keyFile == null) {
log("No filename specified for the private key");
return false;
}
if (keyFile.exists()) {
// log("Not overwriting existing private keys in " + keyFile.getAbsolutePath());
return true;
} else {
File parent = keyFile.getParentFile();
if ((parent != null) && (!parent.exists()))
parent.mkdirs();
}
FileOutputStream fos = null;
try {
fos = new SecureFileOutputStream(keyFile);
SigType stype = PREFERRED_SIGTYPE;
String st = _config.getProperty(OPT_SIG_TYPE);
if (st != null) {
SigType type = SigType.parseSigType(st);
if (type != null && type.isAvailable())
stype = type;
else
log("Unsupported sig type " + st + ", reverting to " + stype);
}
Destination dest = client.createDestination(fos, stype);
String destStr = dest.toBase64();
log("Private key created and saved in " + keyFile.getAbsolutePath());
log("You should backup this file in a secure place.");
log("New destination: " + destStr);
String b32 = dest.toBase32();
log("Base32: " + b32);
File backupDir = new SecureFile(I2PAppContext.getGlobalContext().getConfigDir(), KEY_BACKUP_DIR);
if (backupDir.isDirectory() || backupDir.mkdir()) {
String name = b32 + '-' + I2PAppContext.getGlobalContext().clock().now() + ".dat";
File backup = new File(backupDir, name);
if (FileUtil.copy(keyFile, backup, false, true)) {
SecureFileOutputStream.setPerms(backup);
log("Private key backup saved to " + backup.getAbsolutePath());
}
}
} catch (I2PException ie) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error creating new destination", ie);
log("Error creating new destination: " + ie.getMessage());
return false;
} catch (IOException ioe) {
if (_log.shouldLog(Log.ERROR))
_log.error("Error creating writing the destination to " + keyFile.getAbsolutePath(), ioe);
log("Error writing the keys to " + keyFile.getAbsolutePath());
return false;
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException ioe) {
}
}
return true;
}
use of net.i2p.I2PException in project i2p.i2p by i2p.
the class I2PTunnelDCCClient method clientConnectionRun.
/**
* Accept one connection only.
*/
protected void clientConnectionRun(Socket s) {
I2PSocket i2ps = null;
if (_log.shouldLog(Log.INFO))
_log.info("Opening DCC connection to " + _dest + ':' + _remotePort);
Destination dest = _context.namingService().lookup(_dest);
if (dest == null) {
_log.error("Could not find leaseset for DCC connection to " + _dest + ':' + _remotePort);
closeSocket(s);
stop();
notifyEvent(CONNECT_STOP_EVENT, Integer.valueOf(getLocalPort()));
return;
}
I2PSocketOptions opts = sockMgr.buildOptions();
opts.setPort(_remotePort);
try {
i2ps = createI2PSocket(dest, opts);
Thread t = new Runner(s, i2ps);
// we are called from an unlimited thread pool, so run inline
// t.start();
t.run();
} catch (IOException ex) {
_log.error("Could not make DCC connection to " + _dest + ':' + _remotePort, ex);
notifyEvent(CONNECT_STOP_EVENT, Integer.valueOf(getLocalPort()));
} catch (I2PException ex) {
_log.error("Could not make DCC connection to " + _dest + ':' + _remotePort, ex);
notifyEvent(CONNECT_STOP_EVENT, Integer.valueOf(getLocalPort()));
} finally {
// only because we are running it inline
closeSocket(s);
if (i2ps != null) {
try {
i2ps.close();
} catch (IOException ioe) {
}
}
}
stop();
}
use of net.i2p.I2PException in project i2p.i2p by i2p.
the class I2PSocketEepGet method sendRequest.
/**
* Look up the address, get a socket from the I2PSocketManager supplied in the constructor,
* and send the request.
*
* @param timeout ignored
*/
@Override
protected void sendRequest(SocketTimeout timeout) throws IOException {
if (_outputStream == null) {
File outFile = new File(_outputFile);
if (outFile.exists())
_alreadyTransferred = outFile.length();
}
if (_proxyIn != null)
try {
_proxyIn.close();
} catch (IOException ioe) {
}
if (_proxyOut != null)
try {
_proxyOut.close();
} catch (IOException ioe) {
}
if (_socket != null)
try {
_socket.close();
} catch (IOException ioe) {
}
try {
URI url = new URI(_actualURL);
if ("http".equals(url.getScheme())) {
String host = url.getHost();
if (host == null)
throw new MalformedURLException("no hostname: " + _actualURL);
int port = url.getPort();
if (port <= 0 || port > 65535)
port = 80;
// as the naming service accepts B64KEY (but not B64KEY.i2p atm)
if ("i2p".equals(host)) {
String file = url.getRawPath();
try {
int slash = 1 + file.substring(1).indexOf('/');
host = file.substring(1, slash);
_actualURL = "http://" + host + file.substring(slash);
String query = url.getRawQuery();
if (query != null)
_actualURL = _actualURL + '?' + query;
} catch (IndexOutOfBoundsException ioobe) {
throw new MalformedURLException("Bad /i2p/ format: " + _actualURL);
}
}
// Use existing I2PSession for lookups.
// This is much more efficient than using the naming service
Destination dest;
I2PSession sess = _socketManager.getSession();
if (sess != null && !sess.isClosed()) {
try {
if (host.length() == 60 && host.endsWith(".b32.i2p")) {
byte[] b = Base32.decode(host.substring(0, 52));
if (b != null) {
Hash h = Hash.create(b);
dest = sess.lookupDest(h, 20 * 1000);
} else {
dest = null;
}
} else {
dest = sess.lookupDest(host, 20 * 1000);
}
} catch (I2PSessionException ise) {
dest = null;
}
} else {
dest = _context.namingService().lookup(host);
}
if (dest == null)
throw new UnknownHostException("Unknown or non-i2p host: " + host);
// Set the timeouts, using the other existing options in the socket manager
// This currently duplicates what SocketTimeout is doing in EepGet,
// but when that's ripped out of EepGet to use setsotimeout, we'll need this.
Properties props = new Properties();
props.setProperty(I2PSocketOptions.PROP_CONNECT_TIMEOUT, "" + CONNECT_TIMEOUT);
props.setProperty(I2PSocketOptions.PROP_READ_TIMEOUT, "" + INACTIVITY_TIMEOUT);
// This is important - even if the underlying socket doesn't have a connect delay,
// we want to set it for this connection, so the request headers will go out
// in the SYN packet, saving one RTT.
props.setProperty(PROP_CONNECT_DELAY, CONNECT_DELAY);
I2PSocketOptions opts = _socketManager.buildOptions(props);
opts.setPort(port);
_socket = _socketManager.connect(dest, opts);
} else {
throw new MalformedURLException("Unsupported protocol: " + _actualURL);
}
} catch (URISyntaxException use) {
IOException ioe = new MalformedURLException("Bad URL");
ioe.initCause(use);
throw ioe;
} catch (I2PException ie) {
throw new IOException("I2P error", ie);
}
_proxyIn = _socket.getInputStream();
_proxyOut = _socket.getOutputStream();
// SocketTimeout doesn't take an I2PSocket, but no matter, because we
// always close our socket in fetch() above.
// timeout.setSocket(_socket);
String req = getRequest();
_proxyOut.write(DataHelper.getUTF8(req));
_proxyOut.flush();
}
use of net.i2p.I2PException in project i2p.i2p by i2p.
the class StreamSinkSend method runClient.
/**
* Actually connect and run the client - this call blocks until completion.
*/
public void runClient() {
I2PSocketManager 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) {
}
}
System.out.println("Send " + _sendFile + " to " + peer.calculateHash().toBase64());
try {
I2PSocket sock = mgr.connect(peer);
byte[] buf = new byte[32 * 1024];
OutputStream out = sock.getOutputStream();
long beforeSending = System.currentTimeMillis();
fis = new FileInputStream(_sendFile);
long size = 0;
while (true) {
int read = fis.read(buf);
if (read < 0)
break;
out.write(buf, 0, read);
size += read;
if (_log.shouldLog(Log.DEBUG))
_log.debug("Wrote " + read);
if (_writeDelay > 0) {
try {
Thread.sleep(_writeDelay);
} catch (InterruptedException ie) {
}
}
}
fis.close();
sock.close();
long afterSending = System.currentTimeMillis();
System.out.println("Sent " + (size / 1024) + "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.I2PException in project i2p.i2p by i2p.
the class I2PClientImpl method createDestination.
/**
* Create the destination with the given payload and write it out along with
* the PrivateKey and SigningPrivateKey to the destKeyStream
*
* If cert is a KeyCertificate, the signing keypair will be of the specified type.
* The KeyCertificate data must be .............................
* The padding if any will be randomized. The extra key data if any will be set in the
* key cert.
*
* Caller must close stream.
*
* @param destKeyStream location to write out the destination, PrivateKey, and SigningPrivateKey,
* format is specified in {@link net.i2p.data.PrivateKeyFile PrivateKeyFile}
*/
public Destination createDestination(OutputStream destKeyStream, Certificate cert) throws I2PException, IOException {
Destination d = new Destination();
Object[] keypair = KeyGenerator.getInstance().generatePKIKeypair();
PublicKey publicKey = (PublicKey) keypair[0];
PrivateKey privateKey = (PrivateKey) keypair[1];
SimpleDataStructure[] signingKeys;
if (cert.getCertificateType() == Certificate.CERTIFICATE_TYPE_KEY) {
KeyCertificate kcert = cert.toKeyCertificate();
SigType type = kcert.getSigType();
try {
signingKeys = KeyGenerator.getInstance().generateSigningKeys(type);
} catch (GeneralSecurityException gse) {
throw new I2PException("keygen fail", gse);
}
} else {
signingKeys = KeyGenerator.getInstance().generateSigningKeys();
}
SigningPublicKey signingPubKey = (SigningPublicKey) signingKeys[0];
SigningPrivateKey signingPrivKey = (SigningPrivateKey) signingKeys[1];
d.setPublicKey(publicKey);
d.setSigningPublicKey(signingPubKey);
if (cert.getCertificateType() == Certificate.CERTIFICATE_TYPE_KEY) {
// fix up key certificate or padding
KeyCertificate kcert = cert.toKeyCertificate();
SigType type = kcert.getSigType();
int len = type.getPubkeyLen();
if (len < 128) {
byte[] pad = new byte[128 - len];
RandomSource.getInstance().nextBytes(pad);
d.setPadding(pad);
} else if (len > 128) {
System.arraycopy(signingPubKey.getData(), 128, kcert.getPayload(), KeyCertificate.HEADER_LENGTH, len - 128);
}
}
d.setCertificate(cert);
d.writeBytes(destKeyStream);
privateKey.writeBytes(destKeyStream);
signingPrivKey.writeBytes(destKeyStream);
destKeyStream.flush();
return d;
}
Aggregations