Skip to content

Commit 32df905

Browse files
committed
added basic close code recognition
fixed missing flush of unsent data before closing(closing handshake)
1 parent 962f901 commit 32df905

7 files changed

Lines changed: 199 additions & 33 deletions

File tree

‎src/net/tootallnate/websocket/Charsetfunctions.java‎

Lines changed: 8 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -34,11 +34,7 @@ public static byte[] asciiBytes( String s ) {
3434
}
3535

3636
public static String stingAscii( byte[] bytes ) {
37-
try {
38-
return new String( bytes, "ASCII" );
39-
} catch ( UnsupportedEncodingException e ) {
40-
throw new RuntimeException( e );
41-
}
37+
return stingAscii( bytes, 0, bytes.length );
4238
}
4339

4440
public static String stingAscii( byte[] bytes, int offset, int length ){
@@ -50,8 +46,12 @@ public static String stingAscii( byte[] bytes, int offset, int length ){
5046
}
5147

5248
public static String stingUtf8( byte[] bytes ) throws CharacterCodingException {
53-
CharsetDecoder encode = Charset.forName("UTF8").newDecoder();
54-
encode.onMalformedInput( codingErrorAction );
55-
return encode.decode( ByteBuffer.wrap( bytes ) ).toString();
49+
return stingAscii( bytes, 0, bytes.length );
50+
}
51+
52+
public static String stingUtf8( byte[] bytes, int off, int length ) throws CharacterCodingException {
53+
CharsetDecoder encode = Charset.forName( "UTF8" ).newDecoder();
54+
encode.onMalformedInput( codingErrorAction );
55+
return encode.decode( ByteBuffer.wrap( bytes, off, length ) ).toString();
5656
}
5757
}
Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
package net.tootallnate.websocket;
2+
3+
import java.nio.charset.CharacterCodingException;
4+
5+
public interface CloseFrame extends Framedata {
6+
/**
7+
* indicates a normal closure, meaning whatever purpose the
8+
* connection was established for has been fulfilled.
9+
*/
10+
public static final int NORMAL = 1000;
11+
/**
12+
* 1001 indicates that an endpoint is "going away", such as a server
13+
* going down, or a browser having navigated away from a page.
14+
*/
15+
public static final int GOING_AWAY = 1001;
16+
/**
17+
* 1002 indicates that an endpoint is terminating the connection due
18+
* to a protocol error.
19+
*/
20+
public static final int PROTOCOL_ERROR = 1002;
21+
/**
22+
* 1003 indicates that an endpoint is terminating the connection
23+
* because it has received a type of data it cannot accept (e.g. an
24+
* endpoint that understands only text data MAY send this if it
25+
* receives a binary message).
26+
*/
27+
public static final int REFUSE = 1003;
28+
/*1004: Reserved. The specific meaning might be defined in the future.*/
29+
/**
30+
* 1005 is a reserved value and MUST NOT be set as a status code in a
31+
* Close control frame by an endpoint. It is designated for use in
32+
* applications expecting a status code to indicate that no status
33+
* code was actually present.
34+
*/
35+
public static final int NOCODE = 1005;
36+
/**
37+
* 1006 is a reserved value and MUST NOT be set as a status code in a
38+
* Close control frame by an endpoint. It is designated for use in
39+
* applications expecting a status code to indicate that the
40+
* connection was closed abnormally, e.g. without sending or
41+
* receiving a Close control frame.
42+
*/
43+
public static final int ABNROMAL_CLOSE = 1006;
44+
/**
45+
* 1007 indicates that an endpoint is terminating the connection
46+
* because it has received data within a message that was not
47+
* consistent with the type of the message (e.g., non-UTF-8 [RFC3629]
48+
* data within a text message).
49+
*/
50+
public static final int NO_UTF8 = 1007;
51+
/**
52+
* 1008 indicates that an endpoint is terminating the connection
53+
* because it has received a message that violates its policy. This
54+
* is a generic status code that can be returned when there is no
55+
* other more suitable status code (e.g. 1003 or 1009), or if there
56+
* is a need to hide specific details about the policy.
57+
*/
58+
public static final int POLICY_VALIDATION = 1008;
59+
/**
60+
* 1009 indicates that an endpoint is terminating the connection
61+
* because it has received a message which is too big for it to
62+
* process.
63+
*/
64+
public static final int TOOBIG = 1009;
65+
/**
66+
* 1010 indicates that an endpoint (client) is terminating the
67+
* connection because it has expected the server to negotiate one or
68+
* more extension, but the server didn't return them in the response
69+
* message of the WebSocket handshake. The list of extensions which
70+
* are needed SHOULD appear in the /reason/ part of the Close frame.
71+
* Note that this status code is not used by the server, because it
72+
* can fail the WebSocket handshake instead.
73+
*/
74+
public static final int EXTENSION = 1010;
75+
76+
public int getCloseCode();
77+
public String getMessage() throws CharacterCodingException;
78+
}
Lines changed: 80 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,80 @@
1+
package net.tootallnate.websocket;
2+
3+
import java.nio.ByteBuffer;
4+
import java.nio.charset.CharacterCodingException;
5+
6+
public class CloseFrameBuilder extends FramedataImpl1 implements CloseFrame {
7+
8+
public CloseFrameBuilder() {
9+
super( Opcode.CLOSING );
10+
setFin( true );
11+
}
12+
13+
public CloseFrameBuilder( int code ) {
14+
super( Opcode.CLOSING );
15+
setFin( true );
16+
setCodeAndMessage( code, "" );
17+
}
18+
19+
public CloseFrameBuilder( int code , String m ) {
20+
super( Opcode.CLOSING );
21+
setFin( true );
22+
setCodeAndMessage( code, m );
23+
}
24+
25+
public void setCloseCode( int code ) {
26+
try {
27+
setCodeAndMessage( code, getMessage() );
28+
} catch ( CharacterCodingException e ) {
29+
assert ( false );
30+
// not expected
31+
throw new RuntimeException( e );
32+
}
33+
}
34+
35+
/** This operation changes the payload */
36+
public void setMessage( String message ) {
37+
setCodeAndMessage( getCloseCode(), message );
38+
}
39+
40+
public void setCodeAndMessage( int code, String m ) {
41+
byte[] by = Charsetfunctions.utf8Bytes( m );
42+
ByteBuffer buf = ByteBuffer.allocate( 4 );
43+
buf.putInt( code );
44+
buf.position( 2 );
45+
ByteBuffer pay = ByteBuffer.allocate( 2 + by.length );
46+
pay.put( buf );
47+
pay.put( by );
48+
}
49+
50+
@Override
51+
public int getCloseCode() {
52+
int code = CloseFrame.NOCODE;
53+
if( unmaskedpayload.array().length >= 2 ) {
54+
ByteBuffer bb = ByteBuffer.allocate( 4 );
55+
bb.position( 2 );
56+
bb.put( unmaskedpayload.array(), 0, 2 );
57+
bb.position( 0 );
58+
code = bb.getInt();
59+
if( code < 0 || code > Short.MAX_VALUE )
60+
code = CloseFrame.NOCODE;
61+
}
62+
return code;
63+
}
64+
65+
@Override
66+
public String getMessage() throws CharacterCodingException {
67+
if( getCloseCode() == CloseFrame.NOCODE ) {
68+
return Charsetfunctions.stingUtf8( unmaskedpayload.array() );
69+
}
70+
else{
71+
return Charsetfunctions.stingUtf8( unmaskedpayload.array(),2,unmaskedpayload.array().length-2 );
72+
}
73+
}
74+
75+
@Override
76+
public String toString() {
77+
return super.toString() + "code: " + getCloseCode();
78+
}
79+
80+
}

‎src/net/tootallnate/websocket/FramedataImpl1.java‎

Lines changed: 5 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -5,11 +5,11 @@
55
import net.tootallnate.websocket.exeptions.InvalidFrameException;
66

77
public class FramedataImpl1 implements FrameBuilder {
8-
private static byte[] emptyarray = {};
9-
private boolean fin;
10-
private Opcode optcode;
11-
private ByteBuffer unmaskedpayload;
12-
private boolean transferemasked;
8+
protected static byte[] emptyarray = {};
9+
protected boolean fin;
10+
protected Opcode optcode;
11+
protected ByteBuffer unmaskedpayload;
12+
protected boolean transferemasked;
1313

1414
public FramedataImpl1() {
1515
}

‎src/net/tootallnate/websocket/WebSocket.java‎

Lines changed: 16 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -36,7 +36,7 @@
3636
public final class WebSocket {
3737
// CONSTANTS ///////////////////////////////////////////////////////////////
3838
public enum Role {
39-
CLIENT , SERVER
39+
CLIENT, SERVER
4040
}
4141
/**
4242
* The default port of WebSockets, as defined in the spec. If the nullary
@@ -51,7 +51,9 @@ public enum Role {
5151
* Internally used to determine whether to receive data as part of the
5252
* remote handshake, or as part of a text frame.
5353
*/
54-
private boolean handshakeComplete;
54+
private boolean handshakeComplete = false;
55+
56+
private boolean closeHandshakeComplete = false;
5557
/**
5658
* The listener to notify of WebSocket events.
5759
*/
@@ -114,7 +116,6 @@ public WebSocket( WebSocketListener listener , List<Draft> drafts , SocketChanne
114116
private void init( WebSocketListener listener, Draft draft, SocketChannel sockchannel ) {
115117
this.sockchannel = sockchannel;
116118
this.bufferQueue = new LinkedBlockingQueue<ByteBuffer>( 10 );
117-
this.handshakeComplete = false;
118119
this.socketBuffer = ByteBuffer.allocate( 65558 );
119120
socketBuffer.flip();
120121
this.wsl = listener;
@@ -237,7 +238,7 @@ public void handleRead() throws InterruptedException , IOException {
237238
if( curop == null )// Ignore undefined opcodes
238239
continue;
239240
else if( curop == Opcode.CLOSING ) {
240-
sendFrame( new FramedataImpl1( Opcode.CLOSING ) );
241+
sendFrame( new FramedataImpl1( f ) );
241242
close();
242243
continue;
243244
} else if( curop == Opcode.PING ) {
@@ -293,16 +294,22 @@ public void abort( String problemmessage ) {
293294
* event handler.
294295
*/
295296
public void close() {
296-
// TODO Send HTTP error here in some cases / create abort method
297-
if( draft != null )
298-
draft.reset();
299-
currentframe = null;
300-
handshakerequest = null;
297+
if( closeHandshakeComplete ) {
298+
return;
299+
}
300+
// TODO Send error/closecode here in some cases
301+
closeHandshakeComplete = true;
301302
try {
303+
handleWrite();
302304
sockchannel.close();
303305
} catch ( IOException e ) {
306+
e.printStackTrace();
304307
}
305308
this.wsl.onClose( this );
309+
if( draft != null )
310+
draft.reset();
311+
currentframe = null;
312+
handshakerequest = null;
306313
}
307314

308315
/**

‎src/net/tootallnate/websocket/WebSocketClient.java‎

Lines changed: 2 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -193,7 +193,7 @@ public void run() {
193193
return;
194194
}
195195
}
196-
196+
conn.close(); // close() is synchronously calling onClose(conn) so we don't have to
197197
try {
198198
selector.close();
199199
} catch ( IOException e ) {
@@ -206,11 +206,6 @@ public void run() {
206206
onError( e );
207207
}
208208
client = null;
209-
210-
draft.reset();
211-
draft = null;
212-
213-
conn.close(); // close() is synchronously calling onClose(conn) so we don't have to
214209
}
215210

216211
private int getPort() {
@@ -274,6 +269,7 @@ public void onOpen( WebSocket conn ) {
274269
* @param conn
275270
*/
276271
public void onClose( WebSocket conn ) {
272+
thread.interrupt();
277273
onClose();
278274
}
279275

‎src/net/tootallnate/websocket/drafts/Draft_10.java‎

Lines changed: 10 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010

1111
import net.tootallnate.websocket.Base64;
1212
import net.tootallnate.websocket.Charsetfunctions;
13+
import net.tootallnate.websocket.CloseFrameBuilder;
1314
import net.tootallnate.websocket.Draft;
1415
import net.tootallnate.websocket.FrameBuilder;
1516
import net.tootallnate.websocket.Framedata;
@@ -328,12 +329,16 @@ public Framedata translateSingleFrame( ByteBuffer buffer ) throws IncompleteExce
328329
payload.put( buffer.array(), buffer.position(), payload.limit() );
329330
buffer.position( buffer.position() + payload.limit() );
330331
}
331-
332-
FrameBuilder frame = new FramedataImpl1();
333-
frame.setFin( FIN );
334-
frame.setOptcode( toOpcode( (byte) ( b1 & 15 ) ) );
332+
Opcode optcode = toOpcode( (byte) ( b1 & 15 ) );
333+
FrameBuilder frame;
334+
if( optcode == Opcode.CLOSING ) {
335+
frame = new CloseFrameBuilder();
336+
} else {
337+
frame = new FramedataImpl1();
338+
frame.setFin( FIN );
339+
frame.setOptcode( optcode );
340+
}
335341
frame.setPayload( payload.array() );
336-
337342
return frame;
338343
}
339344

0 commit comments

Comments
 (0)