blob: 059a11ca2c56cad12345f993cbad6a30cb8df24a [file] [log] [blame]
Lorenzo Colitti94a7b432016-03-24 16:47:12 +09001/*
2 * Copyright (C) 2016 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
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090017#include <functional>
18
19#include <linux/netlink.h>
20#include <linux/sock_diag.h>
21#include <linux/inet_diag.h>
22
23struct inet_diag_msg;
Lorenzo Colittif32fc592016-02-15 01:09:14 +090024class SockDiagTest;
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090025
26class SockDiag {
27
28 public:
29 static const int kBufferSize = 4096;
30 typedef std::function<int(uint8_t proto, const inet_diag_msg *)> DumpCallback;
31
32 struct DestroyRequest {
33 nlmsghdr nlh;
34 inet_diag_req_v2 req;
35 } __attribute__((__packed__));
36
Lorenzo Colittif32fc592016-02-15 01:09:14 +090037 SockDiag() : mSock(-1), mWriteSock(-1), mSocketsDestroyed(0) {}
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090038 bool open();
39 virtual ~SockDiag() { closeSocks(); }
40
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090041 int sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090042 int sendDumpRequest(uint8_t proto, uint8_t family, const char *addrstr);
43 int readDiagMsg(uint8_t proto, DumpCallback callback);
44 int sockDestroy(uint8_t proto, const inet_diag_msg *);
Lorenzo Colittif32fc592016-02-15 01:09:14 +090045 int destroySockets(const char *addrstr);
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090046 int destroySockets(uint8_t proto, uid_t uid);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090047
48 private:
49 int mSock;
50 int mWriteSock;
Lorenzo Colittif32fc592016-02-15 01:09:14 +090051 int mSocketsDestroyed;
Lorenzo Colitti94a7b432016-03-24 16:47:12 +090052 int sendDumpRequest(uint8_t proto, uint8_t family, uint32_t states, iovec *iov, int iovcnt);
Lorenzo Colittif32fc592016-02-15 01:09:14 +090053 int destroySockets(uint8_t proto, int family, const char *addrstr);
Lorenzo Colitti8464e1e2016-02-05 00:57:26 +090054 bool hasSocks() { return mSock != -1 && mWriteSock != -1; }
55 void closeSocks() { close(mSock); close(mWriteSock); mSock = mWriteSock = -1; }
56};