Search in sources :

Example 1 with ErrnoException

use of libcore.io.ErrnoException in project android_frameworks_base by ParanoidAndroid.

the class BackupAgent method fullBackupFileTree.

/**
     * Scan the dir tree (if it actually exists) and process each entry we find.  If the
     * 'excludes' parameter is non-null, it is consulted each time a new file system entity
     * is visited to see whether that entity (and its subtree, if appropriate) should be
     * omitted from the backup process.
     *
     * @hide
     */
protected final void fullBackupFileTree(String packageName, String domain, String rootPath, HashSet<String> excludes, FullBackupDataOutput output) {
    File rootFile = new File(rootPath);
    if (rootFile.exists()) {
        LinkedList<File> scanQueue = new LinkedList<File>();
        scanQueue.add(rootFile);
        while (scanQueue.size() > 0) {
            File file = scanQueue.remove(0);
            String filePath;
            try {
                filePath = file.getCanonicalPath();
                // prune this subtree?
                if (excludes != null && excludes.contains(filePath)) {
                    continue;
                }
                // If it's a directory, enqueue its contents for scanning.
                StructStat stat = Libcore.os.lstat(filePath);
                if (OsConstants.S_ISLNK(stat.st_mode)) {
                    if (DEBUG)
                        Log.i(TAG, "Symlink (skipping)!: " + file);
                    continue;
                } else if (OsConstants.S_ISDIR(stat.st_mode)) {
                    File[] contents = file.listFiles();
                    if (contents != null) {
                        for (File entry : contents) {
                            scanQueue.add(0, entry);
                        }
                    }
                }
            } catch (IOException e) {
                if (DEBUG)
                    Log.w(TAG, "Error canonicalizing path of " + file);
                continue;
            } catch (ErrnoException e) {
                if (DEBUG)
                    Log.w(TAG, "Error scanning file " + file + " : " + e);
                continue;
            }
            // Finally, back this file up before proceeding
            FullBackup.backupToTar(packageName, domain, null, rootPath, filePath, output.getData());
        }
    }
}
Also used : StructStat(libcore.io.StructStat) ErrnoException(libcore.io.ErrnoException) IOException(java.io.IOException) File(java.io.File) LinkedList(java.util.LinkedList)

Example 2 with ErrnoException

use of libcore.io.ErrnoException in project android_frameworks_base by ParanoidAndroid.

the class FullBackup method restoreFile.

/**
     * Copy data from a socket to the given File location on permanent storage.  The
     * modification time and access mode of the resulting file will be set if desired,
     * although group/all rwx modes will be stripped: the restored file will not be
     * accessible from outside the target application even if the original file was.
     * If the {@code type} parameter indicates that the result should be a directory,
     * the socket parameter may be {@code null}; even if it is valid, no data will be
     * read from it in this case.
     * <p>
     * If the {@code mode} argument is negative, then the resulting output file will not
     * have its access mode or last modification time reset as part of this operation.
     *
     * @param data Socket supplying the data to be copied to the output file.  If the
     *    output is a directory, this may be {@code null}.
     * @param size Number of bytes of data to copy from the socket to the file.  At least
     *    this much data must be available through the {@code data} parameter.
     * @param type Must be either {@link BackupAgent#TYPE_FILE} for ordinary file data
     *    or {@link BackupAgent#TYPE_DIRECTORY} for a directory.
     * @param mode Unix-style file mode (as used by the chmod(2) syscall) to be set on
     *    the output file or directory.  group/all rwx modes are stripped even if set
     *    in this parameter.  If this parameter is negative then neither
     *    the mode nor the mtime values will be applied to the restored file.
     * @param mtime A timestamp in the standard Unix epoch that will be imposed as the
     *    last modification time of the output file.  if the {@code mode} parameter is
     *    negative then this parameter will be ignored.
     * @param outFile Location within the filesystem to place the data.  This must point
     *    to a location that is writeable by the caller, preferably using an absolute path.
     * @throws IOException
     */
public static void restoreFile(ParcelFileDescriptor data, long size, int type, long mode, long mtime, File outFile) throws IOException {
    if (type == BackupAgent.TYPE_DIRECTORY) {
        // drop down to the final metadata adjustment.
        if (outFile != null)
            outFile.mkdirs();
    } else {
        FileOutputStream out = null;
        // Pull the data from the pipe, copying it to the output file, until we're done
        try {
            if (outFile != null) {
                File parent = outFile.getParentFile();
                if (!parent.exists()) {
                    // in practice this will only be for the default semantic directories,
                    // and using the default mode for those is appropriate.
                    parent.mkdirs();
                }
                out = new FileOutputStream(outFile);
            }
        } catch (IOException e) {
            Log.e(TAG, "Unable to create/open file " + outFile.getPath(), e);
        }
        byte[] buffer = new byte[32 * 1024];
        final long origSize = size;
        FileInputStream in = new FileInputStream(data.getFileDescriptor());
        while (size > 0) {
            int toRead = (size > buffer.length) ? buffer.length : (int) size;
            int got = in.read(buffer, 0, toRead);
            if (got <= 0) {
                Log.w(TAG, "Incomplete read: expected " + size + " but got " + (origSize - size));
                break;
            }
            if (out != null) {
                try {
                    out.write(buffer, 0, got);
                } catch (IOException e) {
                    // Problem writing to the file.  Quit copying data and delete
                    // the file, but of course keep consuming the input stream.
                    Log.e(TAG, "Unable to write to file " + outFile.getPath(), e);
                    out.close();
                    out = null;
                    outFile.delete();
                }
            }
            size -= got;
        }
        if (out != null)
            out.close();
    }
    // Now twiddle the state to match the backup, assuming all went well
    if (mode >= 0 && outFile != null) {
        try {
            // explicitly prevent emplacement of files accessible by outside apps
            mode &= 0700;
            Libcore.os.chmod(outFile.getPath(), (int) mode);
        } catch (ErrnoException e) {
            e.rethrowAsIOException();
        }
        outFile.setLastModified(mtime);
    }
}
Also used : ErrnoException(libcore.io.ErrnoException) FileOutputStream(java.io.FileOutputStream) IOException(java.io.IOException) File(java.io.File) FileInputStream(java.io.FileInputStream)

Example 3 with ErrnoException

use of libcore.io.ErrnoException in project android_frameworks_base by ParanoidAndroid.

the class SharedPreferencesImpl method loadFromDiskLocked.

private void loadFromDiskLocked() {
    if (mLoaded) {
        return;
    }
    if (mBackupFile.exists()) {
        mFile.delete();
        mBackupFile.renameTo(mFile);
    }
    // Debugging
    if (mFile.exists() && !mFile.canRead()) {
        Log.w(TAG, "Attempt to read preferences file " + mFile + " without permission");
    }
    Map map = null;
    StructStat stat = null;
    try {
        stat = Libcore.os.stat(mFile.getPath());
        if (mFile.canRead()) {
            BufferedInputStream str = null;
            try {
                str = new BufferedInputStream(new FileInputStream(mFile), 16 * 1024);
                map = XmlUtils.readMapXml(str);
            } catch (XmlPullParserException e) {
                Log.w(TAG, "getSharedPreferences", e);
            } catch (FileNotFoundException e) {
                Log.w(TAG, "getSharedPreferences", e);
            } catch (IOException e) {
                Log.w(TAG, "getSharedPreferences", e);
            } finally {
                IoUtils.closeQuietly(str);
            }
        }
    } catch (ErrnoException e) {
    }
    mLoaded = true;
    if (map != null) {
        mMap = map;
        mStatTimestamp = stat.st_mtime;
        mStatSize = stat.st_size;
    } else {
        mMap = new HashMap<String, Object>();
    }
    notifyAll();
}
Also used : StructStat(libcore.io.StructStat) ErrnoException(libcore.io.ErrnoException) BufferedInputStream(java.io.BufferedInputStream) FileNotFoundException(java.io.FileNotFoundException) XmlPullParserException(org.xmlpull.v1.XmlPullParserException) IOException(java.io.IOException) HashMap(java.util.HashMap) Map(java.util.Map) WeakHashMap(java.util.WeakHashMap) FileInputStream(java.io.FileInputStream)

Example 4 with ErrnoException

use of libcore.io.ErrnoException in project android_frameworks_base by ParanoidAndroid.

the class SharedPreferencesImpl method hasFileChangedUnexpectedly.

// Has the file changed out from under us?  i.e. writes that
// we didn't instigate.
private boolean hasFileChangedUnexpectedly() {
    synchronized (this) {
        if (mDiskWritesInFlight > 0) {
            // If we know we caused it, it's not unexpected.
            if (DEBUG)
                Log.d(TAG, "disk write in flight, not unexpected.");
            return false;
        }
    }
    final StructStat stat;
    try {
        /*
             * Metadata operations don't usually count as a block guard
             * violation, but we explicitly want this one.
             */
        BlockGuard.getThreadPolicy().onReadFromDisk();
        stat = Libcore.os.stat(mFile.getPath());
    } catch (ErrnoException e) {
        return true;
    }
    synchronized (this) {
        return mStatTimestamp != stat.st_mtime || mStatSize != stat.st_size;
    }
}
Also used : StructStat(libcore.io.StructStat) ErrnoException(libcore.io.ErrnoException)

Example 5 with ErrnoException

use of libcore.io.ErrnoException in project android_frameworks_base by ParanoidAndroid.

the class PackageManagerTests method assertDirOwnerGroupPerms.

private void assertDirOwnerGroupPerms(String reason, int uid, int gid, int perms, String path) {
    final StructStat stat;
    try {
        stat = Libcore.os.lstat(path);
    } catch (ErrnoException e) {
        throw new AssertionError(reason + "\n" + "Got: " + path + " does not exist");
    }
    StringBuilder sb = new StringBuilder();
    if (!S_ISDIR(stat.st_mode)) {
        sb.append("\nExpected type: ");
        sb.append(S_IFDIR);
        sb.append("\ngot type: ");
        sb.append((stat.st_mode & S_IFMT));
    }
    if (stat.st_uid != uid) {
        sb.append("\nExpected owner: ");
        sb.append(uid);
        sb.append("\nGot owner: ");
        sb.append(stat.st_uid);
    }
    if (stat.st_gid != gid) {
        sb.append("\nExpected group: ");
        sb.append(gid);
        sb.append("\nGot group: ");
        sb.append(stat.st_gid);
    }
    if ((stat.st_mode & ~S_IFMT) != perms) {
        sb.append("\nExpected permissions: ");
        sb.append(Integer.toOctalString(perms));
        sb.append("\nGot permissions: ");
        sb.append(Integer.toOctalString(stat.st_mode & ~S_IFMT));
    }
    if (sb.length() > 0) {
        throw new AssertionError(reason + sb.toString());
    }
}
Also used : StructStat(libcore.io.StructStat) ErrnoException(libcore.io.ErrnoException)

Aggregations

ErrnoException (libcore.io.ErrnoException)46 IOException (java.io.IOException)15 FileDescriptor (java.io.FileDescriptor)13 StructStat (libcore.io.StructStat)9 File (java.io.File)7 InetSocketAddress (java.net.InetSocketAddress)7 NonReadableChannelException (java.nio.channels.NonReadableChannelException)6 NonWritableChannelException (java.nio.channels.NonWritableChannelException)6 StructFlock (libcore.io.StructFlock)6 FileOutputStream (java.io.FileOutputStream)5 SocketAddress (java.net.SocketAddress)4 FileInputStream (java.io.FileInputStream)3 SocketTimeoutException (java.net.SocketTimeoutException)3 ClosedChannelException (java.nio.channels.ClosedChannelException)3 FileLock (java.nio.channels.FileLock)3 MutableLong (libcore.util.MutableLong)3 PrintStream (java.io.PrintStream)2 SocketException (java.net.SocketException)2 LinkedList (java.util.LinkedList)2 GaiException (libcore.io.GaiException)2