1 
2 // Copyright (C) 2021 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 #pragma once
16 
17 #include <memory>  // for shared_ptr
18 
19 #include "net/async_data_channel_server.h"  // for AsyncDataChannelServer
20 #include "net/posix/posix_async_socket.h"   // for AsyncManager, PosixAsyncS...
21 
22 namespace rootcanal {
23 class AsyncManager;
24 }  // namespace rootcanal
25 
26 using rootcanal::AsyncManager;
27 
28 namespace android {
29 namespace net {
30 
31 // An AsyncDataChannelServer that binds to all interfaces on the given port and
32 // listens for incoming socket connections.
33 //
34 // It uses the AsyncManager for watching the socket.
35 class PosixAsyncSocketServer : public AsyncDataChannelServer {
36  public:
37   // Binds to the given port on all interfaces.
38   // Note: do not use port 0!
39   PosixAsyncSocketServer(int port, AsyncManager* am);
40 
41   // Return the port that this server was initialized with.
port()42   int port() const { return port_; };
43 
44   bool StartListening() override;
45 
46   void StopListening() override;
47 
48   void Close() override;
49 
50   bool Connected() override;
51 
52  private:
53   void AcceptSocket();
54 
55   int port_;
56   std::shared_ptr<PosixAsyncSocket> server_socket_;
57   AsyncManager* am_;
58 };
59 
60 }  // namespace net
61 }  // namespace android
62