src/java.net.http/share/classes/jdk/internal/net/http/websocket/MessageEncoder.java
branchhttp-client-branch
changeset 56263 4933a477d628
child 56269 234813fd33bc
equal deleted inserted replaced
56262:d818a6a8295a 56263:4933a477d628
       
     1 /*
       
     2  * Copyright (c) 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.common.Utils;
       
    29 import jdk.internal.net.http.websocket.Frame.Opcode;
       
    30 
       
    31 import java.io.IOException;
       
    32 import java.nio.ByteBuffer;
       
    33 import java.nio.CharBuffer;
       
    34 import java.nio.charset.CharacterCodingException;
       
    35 import java.nio.charset.CharsetEncoder;
       
    36 import java.nio.charset.CoderResult;
       
    37 import java.nio.charset.CodingErrorAction;
       
    38 import java.nio.charset.StandardCharsets;
       
    39 import java.security.SecureRandom;
       
    40 
       
    41 /*
       
    42  * A stateful producer of binary representations of WebSocket messages being
       
    43  * sent from the client to the server.
       
    44  *
       
    45  * An encoding methods are given original messages and byte buffers to put the
       
    46  * resulting bytes to.
       
    47  *
       
    48  * The method is called
       
    49  * repeatedly with a non-empty target buffer. Once the caller finds the buffer
       
    50  * unmodified after the call returns, the message has been completely encoded.
       
    51  */
       
    52 
       
    53 /*
       
    54  * The state of encoding.An instance of this class is passed sequentially between messages, so
       
    55  * every message in a sequence can check the context it is in and update it
       
    56  * if necessary.
       
    57  */
       
    58 
       
    59 public class MessageEncoder {
       
    60 
       
    61     // FIXME: write frame method
       
    62 
       
    63     private final static boolean DEBUG = false;
       
    64 
       
    65     private final SecureRandom maskingKeySource = new SecureRandom();
       
    66     private final Frame.HeaderWriter headerWriter = new Frame.HeaderWriter();
       
    67     private final Frame.Masker payloadMasker = new Frame.Masker();
       
    68     private final CharsetEncoder charsetEncoder
       
    69             = StandardCharsets.UTF_8.newEncoder()
       
    70             .onMalformedInput(CodingErrorAction.REPORT)
       
    71             .onUnmappableCharacter(CodingErrorAction.REPORT);
       
    72     /*
       
    73      * This buffer is used both to encode characters to UTF-8 and to calculate
       
    74      * the length of the resulting frame's payload. The length of the payload
       
    75      * must be known before the frame's header can be written.
       
    76      * For implementation reasons, this buffer must have a capacity of at least
       
    77      * the maximum size of a Close frame payload, which is 125 bytes
       
    78      * (or Frame.MAX_CONTROL_FRAME_PAYLOAD_LENGTH).
       
    79      */
       
    80     private final ByteBuffer intermediateBuffer = createIntermediateBuffer(
       
    81             Frame.MAX_CONTROL_FRAME_PAYLOAD_LENGTH);
       
    82     private final ByteBuffer headerBuffer = ByteBuffer.allocate(
       
    83             Frame.MAX_HEADER_SIZE_BYTES);
       
    84 
       
    85     private boolean started;
       
    86     private boolean flushing;
       
    87     private boolean moreText = true;
       
    88     private long headerCount;
       
    89     private boolean previousLast = true;
       
    90     private boolean previousText;
       
    91     private boolean closed;
       
    92 
       
    93     /*
       
    94      * How many bytes of the current message have been already encoded.
       
    95      *
       
    96      * Even though the user hands their buffers over to us, they still can
       
    97      * manipulate these buffers while we are getting data out of them.
       
    98      * The number of produced bytes guards us from such behaviour in the
       
    99      * case of messages that must be restricted in size (Ping, Pong and Close).
       
   100      * For other messages this measure provides a best-effort attempt to detect
       
   101      * concurrent changes to buffer.
       
   102      *
       
   103      * Making a shallow copy (duplicate/slice) and then checking the size
       
   104      * precondition on it would also solve the problem, but at the cost of this
       
   105      * extra copy.
       
   106      */
       
   107     private int actualLen;
       
   108 
       
   109     /*
       
   110      * How many bytes were originally there in the message, before the encoding
       
   111      * started.
       
   112      */
       
   113     private int expectedLen;
       
   114 
       
   115     /* Exposed for testing purposes */
       
   116     protected ByteBuffer createIntermediateBuffer(int minSize) {
       
   117         int capacity = Utils.getIntegerNetProperty(
       
   118                 "jdk.httpclient.websocket.intermediateBufferSize", 16384);
       
   119         return ByteBuffer.allocate(Math.max(minSize, capacity));
       
   120     }
       
   121 
       
   122     public void reset() {
       
   123         // Do not reset the message stream state fields, e.g. previousLast,
       
   124         // previousText. Just an individual message state:
       
   125         started = false;
       
   126         flushing = false;
       
   127         moreText = true;
       
   128         headerCount = 0;
       
   129         actualLen = 0;
       
   130     }
       
   131 
       
   132     /*
       
   133      * Encodes text messages by cutting them into fragments of maximum size of
       
   134      * intermediateBuffer.capacity()
       
   135      */
       
   136     public boolean encodeText(CharBuffer src, boolean last, ByteBuffer dst)
       
   137             throws IOException
       
   138     {
       
   139         if (DEBUG) {
       
   140             System.out.printf("[Output] encodeText src.remaining()=%s, %s, %s%n",
       
   141                               src.remaining(), last, dst);
       
   142         }
       
   143         if (closed) {
       
   144             throw new IOException("Output closed");
       
   145         }
       
   146         if (!started) {
       
   147             if (!previousText && !previousLast) {
       
   148                 // Previous data message was a partial binary message
       
   149                 throw new IllegalStateException("Unexpected text message");
       
   150             }
       
   151             started = true;
       
   152             headerBuffer.position(0).limit(0);
       
   153             intermediateBuffer.position(0).limit(0);
       
   154             charsetEncoder.reset();
       
   155         }
       
   156         while (true) {
       
   157             if (DEBUG) {
       
   158                 System.out.printf("[Output] put%n");
       
   159             }
       
   160             if (!putAvailable(headerBuffer, dst)) {
       
   161                 return false;
       
   162             }
       
   163             if (DEBUG) {
       
   164                 System.out.printf("[Output] mask%n");
       
   165             }
       
   166             if (maskAvailable(intermediateBuffer, dst) < 0) {
       
   167                 return false;
       
   168             }
       
   169             if (DEBUG) {
       
   170                 System.out.printf("[Output] moreText%n");
       
   171             }
       
   172             if (!moreText) {
       
   173                 return true;
       
   174             }
       
   175             intermediateBuffer.clear();
       
   176             CoderResult r = null;
       
   177             if (!flushing) {
       
   178                 r = charsetEncoder.encode(src, intermediateBuffer, true);
       
   179                 if (r.isUnderflow()) {
       
   180                     flushing = true;
       
   181                 }
       
   182             }
       
   183             if (flushing) {
       
   184                 r = charsetEncoder.flush(intermediateBuffer);
       
   185                 if (r.isUnderflow()) {
       
   186                     moreText = false;
       
   187                 }
       
   188             }
       
   189             if (r.isError()) {
       
   190                 try {
       
   191                     r.throwException();
       
   192                 } catch (CharacterCodingException e) {
       
   193                     throw new IOException("Malformed text message", e);
       
   194                 }
       
   195             }
       
   196             if (DEBUG) {
       
   197                 System.out.printf("[Output] header #%s%n", headerCount);
       
   198             }
       
   199             if (headerCount == 0) { // set once
       
   200                 previousLast = last;
       
   201                 previousText = true;
       
   202             }
       
   203             intermediateBuffer.flip();
       
   204             headerBuffer.clear();
       
   205             int mask = maskingKeySource.nextInt();
       
   206             Opcode opcode = previousLast && headerCount == 0
       
   207                     ? Opcode.TEXT : Opcode.CONTINUATION;
       
   208             if (DEBUG) {
       
   209                 System.out.printf("[Output] opcode %s%n", opcode);
       
   210             }
       
   211             headerWriter.fin(last && !moreText)
       
   212                     .opcode(opcode)
       
   213                     .payloadLen(intermediateBuffer.remaining())
       
   214                     .mask(mask)
       
   215                     .write(headerBuffer);
       
   216             headerBuffer.flip();
       
   217             headerCount++;
       
   218             payloadMasker.mask(mask);
       
   219         }
       
   220     }
       
   221 
       
   222     private boolean putAvailable(ByteBuffer src, ByteBuffer dst) {
       
   223         int available = dst.remaining();
       
   224         if (available >= src.remaining()) {
       
   225             dst.put(src);
       
   226             return true;
       
   227         } else {
       
   228             int lim = src.limit();                   // save the limit
       
   229             src.limit(src.position() + available);
       
   230             dst.put(src);
       
   231             src.limit(lim);                          // restore the limit
       
   232             return false;
       
   233         }
       
   234     }
       
   235 
       
   236     public boolean encodeBinary(ByteBuffer src, boolean last, ByteBuffer dst)
       
   237             throws IOException
       
   238     {
       
   239         if (DEBUG) {
       
   240             System.out.printf("[Output] encodeBinary %s, %s, %s%n",
       
   241                               src, last, dst);
       
   242         }
       
   243         if (closed) {
       
   244             throw new IOException("Output closed");
       
   245         }
       
   246         if (!started) {
       
   247             if (previousText && !previousLast) {
       
   248                 // Previous data message was a partial text message
       
   249                 throw new IllegalStateException("Unexpected binary message");
       
   250             }
       
   251             expectedLen = src.remaining();
       
   252             int mask = maskingKeySource.nextInt();
       
   253             headerBuffer.clear();
       
   254             headerWriter.fin(last)
       
   255                     .opcode(previousLast ? Opcode.BINARY : Opcode.CONTINUATION)
       
   256                     .payloadLen(expectedLen)
       
   257                     .mask(mask)
       
   258                     .write(headerBuffer);
       
   259             headerBuffer.flip();
       
   260             payloadMasker.mask(mask);
       
   261             previousLast = last;
       
   262             previousText = false;
       
   263             started = true;
       
   264         }
       
   265         if (!putAvailable(headerBuffer, dst)) {
       
   266             return false;
       
   267         }
       
   268         int count = maskAvailable(src, dst);
       
   269         actualLen += Math.abs(count);
       
   270         if (count >= 0 && actualLen != expectedLen) {
       
   271             throw new IOException("Concurrent message modification");
       
   272         }
       
   273         return count >= 0;
       
   274     }
       
   275 
       
   276     private int maskAvailable(ByteBuffer src, ByteBuffer dst) {
       
   277         int r0 = dst.remaining();
       
   278         payloadMasker.transferMasking(src, dst);
       
   279         int masked = r0 - dst.remaining();
       
   280         return src.hasRemaining() ? -masked : masked;
       
   281     }
       
   282 
       
   283     public boolean encodePing(ByteBuffer src, ByteBuffer dst)
       
   284             throws IOException
       
   285     {
       
   286         if (closed) {
       
   287             throw new IOException("Output closed");
       
   288         }
       
   289         if (DEBUG) System.out.printf("[Output] encodePing %s, %s%n", src, dst);
       
   290         if (!started) {
       
   291             expectedLen = src.remaining();
       
   292             if (expectedLen > Frame.MAX_CONTROL_FRAME_PAYLOAD_LENGTH) {
       
   293                 throw new IllegalArgumentException("Long message: " + expectedLen);
       
   294             }
       
   295             int mask = maskingKeySource.nextInt();
       
   296             headerBuffer.clear();
       
   297             headerWriter.fin(true)
       
   298                     .opcode(Opcode.PING)
       
   299                     .payloadLen(expectedLen)
       
   300                     .mask(mask)
       
   301                     .write(headerBuffer);
       
   302             headerBuffer.flip();
       
   303             payloadMasker.mask(mask);
       
   304             started = true;
       
   305         }
       
   306         if (!putAvailable(headerBuffer, dst)) {
       
   307             return false;
       
   308         }
       
   309         int count = maskAvailable(src, dst);
       
   310         actualLen += Math.abs(count);
       
   311         if (count >= 0 && actualLen != expectedLen) {
       
   312             throw new IOException("Concurrent message modification");
       
   313         }
       
   314         return count >= 0;
       
   315     }
       
   316 
       
   317     public boolean encodePong(ByteBuffer src, ByteBuffer dst)
       
   318             throws IOException
       
   319     {
       
   320         if (closed) {
       
   321             throw new IOException("Output closed");
       
   322         }
       
   323         if (DEBUG) {
       
   324             System.out.printf("[Output] encodePong %s, %s%n",
       
   325                               src, dst);
       
   326         }
       
   327         if (!started) {
       
   328             expectedLen = src.remaining();
       
   329             if (expectedLen > Frame.MAX_CONTROL_FRAME_PAYLOAD_LENGTH) {
       
   330                 throw new IllegalArgumentException("Long message: " + expectedLen);
       
   331             }
       
   332             int mask = maskingKeySource.nextInt();
       
   333             headerBuffer.clear();
       
   334             headerWriter.fin(true)
       
   335                     .opcode(Opcode.PONG)
       
   336                     .payloadLen(expectedLen)
       
   337                     .mask(mask)
       
   338                     .write(headerBuffer);
       
   339             headerBuffer.flip();
       
   340             payloadMasker.mask(mask);
       
   341             started = true;
       
   342         }
       
   343         if (!putAvailable(headerBuffer, dst)) {
       
   344             return false;
       
   345         }
       
   346         int count = maskAvailable(src, dst);
       
   347         actualLen += Math.abs(count);
       
   348         if (count >= 0 && actualLen != expectedLen) {
       
   349             throw new IOException("Concurrent message modification");
       
   350         }
       
   351         return count >= 0;
       
   352     }
       
   353 
       
   354     public boolean encodeClose(int statusCode, CharBuffer reason, ByteBuffer dst)
       
   355             throws IOException
       
   356     {
       
   357         if (DEBUG) {
       
   358             System.out.printf("[Output] encodeClose %s, reason.length=%s, %s%n",
       
   359                               statusCode, reason.length(), dst);
       
   360         }
       
   361         if (closed) {
       
   362             throw new IOException("Output closed");
       
   363         }
       
   364         if (!started) {
       
   365             if (DEBUG) {
       
   366                 System.out.printf("[Output] reason size %s%n", reason.remaining());
       
   367             }
       
   368             intermediateBuffer.position(0).limit(Frame.MAX_CONTROL_FRAME_PAYLOAD_LENGTH);
       
   369             intermediateBuffer.putChar((char) statusCode);
       
   370             CoderResult r = charsetEncoder.reset().encode(reason, intermediateBuffer, true);
       
   371             if (r.isUnderflow()) {
       
   372                 if (DEBUG) {
       
   373                     System.out.printf("[Output] flushing%n");
       
   374                 }
       
   375                 r = charsetEncoder.flush(intermediateBuffer);
       
   376             }
       
   377             if (DEBUG) {
       
   378                 System.out.printf("[Output] encoding result: %s%n", r);
       
   379             }
       
   380             if (r.isError()) {
       
   381                 try {
       
   382                     r.throwException();
       
   383                 } catch (CharacterCodingException e) {
       
   384                     throw new IllegalArgumentException("Malformed reason", e);
       
   385                 }
       
   386             } else if (r.isOverflow()) {
       
   387                 // Here the 125 bytes size is ensured by the check for overflow
       
   388                 throw new IllegalArgumentException("Long reason");
       
   389             } else if (!r.isUnderflow()) {
       
   390                 throw new InternalError(); // assertion
       
   391             }
       
   392             intermediateBuffer.flip();
       
   393             headerBuffer.clear();
       
   394             int mask = maskingKeySource.nextInt();
       
   395             headerWriter.fin(true)
       
   396                     .opcode(Opcode.CLOSE)
       
   397                     .payloadLen(intermediateBuffer.remaining())
       
   398                     .mask(mask)
       
   399                     .write(headerBuffer);
       
   400             headerBuffer.flip();
       
   401             payloadMasker.mask(mask);
       
   402             started = true;
       
   403             closed = true;
       
   404             if (DEBUG) {
       
   405                 System.out.printf("[Output] intermediateBuffer=%s%n",
       
   406                                   intermediateBuffer);
       
   407             }
       
   408         }
       
   409         if (!putAvailable(headerBuffer, dst)) {
       
   410             return false;
       
   411         }
       
   412         return maskAvailable(intermediateBuffer, dst) >= 0;
       
   413     }
       
   414 }
       
   415 
       
   416