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