ghedipunk / PHP-Websockets

A Websockets server written in PHP.
BSD 3-Clause "New" or "Revised" License
913 stars 376 forks source link

Handshake can fail #28

Closed Xaraknid closed 9 years ago

Xaraknid commented 9 years ago

I force the handshake request to be sent over multiple packet and if client did that It will fail.

websocket.php line 79

 if (!$user->handshake) {
$tmp = str_replace("\r", '', $buffer);
if (strpos($tmp, "\n\n") === false ) {
continue; // If the client has not finished sending the header, then wait before sending our upgrade response.
}
$this->doHandshake($user,$buffer);
} 

should be replace with

if (!$user->handshake) {
  if ($user->handlingPartialPacket) {
    $buffer=$user->partialBuffer . $buffer;
    $user->handlingPartialPacket=FALSE;
    $user->partialBuffer='';
  }
  //security buffer overflow if buffer exceed 512 bytes without "\n\n" close the connection
  if ( strlen($buffer)  > 512 ) {
    $handshakeResponse = "HTTP/1.1 400 Bad Request"; 
    socket_write($user->socket,$handshakeResponse,strlen($handshakeResponse));
    $this->disconnect($user->socket);
  }
  else {
    $tmp = str_replace("\r", '', $buffer);
    if (strpos($tmp, "\n\n") !== false ) {
      // If the client has finished sending the header, otherwise wait another call before sending our upgrade response.
      $this->doHandshake($user,$buffer);              
    }
    else {
      //store partial packet to be analysed in next call
      $user->partialBuffer=$buffer;
      $user->handlingPartialPacket=TRUE;
    }
  }
} 

I add a security to prevent too large handshake headers request. As a normal client request should be around 256 bytes.

Xaraknid commented 9 years ago

Please close this issue without merging it. That will be include in the revision I currently working on optimization code and turning it into non-blocking read/write socket.