1 // Copyright (c) 2011 The Chromium Authors. All rights reserved. 2 // Use of this source code is governed by a BSD-style license that can be 3 // found in the LICENSE file. 4 5 #ifndef NET_WEBSOCKETS_WEBSOCKET_FRAME_HANDLER_H_ 6 #define NET_WEBSOCKETS_WEBSOCKET_FRAME_HANDLER_H_ 7 #pragma once 8 9 #include <deque> 10 #include <vector> 11 12 #include "base/basictypes.h" 13 #include "base/memory/ref_counted.h" 14 15 namespace net { 16 17 class IOBuffer; 18 class IOBufferWithSize; 19 20 // Handles WebSocket frame messages. 21 class WebSocketFrameHandler { 22 public: 23 struct FrameInfo { 24 const char* frame_start; 25 int frame_length; 26 const char* message_start; 27 int message_length; 28 }; 29 30 WebSocketFrameHandler(); 31 ~WebSocketFrameHandler(); 32 33 // Appends WebSocket raw data on connection. 34 // For sending, this is data from WebKit. 35 // For receiving, this is data from network. 36 void AppendData(const char* data, int len); 37 38 // Updates current IOBuffer. 39 // If |buffered| is true, it tries to find WebSocket frames. 40 // Otherwise, it just picks the first buffer in |pending_buffers_|. 41 // Returns available size of data, 0 if no more data or current buffer was 42 // not released, and negative if some error occurred. 43 int UpdateCurrentBuffer(bool buffered); 44 45 // Gets current IOBuffer. 46 // For sending, this is data to network. 47 // For receiving, this is data to WebKit. 48 // Returns NULL just after ReleaseCurrentBuffer() was called. GetCurrentBuffer()49 IOBuffer* GetCurrentBuffer() { return current_buffer_.get(); } GetCurrentBufferSize()50 int GetCurrentBufferSize() const { return current_buffer_size_; } 51 52 // Returns original buffer size of current IOBuffer. 53 // This might differ from GetCurrentBufferSize() if frame message is 54 // compressed or decompressed. GetOriginalBufferSize()55 int GetOriginalBufferSize() const { return original_current_buffer_size_; } 56 57 // Releases current IOBuffer. 58 void ReleaseCurrentBuffer(); 59 60 // Parses WebSocket frame in [|buffer|, |buffer|+|size|), fills frame 61 // information in |frame_info|, and returns number of bytes for 62 // complete WebSocket frames. 63 static int ParseWebSocketFrame(const char* buffer, int size, 64 std::vector<FrameInfo>* frame_info); 65 66 private: 67 typedef std::deque< scoped_refptr<IOBufferWithSize> > PendingDataQueue; 68 69 scoped_refptr<IOBuffer> current_buffer_; 70 int current_buffer_size_; 71 72 int original_current_buffer_size_; 73 74 // Deque of IOBuffers in pending. 75 PendingDataQueue pending_buffers_; 76 77 DISALLOW_COPY_AND_ASSIGN(WebSocketFrameHandler); 78 }; 79 80 } // namespace net 81 82 #endif // NET_WEBSOCKETS_WEBSOCKET_FRAME_HANDLER_H_ 83