android.system.ErrnoException Java Examples

The following examples show how to use android.system.ErrnoException. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: DexFile.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Opens a DEX file from a given filename, using a specified file
 * to hold the optimized data.
 *
 * @param sourceName
 *  Jar or APK file with "classes.dex".
 * @param outputName
 *  File that will hold the optimized form of the DEX data.
 * @param flags
 *  Enable optional features.
 * @param loader
 *  The class loader creating the DEX file object.
 * @param elements
 *  The temporary dex path list elements from DexPathList.makeElements
 */
private DexFile(String sourceName, String outputName, int flags, ClassLoader loader,
        DexPathList.Element[] elements) throws IOException {
    if (outputName != null) {
        try {
            String parent = new File(outputName).getParent();
            if (Libcore.os.getuid() != Libcore.os.stat(parent).st_uid) {
                throw new IllegalArgumentException("Optimized data directory " + parent
                        + " is not owned by the current user. Shared storage cannot protect"
                        + " your application from code injection attacks.");
            }
        } catch (ErrnoException ignored) {
            // assume we'll fail with a more contextual error later
        }
    }

    mCookie = openDexFile(sourceName, outputName, flags, loader, elements);
    mInternalCookie = mCookie;
    mFileName = sourceName;
    //System.out.println("DEX FILE cookie is " + mCookie + " sourceName=" + sourceName + " outputName=" + outputName);
}
 
Example #2
Source File: StrictJarFile.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override public int read(byte[] buffer, int byteOffset, int byteCount) throws IOException {
    synchronized (this.fd) {
        final long length = endOffset - offset;
        if (byteCount > length) {
            byteCount = (int) length;
        }
        try {
            Os.lseek(fd, offset, OsConstants.SEEK_SET);
        } catch (ErrnoException e) {
            throw new IOException(e);
        }
        int count = IoBridge.read(fd, buffer, byteOffset, byteCount);
        if (count > 0) {
            offset += count;
            return count;
        } else {
            return -1;
        }
    }
}
 
Example #3
Source File: FileUtils.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
@Override
public void run() {
    final FileDescriptor fd = getInternalFD();
    try {
        int i = 0;
        while (i < data.length) {
            if (sink) {
                i += Os.read(fd, data, i, data.length - i);
            } else {
                i += Os.write(fd, data, i, data.length - i);
            }
        }
    } catch (IOException | ErrnoException e) {
        // Ignored
    } finally {
        if (sink) {
            SystemClock.sleep(TimeUnit.SECONDS.toMillis(1));
        }
        IoUtils.closeQuietly(fd);
    }
}
 
Example #4
Source File: IoBridge.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * java.io always writes every byte it's asked to, or fails with an error. (That is, unlike
 * Unix it never just writes as many bytes as happens to be convenient.)
 */
public static void write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {
    ArrayUtils.throwsIfOutOfBounds(bytes.length, byteOffset, byteCount);
    if (byteCount == 0) {
        return;
    }
    try {
        while (byteCount > 0) {
            int bytesWritten = Libcore.os.write(fd, bytes, byteOffset, byteCount);
            byteCount -= bytesWritten;
            byteOffset += bytesWritten;
        }
    } catch (ErrnoException errnoException) {
        throw errnoException.rethrowAsIOException();
    }
}
 
Example #5
Source File: FileBridge.java    From container with GNU General Public License v3.0 6 votes vote down vote up
/**
 * java.io thinks that a read at EOF is an error and should return -1, contrary to traditional
 * Unix practice where you'd read until you got 0 bytes (and any future read would return -1).
 */
public static int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {
    ArrayUtils.checkOffsetAndCount(bytes.length, byteOffset, byteCount);
    if (byteCount == 0) {
        return 0;
    }
    try {
        int readCount = Os.read(fd, bytes, byteOffset, byteCount);
        if (readCount == 0) {
            return -1;
        }
        return readCount;
    } catch (ErrnoException errnoException) {
        if (errnoException.errno == OsConstants.EAGAIN) {
            // We return 0 rather than throw if we try to read from an empty non-blocking pipe.
            return 0;
        }
        throw new IOException(errnoException);
    }
}
 
Example #6
Source File: IoBridge.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * java.io only throws FileNotFoundException when opening files, regardless of what actually
 * went wrong. Additionally, java.io is more restrictive than POSIX when it comes to opening
 * directories: POSIX says read-only is okay, but java.io doesn't even allow that. We also
 * have an Android-specific hack to alter the default permissions.
 */
public static FileDescriptor open(String path, int flags) throws FileNotFoundException {
    FileDescriptor fd = null;
    try {
        // On Android, we don't want default permissions to allow global access.
        int mode = ((flags & O_ACCMODE) == O_RDONLY) ? 0 : 0600;
        fd = Libcore.os.open(path, flags, mode);
        // Posix open(2) fails with EISDIR only if you ask for write permission.
        // Java disallows reading directories too.
        if (isDirectory(path)) {
            throw new ErrnoException("open", EISDIR);
        }
        return fd;
    } catch (ErrnoException errnoException) {
        try {
            if (fd != null) {
                IoUtils.close(fd);
            }
        } catch (IOException ignored) {
        }
        FileNotFoundException ex = new FileNotFoundException(path + ": " + errnoException.getMessage());
        ex.initCause(errnoException);
        throw ex;
    }
}
 
Example #7
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Splits the given path strings into file elements using the path
 * separator, combining the results and filtering out elements
 * that don't exist, aren't readable, or aren't either a regular
 * file or a directory (as specified). Either string may be empty
 * or {@code null}, in which case it is ignored. If both strings
 * are empty or {@code null}, or all elements get pruned out, then
 * this returns a zero-element list.
 */
@UnsupportedAppUsage
private static List<File> splitPaths(String searchPath, boolean directoriesOnly) {
    List<File> result = new ArrayList<>();

    if (searchPath != null) {
        for (String path : searchPath.split(File.pathSeparator)) {
            if (directoriesOnly) {
                try {
                    StructStat sb = Libcore.os.stat(path);
                    if (!S_ISDIR(sb.st_mode)) {
                        continue;
                    }
                } catch (ErrnoException ignored) {
                    continue;
                }
            }
            result.add(new File(path));
        }
    }

    return result;
}
 
Example #8
Source File: NetworkBridge.java    From j2objc with Apache License 2.0 6 votes vote down vote up
private static int maybeThrowAfterRecvfrom(boolean isRead, boolean isConnected, ErrnoException errnoException) throws SocketException, SocketTimeoutException {
    if (isRead) {
        if (errnoException.errno == EAGAIN) {
            return 0;
        } else {
            throw new SocketException(errnoException.getMessage(), errnoException);
        }
    } else {
        if (isConnected && errnoException.errno == ECONNREFUSED) {
            throw new PortUnreachableException("", errnoException);
        } else if (errnoException.errno == EAGAIN) {
            throw new SocketTimeoutException(errnoException);
        } else {
            throw new SocketException(errnoException.getMessage(), errnoException);
        }
    }
}
 
Example #9
Source File: PackageInstallerSession.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * Determine if creating hard links between source and destination is
 * possible. That is, do they all live on the same underlying device.
 */
private boolean isLinkPossible(List<File> fromFiles, File toDir) {
    try {
        final StructStat toStat = Os.stat(toDir.getAbsolutePath());
        for (File fromFile : fromFiles) {
            final StructStat fromStat = Os.stat(fromFile.getAbsolutePath());
            if (fromStat.st_dev != toStat.st_dev) {
                return false;
            }
        }
    } catch (ErrnoException e) {
        Slog.w(TAG, "Failed to detect if linking possible: " + e);
        return false;
    }
    return true;
}
 
Example #10
Source File: DexFile.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Opens a DEX file from a given filename, using a specified file
 * to hold the optimized data.
 *
 * @param sourceName
 *  Jar or APK file with "classes.dex".
 * @param outputName
 *  File that will hold the optimized form of the DEX data.
 * @param flags
 *  Enable optional features.
 */
private DexFile(String sourceName, String outputName, int flags) throws IOException {
    if (outputName != null) {
        try {
            String parent = new File(outputName).getParent();
            if (Libcore.os.getuid() != Libcore.os.stat(parent).st_uid) {
                throw new IllegalArgumentException("Optimized data directory " + parent
                        + " is not owned by the current user. Shared storage cannot protect"
                        + " your application from code injection attacks.");
            }
        } catch (ErrnoException ignored) {
            // assume we'll fail with a more contextual error later
        }
    }

    mCookie = openDexFile(sourceName, outputName, flags);
    mFileName = sourceName;
    guard.open("close");
    //System.out.println("DEX FILE cookie is " + mCookie + " sourceName=" + sourceName + " outputName=" + outputName);
}
 
Example #11
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Splits the given path strings into file elements using the path
 * separator, combining the results and filtering out elements
 * that don't exist, aren't readable, or aren't either a regular
 * file or a directory (as specified). Either string may be empty
 * or {@code null}, in which case it is ignored. If both strings
 * are empty or {@code null}, or all elements get pruned out, then
 * this returns a zero-element list.
 */
private static List<File> splitPaths(String searchPath, boolean directoriesOnly) {
    List<File> result = new ArrayList<>();

    if (searchPath != null) {
        for (String path : searchPath.split(File.pathSeparator)) {
            if (directoriesOnly) {
                try {
                    StructStat sb = Libcore.os.stat(path);
                    if (!S_ISDIR(sb.st_mode)) {
                        continue;
                    }
                } catch (ErrnoException ignored) {
                    continue;
                }
            }
            result.add(new File(path));
        }
    }

    return result;
}
 
Example #12
Source File: IoBridge.java    From j2objc with Apache License 2.0 6 votes vote down vote up
/**
 * java.io thinks that a read at EOF is an error and should return -1, contrary to traditional
 * Unix practice where you'd read until you got 0 bytes (and any future read would return -1).
 */
public static int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {
    ArrayUtils.throwsIfOutOfBounds(bytes.length, byteOffset, byteCount);
    if (byteCount == 0) {
        return 0;
    }
    try {
        int readCount = Libcore.os.read(fd, bytes, byteOffset, byteCount);
        if (readCount == 0) {
            return -1;
        }
        return readCount;
    } catch (ErrnoException errnoException) {
        if (errnoException.errno == EAGAIN) {
            // We return 0 rather than throw if we try to read from an empty non-blocking pipe.
            return 0;
        }
        throw errnoException.rethrowAsIOException();
    }
}
 
Example #13
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Splits the given path strings into file elements using the path
 * separator, combining the results and filtering out elements
 * that don't exist, aren't readable, or aren't either a regular
 * file or a directory (as specified). Either string may be empty
 * or {@code null}, in which case it is ignored. If both strings
 * are empty or {@code null}, or all elements get pruned out, then
 * this returns a zero-element list.
 */
private static List<File> splitPaths(String searchPath, boolean directoriesOnly) {
    List<File> result = new ArrayList<>();

    if (searchPath != null) {
        for (String path : searchPath.split(File.pathSeparator)) {
            if (directoriesOnly) {
                try {
                    StructStat sb = Libcore.os.stat(path);
                    if (!S_ISDIR(sb.st_mode)) {
                        continue;
                    }
                } catch (ErrnoException ignored) {
                    continue;
                }
            }
            result.add(new File(path));
        }
    }

    return result;
}
 
Example #14
Source File: DexPathList.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Splits the given path strings into file elements using the path
 * separator, combining the results and filtering out elements
 * that don't exist, aren't readable, or aren't either a regular
 * file or a directory (as specified). Either string may be empty
 * or {@code null}, in which case it is ignored. If both strings
 * are empty or {@code null}, or all elements get pruned out, then
 * this returns a zero-element list.
 */
private static List<File> splitPaths(String searchPath, boolean directoriesOnly) {
    List<File> result = new ArrayList<>();

    if (searchPath != null) {
        for (String path : searchPath.split(File.pathSeparator)) {
            if (directoriesOnly) {
                try {
                    StructStat sb = Libcore.os.stat(path);
                    if (!S_ISDIR(sb.st_mode)) {
                        continue;
                    }
                } catch (ErrnoException ignored) {
                    continue;
                }
            }
            result.add(new File(path));
        }
    }

    return result;
}
 
Example #15
Source File: IpSecService.java    From android_9.0.0_r45 with Apache License 2.0 6 votes vote down vote up
/**
 * This function finds and forcibly binds to a random system port, ensuring that the port cannot
 * be unbound.
 *
 * <p>A socket cannot be un-bound from a port if it was bound to that port by number. To select
 * a random open port and then bind by number, this function creates a temp socket, binds to a
 * random port (specifying 0), gets that port number, and then uses is to bind the user's UDP
 * Encapsulation Socket forcibly, so that it cannot be un-bound by the user with the returned
 * FileHandle.
 *
 * <p>The loop in this function handles the inherent race window between un-binding to a port
 * and re-binding, during which the system could *technically* hand that port out to someone
 * else.
 */
private int bindToRandomPort(FileDescriptor sockFd) throws IOException {
    for (int i = MAX_PORT_BIND_ATTEMPTS; i > 0; i--) {
        try {
            FileDescriptor probeSocket = Os.socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
            Os.bind(probeSocket, INADDR_ANY, 0);
            int port = ((InetSocketAddress) Os.getsockname(probeSocket)).getPort();
            Os.close(probeSocket);
            Log.v(TAG, "Binding to port " + port);
            Os.bind(sockFd, INADDR_ANY, port);
            return port;
        } catch (ErrnoException e) {
            // Someone miraculously claimed the port just after we closed probeSocket.
            if (e.errno == OsConstants.EADDRINUSE) {
                continue;
            }
            throw e.rethrowAsIOException();
        }
    }
    throw new IOException("Failed " + MAX_PORT_BIND_ATTEMPTS + " attempts to bind to a port");
}
 
Example #16
Source File: ContextImpl.java    From AndroidComponentPlugin with Apache License 2.0 6 votes vote down vote up
/**
 * Common-path handling of app data dir creation
 */
private static File ensurePrivateDirExists(File file) {
    if (!file.exists()) {
        try {
            Os.mkdir(file.getAbsolutePath(), 0771);
            Os.chmod(file.getAbsolutePath(), 0771);
        } catch (ErrnoException e) {
            if (e.errno == OsConstants.EEXIST) {
                // We must have raced with someone; that's okay
            } else {
                Log.w(TAG, "Failed to ensure " + file + ": " + e.getMessage());
            }
        }
    }
    return file;
}
 
Example #17
Source File: SharedMemory.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
@Override
public void run() {
    try {
        Os.close(mFd);
    } catch (ErrnoException e) { /* swallow error */ }
    mMemoryReference.release();
    mMemoryReference = null;
}
 
Example #18
Source File: FileUtils.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Return owning UID of given path, otherwise -1.
 */
public static int getUid(String path) {
    try {
        return Os.stat(path).st_uid;
    } catch (ErrnoException e) {
        return -1;
    }
}
 
Example #19
Source File: ParcelFileDescriptor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Create two ParcelFileDescriptors structured as a data pipe. The first
 * ParcelFileDescriptor in the returned array is the read side; the second
 * is the write side.
 * <p>
 * The write end has the ability to deliver an error message through
 * {@link #closeWithError(String)} which can be handled by the read end
 * calling {@link #checkError()}, usually after detecting an EOF.
 * This can also be used to detect remote crashes.
 */
public static ParcelFileDescriptor[] createReliablePipe() throws IOException {
    try {
        final FileDescriptor[] comm = createCommSocketPair();
        final FileDescriptor[] fds = Os.pipe();
        return new ParcelFileDescriptor[] {
                new ParcelFileDescriptor(fds[0], comm[0]),
                new ParcelFileDescriptor(fds[1], comm[1]) };
    } catch (ErrnoException e) {
        throw e.rethrowAsIOException();
    }
}
 
Example #20
Source File: IoUtils.java    From j2objc with Apache License 2.0 5 votes vote down vote up
/**
 * Calls close(2) on 'fd'. Also resets the internal int to -1. Does nothing if 'fd' is null
 * or invalid.
 */
public static void close(FileDescriptor fd) throws IOException {
    try {
        if (fd != null && fd.valid()) {
            Libcore.os.close(fd);
        }
    } catch (ErrnoException errnoException) {
        throw errnoException.rethrowAsIOException();
    }
}
 
Example #21
Source File: Posix.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public native void remove(String path) throws ErrnoException /*-[
  if (path) {
    const char* cpath = absolutePath(path);
    int rc = TEMP_FAILURE_RETRY(remove(cpath));
    LibcoreIoPosix_throwIfMinusOneWithNSString_withInt_(@"remove", rc);
  }
]-*/;
 
Example #22
Source File: ParcelFileDescriptor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
private static FileDescriptor[] createCommSocketPair() throws IOException {
    try {
        // Use SOCK_SEQPACKET so that we have a guarantee that the status
        // is written and read atomically as one unit and is not split
        // across multiple IO operations.
        final FileDescriptor comm1 = new FileDescriptor();
        final FileDescriptor comm2 = new FileDescriptor();
        Os.socketpair(AF_UNIX, SOCK_SEQPACKET, 0, comm1, comm2);
        IoUtils.setBlocking(comm1, false);
        IoUtils.setBlocking(comm2, false);
        return new FileDescriptor[] { comm1, comm2 };
    } catch (ErrnoException e) {
        throw e.rethrowAsIOException();
    }
}
 
Example #23
Source File: ParcelFileDescriptor.java    From android_9.0.0_r45 with Apache License 2.0 5 votes vote down vote up
/**
 * Create two ParcelFileDescriptors structured as a data pipe.  The first
 * ParcelFileDescriptor in the returned array is the read side; the second
 * is the write side.
 */
public static ParcelFileDescriptor[] createPipe() throws IOException {
    try {
        final FileDescriptor[] fds = Os.pipe();
        return new ParcelFileDescriptor[] {
                new ParcelFileDescriptor(fds[0]),
                new ParcelFileDescriptor(fds[1]) };
    } catch (ErrnoException e) {
        throw e.rethrowAsIOException();
    }
}
 
Example #24
Source File: NetworkOs.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static native void setsockoptIpMreqn(FileDescriptor fd, int level, int option,
    int value) throws ErrnoException /*-[
  struct ip_mreqn req;
  memset(&req, 0, sizeof(req));
  req.imr_ifindex = value;
  int rc = TEMP_FAILURE_RETRY(setsockopt([fd getInt$], level, option, &req, sizeof(req)));
  LibcoreIoPosix_throwIfMinusOneWithNSString_withInt_(@"setsockopt", rc);
]-*/;
 
Example #25
Source File: ZipUtils.java    From youtubedl-android with GNU General Public License v3.0 5 votes vote down vote up
public static void unzip(File sourceFile, File targetDirectory) throws IOException, ErrnoException, IllegalAccessException {
    try (ZipFile zipFile = new ZipFile(sourceFile)) {
        Enumeration<ZipArchiveEntry> entries = zipFile.getEntries();
        while (entries.hasMoreElements()) {
            ZipArchiveEntry entry = entries.nextElement();
            File entryDestination = new File(targetDirectory, entry.getName());
            // prevent zipSlip
            if (!entryDestination.getCanonicalPath().startsWith(targetDirectory.getCanonicalPath() + File.separator)) {
                throw new IllegalAccessException("Entry is outside of the target dir: " + entry.getName());
            }
            if (entry.isDirectory()) {
                entryDestination.mkdirs();
            } else if (entry.isUnixSymlink()) {
                try (InputStream in = zipFile.getInputStream(entry)) {
                    String symlink = IOUtils.toString(in, StandardCharsets.UTF_8);
                    Os.symlink(symlink, entryDestination.getAbsolutePath());
                }
            } else {
                entryDestination.getParentFile().mkdirs();
                try (InputStream in = zipFile.getInputStream(entry);
                     OutputStream out = new FileOutputStream(entryDestination)) {
                    IOUtils.copy(in, out);
                }
            }
        }
    }
}
 
Example #26
Source File: Posix.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public native FileDescriptor[] pipe() throws ErrnoException /*-[
  int fds[2];
  LibcoreIoPosix_throwIfMinusOneWithNSString_withInt_(@"pipe", TEMP_FAILURE_RETRY(pipe(&fds[0])));
  IOSObjectArray *result = [IOSObjectArray arrayWithLength:2 type:JavaIoFileDescriptor_class_()];
  for (int i = 0; i < 2; ++i) {
    JavaIoFileDescriptor *fd = AUTORELEASE([[JavaIoFileDescriptor alloc] init]);
    [fd setInt$WithInt:fds[i]];
    [result replaceObjectAtIndex:i withObject:fd];
  }
  return result;
]-*/;
 
Example #27
Source File: SambaDir.java    From samba-documents-provider with GNU General Public License v3.0 5 votes vote down vote up
@Override
public void close() throws IOException {
  try {
    int dh = mNativeDh;
    mNativeDh = -1;
    close(mNativeHandler, dh);
  } catch (ErrnoException e) {
    throw new IOException(e);
  }
}
 
Example #28
Source File: Posix.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private native int pwriteBytes(FileDescriptor fd, Object buffer,
    int bufferOffset, int byteCount, long offset) throws ErrnoException /*-[
  const char *bytes = BytesRO(buffer);
  if (!bytes) {
      return -1;
  }
  if (byteCount + offset < 0) {  // If buffer overflow.
    LibcoreIoPosix_throwErrnoExceptionWithNSString_withInt_(@"pwrite", ERANGE);
  }
  int rc =
    TEMP_FAILURE_RETRY(pwrite64([fd getInt$], bytes + bufferOffset, byteCount, offset));
  return LibcoreIoPosix_throwIfMinusOneWithNSString_withInt_(@"pwrite", rc);
]-*/;
 
Example #29
Source File: NetworkOs.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public static native int getsockoptByte(FileDescriptor fd, int level, int option)
    throws ErrnoException /*-[
  u_char result = 0;
  socklen_t size = sizeof(result);
  int rc = TEMP_FAILURE_RETRY(getsockopt([fd getInt$], level, option, &result, &size));
  if (rc == -1) {
    LibcoreIoPosix_throwErrnoExceptionWithNSString_withInt_(@"getsockopt", rc);
  }
  return result;
]-*/;
 
Example #30
Source File: NetworkBridge.java    From j2objc with Apache License 2.0 5 votes vote down vote up
private static String connectDetail(InetAddress inetAddress, int port, int timeoutMs, ErrnoException cause) {
    String detail = "failed to connect to " + inetAddress + " (port " + port + ")";
    if (timeoutMs > 0) {
        detail += " after " + timeoutMs + "ms";
    }
    if (cause != null) {
        detail += ": " + cause.getMessage();
    }
    return detail;
}