Search in sources :

Example 36 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class PersistDHT method saveDHT.

/**
 *  @param saveAll if true, don't check last seen time
 */
public static synchronized void saveDHT(DHTNodes nodes, boolean saveAll, File file) {
    if (nodes.size() <= 0)
        return;
    Log log = I2PAppContext.getGlobalContext().logManager().getLog(PersistDHT.class);
    int count = 0;
    long maxAge = saveAll ? 0 : I2PAppContext.getGlobalContext().clock().now() - MAX_AGE;
    PrintWriter out = null;
    try {
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new SecureFileOutputStream(file), "ISO-8859-1")));
        out.println("# DHT nodes, format is NID:Hash:Destination:port");
        for (NodeInfo ni : nodes.values()) {
            if (ni.lastSeen() < maxAge)
                continue;
            // DHTNodes shouldn't contain us, if that changes check here
            out.println(ni.toPersistentString());
            count++;
        }
        if (out.checkError())
            throw new IOException("Failed write to " + file);
    } catch (IOException ioe) {
        if (log.shouldLog(Log.WARN))
            log.warn("Error writing the DHT File", ioe);
    } finally {
        if (out != null)
            out.close();
    }
    if (log.shouldLog(Log.INFO))
        log.info("Stored " + count + " nodes to " + file);
}
Also used : Log(net.i2p.util.Log) OutputStreamWriter(java.io.OutputStreamWriter) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter)

Example 37 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class CommentSet method save.

/**
 *  File will be gzipped.
 *  Not sorted, includes hidden.
 *  See Comment.toPersistentString() for format.
 *  Sets isModified() to false.
 */
public void save(File file) throws IOException {
    PrintWriter out = null;
    try {
        out = new PrintWriter(new OutputStreamWriter(new GZIPOutputStream(new SecureFileOutputStream(file)), "UTF-8"));
        for (List<Comment> l : map.values()) {
            for (Comment c : l) {
                out.println(c.toPersistentString());
            }
        }
        if (out.checkError())
            throw new IOException("Failed write to " + file);
        modified = false;
    } finally {
        if (out != null)
            out.close();
    }
}
Also used : GZIPOutputStream(java.util.zip.GZIPOutputStream) OutputStreamWriter(java.io.OutputStreamWriter) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) PrintWriter(java.io.PrintWriter)

Example 38 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class MigrateJetty method migrateToJetty9.

/**
 *  Migrate a jetty.xml file to Jetty 9.
 *  Unlike above, where we just migrate the new install file over for Jetty 9,
 *  here we modify the xml file in-place to preserve settings where possible.
 *
 *  @return success
 *  @since Jetty 9
 */
private static boolean migrateToJetty9(File xmlFile) {
    if (xmlFile.getName().equals("jetty-jmx.xml")) {
        // This is lazy but nobody's using jmx, not worth the trouble
        System.err.println("ERROR: Migration  of " + xmlFile + " file is not supported. Copy new file from $I2P/eepsite-jetty9/jetty-jmx.xml");
        return false;
    }
    // we don't re-migrate from the template, we just add the
    // necessary args for the QueuedThreadPool constructor in-place
    // and fixup the renamed set call
    boolean modified = false;
    File eepsite = xmlFile.getParentFile();
    File newFile = new File(eepsite, xmlFile.getName() + System.currentTimeMillis() + ".tmp");
    FileInputStream in = null;
    PrintWriter out = null;
    try {
        in = new FileInputStream(xmlFile);
        out = new PrintWriter(new BufferedWriter(new OutputStreamWriter(new SecureFileOutputStream(newFile), "UTF-8")));
        String s;
        boolean foundQTP = false;
        boolean foundSTP = false;
        boolean foundETP = false;
        boolean foundSCC = false;
        boolean foundHC = false;
        boolean foundSSCC = false;
        while ((s = DataHelper.readLine(in)) != null) {
            // readLine() doesn't strip \r
            if (s.endsWith("\r"))
                s = s.substring(0, s.length() - 1);
            if (s.contains("Modified by I2P migration script for Jetty 9.") || s.contains("This configuration supports Jetty 9.") || s.contains("http://www.eclipse.org/jetty/configure_9_0.dtd")) {
                if (!modified)
                    break;
            // else we've modified it twice?
            } else if (s.contains("org.eclipse.jetty.util.thread.QueuedThreadPool")) {
                foundQTP = true;
            } else if (foundQTP) {
                if (!(s.contains("Modified by") || s.contains("<Arg type=\"int\">"))) {
                    out.println("        <!-- Modified by I2P migration script for Jetty 9. Do not remove this line -->");
                    out.println("        <Arg type=\"int\">20</Arg>     <!-- maxThreads, overridden below -->");
                    out.println("        <Arg type=\"int\">3</Arg>      <!-- minThreads, overridden below -->");
                    out.println("        <Arg type=\"int\">60000</Arg>  <!-- maxIdleTimeMs, overridden below -->");
                    modified = true;
                }
                foundQTP = false;
            }
            if (s.contains("<Set name=\"maxIdleTimeMs\">")) {
                // <Set name="maxIdleTimeMs">60000</Set>
                s = s.replace("<Set name=\"maxIdleTimeMs\">", "<Set name=\"idleTimeout\">");
                modified = true;
            } else if (s.contains("<Set name=\"ThreadPool\">")) {
                // <Set name="ThreadPool">, must be changed to constructor arg
                out.println("    <!-- Modified by I2P migration script for Jetty 9. Do not remove this line -->");
                s = s.replace("<Set name=\"ThreadPool\">", "<Arg>");
                foundSTP = true;
                modified = true;
            } else if (foundSTP && !foundETP && s.contains("</Set>") && !s.contains("<Set")) {
                // </Set> (close of <Set name="ThreadPool">)
                // All the lines above have <Set>...</Set> on the same line, if they don't, this will break.
                s = s.replace("</Set>", "</Arg>");
                foundETP = true;
            } else if (s.contains("org.eclipse.jetty.server.nio.SelectChannelConnector")) {
                s = s.replace("org.eclipse.jetty.server.nio.SelectChannelConnector", "org.eclipse.jetty.server.ServerConnector");
                out.println("          <!-- Modified by I2P migration script for Jetty 9. Do not remove this line -->");
                out.println(s);
                out.println("            <Arg><Ref id=\"Server\" /></Arg>");
                out.println("            <Arg type=\"int\">1</Arg>     <!-- number of acceptors -->");
                out.println("            <Arg type=\"int\">0</Arg>     <!-- default number of selectors -->");
                out.println("            <Arg>");
                out.println("              <Array type=\"org.eclipse.jetty.server.ConnectionFactory\">    <!-- varargs so we need an array -->");
                out.println("                <Item>");
                out.println("                  <New class=\"org.eclipse.jetty.server.HttpConnectionFactory\">");
                out.println("                    <Arg>");
                out.println("                      <New class=\"org.eclipse.jetty.server.HttpConfiguration\">");
                out.println("                        <Set name=\"sendServerVersion\">false</Set>");
                out.println("                        <Set name=\"sendDateHeader\">true</Set>");
                out.println("                      </New>");
                out.println("                    </Arg>");
                out.println("                  </New>");
                out.println("                </Item>");
                out.println("              </Array>");
                out.println("            </Arg>");
                modified = true;
                continue;
            // SSL starts here
            } else if (s.contains("org.eclipse.jetty.http.ssl.SslContextFactory")) {
                s = s.replace("org.eclipse.jetty.http.ssl.SslContextFactory", "org.eclipse.jetty.util.ssl.SslContextFactory");
                out.println("  <!-- Modified by I2P migration script for Jetty 9. Do not remove this line -->");
                out.println(s);
                // don't try to migrate from below, just generate a new list
                out.println("    <Set name=\"ExcludeCipherSuites\">");
                out.println("      <Array type=\"java.lang.String\">");
                for (String ss : I2PSSLSocketFactory.EXCLUDE_CIPHERS) {
                    out.println("        <Item>" + ss + "</Item>");
                }
                out.println("      </Array>");
                out.println("    </Set>");
                out.println("    <Set name=\"ExcludeProtocols\">");
                out.println("      <Array type=\"java.lang.String\">");
                for (String ss : I2PSSLSocketFactory.EXCLUDE_PROTOCOLS) {
                    out.println("        <Item>" + ss + "</Item>");
                }
                out.println("      </Array>");
                out.println("    </Set>");
                modified = true;
                continue;
            } else if (s.contains("org.eclipse.jetty.server.ssl.SslSelectChannelConnector")) {
                s = s.replace("org.eclipse.jetty.server.ssl.SslSelectChannelConnector", "org.eclipse.jetty.server.ServerConnector");
                out.println("      <!-- Modified by I2P migration script for Jetty 9. Do not remove this line -->");
                out.println(s);
                out.println("        <Arg><Ref id=\"Server\" /></Arg>");
                out.println("        <Arg type=\"int\">1</Arg>     <!-- number of acceptors -->");
                out.println("        <Arg type=\"int\">0</Arg>     <!-- default number of selectors -->");
                out.println("        <Arg>");
                out.println("           <Array type=\"org.eclipse.jetty.server.ConnectionFactory\">    <!-- varargs so we need an array -->");
                out.println("              <Item>");
                out.println("                <New class=\"org.eclipse.jetty.server.SslConnectionFactory\">");
                out.println("                  <Arg><Ref id=\"sslContextFactory\" /></Arg>");
                out.println("                  <Arg>http/1.1</Arg>");
                out.println("                </New>");
                out.println("              </Item>");
                out.println("              <Item>");
                out.println("                <New class=\"org.eclipse.jetty.server.HttpConnectionFactory\">");
                out.println("                  <Arg>");
                out.println("                    <New class=\"org.eclipse.jetty.server.HttpConfiguration\">");
                out.println("                      <Set name=\"sendServerVersion\">false</Set>");
                out.println("                      <Set name=\"sendDateHeader\">true</Set>");
                out.println("                    </New>");
                out.println("                  </Arg>");
                out.println("                </New>");
                out.println("              </Item>");
                out.println("            </Array>");
                out.println("        </Arg>");
                foundSSCC = true;
                modified = true;
                continue;
            } else if (foundSSCC && s.contains("<Set name=\"ExcludeCipherSuites\">")) {
                // delete the old ExcludeCipherSuites in this section
                do {
                    s = DataHelper.readLine(in);
                } while (s != null && !s.contains("</Set>"));
                modified = true;
                continue;
            } else if (foundSSCC && s.contains("<Ref id=\"sslContextFactory\"")) {
                // delete old one in this section, replaced above
                modified = true;
                continue;
            } else if (s.contains("<Set name=\"KeyStore\">")) {
                s = s.replace("<Set name=\"KeyStore\">", "<Set name=\"KeyStorePath\">");
                modified = true;
            } else if (s.contains("<Set name=\"TrustStore\">")) {
                s = s.replace("<Set name=\"TrustStore\">", "<Set name=\"TrustStorePath\">");
                modified = true;
            // SSL ends here
            } else if (s.contains("class=\"org.eclipse.jetty.deploy.providers.ContextProvider\">")) {
                // WebAppProvider now also does what ContextProvider used to do
                out.println("        <!-- Modified by I2P migration script for Jetty 9. Do not remove this line -->");
                s = s.replace("class=\"org.eclipse.jetty.deploy.providers.ContextProvider\">", "class=\"org.eclipse.jetty.deploy.providers.WebAppProvider\">");
                modified = true;
            } else if (s.contains("<Set name=\"maxIdleTime\">")) {
                s = s.replace("<Set name=\"maxIdleTime\">", "<Set name=\"idleTimeout\">");
                modified = true;
            } else if (s.contains("<Set name=\"gracefulShutdown\">")) {
                s = s.replace("<Set name=\"gracefulShutdown\">", "<Set name=\"stopTimeout\">");
                modified = true;
            } else if (s.contains("org.eclipse.jetty.server.HttpConfiguration")) {
                foundHC = true;
            } else if (!foundHC && (s.contains("<Set name=\"sendServerVersion\">") || s.contains("<Set name=\"sendDateHeader\">"))) {
                // old ones for Server, not in HTTPConfiguration section, delete
                modified = true;
                continue;
            } else if (s.contains("<Set name=\"Acceptors\">") || s.contains("<Set name=\"acceptors\">") || s.contains("<Set name=\"statsOn\">") || s.contains("<Set name=\"confidentialPort\">") || s.contains("<Set name=\"lowResourcesConnections\">") || s.contains("<Set name=\"lowResourcesMaxIdleTime\">") || s.contains("<Set name=\"useDirectBuffers\">")) {
                // delete
                modified = true;
                continue;
            }
            out.println(s);
        }
    } catch (IOException ioe) {
        if (in != null) {
            System.err.println("FAILED migration of " + xmlFile + ": " + ioe);
        }
        return false;
    } finally {
        if (in != null)
            try {
                in.close();
            } catch (IOException ioe) {
            }
        if (out != null)
            out.close();
    }
    if (modified) {
        return FileUtil.rename(newFile, xmlFile);
    } else {
        newFile.delete();
        return true;
    }
}
Also used : OutputStreamWriter(java.io.OutputStreamWriter) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream) PrintWriter(java.io.PrintWriter) BufferedWriter(java.io.BufferedWriter)

Example 39 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream in project i2p.i2p by i2p.

the class Reseeder method requestReseed.

/**
 *  Start a reseed from a zip or su3 input stream.
 *  Blocking, inline. Should be fast.
 *  This will close the stream.
 *
 *  @return number of valid routerinfos imported
 *  @throws IOException on most errors
 *  @since 0.9.19
 */
int requestReseed(InputStream in) throws IOException {
    _checker.setError("");
    _checker.setStatus("Reseeding from file");
    byte[] su3Magic = DataHelper.getASCII(SU3File.MAGIC);
    byte[] zipMagic = new byte[] { 0x50, 0x4b, 0x03, 0x04 };
    int len = Math.max(su3Magic.length, zipMagic.length);
    byte[] magic = new byte[len];
    File tmp = null;
    OutputStream out = null;
    try {
        DataHelper.read(in, magic);
        boolean isSU3;
        if (DataHelper.eq(magic, 0, su3Magic, 0, su3Magic.length))
            isSU3 = true;
        else if (DataHelper.eq(magic, 0, zipMagic, 0, zipMagic.length))
            isSU3 = false;
        else
            throw new IOException("Not a zip or su3 file");
        tmp = new File(_context.getTempDir(), "manualreseeds-" + _context.random().nextInt() + (isSU3 ? ".su3" : ".zip"));
        out = new BufferedOutputStream(new SecureFileOutputStream(tmp));
        out.write(magic);
        DataHelper.copy(in, out);
        out.close();
        int[] stats;
        ReseedRunner reseedRunner = new ReseedRunner();
        // inline
        if (isSU3)
            stats = reseedRunner.extractSU3(tmp);
        else
            stats = reseedRunner.extractZip(tmp);
        int fetched = stats[0];
        int errors = stats[1];
        if (fetched <= 0)
            throw new IOException("No seeds extracted");
        _checker.setStatus(_t("Reseeding: got router info from file ({0} successful, {1} errors).", fetched, errors));
        System.err.println("Reseed got " + fetched + " router infos from file with " + errors + " errors");
        _context.router().eventLog().addEvent(EventLog.RESEED, fetched + " from file");
        return fetched;
    } finally {
        try {
            in.close();
        } catch (IOException ioe) {
        }
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
        if (tmp != null)
            tmp.delete();
    }
}
Also used : ByteArrayOutputStream(java.io.ByteArrayOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) BufferedOutputStream(java.io.BufferedOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) SU3File(net.i2p.crypto.SU3File) File(java.io.File) BufferedOutputStream(java.io.BufferedOutputStream)

Example 40 with SecureFileOutputStream

use of net.i2p.util.SecureFileOutputStream 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 + "]");
}
Also used : DataFormatException(net.i2p.data.DataFormatException) RouterInfo(net.i2p.data.router.RouterInfo) FileOutputStream(java.io.FileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) Properties(java.util.Properties) File(java.io.File) DataFormatException(net.i2p.data.DataFormatException) IOException(java.io.IOException) KeyData(net.i2p.router.startup.LoadRouterInfoJob.KeyData)

Aggregations

SecureFileOutputStream (net.i2p.util.SecureFileOutputStream)55 IOException (java.io.IOException)50 File (java.io.File)33 OutputStream (java.io.OutputStream)22 OutputStreamWriter (java.io.OutputStreamWriter)21 FileOutputStream (java.io.FileOutputStream)19 BufferedWriter (java.io.BufferedWriter)16 FileInputStream (java.io.FileInputStream)11 SecureFile (net.i2p.util.SecureFile)9 BufferedOutputStream (java.io.BufferedOutputStream)8 PrintWriter (java.io.PrintWriter)7 InputStream (java.io.InputStream)6 GeneralSecurityException (java.security.GeneralSecurityException)6 DataFormatException (net.i2p.data.DataFormatException)6 EncryptedOutputStream (i2p.bote.fileencryption.EncryptedOutputStream)4 KeyStore (java.security.KeyStore)4 X509Certificate (java.security.cert.X509Certificate)4 Properties (java.util.Properties)4 ByteArrayInputStream (java.io.ByteArrayInputStream)3 Writer (java.io.Writer)3