Search in sources :

Example 31 with SecureFileOutputStream

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

the class WebMail method processComposeButtons.

/**
 * process buttons of compose message dialog
 * This must be called BEFORE processStateChangeButtons so we can add the attachment before SEND
 *
 * @param sessionObject
 * @param request
 * @return new state, or null if unknown
 */
private static State processComposeButtons(SessionObject sessionObject, RequestWrapper request) {
    State state = null;
    String filename = request.getFilename(NEW_FILENAME);
    // We handle an attachment whether sending or uploading
    if (filename != null && (buttonPressed(request, NEW_UPLOAD) || buttonPressed(request, SEND))) {
        int i = filename.lastIndexOf('/');
        if (i != -1)
            filename = filename.substring(i + 1);
        i = filename.lastIndexOf('\\');
        if (i != -1)
            filename = filename.substring(i + 1);
        if (filename != null && filename.length() > 0) {
            InputStream in = null;
            OutputStream out = null;
            I2PAppContext ctx = I2PAppContext.getGlobalContext();
            File f = new File(ctx.getTempDir(), "susimail-attachment-" + ctx.random().nextLong());
            try {
                in = request.getInputStream(NEW_FILENAME);
                if (in == null)
                    throw new IOException("no stream");
                out = new SecureFileOutputStream(f);
                DataHelper.copy(in, out);
                String contentType = request.getContentType(NEW_FILENAME);
                String encodeTo;
                String ctlc = contentType.toLowerCase(Locale.US);
                if (ctlc.startsWith("text/")) {
                    encodeTo = "quoted-printable";
                    // interpret it as ISO-8859-1
                    if (!ctlc.contains("charset="))
                        contentType += "; charset=\"utf-8\"";
                } else {
                    encodeTo = "base64";
                }
                Encoding encoding = EncodingFactory.getEncoding(encodeTo);
                if (encoding != null) {
                    if (sessionObject.attachments == null)
                        sessionObject.attachments = new ArrayList<Attachment>();
                    sessionObject.attachments.add(new Attachment(filename, contentType, encodeTo, f));
                } else {
                    sessionObject.error += _t("No Encoding found for {0}", encodeTo) + '\n';
                }
            } catch (IOException e) {
                sessionObject.error += _t("Error reading uploaded file: {0}", e.getMessage()) + '\n';
                f.delete();
            } finally {
                if (in != null)
                    try {
                        in.close();
                    } catch (IOException ioe) {
                    }
                if (out != null)
                    try {
                        out.close();
                    } catch (IOException ioe) {
                    }
            }
        }
        state = State.NEW;
    } else if (sessionObject.attachments != null && buttonPressed(request, DELETE_ATTACHMENT)) {
        for (String item : getCheckedItems(request)) {
            try {
                int n = Integer.parseInt(item);
                for (int i = 0; i < sessionObject.attachments.size(); i++) {
                    Attachment attachment = sessionObject.attachments.get(i);
                    if (attachment.hashCode() == n) {
                        sessionObject.attachments.remove(i);
                        break;
                    }
                }
            } catch (NumberFormatException nfe) {
            }
        }
        state = State.NEW;
    }
    return state;
}
Also used : I2PAppContext(net.i2p.I2PAppContext) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) DecodingOutputStream(i2p.susi.util.DecodingOutputStream) WriterOutputStream(net.i2p.servlet.util.WriterOutputStream) ZipOutputStream(java.util.zip.ZipOutputStream) EscapeHTMLOutputStream(i2p.susi.util.EscapeHTMLOutputStream) OutputStream(java.io.OutputStream) ArrayList(java.util.ArrayList) Encoding(i2p.susi.webmail.encoding.Encoding) IOException(java.io.IOException) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) File(java.io.File)

Example 32 with SecureFileOutputStream

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

the class SubscriptionsBean method locked_save.

private void locked_save() {
    File file = subsFile();
    try {
        // trim and sort
        List<String> urls = new ArrayList<String>();
        InputStream in = new ByteArrayInputStream(content.getBytes("UTF-8"));
        String line;
        while ((line = DataHelper.readLine(in)) != null) {
            line = line.trim();
            if (line.length() > 0)
                urls.add(line);
        }
        Collections.sort(urls);
        PrintWriter out = new PrintWriter(new OutputStreamWriter(new SecureFileOutputStream(file), "UTF-8"));
        for (String url : urls) {
            out.println(url);
        }
        out.close();
        if (out.checkError())
            throw new IOException("Failed write to " + file);
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}
Also used : ByteArrayInputStream(java.io.ByteArrayInputStream) FileInputStream(java.io.FileInputStream) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) ArrayList(java.util.ArrayList) OutputStreamWriter(java.io.OutputStreamWriter) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) File(java.io.File) PrintWriter(java.io.PrintWriter)

Example 33 with SecureFileOutputStream

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

the class MessageHistory method writeEntries.

/**
 * Actually write the specified entries
 */
private synchronized void writeEntries() {
    File f = new File(_historyFile);
    if (!f.isAbsolute())
        f = new File(_context.getLogDir(), _historyFile);
    FileOutputStream fos = null;
    try {
        fos = new SecureFileOutputStream(f, true);
        String entry;
        while ((entry = _unwrittenEntries.poll()) != null) {
            fos.write(DataHelper.getUTF8(entry));
            fos.write(NL);
        }
    } catch (IOException ioe) {
        _log.error("Error writing trace entries", ioe);
    } finally {
        if (fos != null)
            try {
                fos.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : FileOutputStream(java.io.FileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) File(java.io.File)

Example 34 with SecureFileOutputStream

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

the class SnarkManager method locked_writeMetaInfo.

/**
 * Write the metainfo to the file, caller must hold the snarks lock
 * to prevent interference from the DirMonitor.
 *
 * @param metainfo The metainfo for the torrent
 * @param filename The absolute path to save the metainfo to, generally ending in ".torrent".
 *                 Must be a filesystem-safe name.
 * @since 0.8.4
 */
private static void locked_writeMetaInfo(MetaInfo metainfo, String filename, boolean areFilesPublic) throws IOException {
    File file = new File(filename);
    if (file.exists())
        throw new IOException("Cannot overwrite an existing .torrent file: " + file.getPath());
    OutputStream out = null;
    try {
        if (areFilesPublic)
            out = new FileOutputStream(filename);
        else
            out = new SecureFileOutputStream(filename);
        out.write(metainfo.getTorrentData());
    } catch (IOException ioe) {
        // remove any partial
        file.delete();
        throw ioe;
    } finally {
        try {
            if (out != null)
                out.close();
        } catch (IOException ioe) {
        }
    }
}
Also used : SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) OutputStream(java.io.OutputStream) FileOutputStream(java.io.FileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) FileOutputStream(java.io.FileOutputStream) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) IOException(java.io.IOException) File(java.io.File)

Example 35 with SecureFileOutputStream

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

the class TunnelController method createAltPrivateKey.

/**
 * Creates alternate Destination with the same encryption keys as the primary Destination,
 * but a different signing key.
 *
 * Must have already called createPrivateKey() successfully.
 * Does nothing unless option OPT_ALT_PKF is set with the privkey file name.
 * Does nothing if the file already exists.
 *
 * @return success
 * @since 0.9.30
 */
private boolean createAltPrivateKey() {
    if (PREFERRED_SIGTYPE == SigType.DSA_SHA1)
        return false;
    File keyFile = getPrivateKeyFile();
    if (keyFile == null)
        return false;
    if (!keyFile.exists())
        return false;
    File altFile = getAlternatePrivateKeyFile();
    if (altFile == null)
        return false;
    if (altFile.equals(keyFile))
        return false;
    if (altFile.exists())
        return true;
    PrivateKeyFile pkf = new PrivateKeyFile(keyFile);
    FileOutputStream out = null;
    try {
        Destination dest = pkf.getDestination();
        if (dest == null)
            return false;
        if (dest.getSigType() != SigType.DSA_SHA1)
            return false;
        PublicKey pub = dest.getPublicKey();
        PrivateKey priv = pkf.getPrivKey();
        SimpleDataStructure[] signingKeys = KeyGenerator.getInstance().generateSigningKeys(PREFERRED_SIGTYPE);
        SigningPublicKey signingPubKey = (SigningPublicKey) signingKeys[0];
        SigningPrivateKey signingPrivKey = (SigningPrivateKey) signingKeys[1];
        KeyCertificate cert = new KeyCertificate(signingPubKey);
        Destination d = new Destination();
        d.setPublicKey(pub);
        d.setSigningPublicKey(signingPubKey);
        d.setCertificate(cert);
        int len = signingPubKey.length();
        if (len < 128) {
            byte[] pad = new byte[128 - len];
            RandomSource.getInstance().nextBytes(pad);
            d.setPadding(pad);
        } else if (len > 128) {
        // copy of excess data handled in KeyCertificate constructor
        }
        out = new SecureFileOutputStream(altFile);
        d.writeBytes(out);
        priv.writeBytes(out);
        signingPrivKey.writeBytes(out);
        try {
            out.close();
        } catch (IOException ioe) {
        }
        String destStr = d.toBase64();
        log("Alternate private key created and saved in " + altFile.getAbsolutePath());
        log("You should backup this file in a secure place.");
        log("New alternate destination: " + destStr);
        String b32 = d.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(altFile, backup, false, true)) {
                SecureFileOutputStream.setPerms(backup);
                log("Alternate private key backup saved to " + backup.getAbsolutePath());
            }
        }
        return true;
    } catch (GeneralSecurityException e) {
        log("Error creating keys " + e);
        return false;
    } catch (I2PSessionException e) {
        log("Error creating keys " + e);
        return false;
    } catch (I2PException e) {
        log("Error creating keys " + e);
        return false;
    } catch (IOException e) {
        log("Error creating keys " + e);
        return false;
    } catch (RuntimeException e) {
        log("Error creating keys " + e);
        return false;
    } finally {
        if (out != null)
            try {
                out.close();
            } catch (IOException ioe) {
            }
    }
}
Also used : I2PException(net.i2p.I2PException) Destination(net.i2p.data.Destination) SigningPublicKey(net.i2p.data.SigningPublicKey) PrivateKey(net.i2p.data.PrivateKey) SigningPrivateKey(net.i2p.data.SigningPrivateKey) SecureFile(net.i2p.util.SecureFile) SigningPublicKey(net.i2p.data.SigningPublicKey) PublicKey(net.i2p.data.PublicKey) GeneralSecurityException(java.security.GeneralSecurityException) PrivateKeyFile(net.i2p.data.PrivateKeyFile) IOException(java.io.IOException) SigningPrivateKey(net.i2p.data.SigningPrivateKey) KeyCertificate(net.i2p.data.KeyCertificate) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) FileOutputStream(java.io.FileOutputStream) I2PSessionException(net.i2p.client.I2PSessionException) SecureFileOutputStream(net.i2p.util.SecureFileOutputStream) SecureFile(net.i2p.util.SecureFile) PrivateKeyFile(net.i2p.data.PrivateKeyFile) File(java.io.File) SimpleDataStructure(net.i2p.data.SimpleDataStructure)

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