@@ -176,6 +176,9 @@ public String toString() {
176176 @ Override
177177 public void isValid () throws InvalidDataException {
178178 super .isValid ();
179+ if (code == CloseFrame .NO_UTF8 && reason == null ) {
180+ throw new InvalidDataException ( CloseFrame .NO_UTF8 );
181+ }
179182 if (code == CloseFrame .NOCODE && 0 < reason .length ()) {
180183 throw new InvalidDataException (PROTOCOL_ERROR , "A close frame must have a closecode if it has a reason" );
181184 }
@@ -190,35 +193,38 @@ public void isValid() throws InvalidDataException {
190193
191194 @ Override
192195 public void setPayload (ByteBuffer payload ) {
193- code = CloseFrame .NOCODE ;
194- payload .mark ();
195- if ( payload .remaining () >= 2 ) {
196- ByteBuffer bb = ByteBuffer .allocate ( 4 );
197- bb .position ( 2 );
198- bb .putShort ( payload .getShort () );
199- bb .position ( 0 );
200- code = bb .getInt ();
201- }
202- payload .reset ();
203- try {
204- if (code == CloseFrame .NOCODE ) {
205- reason = Charsetfunctions .stringUtf8 (payload );
206- } else {
207- ByteBuffer b = super .getPayloadData ();
208- int mark = b .position ();// because stringUtf8 also creates a mark
209- try {
210- b .position (b .position () + 2 );
211- reason = Charsetfunctions .stringUtf8 (b );
212- } catch (IllegalArgumentException e ) {
213- throw new InvalidFrameException (e );
214- } finally {
215- b .position (mark );
216- }
217- }
218- } catch (InvalidDataException e ) {
219- reason = "" ;
220- }
221- }
196+ code = CloseFrame .NOCODE ;
197+ reason = "" ;
198+ payload .mark ();
199+ if ( payload .remaining () == 0 ) {
200+ code = CloseFrame .NORMAL ;
201+ } else if ( payload .remaining () == 1 ) {
202+ code = CloseFrame .PROTOCOL_ERROR ;
203+ } else {
204+ if ( payload .remaining () >= 2 ) {
205+ ByteBuffer bb = ByteBuffer .allocate ( 4 );
206+ bb .position ( 2 );
207+ bb .putShort ( payload .getShort () );
208+ bb .position ( 0 );
209+ code = bb .getInt ();
210+ }
211+ payload .reset ();
212+ try {
213+ int mark = payload .position ();// because stringUtf8 also creates a mark
214+ try {
215+ payload .position ( payload .position () + 2 );
216+ reason = Charsetfunctions .stringUtf8 ( payload );
217+ } catch ( IllegalArgumentException e ) {
218+ throw new InvalidDataException ( CloseFrame .NO_UTF8 );
219+ } finally {
220+ payload .position ( mark );
221+ }
222+ } catch ( InvalidDataException e ) {
223+ code = CloseFrame .NO_UTF8 ;
224+ reason = null ;
225+ }
226+ }
227+ }
222228
223229 /**
224230 * Update the payload to represent the close code and the reason
0 commit comments