• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 // Copyright 2014 The Chromium Authors
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_SERVER_WEB_SOCKET_ENCODER_H_
6 #define NET_SERVER_WEB_SOCKET_ENCODER_H_
7 
8 #include <memory>
9 #include <string>
10 #include <string_view>
11 #include <vector>
12 
13 #include "net/base/net_export.h"
14 #include "net/server/web_socket.h"
15 #include "net/server/web_socket_parse_result.h"
16 #include "net/websockets/websocket_deflater.h"
17 #include "net/websockets/websocket_inflater.h"
18 
19 namespace net {
20 
21 class WebSocketDeflateParameters;
22 
23 class NET_EXPORT WebSocketEncoder final {
24  public:
25   static const char kClientExtensions[];
26 
27   WebSocketEncoder(const WebSocketEncoder&) = delete;
28   WebSocketEncoder& operator=(const WebSocketEncoder&) = delete;
29 
30   ~WebSocketEncoder();
31 
32   // Creates and returns an encoder for a server without extensions.
33   static std::unique_ptr<WebSocketEncoder> CreateServer();
34   // Creates and returns an encoder.
35   // |extensions| is the value of a Sec-WebSocket-Extensions header.
36   // Returns nullptr when there is an error.
37   static std::unique_ptr<WebSocketEncoder> CreateServer(
38       const std::string& extensions,
39       WebSocketDeflateParameters* params);
40   static std::unique_ptr<WebSocketEncoder> CreateClient(
41       const std::string& response_extensions);
42 
43   WebSocketParseResult DecodeFrame(std::string_view frame,
44                                    int* bytes_consumed,
45                                    std::string* output);
46   void EncodeTextFrame(std::string_view frame,
47                        int masking_key,
48                        std::string* output);
49   void EncodePongFrame(std::string_view frame,
50                        int masking_key,
51                        std::string* output);
52   void EncodeCloseFrame(std::string_view frame,
53                         int masking_key,
54                         std::string* output);
55 
deflate_enabled()56   bool deflate_enabled() const { return !!deflater_; }
57 
58  private:
59   enum Type {
60     FOR_SERVER,
61     FOR_CLIENT,
62   };
63 
64   WebSocketEncoder(Type type,
65                    std::unique_ptr<WebSocketDeflater> deflater,
66                    std::unique_ptr<WebSocketInflater> inflater);
67 
68   std::vector<std::string> continuation_message_frames_;
69   bool is_current_message_compressed_ = false;
70 
71   bool Inflate(std::string* message);
72   bool Deflate(std::string_view message, std::string* output);
73 
74   Type type_;
75   std::unique_ptr<WebSocketDeflater> deflater_;
76   std::unique_ptr<WebSocketInflater> inflater_;
77 };
78 
79 }  // namespace net
80 
81 #endif  // NET_SERVER_WEB_SOCKET_ENCODER_H_
82