View Javadoc

1   //
2   //  ========================================================================
3   //  Copyright (c) 1995-2016 Mort Bay Consulting Pty. Ltd.
4   //  ------------------------------------------------------------------------
5   //  All rights reserved. This program and the accompanying materials
6   //  are made available under the terms of the Eclipse Public License v1.0
7   //  and Apache License v2.0 which accompanies this distribution.
8   //
9   //      The Eclipse Public License is available at
10  //      http://www.eclipse.org/legal/epl-v10.html
11  //
12  //      The Apache License v2.0 is available at
13  //      http://www.opensource.org/licenses/apache2.0.php
14  //
15  //  You may elect to redistribute this code under either of these licenses.
16  //  ========================================================================
17  //
18  
19  package org.eclipse.jetty.websocket.common.io.payload;
20  
21  import java.nio.ByteBuffer;
22  
23  import org.eclipse.jetty.websocket.api.extensions.Frame;
24  
25  public class DeMaskProcessor implements PayloadProcessor
26  {
27      private byte[] maskBytes;
28      private int maskInt;
29      private int maskOffset;
30  
31      @Override
32      public void process(ByteBuffer payload)
33      {
34          if (maskBytes == null)
35          {
36              return;
37          }
38  
39          int maskInt = this.maskInt;
40          int start = payload.position();
41          int end = payload.limit();
42          int offset = this.maskOffset;
43          int remaining;
44          while ((remaining = end - start) > 0)
45          {
46              if (remaining >= 4 && (offset & 3) == 0)
47              {
48                  payload.putInt(start,payload.getInt(start) ^ maskInt);
49                  start += 4;
50                  offset += 4;
51              }
52              else
53              {
54                  payload.put(start,(byte)(payload.get(start) ^ maskBytes[offset & 3]));
55                  ++start;
56                  ++offset;
57              }
58          }
59          maskOffset = offset;
60      }
61  
62      public void reset(byte[] mask)
63      {
64          this.maskBytes = mask;
65          int maskInt = 0;
66          if (mask != null)
67          {
68              for (byte maskByte : mask)
69                  maskInt = (maskInt << 8) + (maskByte & 0xFF);
70          }
71          this.maskInt = maskInt;
72          this.maskOffset = 0;
73      }
74  
75      @Override
76      public void reset(Frame frame)
77      {
78          reset(frame.getMask());
79      }
80  }