1 /*
2  * Copyright (C) 2018 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 #ifndef TCP_SOCKET_MONITOR_H
18 #define TCP_SOCKET_MONITOR_H
19 
20 #include <chrono>
21 #include <condition_variable>
22 #include <mutex>
23 #include <thread>
24 #include <unordered_map>
25 
26 #include <android-base/thread_annotations.h>
27 #include "netdutils/DumpWriter.h"
28 #include "utils/String16.h"
29 
30 #include "Fwmark.h"
31 
32 struct inet_diag_msg;
33 struct tcp_info;
34 
35 namespace android {
36 namespace net {
37 
38 using std::chrono::milliseconds;
39 
40 class TcpSocketMonitor {
41   public:
42     using time_point = std::chrono::time_point<std::chrono::steady_clock>;
43 
44     static const String16 DUMP_KEYWORD;
45     static const milliseconds kDefaultPollingInterval;
46 
47     // A subset of fields found in struct inet_diag_msg and struct tcp_info.
48     struct TcpStats {
49         // Number of packets sent. Tracks struct tcp_sock data_segs_out.
50         // Not available on 3.18 kernels.
51         uint32_t sent;
52         // Number of packets lost. Tracks struct tcp_sock lost_out.
53         uint32_t lost;
54         // Smoothed round trip time. Tracks struct tcp_sock srtt_us.
55         uint32_t rttUs;
56         // Milliseconds difference between the last packet sent and last ack received.
57         int32_t sentAckDiffMs;
58         // Number of socket stats aggregated in this TcpStats entry.
59         int32_t nSockets;
60     };
61 
62     // Socket metadata used for computing TcpStats diff across sock_diag dumps.
63     struct SocketEntry {
64         // Number of packets sent. Tracks struct tcp_sock data_segs_out.
65         // Not available on 3.18 kernels.
66         uint32_t sent;
67         // Number of packets lost. Tracks struct tcp_sock lost_out.
68         uint32_t lost;
69         // Last update timestamp for that socket.
70         time_point lastUpdate;
71         // Socket mark.
72         Fwmark mark;
73         // The uid owning the socket.
74         uint32_t uid;
75     };
76 
77     TcpSocketMonitor();
78     ~TcpSocketMonitor();
79 
80     void dump(netdutils::DumpWriter& dw);
81     void setPollingInterval(milliseconds duration);
82     void resumePolling();
83     void suspendPolling();
84 
85   private:
86     void poll();
87     void waitForNextPoll();
88     bool isRunning();
89     void updateSocketStats(time_point now, Fwmark mark, const struct inet_diag_msg *sockinfo,
90                            const struct tcp_info *tcpinfo, uint32_t tcpinfoLen) REQUIRES(mLock);
91 
92     // Lock guarding all reads and writes to member variables.
93     std::mutex mLock;
94     // Used by the polling thread for sleeping between poll operations.
95     std::condition_variable mCv;
96     // The thread that polls sock_diag continuously.
97     std::thread mPollingThread;
98     // The duration of a sleep between polls. Can be updated by the instance owner for dynamically
99     // adjusting the polling rate.
100     milliseconds mNextSleepDurationMs GUARDED_BY(mLock);
101     // The time of the last successful poll operation.
102     time_point mLastPoll GUARDED_BY(mLock);
103     // True if the polling thread should sleep until notified.
104     bool mIsSuspended GUARDED_BY(mLock);
105     // True while the polling thread should poll.
106     bool mIsRunning GUARDED_BY(mLock);
107     // Map of SocketEntry structs keyed by socket cookie. This map tracks per-socket data needed for
108     // computing diffs between sock_diag dumps. Entries for closed sockets are continuously cleaned
109     // after every dump operation based on timestamps of last updates.
110     std::unordered_map<uint64_t, SocketEntry> mSocketEntries GUARDED_BY(mLock);
111     // Map of TcpStats entries aggregated per network and keyed per network id.
112     // This map tracks per-network data for a single sock_diag dump and is cleared before every dump
113     // operation.
114     std::unordered_map<uint32_t, TcpStats> mNetworkStats GUARDED_BY(mLock);
115 };
116 
117 }  // namespace net
118 }  // namespace android
119 
120 #endif /* TCP_SOCKET_MONITOR_H */
121