InheritedChannel.java 8.2 KB
Newer Older
D
duke 已提交
1
/*
2
 * Copyright (c) 2003, 2004, Oracle and/or its affiliates. All rights reserved.
D
duke 已提交
3 4 5 6
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * This code is free software; you can redistribute it and/or modify it
 * under the terms of the GNU General Public License version 2 only, as
7
 * published by the Free Software Foundation.  Oracle designates this
D
duke 已提交
8
 * particular file as subject to the "Classpath" exception as provided
9
 * by Oracle in the LICENSE file that accompanied this code.
D
duke 已提交
10 11 12 13 14 15 16 17 18 19 20
 *
 * This code is distributed in the hope that it will be useful, but WITHOUT
 * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
 * version 2 for more details (a copy is included in the LICENSE file that
 * accompanied this code).
 *
 * You should have received a copy of the GNU General Public License version
 * 2 along with this work; if not, write to the Free Software Foundation,
 * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
 *
21 22 23
 * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
 * or visit www.oracle.com if you need additional information or have any
 * questions.
D
duke 已提交
24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98
 */

package sun.nio.ch;

import java.lang.reflect.Constructor;
import java.io.FileDescriptor;
import java.io.IOException;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.nio.channels.Channel;
import java.nio.channels.SocketChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.DatagramChannel;
import java.nio.channels.spi.SelectorProvider;

class InheritedChannel {

    // the "types" of socket returned by soType0
    private static final int UNKNOWN            = -1;
    private static final int SOCK_STREAM        = 1;
    private static final int SOCK_DGRAM         = 2;

    // oflag values when opening a file
    private static final int O_RDONLY           = 0;
    private static final int O_WRONLY           = 1;
    private static final int O_RDWR             = 2;

    /*
     * In order to "detach" the standard streams we dup them to /dev/null.
     * In order to reduce the possibility of an error at close time we
     * open /dev/null early - that way we know we won't run out of file
     * descriptors at close time. This makes the close operation a
     * simple dup2 operation for each of the standard streams.
     */
    private static int devnull = -1;

    private static void detachIOStreams() {
        try {
            dup2(devnull, 0);
            dup2(devnull, 1);
            dup2(devnull, 2);
        } catch (IOException ioe) {
            // this shouldn't happen
            throw new InternalError();
        }
    }

    /*
     * Override the implCloseSelectableChannel for each channel type - this
     * allows us to "detach" the standard streams after closing and ensures
     * that the underlying socket really closes.
     */
    public static class InheritedSocketChannelImpl extends SocketChannelImpl {

        InheritedSocketChannelImpl(SelectorProvider sp,
                                   FileDescriptor fd,
                                   InetSocketAddress remote)
            throws IOException
        {
            super(sp, fd, remote);
        }

        protected void implCloseSelectableChannel() throws IOException {
            super.implCloseSelectableChannel();
            detachIOStreams();
        }
    }

    public static class InheritedServerSocketChannelImpl extends
        ServerSocketChannelImpl {

        InheritedServerSocketChannelImpl(SelectorProvider sp,
                                         FileDescriptor fd)
            throws IOException
        {
A
alanb 已提交
99
            super(sp, fd, true);
D
duke 已提交
100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240
        }

        protected void implCloseSelectableChannel() throws IOException {
            super.implCloseSelectableChannel();
            detachIOStreams();
        }

    }

    public static class InheritedDatagramChannelImpl extends
        DatagramChannelImpl {

        InheritedDatagramChannelImpl(SelectorProvider sp,
                                     FileDescriptor fd)
            throws IOException
        {
            super(sp, fd);
        }

        protected void implCloseSelectableChannel() throws IOException {
            super.implCloseSelectableChannel();
            detachIOStreams();
        }
    }

    /*
     * If there's a SecurityManager then check for the appropriate
     * RuntimePermission.
     */
    private static void checkAccess(Channel c) {
        SecurityManager sm = System.getSecurityManager();
        if (sm != null) {
            sm.checkPermission(
                new RuntimePermission("inheritedChannel")
            );
        }
    }


    /*
     * If standard inherited channel is connected to a socket then return a Channel
     * of the appropriate type based standard input.
     */
    private static Channel createChannel() throws IOException {

        // dup the file descriptor - we do this so that for two reasons :-
        // 1. Avoids any timing issues with FileDescriptor.in being closed
        //    or redirected while we create the channel.
        // 2. Allows streams based on file descriptor 0 to co-exist with
        //    the channel (closing one doesn't impact the other)

        int fdVal = dup(0);

        // Examine the file descriptor - if it's not a socket then we don't
        // create a channel so we release the file descriptor.

        int st;
        st = soType0(fdVal);
        if (st != SOCK_STREAM && st != SOCK_DGRAM) {
            close0(fdVal);
            return null;
        }


        // Next we create a FileDescriptor for the dup'ed file descriptor
        // Have to use reflection and also make assumption on how FD
        // is implemented.

        Class paramTypes[] = { int.class };
        Constructor ctr = Reflect.lookupConstructor("java.io.FileDescriptor",
                                                    paramTypes);
        Object args[] = { new Integer(fdVal) };
        FileDescriptor fd = (FileDescriptor)Reflect.invoke(ctr, args);


        // Now create the channel. If the socket is a streams socket then
        // we see if tthere is a peer (ie: connected). If so, then we
        // create a SocketChannel, otherwise a ServerSocketChannel.
        // If the socket is a datagram socket then create a DatagramChannel

        SelectorProvider provider = SelectorProvider.provider();
        assert provider instanceof sun.nio.ch.SelectorProviderImpl;

        Channel c;
        if (st == SOCK_STREAM) {
            InetAddress ia = peerAddress0(fdVal);
            if (ia == null) {
               c = new InheritedServerSocketChannelImpl(provider, fd);
            } else {
               int port = peerPort0(fdVal);
               assert port > 0;
               InetSocketAddress isa = new InetSocketAddress(ia, port);
               c = new InheritedSocketChannelImpl(provider, fd, isa);
            }
        } else {
            c = new InheritedDatagramChannelImpl(provider, fd);
        }
        return c;
    }

    private static boolean haveChannel = false;
    private static Channel channel = null;

    /*
     * Returns a Channel representing the inherited channel if the
     * inherited channel is a stream connected to a network socket.
     */
    public static synchronized Channel getChannel() throws IOException {
        if (devnull < 0) {
            devnull = open0("/dev/null", O_RDWR);
        }

        // If we don't have the channel try to create it
        if (!haveChannel) {
            channel = createChannel();
            haveChannel = true;
        }

        // if there is a channel then do the security check before
        // returning it.
        if (channel != null) {
            checkAccess(channel);
        }
        return channel;
    }


    // -- Native methods --

    private static native int dup(int fd) throws IOException;
    private static native void dup2(int fd, int fd2) throws IOException;
    private static native int open0(String path, int oflag) throws IOException;
    private static native void close0(int fd) throws IOException;
    private static native int soType0(int fd);
    private static native InetAddress peerAddress0(int fd);
    private static native int peerPort0(int fd);

    static {
        Util.load();
    }
}