package io.undertow.websockets.core.protocol.version07;
import io.undertow.server.protocol.framed.FrameHeaderData;
import io.undertow.websockets.core.function.ChannelFunction;
import java.nio.ByteBuffer;
public final class Masker implements ChannelFunction {
private byte[] maskingKey;
int m;
Masker(int maskingKey) {
this.maskingKey = createsMaskingKey(maskingKey);
}
public void setMaskingKey(int maskingKey) {
this.maskingKey = createsMaskingKey(maskingKey);
m = 0;
}
private static byte[] createsMaskingKey(int maskingKey) {
byte[] key = new byte[4];
key[0] = (byte) (maskingKey >> 24 & 0xFF);
key[1] = (byte) (maskingKey >> 16 & 0xFF);
key[2] = (byte) (maskingKey >> 8 & 0xFF);
key[3] = (byte) (maskingKey & 0xFF);
return key;
}
private void mask(ByteBuffer buf, int position, int length) {
int limit = position + length;
for (int i = position ; i < limit; ++i) {
buf.put(i, (byte) (buf.get(i) ^ maskingKey[m++]));
m %= 4;
}
}
@Override
public void (FrameHeaderData headerData) {
WebSocket07Channel.WebSocketFrameHeader header = (WebSocket07Channel.WebSocketFrameHeader) headerData;
setMaskingKey(header.getMaskingKey());
}
@Override
public void afterRead(ByteBuffer buf, int position, int length) {
mask(buf, position, length);
}
@Override
public void beforeWrite(ByteBuffer buf, int position, int length) {
mask(buf, position, length);
}
@Override
public void complete() {
}
}