Skip to main content
aboutsummaryrefslogtreecommitdiffstats
blob: b4f7b035ea61ac95e8f9a59b3b1fb510e84a100f (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
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
99
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
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
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
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
// ========================================================================
// Copyright 2011-2012 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
//
//     The Eclipse Public License is available at
//     http://www.eclipse.org/legal/epl-v10.html
//
//     The Apache License v2.0 is available at
//     http://www.opensource.org/licenses/apache2.0.php
//
// You may elect to redistribute this code under either of these licenses.
//========================================================================
package org.eclipse.jetty.websocket.protocol;

import java.nio.ByteBuffer;

import org.eclipse.jetty.util.BufferUtil;
import org.eclipse.jetty.util.StringUtil;
import org.eclipse.jetty.websocket.api.ProtocolException;

/**
 * A Base Frame as seen in <a href="https://tools.ietf.org/html/rfc6455#section-5.2">RFC 6455. Sec 5.2</a>
 * 
 * <pre>
 *    0                   1                   2                   3
 *    0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
 *   +-+-+-+-+-------+-+-------------+-------------------------------+
 *   |F|R|R|R| opcode|M| Payload len |    Extended payload length    |
 *   |I|S|S|S|  (4)  |A|     (7)     |             (16/64)           |
 *   |N|V|V|V|       |S|             |   (if payload len==126/127)   |
 *   | |1|2|3|       |K|             |                               |
 *   +-+-+-+-+-------+-+-------------+ - - - - - - - - - - - - - - - +
 *   |     Extended payload length continued, if payload len == 127  |
 *   + - - - - - - - - - - - - - - - +-------------------------------+
 *   |                               |Masking-key, if MASK set to 1  |
 *   +-------------------------------+-------------------------------+
 *   | Masking-key (continued)       |          Payload Data         |
 *   +-------------------------------- - - - - - - - - - - - - - - - +
 *   :                     Payload Data continued ...                :
 *   + - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - +
 *   |                     Payload Data continued ...                |
 *   +---------------------------------------------------------------+
 * </pre>
 */
public class WebSocketFrame implements Frame
{
    /** Maximum size of Control frame, per RFC 6455 */
    public static final int MAX_CONTROL_PAYLOAD = 125;

    public static WebSocketFrame binary()
    {
        return new WebSocketFrame(OpCode.BINARY);
    }

    public static WebSocketFrame binary(byte buf[])
    {
        return new WebSocketFrame(OpCode.BINARY).setPayload(buf);
    }

    public static WebSocketFrame ping()
    {
        return new WebSocketFrame(OpCode.PING);
    }

    public static WebSocketFrame pong()
    {
        return new WebSocketFrame(OpCode.PONG);
    }

    public static WebSocketFrame text()
    {
        return new WebSocketFrame(OpCode.TEXT);
    }

    public static WebSocketFrame text(String msg)
    {
        return new WebSocketFrame(OpCode.TEXT).setPayload(msg);
    }

    private boolean fin = true;
    private boolean rsv1 = false;
    private boolean rsv2 = false;
    private boolean rsv3 = false;
    private byte opcode = -1;
    private boolean masked = false;
    private byte mask[];
    /**
     * The payload data.
     * <p>
     * It is assumed to always be in FLUSH mode (ready to read) in this object.
     */
    private ByteBuffer data;
    private int payloadLength = 0;
    /** position of start of data within a fresh payload */
    private int payloadStart = -1;

    private boolean continuation = false;
    private int continuationIndex = 0;

    /**
     * Default constructor
     */
    public WebSocketFrame()
    {
        this(OpCode.UNDEFINED);
    }

    /**
     * Construct form opcode
     */
    public WebSocketFrame(byte opcode)
    {
        reset();
        this.opcode = opcode;
    }

    /**
     * Copy constructor for the websocket frame.
     * <p>
     * Note: the underlying payload is merely a {@link ByteBuffer#slice()} of the input frame.
     * 
     * @param copy
     *            the websocket to copy.
     */
    public WebSocketFrame(WebSocketFrame copy)
    {
        fin = copy.fin;
        rsv1 = copy.rsv2;
        rsv2 = copy.rsv2;
        rsv3 = copy.rsv3;
        opcode = copy.opcode;
        masked = copy.masked;
        mask = null;
        if (copy.mask != null)
        {
            mask = new byte[copy.mask.length];
            System.arraycopy(copy.mask,0,mask,0,mask.length);
        }
        payloadLength = copy.payloadLength;
        payloadStart = copy.payloadStart;
        if (copy.data != null) // deal with empty payloads
        {
            data = copy.data.slice();
        }
        continuationIndex = copy.continuationIndex;
        continuation = copy.continuation;
    }

    public void assertValid()
    {
        if (OpCode.isControlFrame(opcode))
        {
            if (getPayloadLength() > WebSocketFrame.MAX_CONTROL_PAYLOAD)
            {
                throw new ProtocolException("Desired payload length [" + getPayloadLength() + "] exceeds maximum control payload length ["
                        + MAX_CONTROL_PAYLOAD + "]");
            }

            if (fin == false)
            {
                throw new ProtocolException("Cannot have FIN==false on Control frames");
            }

            if (rsv1 == true)
            {
                throw new ProtocolException("Cannot have RSV1==true on Control frames");
            }

            if (rsv2 == true)
            {
                throw new ProtocolException("Cannot have RSV2==true on Control frames");
            }

            if (rsv3 == true)
            {
                throw new ProtocolException("Cannot have RSV3==true on Control frames");
            }

            if (isContinuation())
            {
                throw new ProtocolException("Control frames cannot be Continuations");
            }
        }
    }

    /**
     * The number of fragments this frame consists of.
     * <p>
     * For every {@link OpCode#CONTINUATION} opcode encountered, this increments by one.
     * <p>
     * Note: Not part of the Base Framing Protocol / header information.
     * 
     * @return the number of continuation fragments encountered.
     */
    public int getContinuationIndex()
    {
        return continuationIndex;
    }

    @Override
    public byte[] getMask()
    {
        if (!masked)
        {
            throw new IllegalStateException("Frame is not masked");
        }
        return mask;
    }

    @Override
    public final byte getOpCode()
    {
        return opcode;
    }

    /**
     * Get the payload ByteBuffer. possible null.
     * <p>
     * 
     * @return A {@link ByteBuffer#slice()} of the payload buffer (to prevent modification of the buffer state). Possibly null if no payload present.
     *         <p>
     *         Note: this method is exposed via the immutable {@link Frame#getPayload()} method.
     */
    @Override
    public ByteBuffer getPayload()
    {
        if (data != null)
        {
            return data;
        }
        else
        {
            return null;
        }
    }

    public String getPayloadAsUTF8()
    {
        if (data == null)
        {
            return null;
        }
        return BufferUtil.toUTF8String(data);
    }

    @Override
    public int getPayloadLength()
    {
        if (data == null)
        {
            return 0;
        }
        return payloadLength;
    }

    public int getPayloadStart()
    {
        if (data == null)
        {
            return -1;
        }
        return payloadStart;
    }

    public boolean hasPayload()
    {
        return ((data != null) && (payloadLength > 0));
    }

    public boolean isContinuation()
    {
        return continuation;
    }

    public boolean isControlFrame()
    {
        return OpCode.isControlFrame(opcode);
    }

    public boolean isDataFrame()
    {
        return OpCode.isDataFrame(opcode);
    }

    @Override
    public boolean isFin()
    {
        return fin;
    }

    public boolean isLastFrame()
    {
        return fin;
    }

    @Override
    public boolean isMasked()
    {
        return masked;
    }

    @Override
    public boolean isRsv1()
    {
        return rsv1;
    }

    @Override
    public boolean isRsv2()
    {
        return rsv2;
    }

    @Override
    public boolean isRsv3()
    {
        return rsv3;
    }

    /**
     * Get the position currently within the payload data.
     * <p>
     * Used by flow control, generator and window sizing.
     * 
     * @return the number of bytes remaining in the payload data that has not yet been written out to Network ByteBuffers.
     */
    public int position()
    {
        if (data == null)
        {
            return -1;
        }
        return data.position();
    }

    /**
     * Get the number of bytes remaining to write out to the Network ByteBuffer.
     * <p>
     * Used by flow control, generator and window sizing.
     * 
     * @return the number of bytes remaining in the payload data that has not yet been written out to Network ByteBuffers.
     */
    public int remaining()
    {
        if (data == null)
        {
            return 0;
        }
        return data.remaining();
    }

    public void reset()
    {
        fin = true;
        rsv1 = false;
        rsv2 = false;
        rsv3 = false;
        opcode = -1;
        masked = false;
        data = null;
        payloadLength = 0;
        mask = null;
        continuationIndex = 0;
        continuation = false;
    }

    public WebSocketFrame setContinuation(boolean continuation)
    {
        this.continuation = continuation;
        return this;
    }

    public WebSocketFrame setContinuationIndex(int continuationIndex)
    {
        this.continuationIndex = continuationIndex;
        return this;
    }

    public WebSocketFrame setFin(boolean fin)
    {
        this.fin = fin;
        return this;
    }

    public WebSocketFrame setMask(byte[] maskingKey)
    {
        this.mask = maskingKey;
        this.masked = (mask != null);
        return this;
    }

    public WebSocketFrame setMasked(boolean mask)
    {
        this.masked = mask;
        return this;
    }

    public WebSocketFrame setOpCode(byte op)
    {
        this.opcode = op;
        return this;
    }

    /**
     * Set the data and payload length.
     * 
     * @param buf
     *            the bytebuffer to set
     */
    public WebSocketFrame setPayload(byte buf[])
    {
        if (buf == null)
        {
            data = null;
            return this;
        }

        if (OpCode.isControlFrame(opcode))
        {
            if (buf.length > WebSocketFrame.MAX_CONTROL_PAYLOAD)
            {
                throw new ProtocolException("Control Payloads can not exceed 125 bytes in length.");
            }
        }

        data = BufferUtil.toBuffer(buf);
        payloadStart = data.position();
        payloadLength = data.limit();
        return this;
    }

    /**
     * Set the data and payload length.
     * 
     * @param buf
     *            the bytebuffer to set
     */
    public WebSocketFrame setPayload(byte buf[], int offset, int len)
    {
        if (buf == null)
        {
            data = null;
            return this;
        }

        if (OpCode.isControlFrame(opcode))
        {
            if (len > WebSocketFrame.MAX_CONTROL_PAYLOAD)
            {
                throw new ProtocolException("Control Payloads can not exceed 125 bytes in length.");
            }
        }

        data = BufferUtil.toBuffer(buf,offset,len);
        payloadStart = data.position();
        payloadLength = data.limit();
        return this;
    }

    /**
     * Set the data payload.
     * <p>
     * The provided buffer will be used as is, no copying of bytes performed.
     * <p>
     * The provided buffer should be flipped and ready to READ from.
     * 
     * @param buf
     *            the bytebuffer to set
     */
    public WebSocketFrame setPayload(ByteBuffer buf)
    {
        if (buf == null)
        {
            data = null;
            return this;
        }

        if (OpCode.isControlFrame(opcode))
        {
            if (buf.remaining() > WebSocketFrame.MAX_CONTROL_PAYLOAD)
            {
                throw new ProtocolException("Control Payloads can not exceed 125 bytes in length.");
            }
        }

        data = buf.slice();
        payloadStart = data.position();
        payloadLength = data.limit();
        return this;
    }

    public WebSocketFrame setPayload(String str)
    {
        setPayload(BufferUtil.toBuffer(str,StringUtil.__UTF8_CHARSET));
        return this;
    }

    public WebSocketFrame setRsv1(boolean rsv1)
    {
        this.rsv1 = rsv1;
        return this;
    }

    public WebSocketFrame setRsv2(boolean rsv2)
    {
        this.rsv2 = rsv2;
        return this;
    }

    public WebSocketFrame setRsv3(boolean rsv3)
    {
        this.rsv3 = rsv3;
        return this;
    }

    @Override
    public String toString()
    {
        StringBuilder b = new StringBuilder();
        b.append(OpCode.name(opcode));
        b.append('[');
        b.append("len=").append(payloadLength);
        b.append(",fin=").append(fin);
        b.append(",masked=").append(masked);
        b.append(",continuation=").append(continuation);
        b.append(']');
        return b.toString();
    }
}

Back to the top