use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.
the class SessionStatusMessage method doWriteMessage.
@Override
protected byte[] doWriteMessage() throws I2CPMessageException, IOException {
if (_sessionId == null)
throw new I2CPMessageException("Unable to write out the message as there is not enough data");
ByteArrayOutputStream os = new ByteArrayOutputStream(64);
try {
_sessionId.writeBytes(os);
DataHelper.writeLong(os, 1, _status);
} catch (DataFormatException dfe) {
throw new I2CPMessageException("Error writing out the message data", dfe);
}
return os.toByteArray();
}
use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.
the class LoadRouterInfoJob method readKeyData.
/**
* @param rkf1 in router.keys format, tried second
* @param rkf2 in eepPriv.dat format, tried first
* @return non-null, throws IOE if neither exisits
* @since 0.9.16
*/
public static KeyData readKeyData(File rkf1, File rkf2) throws DataFormatException, IOException {
RouterIdentity ri;
PrivateKey privkey;
SigningPrivateKey signingPrivKey;
if (rkf2.exists()) {
RouterPrivateKeyFile pkf = new RouterPrivateKeyFile(rkf2);
ri = pkf.getRouterIdentity();
if (!pkf.validateKeyPairs())
throw new DataFormatException("Key pairs invalid");
privkey = pkf.getPrivKey();
signingPrivKey = pkf.getSigningPrivKey();
} else {
InputStream fis = null;
try {
fis = new BufferedInputStream(new FileInputStream(rkf1));
privkey = new PrivateKey();
privkey.readBytes(fis);
signingPrivKey = new SigningPrivateKey();
signingPrivKey.readBytes(fis);
PublicKey pubkey = new PublicKey();
pubkey.readBytes(fis);
SigningPublicKey signingPubKey = new SigningPublicKey();
signingPubKey.readBytes(fis);
// validate
try {
if (!pubkey.equals(KeyGenerator.getPublicKey(privkey)))
throw new DataFormatException("Key pairs invalid");
if (!signingPubKey.equals(KeyGenerator.getSigningPublicKey(signingPrivKey)))
throw new DataFormatException("Key pairs invalid");
} catch (IllegalArgumentException iae) {
throw new DataFormatException("Key pairs invalid", iae);
}
ri = new RouterIdentity();
ri.setPublicKey(pubkey);
ri.setSigningPublicKey(signingPubKey);
ri.setCertificate(Certificate.NULL_CERT);
} finally {
if (fis != null)
try {
fis.close();
} catch (IOException ioe) {
}
}
}
return new KeyData(ri, privkey, signingPrivKey);
}
use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.
the class ReseedBundler method createZip.
/**
* Create a zip file with
* a random selection of 'count' router infos from configDir/netDb
* to 'toDir'. Skip your own router info, and old, hidden, unreachable, and
* introduced routers, and those from bad countries.
*
* The file will be in the temp directory. Caller must move or delete.
*/
public File createZip(int count) throws IOException {
Hash me = _context.routerHash();
int routerCount = 0;
int copied = 0;
long tooOld = System.currentTimeMillis() - 7 * 24 * 60 * 60 * 1000L;
List<RouterInfo> infos = new ArrayList<RouterInfo>(_context.netDb().getRouters());
// IP to router hash
Map<String, Hash> ipMap = new HashMap<String, Hash>(count);
List<RouterInfo> toWrite = new ArrayList<RouterInfo>(count);
Collections.shuffle(infos);
for (RouterInfo ri : infos) {
if (copied >= count)
break;
Hash key = ri.getIdentity().calculateHash();
if (key.equals(me)) {
continue;
}
if (ri.getPublished() < tooOld)
continue;
if (ri.getCapabilities().contains("U"))
continue;
if (ri.getCapabilities().contains("K"))
continue;
Collection<RouterAddress> addrs = ri.getAddresses();
if (addrs.isEmpty())
continue;
String name = getRouterInfoName(key);
boolean hasIntro = false;
boolean hasIPv4 = false;
boolean dupIP = false;
for (RouterAddress addr : addrs) {
if ("SSU".equals(addr.getTransportStyle()) && addr.getOption("ihost0") != null) {
hasIntro = true;
break;
}
String host = addr.getHost();
if (host != null && host.contains(".")) {
hasIPv4 = true;
Hash old = ipMap.put(host, key);
if (old != null && !old.equals(key)) {
dupIP = true;
break;
}
}
}
if (dupIP)
continue;
if (hasIntro)
continue;
if (!hasIPv4)
continue;
if (_context.commSystem().isInBadCountry(ri))
continue;
toWrite.add(ri);
copied++;
}
if (toWrite.isEmpty())
throw new IOException("No router infos to include. Reseed yourself first.");
if (toWrite.size() < Math.min(count, MINIMUM))
throw new IOException("Not enough router infos to include, wanted " + count + " but only found " + toWrite.size() + ". Please try again later.");
File rv = new File(_context.getTempDir(), "genreseed-" + _context.random().nextInt() + ".zip");
ZipOutputStream zip = null;
try {
zip = new ZipOutputStream(new FileOutputStream(rv));
for (RouterInfo ri : toWrite) {
String name = getRouterInfoName(ri.getIdentity().calculateHash());
ZipEntry entry = new ZipEntry(name);
entry.setTime(ri.getPublished());
zip.putNextEntry(entry);
ri.writeBytes(zip);
zip.closeEntry();
}
} catch (DataFormatException dfe) {
rv.delete();
IOException ioe = new IOException(dfe.getMessage());
ioe.initCause(dfe);
throw ioe;
} catch (IOException ioe) {
rv.delete();
throw ioe;
} finally {
if (zip != null) {
try {
zip.finish();
zip.close();
} catch (IOException ioe) {
rv.delete();
throw ioe;
}
}
}
return rv;
}
use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.
the class RebuildRouterInfoJob method rebuildRouterInfo.
/**
* @param alreadyRunning unused
*/
void rebuildRouterInfo(boolean alreadyRunning) {
_log.debug("Rebuilding the new router info");
RouterInfo info = null;
File infoFile = new File(getContext().getRouterDir(), CreateRouterInfoJob.INFO_FILENAME);
File keyFile = new File(getContext().getRouterDir(), CreateRouterInfoJob.KEYS_FILENAME);
File keyFile2 = new File(getContext().getRouterDir(), CreateRouterInfoJob.KEYS2_FILENAME);
if (keyFile2.exists() || keyFile.exists()) {
// ok, no need to rebuild a brand new identity, just update what we can
RouterInfo oldinfo = getContext().router().getRouterInfo();
if (oldinfo == null) {
try {
KeyData kd = LoadRouterInfoJob.readKeyData(keyFile, keyFile2);
info = new RouterInfo();
info.setIdentity(kd.routerIdentity);
} catch (DataFormatException e) {
_log.log(Log.CRIT, "Error reading in the key data from " + keyFile.getAbsolutePath(), e);
keyFile.delete();
keyFile2.delete();
rebuildRouterInfo(alreadyRunning);
return;
} catch (IOException e) {
_log.log(Log.CRIT, "Error reading in the key data from " + keyFile.getAbsolutePath(), e);
keyFile.delete();
keyFile2.delete();
rebuildRouterInfo(alreadyRunning);
return;
}
} else {
// Make a new RI from the old identity, or else info.setAddresses() will throw an ISE
info = new RouterInfo(oldinfo);
}
try {
info.setAddresses(getContext().commSystem().createAddresses());
Properties stats = getContext().statPublisher().publishStatistics(info.getHash());
info.setOptions(stats);
// info.setPeers(new HashSet()); // this would have the trusted peers
info.setPublished(CreateRouterInfoJob.getCurrentPublishDate(getContext()));
info.sign(getContext().keyManager().getSigningPrivateKey());
} catch (DataFormatException dfe) {
_log.log(Log.CRIT, "Error rebuilding the new router info", dfe);
return;
}
if (!info.isValid()) {
_log.log(Log.CRIT, "RouterInfo we just built is invalid: " + info, new Exception());
return;
}
FileOutputStream fos = null;
synchronized (getContext().router().routerInfoFileLock) {
try {
fos = new SecureFileOutputStream(infoFile);
info.writeBytes(fos);
} catch (DataFormatException dfe) {
_log.log(Log.CRIT, "Error rebuilding the router information", dfe);
} catch (IOException ioe) {
_log.log(Log.CRIT, "Error writing out the rebuilt router information", ioe);
} finally {
if (fos != null)
try {
fos.close();
} catch (IOException ioe) {
}
}
}
} else {
_log.warn("Private key file " + keyFile.getAbsolutePath() + " deleted! Rebuilding a brand new router identity!");
// this proc writes the keys and info to the file as well as builds the latest and greatest info
CreateRouterInfoJob j = new CreateRouterInfoJob(getContext(), null);
synchronized (getContext().router().routerInfoFileLock) {
info = j.createRouterInfo();
}
}
// MessageHistory.initialize();
getContext().router().setRouterInfo(info);
_log.info("Router info rebuilt and stored at " + infoFile + " [" + info + "]");
}
use of net.i2p.data.DataFormatException in project i2p.i2p by i2p.
the class SAMv1Handler method execDgOrRawMessage.
/*
* Parse and execute a RAW or DATAGRAM SEND message.
* This is for v1/v2 compatible sending only.
* For v3 sending, see SAMv3DatagramServer.
*
* Note that props are from the command line only.
* Session defaults from CREATE are NOT honored here.
* FIXME if we care, but nobody's probably using v3.2 options for v1/v2 sending.
*
* @since 0.9.25 consolidated from execDatagramMessage() and execRawMessage()
*/
private boolean execDgOrRawMessage(boolean isRaw, String opcode, Properties props) {
if (opcode.equals("SEND")) {
if (props.isEmpty()) {
if (_log.shouldLog(Log.DEBUG))
_log.debug("No parameters specified in SEND message");
return false;
}
String dest = props.getProperty("DESTINATION");
if (dest == null) {
if (_log.shouldWarn())
_log.warn("Destination not specified in SEND message");
return false;
}
int size;
String strsize = props.getProperty("SIZE");
if (strsize == null) {
if (_log.shouldLog(Log.WARN))
_log.warn("Size not specified in SEND message");
return false;
}
try {
size = Integer.parseInt(strsize);
} catch (NumberFormatException e) {
if (_log.shouldLog(Log.WARN))
_log.warn("Invalid SEND size specified: " + strsize);
return false;
}
boolean ok = isRaw ? checkSize(size) : checkDatagramSize(size);
if (!ok) {
if (_log.shouldLog(Log.WARN))
_log.warn("Specified size (" + size + ") is out of protocol limits");
return false;
}
int fromPort = I2PSession.PORT_UNSPECIFIED;
int toPort = I2PSession.PORT_UNSPECIFIED;
int proto;
if (isRaw) {
proto = I2PSession.PROTO_DATAGRAM_RAW;
String s = props.getProperty("PROTOCOL");
if (s != null) {
try {
proto = Integer.parseInt(s);
} catch (NumberFormatException e) {
if (_log.shouldLog(Log.WARN))
_log.warn("Invalid SEND protocol specified: " + s);
}
}
} else {
proto = I2PSession.PROTO_DATAGRAM;
}
String s = props.getProperty("FROM_PORT");
if (s != null) {
try {
fromPort = Integer.parseInt(s);
} catch (NumberFormatException e) {
if (_log.shouldLog(Log.WARN))
_log.warn("Invalid SEND port specified: " + s);
}
}
s = props.getProperty("TO_PORT");
if (s != null) {
try {
toPort = Integer.parseInt(s);
} catch (NumberFormatException e) {
if (_log.shouldLog(Log.WARN))
_log.warn("Invalid SEND port specified: " + s);
}
}
try {
DataInputStream in = new DataInputStream(getClientSocket().socket().getInputStream());
byte[] data = new byte[size];
in.readFully(data);
SAMMessageSess sess = isRaw ? rawSession : datagramSession;
if (!sess.sendBytes(dest, data, proto, fromPort, toPort)) {
if (_log.shouldWarn())
_log.warn((isRaw ? "SEND RAW to " : "SEND DATAGRAM to ") + dest + " size " + size + " failed");
// a message send failure is no reason to drop the SAM session
// for raw and repliable datagrams, just carry on our merry way
}
return true;
} catch (EOFException e) {
if (_log.shouldWarn())
_log.warn("Too few bytes with SEND message (expected: " + size, e);
return false;
} catch (IOException e) {
if (_log.shouldWarn())
_log.warn("Caught IOException while parsing SEND message", e);
return false;
} catch (DataFormatException e) {
if (_log.shouldWarn())
_log.warn("Invalid key specified with SEND message", e);
return false;
} catch (I2PSessionException e) {
_log.error("Session error with SEND message", e);
return false;
}
} else {
if (_log.shouldWarn())
_log.warn("Unrecognized message opcode: \"" + opcode + "\"");
return false;
}
}
Aggregations