1 /*
2  * Copyright (C) 2019 The Android Open Source Project
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15  */
16 
17 #include <https/BufferedSocket.h>
18 
19 #include <https/WebSocketHandler.h>
20 
21 #include <arpa/inet.h>
22 #include <vector>
23 #include <memory>
24 
25 #include <https/PlainSocket.h>
26 #include <https/SSLSocket.h>
27 
28 struct HTTPServer;
29 struct RunLoop;
30 struct ServerSocket;
31 
32 struct ClientSocket : public std::enable_shared_from_this<ClientSocket> {
33     explicit ClientSocket(
34             std::shared_ptr<RunLoop> rl,
35             HTTPServer *server,
36             ServerSocket *parent,
37             const sockaddr_in &addr,
38             int sock);
39 
40     ClientSocket(const ClientSocket &) = delete;
41     ClientSocket &operator=(const ClientSocket &) = delete;
42 
43     void run();
44 
45     int fd() const;
46 
47     void queueResponse(const std::string &response, const std::string &body);
48     void setWebSocketHandler(std::shared_ptr<WebSocketHandler> handler);
49 
50     void queueOutputData(const uint8_t *data, size_t size);
51 
52     sockaddr_in remoteAddr() const;
53 
54 private:
55     std::shared_ptr<RunLoop> mRunLoop;
56     HTTPServer *mServer;
57     ServerSocket *mParent;
58     sockaddr_in mRemoteAddr;
59 
60     std::shared_ptr<BufferedSocket> mImplPlain;
61     std::shared_ptr<SSLSocket> mImplSSL;
62 
63     std::vector<uint8_t> mInBuffer;
64     size_t mInBufferLen;
65 
66     std::vector<uint8_t> mOutBuffer;
67     bool mSendPending;
68 
69     bool mDisconnecting;
70 
71     std::shared_ptr<WebSocketHandler> mWebSocketHandler;
72 
73     void handleIncomingData();
74 
75     // Returns true iff the client should close the connection.
76     bool handleRequest(bool isEOS);
77 
78     void sendOutputData();
79 
80     void disconnect();
81     void finishDisconnect();
82 
getImplClientSocket83     BufferedSocket *getImpl() const {
84         return mImplSSL ? mImplSSL.get() : mImplPlain.get();
85     }
86 };
87