src/java.net.http/share/classes/jdk/internal/net/http/websocket/OutgoingMessage.java
branchhttp-client-branch
changeset 56263 4933a477d628
parent 56262 d818a6a8295a
child 56264 c012b93297b0
equal deleted inserted replaced
56262:d818a6a8295a 56263:4933a477d628
     1 /*
       
     2  * Copyright (c) 2015, 2018, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 package jdk.internal.net.http.websocket;
       
    27 
       
    28 import jdk.internal.net.http.websocket.Frame.Opcode;
       
    29 
       
    30 import java.io.IOException;
       
    31 import java.nio.ByteBuffer;
       
    32 import java.nio.CharBuffer;
       
    33 import java.nio.charset.CharacterCodingException;
       
    34 import java.nio.charset.CharsetEncoder;
       
    35 import java.nio.charset.CoderResult;
       
    36 import java.security.SecureRandom;
       
    37 
       
    38 import static java.nio.charset.StandardCharsets.UTF_8;
       
    39 import static java.util.Objects.requireNonNull;
       
    40 import static jdk.internal.net.http.common.Utils.EMPTY_BYTEBUFFER;
       
    41 import static jdk.internal.net.http.websocket.Frame.MAX_HEADER_SIZE_BYTES;
       
    42 import static jdk.internal.net.http.websocket.Frame.Opcode.BINARY;
       
    43 import static jdk.internal.net.http.websocket.Frame.Opcode.CLOSE;
       
    44 import static jdk.internal.net.http.websocket.Frame.Opcode.CONTINUATION;
       
    45 import static jdk.internal.net.http.websocket.Frame.Opcode.PING;
       
    46 import static jdk.internal.net.http.websocket.Frame.Opcode.PONG;
       
    47 import static jdk.internal.net.http.websocket.Frame.Opcode.TEXT;
       
    48 
       
    49 /*
       
    50  * A stateful object that represents a WebSocket message being sent to the
       
    51  * channel.
       
    52  *
       
    53  * Data provided to the constructors is copied. Otherwise we would have to deal
       
    54  * with mutability, security, masking/unmasking, readonly status, etc. So
       
    55  * copying greatly simplifies the implementation.
       
    56  *
       
    57  * In the case of memory-sensitive environments an alternative implementation
       
    58  * could use an internal pool of buffers though at the cost of extra complexity
       
    59  * and possible performance degradation.
       
    60  */
       
    61 abstract class OutgoingMessage {
       
    62 
       
    63     // Share per WebSocket?
       
    64     private static final SecureRandom maskingKeys = new SecureRandom();
       
    65 
       
    66     protected ByteBuffer[] frame;
       
    67     protected int offset;
       
    68 
       
    69     /*
       
    70      * Performs contextualization. This method is not a part of the constructor
       
    71      * so it would be possible to defer the work it does until the most
       
    72      * convenient moment (up to the point where sentTo is invoked).
       
    73      */
       
    74     protected boolean contextualize(Context context) {
       
    75         // masking and charset decoding should be performed here rather than in
       
    76         // the constructor (as of today)
       
    77         if (context.isCloseSent()) {
       
    78             throw new IllegalStateException("Close sent");
       
    79         }
       
    80         return true;
       
    81     }
       
    82 
       
    83     protected boolean sendTo(RawChannel channel) throws IOException {
       
    84         while ((offset = nextUnwrittenIndex()) != -1) {
       
    85             long n = channel.write(frame, offset, frame.length - offset);
       
    86             if (n == 0) {
       
    87                 return false;
       
    88             }
       
    89         }
       
    90         return true;
       
    91     }
       
    92 
       
    93     private int nextUnwrittenIndex() {
       
    94         for (int i = offset; i < frame.length; i++) {
       
    95             if (frame[i].hasRemaining()) {
       
    96                 return i;
       
    97             }
       
    98         }
       
    99         return -1;
       
   100     }
       
   101 
       
   102     static final class Text extends OutgoingMessage {
       
   103 
       
   104         private final ByteBuffer payload;
       
   105         private final boolean isLast;
       
   106 
       
   107         Text(CharSequence characters, boolean isLast) {
       
   108             CharsetEncoder encoder = UTF_8.newEncoder(); // Share per WebSocket?
       
   109             try {
       
   110                 payload = encoder.encode(CharBuffer.wrap(characters));
       
   111             } catch (CharacterCodingException e) {
       
   112                 throw new IllegalArgumentException(
       
   113                         "Malformed UTF-8 text message");
       
   114             }
       
   115             this.isLast = isLast;
       
   116         }
       
   117 
       
   118         @Override
       
   119         protected boolean contextualize(Context context) {
       
   120             super.contextualize(context);
       
   121             if (context.isPreviousBinary() && !context.isPreviousLast()) {
       
   122                 throw new IllegalStateException("Unexpected text message");
       
   123             }
       
   124             frame = getDataMessageBuffers(
       
   125                     TEXT, context.isPreviousLast(), isLast, payload, payload);
       
   126             context.setPreviousBinary(false);
       
   127             context.setPreviousText(true);
       
   128             context.setPreviousLast(isLast);
       
   129             return true;
       
   130         }
       
   131     }
       
   132 
       
   133     static final class Binary extends OutgoingMessage {
       
   134 
       
   135         private final ByteBuffer payload;
       
   136         private final boolean isLast;
       
   137 
       
   138         Binary(ByteBuffer payload, boolean isLast) {
       
   139             this.payload = requireNonNull(payload);
       
   140             this.isLast = isLast;
       
   141         }
       
   142 
       
   143         @Override
       
   144         protected boolean contextualize(Context context) {
       
   145             super.contextualize(context);
       
   146             if (context.isPreviousText() && !context.isPreviousLast()) {
       
   147                 throw new IllegalStateException("Unexpected binary message");
       
   148             }
       
   149             ByteBuffer newBuffer = ByteBuffer.allocate(payload.remaining());
       
   150             frame = getDataMessageBuffers(
       
   151                     BINARY, context.isPreviousLast(), isLast, payload, newBuffer);
       
   152             context.setPreviousText(false);
       
   153             context.setPreviousBinary(true);
       
   154             context.setPreviousLast(isLast);
       
   155             return true;
       
   156         }
       
   157     }
       
   158 
       
   159     static final class Ping extends OutgoingMessage {
       
   160 
       
   161         Ping(ByteBuffer payload) {
       
   162             frame = getControlMessageBuffers(PING, payload);
       
   163         }
       
   164     }
       
   165 
       
   166     static final class Pong extends OutgoingMessage {
       
   167 
       
   168         Pong(ByteBuffer payload) {
       
   169             frame = getControlMessageBuffers(PONG, payload);
       
   170         }
       
   171     }
       
   172 
       
   173     static final class Close extends OutgoingMessage {
       
   174 
       
   175         Close() {
       
   176             frame = getControlMessageBuffers(CLOSE, EMPTY_BYTEBUFFER);
       
   177         }
       
   178 
       
   179         Close(int statusCode, CharSequence reason) {
       
   180             ByteBuffer payload = ByteBuffer.allocate(125)
       
   181                     .putChar((char) statusCode);
       
   182             CoderResult result = UTF_8.newEncoder()
       
   183                     .encode(CharBuffer.wrap(reason),
       
   184                             payload,
       
   185                             true);
       
   186             if (result.isOverflow()) {
       
   187                 throw new IllegalArgumentException("Long reason");
       
   188             } else if (result.isError()) {
       
   189                 try {
       
   190                     result.throwException();
       
   191                 } catch (CharacterCodingException e) {
       
   192                     throw new IllegalArgumentException(
       
   193                             "Malformed UTF-8 reason", e);
       
   194                 }
       
   195             }
       
   196             payload.flip();
       
   197             frame = getControlMessageBuffers(CLOSE, payload);
       
   198         }
       
   199 
       
   200         @Override
       
   201         protected boolean contextualize(Context context) {
       
   202             if (context.isCloseSent()) {
       
   203                 return false;
       
   204             } else {
       
   205                 context.setCloseSent();
       
   206                 return true;
       
   207             }
       
   208         }
       
   209     }
       
   210 
       
   211     private static ByteBuffer[] getControlMessageBuffers(Opcode opcode,
       
   212                                                          ByteBuffer payload) {
       
   213         assert opcode.isControl() : opcode;
       
   214         int remaining = payload.remaining();
       
   215         if (remaining > 125) {
       
   216             throw new IllegalArgumentException
       
   217                     ("Long message: " + remaining);
       
   218         }
       
   219         ByteBuffer frame = ByteBuffer.allocate(MAX_HEADER_SIZE_BYTES + remaining);
       
   220         int mask = maskingKeys.nextInt();
       
   221         new Frame.HeaderWriter()
       
   222                 .fin(true)
       
   223                 .opcode(opcode)
       
   224                 .payloadLen(remaining)
       
   225                 .mask(mask)
       
   226                 .write(frame);
       
   227         Frame.Masker.transferMasking(payload, frame, mask);
       
   228         frame.flip();
       
   229         return new ByteBuffer[]{frame};
       
   230     }
       
   231 
       
   232     private static ByteBuffer[] getDataMessageBuffers(Opcode type,
       
   233                                                       boolean isPreviousLast,
       
   234                                                       boolean isLast,
       
   235                                                       ByteBuffer payloadSrc,
       
   236                                                       ByteBuffer payloadDst) {
       
   237         assert !type.isControl() && type != CONTINUATION : type;
       
   238         ByteBuffer header = ByteBuffer.allocate(MAX_HEADER_SIZE_BYTES);
       
   239         int mask = maskingKeys.nextInt();
       
   240         new Frame.HeaderWriter()
       
   241                 .fin(isLast)
       
   242                 .opcode(isPreviousLast ? type : CONTINUATION)
       
   243                 .payloadLen(payloadDst.remaining())
       
   244                 .mask(mask)
       
   245                 .write(header);
       
   246         header.flip();
       
   247         Frame.Masker.transferMasking(payloadSrc, payloadDst, mask);
       
   248         payloadDst.flip();
       
   249         return new ByteBuffer[]{header, payloadDst};
       
   250     }
       
   251 
       
   252     /*
       
   253      * An instance of this class is passed sequentially between messages, so
       
   254      * every message in a sequence can check the context it is in and update it
       
   255      * if necessary.
       
   256      */
       
   257     public static class Context {
       
   258 
       
   259         boolean previousLast = true;
       
   260         boolean previousBinary;
       
   261         boolean previousText;
       
   262         boolean closeSent;
       
   263 
       
   264         private boolean isPreviousText() {
       
   265             return this.previousText;
       
   266         }
       
   267 
       
   268         private void setPreviousText(boolean value) {
       
   269             this.previousText = value;
       
   270         }
       
   271 
       
   272         private boolean isPreviousBinary() {
       
   273             return this.previousBinary;
       
   274         }
       
   275 
       
   276         private void setPreviousBinary(boolean value) {
       
   277             this.previousBinary = value;
       
   278         }
       
   279 
       
   280         private boolean isPreviousLast() {
       
   281             return this.previousLast;
       
   282         }
       
   283 
       
   284         private void setPreviousLast(boolean value) {
       
   285             this.previousLast = value;
       
   286         }
       
   287 
       
   288         private boolean isCloseSent() {
       
   289             return closeSent;
       
   290         }
       
   291 
       
   292         private void setCloseSent() {
       
   293             closeSent = true;
       
   294         }
       
   295     }
       
   296 }