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 #pragma once
18 
19 #include <cstdint>
20 #include <memory>
21 #include <optional>
22 #include <string>
23 #include <vector>
24 
25 struct ClientSocket;
26 struct HTTPServer;
27 struct RunLoop;
28 
29 struct ServerSocket : public std::enable_shared_from_this<ServerSocket> {
30     enum class TransportType {
31         TCP,
32         TLS,
33     };
34 
35     explicit ServerSocket(
36             HTTPServer *server,
37             TransportType transportType,
38             const char *iface,
39             uint16_t port,
40             const std::optional<std::string> &certificate_pem_path,
41             const std::optional<std::string> &private_key_pem_path);
42 
43     ~ServerSocket();
44 
45     ServerSocket(const ServerSocket &) = delete;
46     ServerSocket &operator=(const ServerSocket &) = delete;
47 
48     int initCheck() const;
49 
50     TransportType transportType() const;
51 
52     int run(std::shared_ptr<RunLoop> rl);
53 
54     void onClientSocketClosed(int sock);
55 
56     std::optional<std::string> certificate_pem_path() const;
57     std::optional<std::string> private_key_pem_path() const;
58 
59 private:
60     int mInitCheck;
61     HTTPServer *mServer;
62     std::optional<std::string> mCertificatePath, mPrivateKeyPath;
63     int mSocket;
64     TransportType mTransportType;
65 
66     std::shared_ptr<RunLoop> mRunLoop;
67     std::vector<std::shared_ptr<ClientSocket>> mClientSockets;
68 
69     void acceptIncomingConnection();
70 };
71 
72