Revision: ce22c2c6589e
Author: vralev <vralev@8e71dc83-d81e-6649-80f2-80b843a9b2be>
Date: Thu Aug 23 16:29:19 2012
Log: Update Issue JSIP-432
Update Issue 15 (git repo)
Initial infrastructure to accommodate websockets - we have server side HTTP
handshaking rev 13, Websocket text frames server side and buffering. This
is sufficient for sipml5.org with chrome inbound REGISTER and calls.
git-svn-id:
https://svn.java.net/svn/jsip~svn/branches/JAIN-SIP-NIO-year-2012@2155
8e71dc83-d81e-6649-80f2-80b843a9b2be
http://code.google.com/p/jain-sip/source/detail?r=ce22c2c6589e
Added:
/src/gov/nist/javax/sip/stack/Base64Coder.java
/src/gov/nist/javax/sip/stack/NioWebSocketMessageChannel.java
/src/gov/nist/javax/sip/stack/NioWebSocketMessageProcessor.java
/src/gov/nist/javax/sip/stack/WebSocketCodec.java
/src/gov/nist/javax/sip/stack/WebSocketHttpHandshake.java
Modified:
/src/gov/nist/javax/sip/SipStackImpl.java
/src/gov/nist/javax/sip/parser/NioPipelineParser.java
/src/gov/nist/javax/sip/stack/NioMessageProcessorFactory.java
=======================================
--- /dev/null
+++ /src/gov/nist/javax/sip/stack/Base64Coder.java Thu Aug 23 16:29:19 2012
@@ -0,0 +1,227 @@
+// Copyright 2003-2010 Christian d'Heureuse, Inventec Informatik AG,
Zurich, Switzerland
+// www.source-code.biz, www.inventec.ch/chdh
+//
+// This module is multi-licensed and may be used under the terms
+// of any of the following licenses:
+//
+// EPL, Eclipse Public License, V1.0 or later,
http://www.eclipse.org/legal
+// LGPL, GNU Lesser General Public License, V2.1 or later,
http://www.gnu.org/licenses/lgpl.html
+// GPL, GNU General Public License, V2 or later,
http://www.gnu.org/licenses/gpl.html
+// AL, Apache License, V2.0 or later, http://www.apache.org/licenses
+// BSD, BSD License, http://www.opensource.org/licenses/bsd-license.php
+// MIT, MIT License, http://www.opensource.org/licenses/MIT
+//
+// Please contact the author if you need another license.
+// This module is provided "as is", without warranties of any kind.
+
+package gov.nist.javax.sip.stack;
+
+/**
+ * A Base64 encoder/decoder.
+ *
+ * <p>
+ * This class is used to encode and decode data in Base64 format as
described in RFC 1521.
+ *
+ * <p>
+ * Project home page: <a
href="http://www.source-code.biz/base64coder/java/">www.source-code.biz/base64coder/java</a><br>
+ * Author: Christian d'Heureuse, Inventec Informatik AG, Zurich,
Switzerland<br>
+ * Multi-licensed: EPL / LGPL / GPL / AL / BSD / MIT.
+ */
+public class Base64Coder {
+
+ // The line separator string of the operating system.
+ private static final String systemLineSeparator =
System.getProperty("line.separator");
+
+ // Mapping table from 6-bit nibbles to Base64 characters.
+ private static final char[] map1 = new char[64];
+ static {
+ int i=0;
+ for (char c='A'; c<='Z'; c++) map1[i++] = c;
+ for (char c='a'; c<='z'; c++) map1[i++] = c;
+ for (char c='0'; c<='9'; c++) map1[i++] = c;
+ map1[i++] = '+'; map1[i++] = '/'; }
+
+ // Mapping table from Base64 characters to 6-bit nibbles.
+ private static final byte[] map2 = new byte[128];
+ static {
+ for (int i=0; i<map2.length; i++) map2[i] = -1;
+ for (int i=0; i<64; i++) map2[map1[i]] = (byte)i; }
+
+ /**
+ * Encodes a string into Base64 format.
+ * No blanks or line breaks are inserted.
+ * @param s A String to be encoded.
+ * @return A String containing the Base64 encoded data.
+ */
+ public static String encodeString (String s) {
+ return new String(encode(s.getBytes())); }
+
+ /**
+ * Encodes a byte array into Base 64 format and breaks the output into
lines of 76 characters.
+ * This method is compatible with
<code>sun.misc.BASE64Encoder.encodeBuffer(byte[])</code>.
+ * @param in An array containing the data bytes to be encoded.
+ * @return A String containing the Base64 encoded data, broken into
lines.
+ */
+ public static String encodeLines (byte[] in) {
+ return encodeLines(in, 0, in.length, 76, systemLineSeparator); }
+
+ /**
+ * Encodes a byte array into Base 64 format and breaks the output into
lines.
+ * @param in An array containing the data bytes to be
encoded.
+ * @param iOff Offset of the first byte in <code>in</code> to be
processed.
+ * @param iLen Number of bytes to be processed in
<code>in</code>, starting at <code>iOff</code>.
+ * @param lineLen Line length for the output data. Should be a
multiple of 4.
+ * @param lineSeparator The line separator to be used to separate the
output lines.
+ * @return A String containing the Base64 encoded data,
broken into lines.
+ */
+ public static String encodeLines (byte[] in, int iOff, int iLen, int
lineLen, String lineSeparator) {
+ int blockLen = (lineLen*3) / 4;
+ if (blockLen <= 0) throw new IllegalArgumentException();
+ int lines = (iLen+blockLen-1) / blockLen;
+ int bufLen = ((iLen+2)/3)*4 + lines*lineSeparator.length();
+ StringBuilder buf = new StringBuilder(bufLen);
+ int ip = 0;
+ while (ip < iLen) {
+ int l = Math.min(iLen-ip, blockLen);
+ buf.append (encode(in, iOff+ip, l));
+ buf.append (lineSeparator);
+ ip += l; }
+ return buf.toString(); }
+
+ /**
+ * Encodes a byte array into Base64 format.
+ * No blanks or line breaks are inserted in the output.
+ * @param in An array containing the data bytes to be encoded.
+ * @return A character array containing the Base64 encoded data.
+ */
+ public static char[] encode (byte[] in) {
+ return encode(in, 0, in.length); }
+
+ /**
+ * Encodes a byte array into Base64 format.
+ * No blanks or line breaks are inserted in the output.
+ * @param in An array containing the data bytes to be encoded.
+ * @param iLen Number of bytes to process in <code>in</code>.
+ * @return A character array containing the Base64 encoded data.
+ */
+ public static char[] encode (byte[] in, int iLen) {
+ return encode(in, 0, iLen); }
+
+ /**
+ * Encodes a byte array into Base64 format.
+ * No blanks or line breaks are inserted in the output.
+ * @param in An array containing the data bytes to be encoded.
+ * @param iOff Offset of the first byte in <code>in</code> to be
processed.
+ * @param iLen Number of bytes to process in <code>in</code>, starting
at <code>iOff</code>.
+ * @return A character array containing the Base64 encoded data.
+ */
+ public static char[] encode (byte[] in, int iOff, int iLen) {
+ int oDataLen = (iLen*4+2)/3; // output length without
padding
+ int oLen = ((iLen+2)/3)*4; // output length including
padding
+ char[] out = new char[oLen];
+ int ip = iOff;
+ int iEnd = iOff + iLen;
+ int op = 0;
+ while (ip < iEnd) {
+ int i0 = in[ip++] & 0xff;
+ int i1 = ip < iEnd ? in[ip++] & 0xff : 0;
+ int i2 = ip < iEnd ? in[ip++] & 0xff : 0;
+ int o0 = i0 >>> 2;
+ int o1 = ((i0 & 3) << 4) | (i1 >>> 4);
+ int o2 = ((i1 & 0xf) << 2) | (i2 >>> 6);
+ int o3 = i2 & 0x3F;
+ out[op++] = map1[o0];
+ out[op++] = map1[o1];
+ out[op] = op < oDataLen ? map1[o2] : '='; op++;
+ out[op] = op < oDataLen ? map1[o3] : '='; op++; }
+ return out; }
+
+ /**
+ * Decodes a string from Base64 format.
+ * No blanks or line breaks are allowed within the Base64 encoded input
data.
+ * @param s A Base64 String to be decoded.
+ * @return A String containing the decoded data.
+ * @throws IllegalArgumentException If the input is not valid Base64
encoded data.
+ */
+ public static String decodeString (String s) {
+ return new String(decode(s)); }
+
+ /**
+ * Decodes a byte array from Base64 format and ignores line separators,
tabs and blanks.
+ * CR, LF, Tab and Space characters are ignored in the input data.
+ * This method is compatible with
<code>sun.misc.BASE64Decoder.decodeBuffer(String)</code>.
+ * @param s A Base64 String to be decoded.
+ * @return An array containing the decoded data bytes.
+ * @throws IllegalArgumentException If the input is not valid Base64
encoded data.
+ */
+ public static byte[] decodeLines (String s) {
+ char[] buf = new char[s.length()];
+ int p = 0;
+ for (int ip = 0; ip < s.length(); ip++) {
+ char c = s.charAt(ip);
+ if (c != ' ' && c != '\r' && c != '\n' && c != '\t')
+ buf[p++] = c; }
+ return decode(buf, 0, p); }
+
+ /**
+ * Decodes a byte array from Base64 format.
+ * No blanks or line breaks are allowed within the Base64 encoded input
data.
+ * @param s A Base64 String to be decoded.
+ * @return An array containing the decoded data bytes.
+ * @throws IllegalArgumentException If the input is not valid Base64
encoded data.
+ */
+ public static byte[] decode (String s) {
+ return decode(s.toCharArray()); }
+
+ /**
+ * Decodes a byte array from Base64 format.
+ * No blanks or line breaks are allowed within the Base64 encoded input
data.
+ * @param in A character array containing the Base64 encoded data.
+ * @return An array containing the decoded data bytes.
+ * @throws IllegalArgumentException If the input is not valid Base64
encoded data.
+ */
+ public static byte[] decode (char[] in) {
+ return decode(in, 0, in.length); }
+
+ /**
+ * Decodes a byte array from Base64 format.
+ * No blanks or line breaks are allowed within the Base64 encoded input
data.
+ * @param in A character array containing the Base64 encoded data.
+ * @param iOff Offset of the first character in <code>in</code> to be
processed.
+ * @param iLen Number of characters to process in <code>in</code>,
starting at <code>iOff</code>.
+ * @return An array containing the decoded data bytes.
+ * @throws IllegalArgumentException If the input is not valid Base64
encoded data.
+ */
+ public static byte[] decode (char[] in, int iOff, int iLen) {
+ if (iLen%4 != 0) throw new IllegalArgumentException ("Length of Base64
encoded input string is not a multiple of 4.");
+ while (iLen > 0 && in[iOff+iLen-1] == '=') iLen--;
+ int oLen = (iLen*3) / 4;
+ byte[] out = new byte[oLen];
+ int ip = iOff;
+ int iEnd = iOff + iLen;
+ int op = 0;
+ while (ip < iEnd) {
+ int i0 = in[ip++];
+ int i1 = in[ip++];
+ int i2 = ip < iEnd ? in[ip++] : 'A';
+ int i3 = ip < iEnd ? in[ip++] : 'A';
+ if (i0 > 127 || i1 > 127 || i2 > 127 || i3 > 127)
+ throw new IllegalArgumentException ("Illegal character in Base64
encoded data.");
+ int b0 = map2[i0];
+ int b1 = map2[i1];
+ int b2 = map2[i2];
+ int b3 = map2[i3];
+ if (b0 < 0 || b1 < 0 || b2 < 0 || b3 < 0)
+ throw new IllegalArgumentException ("Illegal character in Base64
encoded data.");
+ int o0 = ( b0 <<2) | (b1>>>4);
+ int o1 = ((b1 & 0xf)<<4) | (b2>>>2);
+ int o2 = ((b2 & 3)<<6) | b3;
+ out[op++] = (byte)o0;
+ if (op<oLen) out[op++] = (byte)o1;
+ if (op<oLen) out[op++] = (byte)o2; }
+ return out; }
+
+ // Dummy constructor.
+ private Base64Coder() {}
+
+} // end class Base64Coder
=======================================
--- /dev/null
+++ /src/gov/nist/javax/sip/stack/NioWebSocketMessageChannel.java Thu Aug
23 16:29:19 2012
@@ -0,0 +1,136 @@
+/*
+ * Conditions Of Use
+ *
+ * This software was developed by employees of the National Institute of
+ * Standards and Technology (NIST), an agency of the Federal Government.
+ * Pursuant to title 15 Untied States Code Section 105, works of NIST
+ * employees are not subject to copyright protection in the United States
+ * and are considered to be in the public domain. As a result, a formal
+ * license is not needed to use the software.
+ *
+ * This software is provided by NIST as a service and is expressly
+ * provided "AS IS." NIST MAKES NO WARRANTY OF ANY KIND, EXPRESS, IMPLIED
+ * OR STATUTORY, INCLUDING, WITHOUT LIMITATION, THE IMPLIED WARRANTY OF
+ * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, NON-INFRINGEMENT
+ * AND DATA ACCURACY. NIST does not warrant or make any representations
+ * regarding the use of the software or the results thereof, including but
+ * not limited to the correctness, accuracy, reliability or usefulness of
+ * the software.
+ *
+ * Permission to use this software is contingent upon your acceptance
+ * of the terms of this agreement
+ *
+ * .
+ *
+ */
+package gov.nist.javax.sip.stack;
+
+import gov.nist.core.CommonLogger;
+import gov.nist.core.LogWriter;
+import gov.nist.core.StackLogger;
+import java.io.ByteArrayInputStream;
+import java.io.IOException;
+import java.net.InetAddress;
+import java.nio.channels.SocketChannel;
+
+public class NioWebSocketMessageChannel extends NioTcpMessageChannel{
+
+ private static StackLogger logger = CommonLogger
+ .getLogger(NioWebSocketMessageChannel.class);
+
+ public static NioWebSocketMessageChannel create(
+ NioWebSocketMessageProcessor nioTcpMessageProcessor,
+ SocketChannel socketChannel) throws IOException {
+ NioWebSocketMessageChannel retval = (NioWebSocketMessageChannel)
channelMap.get(socketChannel);
+ if (retval == null) {
+ retval = new
NioWebSocketMessageChannel(nioTcpMessageProcessor,
+ socketChannel);
+ channelMap.put(socketChannel, retval);
+ }
+ return retval;
+ }
+
+ protected NioWebSocketMessageChannel(NioTcpMessageProcessor
nioTcpMessageProcessor,
+ SocketChannel socketChannel) throws IOException {
+ super(nioTcpMessageProcessor, socketChannel);
+
+ messageProcessor = nioTcpMessageProcessor;
+ myClientInputStream = socketChannel.socket().getInputStream();
+ }
+
+ @Override
+ protected void sendMessage(final byte[] msg, final boolean isClient)
throws IOException {
+ super.sendMessage(msg, isClient);
+ }
+
+ protected void sendNonWebSocketMessage(byte[] msg, boolean isClient)
throws IOException {
+
+ if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+ logger.logDebug("sendMessage isClient = " + isClient + " this = " +
this);
+ }
+ lastActivityTimeStamp = System.currentTimeMillis();
+
+ NIOHandler nioHandler = ((NioTcpMessageProcessor)
messageProcessor).nioHandler;
+ if(this.socketChannel != null && this.socketChannel.isConnected() &&
this.socketChannel.isOpen()) {
+ nioHandler.putSocket(NIOHandler.makeKey(this.peerAddress,
this.peerPort), this.socketChannel);
+ }
+ super.sendTCPMessage(msg, this.peerAddress, this.peerPort,
isClient);
+ }
+
+ private byte[] wrapBufferIntoWebSocketFrame(byte[] buffer) {
+ try {
+ return WebSocketCodec.encode(buffer, 0, true);
+ } catch (Exception e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ @Override
+ public void sendTCPMessage(byte message[], InetAddress receiverAddress,
+ int receiverPort, boolean retry) throws IOException {
+ message = wrapBufferIntoWebSocketFrame(message);
+ super.sendTCPMessage(message, receiverAddress, receiverPort,
retry);
+ }
+
+ @Override
+ public void sendMessage(final byte message[], final InetAddress
receiverAddress,
+ final int receiverPort, final boolean retry) throws
IOException {
+ sendTCPMessage(message, receiverAddress, receiverPort, retry);
+ }
+
+ public NioWebSocketMessageChannel(InetAddress inetAddress, int port,
+ SIPTransactionStack sipStack,
+ NioTcpMessageProcessor nioTcpMessageProcessor) throws
IOException {
+ super(inetAddress, port, sipStack, nioTcpMessageProcessor);
+ }
+
+ @Override
+ protected void addBytes(byte[] bytes) throws Exception {
+ String s = new String(bytes);
+
+ if(s.startsWith("GET")) {
+ byte[] response = new
WebSocketHttpHandshake().createHttpResponse(s);
+ sendNonWebSocketMessage(response, false);
+ } else {
+ ByteArrayInputStream bios = new
ByteArrayInputStream(bytes);
+ WebSocketCodec codec = new WebSocketCodec(true, true);
+ byte[] decodedMsg = codec.decode(bios);
+ System.out.println(new String(decodedMsg));
+ nioParser.addBytes(decodedMsg);
+ }
+ }
+
+ @Override
+ public String getTransport() {
+ return "WS";
+ }
+
+ @Override
+ public void onNewSocket() {
+ super.onNewSocket();
+
+ }
+
+}
=======================================
--- /dev/null
+++ /src/gov/nist/javax/sip/stack/NioWebSocketMessageProcessor.java Thu Aug
23 16:29:19 2012
@@ -0,0 +1,86 @@
+package gov.nist.javax.sip.stack;
+
+
+import gov.nist.core.CommonLogger;
+import gov.nist.core.HostPort;
+import gov.nist.core.LogWriter;
+import gov.nist.core.StackLogger;
+
+import java.io.IOException;
+import java.net.InetAddress;
+import java.nio.channels.SocketChannel;
+import java.util.HashMap;
+
+public class NioWebSocketMessageProcessor extends NioTcpMessageProcessor {
+
+ private static StackLogger logger =
CommonLogger.getLogger(NioWebSocketMessageProcessor.class);
+
+ public static HashMap<String, NioWebSocketMessageChannel> addressMap =
new HashMap<String, NioWebSocketMessageChannel>();
+
+ public NioWebSocketMessageProcessor(InetAddress ipAddress,
+ SIPTransactionStack sipStack, int port) {
+ super(ipAddress, sipStack, port);
+ transport = "WS";
+ }
+
+ @Override
+ public NioTcpMessageChannel createMessageChannel(NioTcpMessageProcessor
nioTcpMessageProcessor, SocketChannel client) throws IOException {
+ return NioWebSocketMessageChannel.create(this, client);
+ }
+
+ @Override
+ public MessageChannel createMessageChannel(HostPort targetHostPort)
throws IOException {
+ if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+ logger.logDebug(":createMessageChannel: " + targetHostPort);
+ }
+ try {
+ String key = MessageChannel.getKey(targetHostPort, "WS");
+ if (messageChannels.get(key) != null) {
+ return this.messageChannels.get(key);
+ } else {
+ NioWebSocketMessageChannel retval = new
NioWebSocketMessageChannel(targetHostPort.getInetAddress(),
+ targetHostPort.getPort(), sipStack,
this);
+
+
+ // retval.getSocketChannel().register(selector,
SelectionKey.OP_READ);
+ synchronized(messageChannels) {
+ this.messageChannels.put(key, retval);
+ }
+ retval.isCached = true;
+ if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+ logger.logDebug("key " + key);
+ logger.logDebug("Creating " + retval);
+ }
+ selector.wakeup();
+ return retval;
+
+ }
+ } finally {
+ if(logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+ logger.logDebug("MessageChannel::createMessageChannel -
exit");
+ }
+ }
+ }
+
+ @Override
+ public MessageChannel createMessageChannel(InetAddress targetHost, int
port) throws IOException {
+ String key = MessageChannel.getKey(targetHost, port, "WS");
+ if (messageChannels.get(key) != null) {
+ return this.messageChannels.get(key);
+ } else {
+ NioWebSocketMessageChannel retval = new
NioWebSocketMessageChannel(targetHost, port, sipStack, this);
+
+ selector.wakeup();
+ // retval.getSocketChannel().register(selector,
SelectionKey.OP_READ);
+ this.messageChannels.put(key, retval);
+ retval.isCached = true;
+ if (logger.isLoggingEnabled(LogWriter.TRACE_DEBUG)) {
+ logger.logDebug("key " + key);
+ logger.logDebug("Creating " + retval);
+ }
+ return retval;
+ }
+
+ }
+
+}
=======================================
--- /dev/null
+++ /src/gov/nist/javax/sip/stack/WebSocketCodec.java Thu Aug 23 16:29:19
2012
@@ -0,0 +1,248 @@
+package gov.nist.javax.sip.stack;
+
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+
+import gov.nist.core.CommonLogger;
+import gov.nist.core.LogLevels;
+import gov.nist.core.StackLogger;
+
+/**
+ *
+ * Decodes a web socket frame from wire protocol version 8 format. This
code was forked from <a
+ * href="https://github.com/joewalnes/webbit">webbit</a> and modified.
+ *
+ * @author vladimirralev
+ *
+ */
+public class WebSocketCodec {
+
+ private static StackLogger logger = CommonLogger
+ .getLogger(WebSocketCodec.class);
+ private static final byte OPCODE_CONT = 0x0;
+ private static final byte OPCODE_TEXT = 0x1;
+ private static final byte OPCODE_BINARY = 0x2;
+ private static final byte OPCODE_CLOSE = 0x8;
+ private static final byte OPCODE_PING = 0x9;
+ private static final byte OPCODE_PONG = 0xA;
+
+ private int fragmentedFramesCount;
+
+ private boolean frameFinalFlag;
+ private int frameRsv;
+ private int frameOpcode;
+ private long framePayloadLength;
+ private byte[] maskingKey = new byte[4];
+
+ private final boolean allowExtensions;
+ private final boolean maskedPayload;
+ State state = null;
+ public enum State {
+ FRAME_START, MASKING_KEY, PAYLOAD, CORRUPT
+ }
+
+ public WebSocketCodec(boolean maskedPayload, boolean allowExtensions) {
+ state = State.FRAME_START;
+ this.maskedPayload = maskedPayload;
+ this.allowExtensions = allowExtensions;
+ }
+
+ protected byte[] decode(InputStream is)
+ throws Exception {
+
+ switch (state) {
+ case FRAME_START:
+ framePayloadLength = -1;
+
+ // FIN, RSV, OPCODE
+ byte b = (byte) is.read();
+ frameFinalFlag = (b & 0x80) != 0;
+ frameRsv = (b & 0x70) >> 4;
+ frameOpcode = b & 0x0F;
+
+ logger.logDebug("Decoding WebSocket Frame opCode=" +
frameOpcode);
+
+
+ // MASK, PAYLOAD LEN 1
+ b = (byte) is.read();
+ boolean frameMasked = (b & 0x80) != 0;
+ int framePayloadLen1 = b & 0x7F;
+
+ if (frameRsv != 0 && !allowExtensions) {
+ protocolViolation("RSV != 0 and no extension negotiated,
RSV:" + frameRsv);
+ return null;
+ }
+
+ if (maskedPayload && !frameMasked) {
+ protocolViolation("unmasked client to server frame");
+ return null;
+ }
+ if (frameOpcode > 7) { // control frame (have MSB in opcode
set)
+
+ // control frames MUST NOT be fragmented
+ if (!frameFinalFlag) {
+ protocolViolation("fragmented control frame");
+ return null;
+ }
+
+ // control frames MUST have payload 125 octets or less
+ if (framePayloadLen1 > 125) {
+ protocolViolation("control frame with payload length >
125 octets");
+ return null;
+ }
+
+ // check for reserved control frame opcodes
+ if (!(frameOpcode == OPCODE_CLOSE || frameOpcode ==
OPCODE_PING || frameOpcode == OPCODE_PONG)) {
+ protocolViolation("control frame using reserved
opcode " + frameOpcode);
+ return null;
+ }
+
+ // close frame : if there is a body, the first two bytes
of the
+ // body MUST be a 2-byte unsigned integer (in network byte
+ // order) representing a status code
+ if (frameOpcode == 8 && framePayloadLen1 == 1) {
+ protocolViolation("received close control frame with
payload len 1");
+ return null;
+ }
+ } else { // data frame
+ // check for reserved data frame opcodes
+ if (!(frameOpcode == OPCODE_CONT || frameOpcode ==
OPCODE_TEXT || frameOpcode == OPCODE_BINARY)) {
+ protocolViolation("data frame using reserved opcode "
+ frameOpcode);
+ return null;
+ }
+
+ // check opcode vs message fragmentation state 1/2
+ if (fragmentedFramesCount == 0 && frameOpcode ==
OPCODE_CONT) {
+ protocolViolation("received continuation data frame
outside fragmented message");
+ return null;
+ }
+
+ // check opcode vs message fragmentation state 2/2
+ if (fragmentedFramesCount != 0 && frameOpcode !=
OPCODE_CONT && frameOpcode != OPCODE_PING) {
+ protocolViolation("received non-continuation data
frame while inside fragmented message");
+ return null;
+ }
+ }
+
+ // Read frame payload length
+ if (framePayloadLen1 == 126) {
+ int value = is.read()<<8 + is.read();
+ framePayloadLength = value;
+ //This check fails with chrome!!!
+// if (framePayloadLength < 126) {
+// protocolViolation("invalid data frame length (not
using minimal length encoding)");
+// return null;
+// }
+ } else if (framePayloadLen1 == 127) {
+ long value = 0;
+ for(int q=0;q<8;q++) {
+ value &= is.read()<<(7-q);
+ }
+ framePayloadLength = value;
+
+ if (framePayloadLength < 65536) {
+ protocolViolation("invalid data frame length (not
using minimal length encoding)");
+ return null;
+ }
+ } else {
+ framePayloadLength = framePayloadLen1;
+ }
+
+ if(logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
+ logger.logDebug("Decoding WebSocket Frame length=" +
framePayloadLength);
+ }
+
+ state = State.MASKING_KEY;
+ case MASKING_KEY:
+ if (maskedPayload) {
+ for(int q=0;q<4;q++)
+ maskingKey[q] = (byte) is.read();
+ }
+ state = State.PAYLOAD;
+ case PAYLOAD:
+ // Sometimes, the payload may not be delivered in 1 nice packet
+ // We need to accumulate the data until we have it all
+ byte[] framePayload = new byte[66000];
+ int num = is.read(framePayload);
+
+
+ // Unmask data if needed
+ if (maskedPayload) {
+ unmask(framePayload);
+ }
+
+ byte[] msg = new byte[num];
+ System.arraycopy(framePayload, 0, msg, 0, num);
+ return msg;
+ case CORRUPT:
+ return null;
+ default:
+ throw new Error("Shouldn't reach here.");
+ }
+ }
+
+ protected static byte[] encode(byte[] msg, int rsv, boolean fin)
throws Exception {
+
+ boolean maskPayload = false;
+ ByteArrayOutputStream frame = new ByteArrayOutputStream();
+
+ byte opcode;
+ opcode = OPCODE_TEXT;
+
+
+ int length = msg.length;
+
+ if(logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
+ logger.logDebug("Encoding WebSocket Frame opCode=" + opcode + "
length=" + length);
+ }
+
+ int b0 = 0;
+ if (fin) {
+ b0 |= 1 << 7;
+ }
+ b0 |= rsv % 8 << 4;
+ b0 |= opcode % 128;
+
+
+ if (length <= 125) {
+ frame.write(b0);
+ byte b = (byte) (maskPayload ? 0x80 | (byte) length : (byte)
length);
+ frame.write(b);
+ } else if (length <= 0xFFFF) {
+ frame.write(b0);
+ frame.write(maskPayload ? 0xFE : 126);
+ frame.write(length >>> 8 & 0xFF);
+ frame.write(length & 0xFF);
+ } else {
+ frame.write(b0);
+ frame.write(maskPayload ? 0xFF : 127);
+ for(int q=0;q<8;q++) {
+ frame.write((0xFF)&(length>>q));
+ }
+ }
+
+ frame.write(msg);
+ return frame.toByteArray();
+
+ }
+
+ private void unmask(byte[] frame) {
+ for (int i = 0; i < frame.length; i++) {
+ frame[i] = (byte) (frame[i] ^ maskingKey[i % 4]);
+ }
+ }
+
+ public byte readByte(InputStream is) throws IOException {
+ byte value = (byte) (0xFF&is.read());
+ return value;
+ }
+
+ private void protocolViolation(String reason) {
+ state = State.CORRUPT;
+
+ throw new RuntimeException(reason);
+ }
+
+
+}
=======================================
--- /dev/null
+++ /src/gov/nist/javax/sip/stack/WebSocketHttpHandshake.java Thu Aug 23
16:29:19 2012
@@ -0,0 +1,170 @@
+package gov.nist.javax.sip.stack;
+
+import gov.nist.core.CommonLogger;
+import gov.nist.core.LogLevels;
+import gov.nist.core.StackLogger;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.MessageDigest;
+import java.security.NoSuchAlgorithmException;
+import java.util.HashMap;
+
+/**
+ * Websocket handshake rev 13 and rev 8
+ *
+ */
+public class WebSocketHttpHandshake {
+
+ private static StackLogger logger = CommonLogger
+ .getLogger(WebSocketHttpHandshake.class);
+
+ private HashMap<String, String> headers = new HashMap<String, String>();
+
+ public byte[] createHttpResponse(String request) throws Exception {
+
+ if(logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
+ logger.logDebug("Request=" + request);
+ }
+ InputStream is = new ByteArrayInputStream(request.getBytes());
+
+ boolean isSecure = false;
+
+ String line = readLine(is);
+
+ if (line == null) {
+ return null;
+ }
+
+ String[] parts = line.split(" ");
+ if (parts.length >= 3) {
+ headers.put("ctx", parts[1]);
+ }
+ while (!line.isEmpty()) {
+ line = readLine(is);
+
+ if (line == null) {
+ continue;
+ }
+
+ if (line.isEmpty()) {
+ continue;
+ }
+
+ parts = line.split(":", 2);
+ if (parts.length != 2) {
+ continue;
+ }
+ if
(parts[0].toLowerCase().startsWith("sec-websocket-key")) {
+ isSecure = true;
+ }
+ headers.put(parts[0].trim(), parts[1].trim());
+ }
+ if (isSecure) {
+ byte[] key3 = new byte[8];
+ is.read(key3);
+ }
+
+ //answer the handshake
+ StringBuilder sb = new StringBuilder();
+ String lineSeparator = "\r\n";
+ sb.append("HTTP/1.1 101 Web Socket Protocol
Handshake").append("\r\n");
+ sb.append("Upgrade: WebSocket").append(lineSeparator);
+ sb.append("Connection: Upgrade").append(lineSeparator);
+ if (isSecure) {
+ sb.append("Sec-");
+ }
+
+
sb.append("WebSocket-Origin: ").append(headers.get("Origin")).append(lineSeparator);
+
+
+ if (isSecure) {
+ sb.append("Sec-");
+ }
+ sb.append("WebSocket-Location:
ws://").append(headers.get("Host")).
+ append(headers.get("ctx")).append(lineSeparator);
+
+
sb.append("Sec-WebSocket-Accept: ").append(computeRev13Response(headers.get("Sec-WebSocket-Key"))).append(lineSeparator);
+ //sb.append("myheader: nothing");
+ //.append("Sec-WebSocket-Protocol: chat")
+ // .append("Server: Kaazing Gateway\n" +
+ // "Date: Tue, 21 Aug 2012 00:59:35 GMT\n"
+
+ // "Access-Control-Allow-Origin:
http://www.websocket.org\n" +
+ // "Access-Control-Allow-Credentials:
true\n" +
+ // "Access-Control-Allow-Headers:
content-type\n" +
+ // "Access-Control-Allow-Headers:
authorization\n" +
+ // "Access-Control-Allow-Headers:
x-websocket-extensions\n" +
+ // "Access-Control-Allow-Headers:
x-websocket-version\n" +
+ // "Access-Control-Allow-Headers:
x-websocket-protocol\n");
+ if (headers.get("Protocol") != null) {
+ if (isSecure) {
+ sb.append("Sec-");
+ }
+
sb.append("Protocol: ").append(headers.get("Protocol")).append(lineSeparator);
+ }
+
+ if (headers.get("Sec-WebSocket-Protocol") != null) {
+
sb.append("Sec-WebSocket-Protocol: ").append(headers.get("Sec-WebSocket-Protocol")).append(lineSeparator);
+ }
+ sb.append(lineSeparator);
+
+ String response = sb.toString();
+
+ if(logger.isLoggingEnabled(LogLevels.TRACE_DEBUG)) {
+ logger.logDebug("Response=" + response);
+ }
+ byte[] output = sb.toString().getBytes();
+
+ return output;
+ }
+
+ static String computeRev13Response(String key) throws IOException {
+ key = key + "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
+ MessageDigest md = null;
+ try {
+ md = MessageDigest.getInstance("SHA1");
+ md.reset();
+ } catch (NoSuchAlgorithmException ex) {
+ // log.log(Level.SEVERE, "MD5 Algorithm not found", ex);
+ ex.printStackTrace();
+ }
+ byte[] digest = md.digest(key.getBytes());
+ ByteArrayOutputStream baos = new ByteArrayOutputStream();
+ return new String(Base64Coder.encode(digest));
+
+ }
+
+
+ private String readLine(InputStream is) throws IOException {
+ StringBuilder sb = new StringBuilder();
+
+ int cr = '\r';
+ int nl = '\n';
+
+ boolean gotcr = false;
+
+ while (true) {
+ int input = is.read();
+
+ if (input == -1) {
+ return null;
+ }
+
+ if (input == cr) {
+ gotcr = true;
+ continue;
+ }
+ if (input == nl && gotcr) {
+ break;
+ } else if (input == nl) {
+ //we do this only because the protocol
+ //tells ut that there must be a cr before the
nl.
+ return null;
+ }
+ sb.append((char) input);
+ }
+ return sb.toString();
+ }
+}
=======================================
--- /src/gov/nist/javax/sip/SipStackImpl.java Wed Aug 1 03:00:34 2012
+++ /src/gov/nist/javax/sip/SipStackImpl.java Thu Aug 23 16:29:19 2012
@@ -1440,7 +1440,8 @@
if (!transport.equalsIgnoreCase("UDP")
&& !transport.equalsIgnoreCase("TLS")
&& !transport.equalsIgnoreCase("TCP")
- && !transport.equalsIgnoreCase("SCTP"))
+ && !transport.equalsIgnoreCase("SCTP")
+ && !transport.equalsIgnoreCase("WS"))
throw new TransportNotSupportedException("bad transport
"
+ transport);
=======================================
--- /src/gov/nist/javax/sip/parser/NioPipelineParser.java Tue Apr 3
03:21:23 2012
+++ /src/gov/nist/javax/sip/parser/NioPipelineParser.java Thu Aug 23
16:29:19 2012
@@ -48,11 +48,17 @@
import javax.sip.header.ContentLengthHeader;
/**
- * This is a FSM that can parse a single stream of messages with they
bodies and then pass the sip message to the listeners.
+ * This is a FSM that can parse a single stream of messages with they
bodies and
+ * then pass the sip message to the listeners. It accumulates bytes until
end of
+ * message is detected or some DoS trigger terminates it due to excessive
amount
+ * of bytes per message or line.
+ *
+ * Once parsed it will pass the message to the SIPMessageListener
*
* @see SIPMessageListener
+ * @author vladimirralev
*/
-public final class NioPipelineParser {
+public class NioPipelineParser {
boolean currentStreamEnded = false;
boolean readingMessageBodyContents = false;
=======================================
--- /src/gov/nist/javax/sip/stack/NioMessageProcessorFactory.java Sat Mar
24 04:34:55 2012
+++ /src/gov/nist/javax/sip/stack/NioMessageProcessorFactory.java Thu Aug
23 16:29:19 2012
@@ -47,6 +47,11 @@
throw new IllegalArgumentException("Error initializing
SCTP",
ie);
}
+ } else if (transport.equalsIgnoreCase(ListeningPoint.WS)) {
+
+ NioWebSocketMessageProcessor tlsMessageProcessor = new
NioWebSocketMessageProcessor(
+ ipAddress, sipStack, port);
+ return tlsMessageProcessor;
} else {
throw new IllegalArgumentException("bad transport");
}