SocketAdaptor.java 14.4 KB
Newer Older
D
duke 已提交
1
/*
A
alanb 已提交
2
 * Copyright (c) 2000, 2018, 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
 */

package sun.nio.ch;

A
alanb 已提交
28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.SocketException;
import java.net.SocketImpl;
import java.net.SocketOption;
import java.net.SocketTimeoutException;
import java.net.StandardSocketOptions;
import java.nio.ByteBuffer;
import java.nio.channels.Channels;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.IllegalBlockingModeException;
import java.nio.channels.SocketChannel;
D
duke 已提交
45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61
import java.security.AccessController;
import java.security.PrivilegedExceptionAction;
import java.util.*;


// Make a socket channel look like a socket.
//
// The only aspects of java.net.Socket-hood that we don't attempt to emulate
// here are the interrupted-I/O exceptions (which our Solaris implementations
// attempt to support) and the sending of urgent data.  Otherwise an adapted
// socket should look enough like a real java.net.Socket to fool most of the
// developers most of the time, right down to the exception message strings.
//
// The methods in this class are defined in exactly the same order as in
// java.net.Socket so as to simplify tracking future changes to that class.
//

A
alanb 已提交
62
class SocketAdaptor
D
duke 已提交
63 64 65 66 67 68 69 70 71
    extends Socket
{

    // The channel being adapted
    private final SocketChannelImpl sc;

    // Timeout "option" value for reads
    private volatile int timeout = 0;

72 73
    private SocketAdaptor(SocketChannelImpl sc) throws SocketException {
        super((SocketImpl) null);
D
duke 已提交
74 75 76 77
        this.sc = sc;
    }

    public static Socket create(SocketChannelImpl sc) {
78 79 80 81 82
        try {
            return new SocketAdaptor(sc);
        } catch (SocketException e) {
            throw new InternalError("Should not reach here");
        }
D
duke 已提交
83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119
    }

    public SocketChannel getChannel() {
        return sc;
    }

    // Override this method just to protect against changes in the superclass
    //
    public void connect(SocketAddress remote) throws IOException {
        connect(remote, 0);
    }

    public void connect(SocketAddress remote, int timeout) throws IOException {
        if (remote == null)
            throw new IllegalArgumentException("connect: The address can't be null");
        if (timeout < 0)
            throw new IllegalArgumentException("connect: timeout can't be negative");

        synchronized (sc.blockingLock()) {
            if (!sc.isBlocking())
                throw new IllegalBlockingModeException();

            try {
                if (timeout == 0) {
                    sc.connect(remote);
                    return;
                }

                sc.configureBlocking(false);
                try {
                    if (sc.connect(remote))
                        return;
                    long to = timeout;
                    for (;;) {
                        if (!sc.isOpen())
                            throw new ClosedChannelException();
                        long st = System.currentTimeMillis();
120

121
                        int result = sc.poll(Net.POLLCONN, to);
122
                        if (result > 0 && sc.finishConnect())
D
duke 已提交
123 124 125 126 127 128 129 130 131 132
                            break;
                        to -= System.currentTimeMillis() - st;
                        if (to <= 0) {
                            try {
                                sc.close();
                            } catch (IOException x) { }
                            throw new SocketTimeoutException();
                        }
                    }
                } finally {
A
alanb 已提交
133
                    try {
D
duke 已提交
134
                        sc.configureBlocking(true);
A
alanb 已提交
135
                    } catch (ClosedChannelException e) { }
D
duke 已提交
136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153
                }

            } catch (Exception x) {
                Net.translateException(x, true);
            }
        }

    }

    public void bind(SocketAddress local) throws IOException {
        try {
            sc.bind(local);
        } catch (Exception x) {
            Net.translateException(x);
        }
    }

    public InetAddress getInetAddress() {
154 155
        SocketAddress remote = sc.remoteAddress();
        if (remote == null) {
D
duke 已提交
156
            return null;
157 158 159
        } else {
            return ((InetSocketAddress)remote).getAddress();
        }
D
duke 已提交
160 161 162
    }

    public InetAddress getLocalAddress() {
163
        if (sc.isOpen()) {
164 165 166 167
            InetSocketAddress local = sc.localAddress();
            if (local != null) {
                return Net.getRevealedLocalAddress(local).getAddress();
            }
168 169
        }
        return new InetSocketAddress(0).getAddress();
D
duke 已提交
170 171 172
    }

    public int getPort() {
173 174
        SocketAddress remote = sc.remoteAddress();
        if (remote == null) {
D
duke 已提交
175
            return 0;
176 177 178
        } else {
            return ((InetSocketAddress)remote).getPort();
        }
D
duke 已提交
179 180 181
    }

    public int getLocalPort() {
182 183
        SocketAddress local = sc.localAddress();
        if (local == null) {
D
duke 已提交
184
            return -1;
185 186 187
        } else {
            return ((InetSocketAddress)local).getPort();
        }
D
duke 已提交
188 189 190 191 192 193 194 195 196 197 198 199 200 201 202
    }

    private class SocketInputStream
        extends ChannelInputStream
    {
        private SocketInputStream() {
            super(sc);
        }

        protected int read(ByteBuffer bb)
            throws IOException
        {
            synchronized (sc.blockingLock()) {
                if (!sc.isBlocking())
                    throw new IllegalBlockingModeException();
A
alanb 已提交
203

D
duke 已提交
204 205
                if (timeout == 0)
                    return sc.read(bb);
206

A
alanb 已提交
207
                sc.configureBlocking(false);
D
duke 已提交
208 209 210 211 212 213 214 215 216
                try {
                    int n;
                    if ((n = sc.read(bb)) != 0)
                        return n;
                    long to = timeout;
                    for (;;) {
                        if (!sc.isOpen())
                            throw new ClosedChannelException();
                        long st = System.currentTimeMillis();
217
                        int result = sc.poll(Net.POLLIN, to);
218
                        if (result > 0) {
D
duke 已提交
219 220 221 222 223 224 225 226
                            if ((n = sc.read(bb)) != 0)
                                return n;
                        }
                        to -= System.currentTimeMillis() - st;
                        if (to <= 0)
                            throw new SocketTimeoutException();
                    }
                } finally {
A
alanb 已提交
227
                    try {
D
duke 已提交
228
                        sc.configureBlocking(true);
A
alanb 已提交
229
                    } catch (ClosedChannelException e) { }
D
duke 已提交
230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245
                }
            }
        }
    }

    private InputStream socketInputStream = null;

    public InputStream getInputStream() throws IOException {
        if (!sc.isOpen())
            throw new SocketException("Socket is closed");
        if (!sc.isConnected())
            throw new SocketException("Socket is not connected");
        if (!sc.isInputOpen())
            throw new SocketException("Socket input is shutdown");
        if (socketInputStream == null) {
            try {
246 247 248
                socketInputStream = AccessController.doPrivileged(
                    new PrivilegedExceptionAction<InputStream>() {
                        public InputStream run() throws IOException {
D
duke 已提交
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267
                            return new SocketInputStream();
                        }
                    });
            } catch (java.security.PrivilegedActionException e) {
                throw (IOException)e.getException();
            }
        }
        return socketInputStream;
    }

    public OutputStream getOutputStream() throws IOException {
        if (!sc.isOpen())
            throw new SocketException("Socket is closed");
        if (!sc.isConnected())
            throw new SocketException("Socket is not connected");
        if (!sc.isOutputOpen())
            throw new SocketException("Socket output is shutdown");
        OutputStream os = null;
        try {
268 269 270
            os = AccessController.doPrivileged(
                new PrivilegedExceptionAction<OutputStream>() {
                    public OutputStream run() throws IOException {
D
duke 已提交
271 272 273 274 275 276 277 278 279
                        return Channels.newOutputStream(sc);
                    }
                });
        } catch (java.security.PrivilegedActionException e) {
            throw (IOException)e.getException();
        }
        return os;
    }

280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315
    private void setBooleanOption(SocketOption<Boolean> name, boolean value)
        throws SocketException
    {
        try {
            sc.setOption(name, value);
        } catch (IOException x) {
            Net.translateToSocketException(x);
        }
    }

    private void setIntOption(SocketOption<Integer> name, int value)
        throws SocketException
    {
        try {
            sc.setOption(name, value);
        } catch (IOException x) {
            Net.translateToSocketException(x);
        }
    }

    private boolean getBooleanOption(SocketOption<Boolean> name) throws SocketException {
        try {
            return sc.getOption(name).booleanValue();
        } catch (IOException x) {
            Net.translateToSocketException(x);
            return false;       // keep compiler happy
        }
    }

    private int getIntOption(SocketOption<Integer> name) throws SocketException {
        try {
            return sc.getOption(name).intValue();
        } catch (IOException x) {
            Net.translateToSocketException(x);
            return -1;          // keep compiler happy
        }
D
duke 已提交
316 317 318
    }

    public void setTcpNoDelay(boolean on) throws SocketException {
319
        setBooleanOption(StandardSocketOptions.TCP_NODELAY, on);
D
duke 已提交
320 321 322
    }

    public boolean getTcpNoDelay() throws SocketException {
323
        return getBooleanOption(StandardSocketOptions.TCP_NODELAY);
D
duke 已提交
324 325 326
    }

    public void setSoLinger(boolean on, int linger) throws SocketException {
327 328
        if (!on)
            linger = -1;
329
        setIntOption(StandardSocketOptions.SO_LINGER, linger);
D
duke 已提交
330 331 332
    }

    public int getSoLinger() throws SocketException {
333
        return getIntOption(StandardSocketOptions.SO_LINGER);
D
duke 已提交
334 335 336
    }

    public void sendUrgentData(int data) throws IOException {
337 338 339
        int n = sc.sendOutOfBandData((byte) data);
        if (n == 0)
            throw new IOException("Socket buffer full");
D
duke 已提交
340 341 342
    }

    public void setOOBInline(boolean on) throws SocketException {
343
        setBooleanOption(ExtendedSocketOption.SO_OOBINLINE, on);
D
duke 已提交
344 345 346
    }

    public boolean getOOBInline() throws SocketException {
347
        return getBooleanOption(ExtendedSocketOption.SO_OOBINLINE);
D
duke 已提交
348 349 350 351 352 353 354 355 356 357 358 359 360
    }

    public void setSoTimeout(int timeout) throws SocketException {
        if (timeout < 0)
            throw new IllegalArgumentException("timeout can't be negative");
        this.timeout = timeout;
    }

    public int getSoTimeout() throws SocketException {
        return timeout;
    }

    public void setSendBufferSize(int size) throws SocketException {
361 362 363
        // size 0 valid for SocketChannel, invalid for Socket
        if (size <= 0)
            throw new IllegalArgumentException("Invalid send size");
364
        setIntOption(StandardSocketOptions.SO_SNDBUF, size);
D
duke 已提交
365 366 367
    }

    public int getSendBufferSize() throws SocketException {
368
        return getIntOption(StandardSocketOptions.SO_SNDBUF);
D
duke 已提交
369 370 371
    }

    public void setReceiveBufferSize(int size) throws SocketException {
372 373 374
        // size 0 valid for SocketChannel, invalid for Socket
        if (size <= 0)
            throw new IllegalArgumentException("Invalid receive size");
375
        setIntOption(StandardSocketOptions.SO_RCVBUF, size);
D
duke 已提交
376 377 378
    }

    public int getReceiveBufferSize() throws SocketException {
379
        return getIntOption(StandardSocketOptions.SO_RCVBUF);
D
duke 已提交
380 381 382
    }

    public void setKeepAlive(boolean on) throws SocketException {
383
        setBooleanOption(StandardSocketOptions.SO_KEEPALIVE, on);
D
duke 已提交
384 385 386
    }

    public boolean getKeepAlive() throws SocketException {
387
        return getBooleanOption(StandardSocketOptions.SO_KEEPALIVE);
D
duke 已提交
388 389 390
    }

    public void setTrafficClass(int tc) throws SocketException {
391
        setIntOption(StandardSocketOptions.IP_TOS, tc);
D
duke 已提交
392 393 394
    }

    public int getTrafficClass() throws SocketException {
395
        return getIntOption(StandardSocketOptions.IP_TOS);
D
duke 已提交
396 397 398
    }

    public void setReuseAddress(boolean on) throws SocketException {
399
        setBooleanOption(StandardSocketOptions.SO_REUSEADDR, on);
D
duke 已提交
400 401 402
    }

    public boolean getReuseAddress() throws SocketException {
403
        return getBooleanOption(StandardSocketOptions.SO_REUSEADDR);
D
duke 已提交
404 405 406
    }

    public void close() throws IOException {
407
        sc.close();
D
duke 已提交
408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438
    }

    public void shutdownInput() throws IOException {
        try {
            sc.shutdownInput();
        } catch (Exception x) {
            Net.translateException(x);
        }
    }

    public void shutdownOutput() throws IOException {
        try {
            sc.shutdownOutput();
        } catch (Exception x) {
            Net.translateException(x);
        }
    }

    public String toString() {
        if (sc.isConnected())
            return "Socket[addr=" + getInetAddress() +
                ",port=" + getPort() +
                ",localport=" + getLocalPort() + "]";
        return "Socket[unconnected]";
    }

    public boolean isConnected() {
        return sc.isConnected();
    }

    public boolean isBound() {
439
        return sc.localAddress() != null;
D
duke 已提交
440 441 442 443 444 445 446 447 448 449 450 451 452 453 454
    }

    public boolean isClosed() {
        return !sc.isOpen();
    }

    public boolean isInputShutdown() {
        return !sc.isInputOpen();
    }

    public boolean isOutputShutdown() {
        return !sc.isOutputOpen();
    }

}