IoBridge.java revision 51cf1b49bca54ec0229a51df400ad1bee580b1bb
10b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes/*
20b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * Copyright (C) 2011 The Android Open Source Project
30b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes *
40b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * Licensed under the Apache License, Version 2.0 (the "License");
50b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * you may not use this file except in compliance with the License.
60b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * You may obtain a copy of the License at
70b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes *
80b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes *      http://www.apache.org/licenses/LICENSE-2.0
90b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes *
100b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * Unless required by applicable law or agreed to in writing, software
110b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * distributed under the License is distributed on an "AS IS" BASIS,
120b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
130b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * See the License for the specific language governing permissions and
140b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * limitations under the License.
150b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes */
160b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
170b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughespackage libcore.io;
180b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
190b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.io.FileDescriptor;
200b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.io.FileNotFoundException;
210b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.io.IOException;
220b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.BindException;
230b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.ConnectException;
240b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.DatagramPacket;
250b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.Inet4Address;
260b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.Inet6Address;
270b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.InetAddress;
280b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.InetSocketAddress;
290b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.NetworkInterface;
300b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.PortUnreachableException;
310b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.SocketAddress;
320b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.SocketException;
330b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.SocketOptions;
340b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.SocketTimeoutException;
350b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.net.UnknownHostException;
360b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.nio.ByteBuffer;
370b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport java.util.Arrays;
380b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughesimport static libcore.io.OsConstants.*;
392ca11d6eae460f94bc42bc2e453fac93f4b94eb0Jesse Wilsonimport libcore.util.MutableInt;
400b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
410b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes/**
420b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes * Implements java.io/java.net/java.nio semantics in terms of the underlying POSIX system calls.
430b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes */
440b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughespublic final class IoBridge {
450b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
460b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    private IoBridge() {
470b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
480b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
490b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static int available(FileDescriptor fd) throws IOException {
500b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
510b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            MutableInt available = new MutableInt(0);
522ca11d6eae460f94bc42bc2e453fac93f4b94eb0Jesse Wilson            Libcore.os.ioctlInt(fd, FIONREAD, available);
530b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (available.value < 0) {
540b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // If the fd refers to a regular file, the result is the difference between
550b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // the file size and the file position. This may be negative if the position
560b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // is past the end of the file. If the fd refers to a special file masquerading
570b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // as a regular file, the result may be negative because the special file
580b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // may appear to have zero size and yet a previous read call may have
590b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // read some amount of data and caused the file position to be advanced.
600b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                available.value = 0;
610b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
620b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return available.value;
630b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
640b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (errnoException.errno == ENOTTY) {
650b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // The fd is unwilling to opine about its read buffer.
660b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return 0;
670b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
680b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw errnoException.rethrowAsIOException();
690b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
700b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
710b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
720b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
730b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static void bind(FileDescriptor fd, InetAddress address, int port) throws SocketException {
740b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (address instanceof Inet6Address && ((Inet6Address) address).getScopeId() == 0) {
750b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // Linux won't let you bind a link-local address without a scope id. Find one.
760b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            NetworkInterface nif = NetworkInterface.getByInetAddress(address);
770b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (nif == null) {
780b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                throw new SocketException("Can't bind to a link-local address without a scope id: " + address);
790b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
800b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            try {
810b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                address = Inet6Address.getByAddress(address.getHostName(), address.getAddress(), nif.getIndex());
820b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            } catch (UnknownHostException ex) {
830b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                throw new AssertionError(ex); // Can't happen.
840b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
850b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
860b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
870b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.bind(fd, address, port);
880b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
890b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new BindException(errnoException.getMessage(), errnoException);
900b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
910b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
920b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
930b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
940b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    /**
950b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * Connects socket 'fd' to 'inetAddress' on 'port', with no timeout. The lack of a timeout
960b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * means this method won't throw SocketTimeoutException.
970b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     */
980b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static boolean connect(FileDescriptor fd, InetAddress inetAddress, int port) throws SocketException {
990b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
1000b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return IoBridge.connect(fd, inetAddress, port, 0);
1010b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (SocketTimeoutException ex) {
1020b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new AssertionError(ex); // Can't happen for a connect without a timeout.
1030b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
1040b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
1050b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
1060b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    /**
1070b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * Connects socket 'fd' to 'inetAddress' on 'port', with a the given 'timeoutMs'.
1080b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * Use timeoutMs == 0 for a blocking connect with no timeout.
1090b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     */
1100b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static boolean connect(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs) throws SocketException, SocketTimeoutException {
1110b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
1120b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return connectErrno(fd, inetAddress, port, timeoutMs);
1130b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
1140b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new ConnectException(connectDetail(inetAddress, port, timeoutMs, errnoException), errnoException);
1150b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (SocketException ex) {
1160b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw ex; // We don't want to doubly wrap these.
1170b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (SocketTimeoutException ex) {
1180b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw ex; // We don't want to doubly wrap these.
1190b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (IOException ex) {
1200b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new SocketException(ex);
1210b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
1220b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
1230b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
1249b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes    private static boolean connectErrno(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs) throws ErrnoException, IOException {
1250b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        // With no timeout, just call connect(2) directly.
1260b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (timeoutMs == 0) {
1270b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.connect(fd, inetAddress, port);
1280b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return true;
1290b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
1300b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
131796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        // For connect with a timeout, we:
132796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        //   1. set the socket to non-blocking,
133796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        //   2. connect(2),
134796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        //   3. loop using poll(2) to decide whether we're connected, whether we should keep
135796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        //      waiting, or whether we've seen a permanent failure and should give up,
136796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        //   4. set the socket back to blocking.
137796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes
138796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        // 1. set the socket to non-blocking.
1390b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        IoUtils.setBlocking(fd, false);
140796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes
141796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        // 2. call connect(2) non-blocking.
142796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        long finishTimeMs = System.currentTimeMillis() + timeoutMs;
1430b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
144796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            Libcore.os.connect(fd, inetAddress, port);
145796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            IoUtils.setBlocking(fd, true); // 4. set the socket back to blocking.
146796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            return true; // We connected immediately.
147796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        } catch (ErrnoException errnoException) {
148796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            if (errnoException.errno != EINPROGRESS) {
149796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes                throw errnoException;
1500b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
151796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            // EINPROGRESS means we should keep trying...
1520b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
153796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes
154796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        // 3. loop using poll(2).
155796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        int remainingTimeoutMs;
156796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        do {
157796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            remainingTimeoutMs = (int) (finishTimeMs - System.currentTimeMillis());
158796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            if (remainingTimeoutMs <= 0) {
159796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes                throw new SocketTimeoutException(connectDetail(inetAddress, port, timeoutMs, null));
160796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            }
161796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        } while (!IoBridge.isConnected(fd, inetAddress, port, timeoutMs, remainingTimeoutMs));
162796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        IoUtils.setBlocking(fd, true); // 4. set the socket back to blocking.
163796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes        return true; // Or we'd have thrown.
1640b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
1650b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
1660b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    private static String connectDetail(InetAddress inetAddress, int port, int timeoutMs, ErrnoException cause) {
1670b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        String detail = "failed to connect to " + inetAddress + " (port " + port + ")";
1680b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (timeoutMs > 0) {
1690b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            detail += " after " + timeoutMs + "ms";
1700b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
1710b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (cause != null) {
1720b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            detail += ": " + cause.getMessage();
1730b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
1740b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        return detail;
1750b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
1760b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
1770b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static void closeSocket(FileDescriptor fd) throws IOException {
1780b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (!fd.valid()) {
1790b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // Socket.close doesn't throw if you try to close an already-closed socket.
1800b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
1810b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
1820b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        int intFd = fd.getInt$();
1830b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        fd.setInt$(-1);
1840b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        FileDescriptor oldFd = new FileDescriptor();
1850b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        oldFd.setInt$(intFd);
1860b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        AsynchronousCloseMonitor.signalBlockedThreads(oldFd);
1870b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
1880b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.close(oldFd);
1890b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
1900b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // TODO: are there any cases in which we should throw?
1910b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
1920b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
1930b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
1940b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static boolean isConnected(FileDescriptor fd, InetAddress inetAddress, int port, int timeoutMs, int remainingTimeoutMs) throws IOException {
1952ca11d6eae460f94bc42bc2e453fac93f4b94eb0Jesse Wilson        ErrnoException cause;
1960b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
1970b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            StructPollfd[] pollFds = new StructPollfd[] { new StructPollfd() };
1980b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            pollFds[0].fd = fd;
1990b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            pollFds[0].events = (short) POLLOUT;
2000b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            int rc = Libcore.os.poll(pollFds, remainingTimeoutMs);
2010b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (rc == 0) {
2020b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return false; // Timeout.
2030b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
2040b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            int connectError = Libcore.os.getsockoptInt(fd, SOL_SOCKET, SO_ERROR);
2050b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (connectError == 0) {
2060b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return true; // Success!
2070b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
2080b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new ErrnoException("isConnected", connectError); // The connect(2) failed.
2090b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
210796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            if (!fd.valid()) {
211796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes                throw new SocketException("Socket closed");
212796f0d5a4e7b83c3efc5e587b6766977dc20b0c3Elliott Hughes            }
2130b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (errnoException.errno == EINTR) {
2140b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return false; // Punt and ask the caller to try again.
2150b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            } else {
2160b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                cause = errnoException;
2170b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
2180b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
2190b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        String detail = connectDetail(inetAddress, port, timeoutMs, cause);
22051f50987458f4b9c3bf3d53f829331a335f67113Elliott Hughes        if (cause.errno == ETIMEDOUT) {
2210b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new SocketTimeoutException(detail, cause);
2220b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
22351f50987458f4b9c3bf3d53f829331a335f67113Elliott Hughes        throw new ConnectException(detail, cause);
2240b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
2250b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
2260b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    // Socket options used by java.net but not exposed in SocketOptions.
2270b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static final int JAVA_MCAST_JOIN_GROUP = 19;
2280b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static final int JAVA_MCAST_LEAVE_GROUP = 20;
2290b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static final int JAVA_IP_MULTICAST_TTL = 17;
2300b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
2310b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    /**
2320b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * java.net has its own socket options similar to the underlying Unix ones. We paper over the
2330b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * differences here.
2340b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     */
2350b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static Object getSocketOption(FileDescriptor fd, int option) throws SocketException {
2360b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
2370b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return getSocketOptionErrno(fd, option);
2380b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
2390b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw errnoException.rethrowAsSocketException();
2400b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
2410b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
2420b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
2439b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes    private static Object getSocketOptionErrno(FileDescriptor fd, int option) throws ErrnoException, SocketException {
2440b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        switch (option) {
2450b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.IP_MULTICAST_IF:
2460b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // This is IPv4-only.
2470b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return Libcore.os.getsockoptInAddr(fd, IPPROTO_IP, IP_MULTICAST_IF);
2480b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.IP_MULTICAST_IF2:
2490b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // This is IPv6-only.
2500b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return Libcore.os.getsockoptInt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF);
2510b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.IP_MULTICAST_LOOP:
2520b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // Since setting this from java.net always sets IPv4 and IPv6 to the same value,
2530b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // it doesn't matter which we return.
2540b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return booleanFromInt(Libcore.os.getsockoptInt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP));
2550b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case IoBridge.JAVA_IP_MULTICAST_TTL:
2560b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // Since setting this from java.net always sets IPv4 and IPv6 to the same value,
2570b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // it doesn't matter which we return.
2580b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return Libcore.os.getsockoptInt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS);
2590b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.IP_TOS:
2600b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // Since setting this from java.net always sets IPv4 and IPv6 to the same value,
2610b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // it doesn't matter which we return.
2620b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return Libcore.os.getsockoptInt(fd, IPPROTO_IPV6, IPV6_TCLASS);
2630b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_BROADCAST:
2640b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return booleanFromInt(Libcore.os.getsockoptInt(fd, SOL_SOCKET, SO_BROADCAST));
2650b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_KEEPALIVE:
2660b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return booleanFromInt(Libcore.os.getsockoptInt(fd, SOL_SOCKET, SO_KEEPALIVE));
2670b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_LINGER:
2680b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            StructLinger linger = Libcore.os.getsockoptLinger(fd, SOL_SOCKET, SO_LINGER);
2690b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (!linger.isOn()) {
2700b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return false;
2710b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
2720b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return linger.l_linger;
2730b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_OOBINLINE:
2740b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return booleanFromInt(Libcore.os.getsockoptInt(fd, SOL_SOCKET, SO_OOBINLINE));
2750b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_RCVBUF:
27651cf1b49bca54ec0229a51df400ad1bee580b1bbBrian Carlstrom            return Libcore.os.getsockoptInt(fd, SOL_SOCKET, SO_RCVBUF);
2770b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_REUSEADDR:
2780b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return booleanFromInt(Libcore.os.getsockoptInt(fd, SOL_SOCKET, SO_REUSEADDR));
2790b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_SNDBUF:
2800b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return Libcore.os.getsockoptInt(fd, SOL_SOCKET, SO_SNDBUF);
2810b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_TIMEOUT:
2820b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return (int) Libcore.os.getsockoptTimeval(fd, SOL_SOCKET, SO_RCVTIMEO).toMillis();
2830b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.TCP_NODELAY:
2840b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return booleanFromInt(Libcore.os.getsockoptInt(fd, IPPROTO_TCP, TCP_NODELAY));
2850b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        default:
2860b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new SocketException("Unknown socket option: " + option);
2870b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
2880b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
2890b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
2900b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    private static boolean booleanFromInt(int i) {
2910b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        return (i != 0);
2920b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
2930b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
2940b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    private static int booleanToInt(boolean b) {
2950b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        return b ? 1 : 0;
2960b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
2970b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
2980b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    /**
2990b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * java.net has its own socket options similar to the underlying Unix ones. We paper over the
3000b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * differences here.
3010b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     */
3020b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static void setSocketOption(FileDescriptor fd, int option, Object value) throws SocketException {
3030b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
3040b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            setSocketOptionErrno(fd, option, value);
3050b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
3060b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw errnoException.rethrowAsSocketException();
3070b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
3080b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
3090b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
3109b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes    private static void setSocketOptionErrno(FileDescriptor fd, int option, Object value) throws ErrnoException, SocketException {
3110b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        switch (option) {
3120b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.IP_MULTICAST_IF:
3130b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new UnsupportedOperationException("Use IP_MULTICAST_IF2 on Android");
3140b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.IP_MULTICAST_IF2:
3150b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // Although IPv6 was cleaned up to use int, IPv4 uses an ip_mreqn containing an int.
3160b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptIpMreqn(fd, IPPROTO_IP, IP_MULTICAST_IF, (Integer) value);
3170b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, IPPROTO_IPV6, IPV6_MULTICAST_IF, (Integer) value);
3180b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3190b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.IP_MULTICAST_LOOP:
3200b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // Although IPv6 was cleaned up to use int, IPv4 multicast loopback uses a byte.
3210b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptByte(fd, IPPROTO_IP, IP_MULTICAST_LOOP, booleanToInt((Boolean) value));
3220b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, IPPROTO_IPV6, IPV6_MULTICAST_LOOP, booleanToInt((Boolean) value));
3230b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3240b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case IoBridge.JAVA_IP_MULTICAST_TTL:
3250b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // Although IPv6 was cleaned up to use int, and IPv4 non-multicast TTL uses int,
3260b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // IPv4 multicast TTL uses a byte.
3270b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptByte(fd, IPPROTO_IP, IP_MULTICAST_TTL, (Integer) value);
3280b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, (Integer) value);
3290b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3300b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.IP_TOS:
3310b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, IPPROTO_IP, IP_TOS, (Integer) value);
3320b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, IPPROTO_IPV6, IPV6_TCLASS, (Integer) value);
3330b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3340b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_BROADCAST:
3350b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, SOL_SOCKET, SO_BROADCAST, booleanToInt((Boolean) value));
3360b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3370b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_KEEPALIVE:
3380b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, SOL_SOCKET, SO_KEEPALIVE, booleanToInt((Boolean) value));
3390b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3400b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_LINGER:
3410b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            boolean on = false;
3420b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            int seconds = 0;
3430b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (value instanceof Integer) {
3440b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                on = true;
3450b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                seconds = Math.min((Integer) value, 65535);
3460b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
3470b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            StructLinger linger = new StructLinger(booleanToInt(on), seconds);
3480b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptLinger(fd, SOL_SOCKET, SO_LINGER, linger);
3490b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3500b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_OOBINLINE:
3510b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, SOL_SOCKET, SO_OOBINLINE, booleanToInt((Boolean) value));
3520b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3530b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_RCVBUF:
3540b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, SOL_SOCKET, SO_RCVBUF, (Integer) value);
3550b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3560b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_REUSEADDR:
3570b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, SOL_SOCKET, SO_REUSEADDR, booleanToInt((Boolean) value));
3580b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3590b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_SNDBUF:
3600b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, SOL_SOCKET, SO_SNDBUF, (Integer) value);
3610b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3620b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.SO_TIMEOUT:
3630b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            int millis = (Integer) value;
3640b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            StructTimeval tv = StructTimeval.fromMillis(millis);
3650b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptTimeval(fd, SOL_SOCKET, SO_RCVTIMEO, tv);
3660b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3670b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case SocketOptions.TCP_NODELAY:
3680b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptInt(fd, IPPROTO_TCP, TCP_NODELAY, booleanToInt((Boolean) value));
3690b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3700b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case IoBridge.JAVA_MCAST_JOIN_GROUP:
3710b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        case IoBridge.JAVA_MCAST_LEAVE_GROUP:
3720b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            StructGroupReq groupReq = (StructGroupReq) value;
3730b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            int level = (groupReq.gr_group instanceof Inet4Address) ? IPPROTO_IP : IPPROTO_IPV6;
3740b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            int op = (option == JAVA_MCAST_JOIN_GROUP) ? MCAST_JOIN_GROUP : MCAST_LEAVE_GROUP;
3750b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            Libcore.os.setsockoptGroupReq(fd, level, op, groupReq);
3760b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
3770b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        default:
3780b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw new SocketException("Unknown socket option: " + option);
3790b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
3800b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
3810b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
3820b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    /**
3830b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * java.io only throws FileNotFoundException when opening files, regardless of what actually
3840b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * went wrong. Additionally, java.io is more restrictive than POSIX when it comes to opening
3850b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * directories: POSIX says read-only is okay, but java.io doesn't even allow that. We also
3860b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * have an Android-specific hack to alter the default permissions.
3870b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     */
3880b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static FileDescriptor open(String path, int flags) throws FileNotFoundException {
3890b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        FileDescriptor fd = null;
3900b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
3910b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // On Android, we don't want default permissions to allow global access.
3920b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            int mode = ((flags & O_ACCMODE) == O_RDONLY) ? 0 : 0600;
3930b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            fd = Libcore.os.open(path, flags, mode);
3940b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (fd.valid()) {
3950b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // Posix open(2) fails with EISDIR only if you ask for write permission.
3960b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // Java disallows reading directories too.
3970b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                if (S_ISDIR(Libcore.os.fstat(fd).st_mode)) {
3980b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                    throw new ErrnoException("open", EISDIR);
3990b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                }
4000b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
4010b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return fd;
4020b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
4030b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            try {
4040b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                if (fd != null) {
4050b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                    IoUtils.close(fd);
4060b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                }
4070b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            } catch (IOException ignored) {
4080b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
4090b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            FileNotFoundException ex = new FileNotFoundException(path + ": " + errnoException.getMessage());
4100b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            ex.initCause(errnoException);
4110b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw ex;
4120b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4130b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
4140b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
4150b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    /**
4160b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * java.io thinks that a read at EOF is an error and should return -1, contrary to traditional
4170b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * Unix practice where you'd read until you got 0 bytes (and any future read would return -1).
4180b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     */
4190b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static int read(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {
4200b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        Arrays.checkOffsetAndCount(bytes.length, byteOffset, byteCount);
4210b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (byteCount == 0) {
4220b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return 0;
4230b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4240b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
4250b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            int readCount = Libcore.os.read(fd, bytes, byteOffset, byteCount);
4260b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (readCount == 0) {
4270b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return -1;
4280b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
4290b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return readCount;
4300b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
4310b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (errnoException.errno == EAGAIN) {
4320b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // We return 0 rather than throw if we try to read from an empty non-blocking pipe.
4330b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return 0;
4340b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
4350b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw errnoException.rethrowAsIOException();
4360b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4370b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
4380b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
4390b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    /**
4400b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * java.io always writes every byte it's asked to, or fails with an error. (That is, unlike
4410b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     * Unix it never just writes as many bytes as happens to be convenient.)
4420b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes     */
4430b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static void write(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount) throws IOException {
4440b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        Arrays.checkOffsetAndCount(bytes.length, byteOffset, byteCount);
4450b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (byteCount == 0) {
4460b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return;
4470b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4480b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
4490b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            while (byteCount > 0) {
4500b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                int bytesWritten = Libcore.os.write(fd, bytes, byteOffset, byteCount);
4510b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                byteCount -= bytesWritten;
4520b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                byteOffset += bytesWritten;
4530b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
4540b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
4550b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw errnoException.rethrowAsIOException();
4560b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4570b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
4580b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
4590b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static int sendto(FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, int flags, InetAddress inetAddress, int port) throws IOException {
4600b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        boolean isDatagram = (inetAddress != null);
4610b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (!isDatagram && byteCount <= 0) {
4620b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return 0;
4630b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4640b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        int result;
4650b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
4660b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = Libcore.os.sendto(fd, bytes, byteOffset, byteCount, flags, inetAddress, port);
4670b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
4680b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = maybeThrowAfterSendto(isDatagram, errnoException);
4690b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4700b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        return result;
4710b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
4720b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
4730b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static int sendto(FileDescriptor fd, ByteBuffer buffer, int flags, InetAddress inetAddress, int port) throws IOException {
4740b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        boolean isDatagram = (inetAddress != null);
4750b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (!isDatagram && buffer.remaining() == 0) {
4760b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return 0;
4770b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4780b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        int result;
4790b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
4800b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = Libcore.os.sendto(fd, buffer, flags, inetAddress, port);
4810b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
4820b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = maybeThrowAfterSendto(isDatagram, errnoException);
4830b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4840b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        return result;
4850b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
4860b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
4870b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    private static int maybeThrowAfterSendto(boolean isDatagram, ErrnoException errnoException) throws SocketException {
4880b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (isDatagram) {
4890b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (errnoException.errno == ECONNRESET || errnoException.errno == ECONNREFUSED) {
4900b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return 0;
4910b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
4920b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } else {
4930b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (errnoException.errno == EAGAIN || errnoException.errno == EWOULDBLOCK) {
4940b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // We were asked to write to a non-blocking socket, but were told
4950b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                // it would block, so report "no bytes written".
4960b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return 0;
4970b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
4980b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
4990b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        throw errnoException.rethrowAsSocketException();
5000b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
5010b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5020b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static int recvfrom(boolean isRead, FileDescriptor fd, byte[] bytes, int byteOffset, int byteCount, int flags, DatagramPacket packet, boolean isConnected) throws IOException {
5030b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        int result;
5040b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
5050b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            InetSocketAddress srcAddress = (packet != null && !isConnected) ? new InetSocketAddress() : null;
5060b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = Libcore.os.recvfrom(fd, bytes, byteOffset, byteCount, flags, srcAddress);
5070b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = postRecvfrom(isRead, packet, isConnected, srcAddress, result);
5080b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
5090b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = maybeThrowAfterRecvfrom(isRead, isConnected, errnoException);
5100b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
5110b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        return result;
5120b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
5130b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5140b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static int recvfrom(boolean isRead, FileDescriptor fd, ByteBuffer buffer, int flags, DatagramPacket packet, boolean isConnected) throws IOException {
5150b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        int result;
5160b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
5170b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            InetSocketAddress srcAddress = (packet != null && !isConnected) ? new InetSocketAddress() : null;
5180b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = Libcore.os.recvfrom(fd, buffer, flags, srcAddress);
5190b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = postRecvfrom(isRead, packet, isConnected, srcAddress, result);
5200b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
5210b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            result = maybeThrowAfterRecvfrom(isRead, isConnected, errnoException);
5220b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
5230b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        return result;
5240b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
5250b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5260b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    private static int postRecvfrom(boolean isRead, DatagramPacket packet, boolean isConnected, InetSocketAddress srcAddress, int byteCount) {
5270b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (isRead && byteCount == 0) {
5280b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return -1;
5290b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
5300b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (packet != null) {
531e50d82455c813210a2d452070f45fd38d9903159Elliott Hughes            packet.setReceivedLength(byteCount);
5320b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (!isConnected) {
5330b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                packet.setAddress(srcAddress.getAddress());
5340b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                packet.setPort(srcAddress.getPort());
5350b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
5360b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
5370b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        return byteCount;
5380b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
5390b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5400b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    private static int maybeThrowAfterRecvfrom(boolean isRead, boolean isConnected, ErrnoException errnoException) throws SocketException, SocketTimeoutException {
5410b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        if (isRead) {
5420b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (errnoException.errno == EAGAIN || errnoException.errno == EWOULDBLOCK) {
5430b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                return 0;
5440b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            } else {
5450b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                throw errnoException.rethrowAsSocketException();
5460b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
5470b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } else {
5480b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (isConnected && errnoException.errno == ECONNREFUSED) {
5490b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                throw new PortUnreachableException("", errnoException);
5500b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            } else if (errnoException.errno == EAGAIN || errnoException.errno == EWOULDBLOCK) {
5510b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                throw new SocketTimeoutException(errnoException);
5520b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            } else {
5530b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                throw errnoException.rethrowAsSocketException();
5540b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
5550b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
5560b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
5570b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5580b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static FileDescriptor socket(boolean stream) throws SocketException {
5590b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        FileDescriptor fd;
5600b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        try {
5610b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            fd = Libcore.os.socket(AF_INET6, stream ? SOCK_STREAM : SOCK_DGRAM, 0);
5620b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5630b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // The RFC (http://www.ietf.org/rfc/rfc3493.txt) says that IPV6_MULTICAST_HOPS defaults
5640b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // to 1. The Linux kernel (at least up to 2.6.38) accidentally defaults to 64 (which
5650b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // would be correct for the *unicast* hop limit).
5660b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // See http://www.spinics.net/lists/netdev/msg129022.html, though no patch appears to
5670b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // have been applied as a result of that discussion. If that bug is ever fixed, we can
5680b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // remove this code. Until then, we manually set the hop limit on IPv6 datagram sockets.
5690b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            // (IPv4 is already correct.)
5700b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            if (!stream) {
5710b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes                Libcore.os.setsockoptInt(fd, IPPROTO_IPV6, IPV6_MULTICAST_HOPS, 1);
5720b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            }
5730b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5740b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            return fd;
5750b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        } catch (ErrnoException errnoException) {
5760b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes            throw errnoException.rethrowAsSocketException();
5770b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes        }
5780b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
5790b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5800b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static InetAddress getSocketLocalAddress(FileDescriptor fd) {
5819b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes        try {
5829b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes            SocketAddress sa = Libcore.os.getsockname(fd);
5839b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes            InetSocketAddress isa = (InetSocketAddress) sa;
5849b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes            return isa.getAddress();
5859b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes        } catch (ErrnoException errnoException) {
5869b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes            throw new AssertionError(errnoException);
5879b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes        }
5880b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
5890b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes
5900b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    public static int getSocketLocalPort(FileDescriptor fd) {
5919b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes        try {
5929b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes            SocketAddress sa = Libcore.os.getsockname(fd);
5939b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes            InetSocketAddress isa = (InetSocketAddress) sa;
5949b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes            return isa.getPort();
5959b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes        } catch (ErrnoException errnoException) {
5969b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes            throw new AssertionError(errnoException);
5979b510df35b57946d843ffc34cf23fdcfc84c5220Elliott Hughes        }
5980b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes    }
5990b736ebc4efef64f2db1999aea90297ad8196146Elliott Hughes}
600