Search in sources :

Example 86 with RandomAccessFile

use of java.io.RandomAccessFile in project android_frameworks_base by ResurrectionRemix.

the class RecoverySystem method verifyPackage.

/**
     * Verify the cryptographic signature of a system update package
     * before installing it.  Note that the package is also verified
     * separately by the installer once the device is rebooted into
     * the recovery system.  This function will return only if the
     * package was successfully verified; otherwise it will throw an
     * exception.
     *
     * Verification of a package can take significant time, so this
     * function should not be called from a UI thread.  Interrupting
     * the thread while this function is in progress will result in a
     * SecurityException being thrown (and the thread's interrupt flag
     * will be cleared).
     *
     * @param packageFile  the package to be verified
     * @param listener     an object to receive periodic progress
     * updates as verification proceeds.  May be null.
     * @param deviceCertsZipFile  the zip file of certificates whose
     * public keys we will accept.  Verification succeeds if the
     * package is signed by the private key corresponding to any
     * public key in this file.  May be null to use the system default
     * file (currently "/system/etc/security/otacerts.zip").
     *
     * @throws IOException if there were any errors reading the
     * package or certs files.
     * @throws GeneralSecurityException if verification failed
     */
public static void verifyPackage(File packageFile, ProgressListener listener, File deviceCertsZipFile) throws IOException, GeneralSecurityException {
    final long fileLen = packageFile.length();
    final RandomAccessFile raf = new RandomAccessFile(packageFile, "r");
    try {
        final long startTimeMillis = System.currentTimeMillis();
        if (listener != null) {
            listener.onProgress(0);
        }
        raf.seek(fileLen - 6);
        byte[] footer = new byte[6];
        raf.readFully(footer);
        if (footer[2] != (byte) 0xff || footer[3] != (byte) 0xff) {
            throw new SignatureException("no signature in file (no footer)");
        }
        final int commentSize = (footer[4] & 0xff) | ((footer[5] & 0xff) << 8);
        final int signatureStart = (footer[0] & 0xff) | ((footer[1] & 0xff) << 8);
        byte[] eocd = new byte[commentSize + 22];
        raf.seek(fileLen - (commentSize + 22));
        raf.readFully(eocd);
        // end-of-central-directory record.
        if (eocd[0] != (byte) 0x50 || eocd[1] != (byte) 0x4b || eocd[2] != (byte) 0x05 || eocd[3] != (byte) 0x06) {
            throw new SignatureException("no signature in file (bad footer)");
        }
        for (int i = 4; i < eocd.length - 3; ++i) {
            if (eocd[i] == (byte) 0x50 && eocd[i + 1] == (byte) 0x4b && eocd[i + 2] == (byte) 0x05 && eocd[i + 3] == (byte) 0x06) {
                throw new SignatureException("EOCD marker found after start of EOCD");
            }
        }
        // Parse the signature
        PKCS7 block = new PKCS7(new ByteArrayInputStream(eocd, commentSize + 22 - signatureStart, signatureStart));
        // Take the first certificate from the signature (packages
        // should contain only one).
        X509Certificate[] certificates = block.getCertificates();
        if (certificates == null || certificates.length == 0) {
            throw new SignatureException("signature contains no certificates");
        }
        X509Certificate cert = certificates[0];
        PublicKey signatureKey = cert.getPublicKey();
        SignerInfo[] signerInfos = block.getSignerInfos();
        if (signerInfos == null || signerInfos.length == 0) {
            throw new SignatureException("signature contains no signedData");
        }
        SignerInfo signerInfo = signerInfos[0];
        // Check that the public key of the certificate contained
        // in the package equals one of our trusted public keys.
        boolean verified = false;
        HashSet<X509Certificate> trusted = getTrustedCerts(deviceCertsZipFile == null ? DEFAULT_KEYSTORE : deviceCertsZipFile);
        for (X509Certificate c : trusted) {
            if (c.getPublicKey().equals(signatureKey)) {
                verified = true;
                break;
            }
        }
        if (!verified) {
            throw new SignatureException("signature doesn't match any trusted key");
        }
        // The signature cert matches a trusted key.  Now verify that
        // the digest in the cert matches the actual file data.
        raf.seek(0);
        final ProgressListener listenerForInner = listener;
        SignerInfo verifyResult = block.verify(signerInfo, new InputStream() {

            // The signature covers all of the OTA package except the
            // archive comment and its 2-byte length.
            long toRead = fileLen - commentSize - 2;

            long soFar = 0;

            int lastPercent = 0;

            long lastPublishTime = startTimeMillis;

            @Override
            public int read() throws IOException {
                throw new UnsupportedOperationException();
            }

            @Override
            public int read(byte[] b, int off, int len) throws IOException {
                if (soFar >= toRead) {
                    return -1;
                }
                if (Thread.currentThread().isInterrupted()) {
                    return -1;
                }
                int size = len;
                if (soFar + size > toRead) {
                    size = (int) (toRead - soFar);
                }
                int read = raf.read(b, off, size);
                soFar += read;
                if (listenerForInner != null) {
                    long now = System.currentTimeMillis();
                    int p = (int) (soFar * 100 / toRead);
                    if (p > lastPercent && now - lastPublishTime > PUBLISH_PROGRESS_INTERVAL_MS) {
                        lastPercent = p;
                        lastPublishTime = now;
                        listenerForInner.onProgress(lastPercent);
                    }
                }
                return read;
            }
        });
        final boolean interrupted = Thread.interrupted();
        if (listener != null) {
            listener.onProgress(100);
        }
        if (interrupted) {
            throw new SignatureException("verification was interrupted");
        }
        if (verifyResult == null) {
            throw new SignatureException("signature digest verification failed");
        }
    } finally {
        raf.close();
    }
}
Also used : PKCS7(sun.security.pkcs.PKCS7) PublicKey(java.security.PublicKey) ByteArrayInputStream(java.io.ByteArrayInputStream) InputStream(java.io.InputStream) SignatureException(java.security.SignatureException) IOException(java.io.IOException) X509Certificate(java.security.cert.X509Certificate) SignerInfo(sun.security.pkcs.SignerInfo) RandomAccessFile(java.io.RandomAccessFile) ByteArrayInputStream(java.io.ByteArrayInputStream)

Example 87 with RandomAccessFile

use of java.io.RandomAccessFile in project ACS by ACS-Community.

the class StatHashMap method openOutputFile.

/**
	 * Open and create the output stream for writing statistics on file.
	 * <P>
	 * The file is opened for each writing and closed immediately.
	 * A new file is created, whenever the size of the actual file is
	 * greater then {@link #maxFileSize}.
	 * 
	 * @return The stream for writing into the file
	 * @throws IOException If can't open/create the file for writing
	 * @throws ValidationException In case of error validating the Statistics element (should never happen)
	 * @throws MarshalException Error writing Statistics header in the file
	 */
private BufferedWriter openOutputFile() throws IOException, MarshalException, ValidationException {
    String actualFileName = fileNamePrefix + fileNumber + ".xml";
    String folderName = folder.getAbsolutePath();
    if (!folderName.endsWith("" + File.separator)) {
        folderName = folderName + File.separator;
    }
    // Check the size of the file if it exists
    File f = new File(folderName + actualFileName);
    if (f.exists() && f.length() > maxFileSize) {
        fileNumber++;
        return openOutputFile();
    }
    if (f.length() == 0) {
        // New file: write the header
        Statistics statistics = new Statistics();
        BufferedWriter outF = new BufferedWriter(new FileWriter(f, true));
        Marshaller marshaller = getMarshaller(outF);
        marshaller.setSupressXMLDeclaration(false);
        marshaller.marshal(statistics);
        outF.flush();
        outF.close();
        RandomAccessFile raf = new RandomAccessFile(f, "rw");
        raf.setLength(raf.length() - 3);
        raf.seek(raf.length());
        raf.writeBytes(">\n");
        raf.close();
    } else {
        // Remove the closing tag (closeXMLTag) before adding a new record
        RandomAccessFile raf = new RandomAccessFile(f, "rw");
        raf.setLength(raf.length() - closeXMLTag.length() - 1);
        raf.seek(raf.length());
        raf.writeBytes("\n");
        raf.close();
    }
    return new BufferedWriter(new FileWriter(f, true));
}
Also used : Marshaller(org.exolab.castor.xml.Marshaller) RandomAccessFile(java.io.RandomAccessFile) FileWriter(java.io.FileWriter) RandomAccessFile(java.io.RandomAccessFile) File(java.io.File) Statistics(alma.alarmsystem.statistics.generated.Statistics) BufferedWriter(java.io.BufferedWriter)

Example 88 with RandomAccessFile

use of java.io.RandomAccessFile in project ACS by ACS-Community.

the class DefaultXmlQueueFileHandlerImpl method fileProcessed.

/**
	 * Append the XML footer to the passed file before calling 
	 * {@link DefaultQueueFileHandlerImpl#fileProcessed(File, String, String)}
	 */
@Override
public void fileProcessed(File filePointer, String minTime, String maxTime) {
    try {
        RandomAccessFile rf = new RandomAccessFile(filePointer.getAbsolutePath(), "rw");
        rf.seek(rf.length());
        rf.writeBytes("\n</" + xmlTag + ">");
        rf.close();
    } catch (Throwable t) {
        // A error happening writing the footer will be ignored (but still we want to print it out)
        System.err.println("Error writing the footer: " + t.getMessage());
        t.printStackTrace(System.err);
    }
    super.fileProcessed(filePointer, minTime, maxTime);
}
Also used : RandomAccessFile(java.io.RandomAccessFile)

Example 89 with RandomAccessFile

use of java.io.RandomAccessFile in project ACS by ACS-Community.

the class EntriesQueue method writePageOnFile.

/**
	 * Write a page of <code>QueueEntry</code> in the file
	 * 
	 * @throws IOException In case of error creating a new temporary file
	 */
private void writePageOnFile() throws IOException {
    if (file == null) {
        file = getNewFile();
        try {
            raFile = new RandomAccessFile(file, "rw");
        } catch (FileNotFoundException e) {
            // Ops an error creating the file
            // print a message and exit: in this way it will try again
            // at next iteration
            file = null;
            raFile = null;
            IOException ioe = new IOException("Error creating the random file", e);
            throw ioe;
        }
    }
    if (cachedEntries.size() < PAGE_LEN) {
        throw new IllegalStateException("Not enough entries in vector");
    }
    for (int t = 0; t < PAGE_LEN; t++) {
        QueueEntry e = cachedEntries.get(t);
        byte[] hexBytes = e.toHexadecimal().getBytes();
        for (int y = 0; y < hexBytes.length; y++) {
            fileBuffer[t * QueueEntry.ENTRY_LENGTH + y] = hexBytes[y];
        }
    }
    raFile.seek(raFile.length());
    raFile.write(fileBuffer);
    // the data still in the vector
    for (int t = 0; t < PAGE_LEN; t++) {
        cachedEntries.remove(0);
    }
    pagesOnFile++;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) FileNotFoundException(java.io.FileNotFoundException) IOException(java.io.IOException)

Example 90 with RandomAccessFile

use of java.io.RandomAccessFile in project android-gps-test-tool by Esri.

the class GPSTesterActivityController method getCPU.

/**
	 * Returns CPU usage info. Careful using this it's CPU intensive by itself! 
	 * @return Percentage
	 */
private float getCPU() {
    try {
        RandomAccessFile reader = new RandomAccessFile("/proc/stat", "r");
        String load = reader.readLine();
        String[] toks = load.split(" ");
        long idle1 = Long.parseLong(toks[5]);
        long cpu1 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
        try {
            Thread.sleep(360);
        } catch (Exception e) {
        }
        reader.seek(0);
        load = reader.readLine();
        reader.close();
        toks = load.split(" ");
        long idle2 = Long.parseLong(toks[5]);
        long cpu2 = Long.parseLong(toks[2]) + Long.parseLong(toks[3]) + Long.parseLong(toks[4]) + Long.parseLong(toks[6]) + Long.parseLong(toks[7]) + Long.parseLong(toks[8]);
        return (float) (cpu2 - cpu1) / ((cpu2 + idle2) - (cpu1 + idle1));
    } catch (IOException ex) {
        ex.printStackTrace();
    }
    return 0;
}
Also used : RandomAccessFile(java.io.RandomAccessFile) IOException(java.io.IOException) IOException(java.io.IOException)

Aggregations

RandomAccessFile (java.io.RandomAccessFile)1607 IOException (java.io.IOException)761 File (java.io.File)691 FileChannel (java.nio.channels.FileChannel)284 ByteBuffer (java.nio.ByteBuffer)174 FileNotFoundException (java.io.FileNotFoundException)167 Test (org.junit.Test)152 FileOutputStream (java.io.FileOutputStream)91 FileLock (java.nio.channels.FileLock)91 MappedByteBuffer (java.nio.MappedByteBuffer)83 InputStream (java.io.InputStream)68 FileInputStream (java.io.FileInputStream)63 EOFException (java.io.EOFException)55 ArrayList (java.util.ArrayList)45 ByteArrayOutputStream (java.io.ByteArrayOutputStream)39 BufferedInputStream (java.io.BufferedInputStream)35 ByteArrayInputStream (java.io.ByteArrayInputStream)35 Random (java.util.Random)33 HashMap (java.util.HashMap)24 BinaryMapIndexReader (net.osmand.binary.BinaryMapIndexReader)23