xref: /openbmc/linux/net/ipv4/inet_diag.c (revision b03afaa8)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * inet_diag.c	Module for monitoring INET transport protocols sockets.
4  *
5  * Authors:	Alexey Kuznetsov, <kuznet@ms2.inr.ac.ru>
6  */
7 
8 #include <linux/kernel.h>
9 #include <linux/module.h>
10 #include <linux/types.h>
11 #include <linux/fcntl.h>
12 #include <linux/random.h>
13 #include <linux/slab.h>
14 #include <linux/cache.h>
15 #include <linux/init.h>
16 #include <linux/time.h>
17 
18 #include <net/icmp.h>
19 #include <net/tcp.h>
20 #include <net/ipv6.h>
21 #include <net/inet_common.h>
22 #include <net/inet_connection_sock.h>
23 #include <net/inet_hashtables.h>
24 #include <net/inet_timewait_sock.h>
25 #include <net/inet6_hashtables.h>
26 #include <net/bpf_sk_storage.h>
27 #include <net/netlink.h>
28 
29 #include <linux/inet.h>
30 #include <linux/stddef.h>
31 
32 #include <linux/inet_diag.h>
33 #include <linux/sock_diag.h>
34 
35 static const struct inet_diag_handler **inet_diag_table;
36 
37 struct inet_diag_entry {
38 	const __be32 *saddr;
39 	const __be32 *daddr;
40 	u16 sport;
41 	u16 dport;
42 	u16 family;
43 	u16 userlocks;
44 	u32 ifindex;
45 	u32 mark;
46 #ifdef CONFIG_SOCK_CGROUP_DATA
47 	u64 cgroup_id;
48 #endif
49 };
50 
51 static DEFINE_MUTEX(inet_diag_table_mutex);
52 
53 static const struct inet_diag_handler *inet_diag_lock_handler(int proto)
54 {
55 	if (proto < 0 || proto >= IPPROTO_MAX) {
56 		mutex_lock(&inet_diag_table_mutex);
57 		return ERR_PTR(-ENOENT);
58 	}
59 
60 	if (!inet_diag_table[proto])
61 		sock_load_diag_module(AF_INET, proto);
62 
63 	mutex_lock(&inet_diag_table_mutex);
64 	if (!inet_diag_table[proto])
65 		return ERR_PTR(-ENOENT);
66 
67 	return inet_diag_table[proto];
68 }
69 
70 static void inet_diag_unlock_handler(const struct inet_diag_handler *handler)
71 {
72 	mutex_unlock(&inet_diag_table_mutex);
73 }
74 
75 void inet_diag_msg_common_fill(struct inet_diag_msg *r, struct sock *sk)
76 {
77 	r->idiag_family = sk->sk_family;
78 
79 	r->id.idiag_sport = htons(sk->sk_num);
80 	r->id.idiag_dport = sk->sk_dport;
81 	r->id.idiag_if = sk->sk_bound_dev_if;
82 	sock_diag_save_cookie(sk, r->id.idiag_cookie);
83 
84 #if IS_ENABLED(CONFIG_IPV6)
85 	if (sk->sk_family == AF_INET6) {
86 		*(struct in6_addr *)r->id.idiag_src = sk->sk_v6_rcv_saddr;
87 		*(struct in6_addr *)r->id.idiag_dst = sk->sk_v6_daddr;
88 	} else
89 #endif
90 	{
91 	memset(&r->id.idiag_src, 0, sizeof(r->id.idiag_src));
92 	memset(&r->id.idiag_dst, 0, sizeof(r->id.idiag_dst));
93 
94 	r->id.idiag_src[0] = sk->sk_rcv_saddr;
95 	r->id.idiag_dst[0] = sk->sk_daddr;
96 	}
97 }
98 EXPORT_SYMBOL_GPL(inet_diag_msg_common_fill);
99 
100 static size_t inet_sk_attr_size(struct sock *sk,
101 				const struct inet_diag_req_v2 *req,
102 				bool net_admin)
103 {
104 	const struct inet_diag_handler *handler;
105 	size_t aux = 0;
106 
107 	handler = inet_diag_table[req->sdiag_protocol];
108 	if (handler && handler->idiag_get_aux_size)
109 		aux = handler->idiag_get_aux_size(sk, net_admin);
110 
111 	return	  nla_total_size(sizeof(struct tcp_info))
112 		+ nla_total_size(sizeof(struct inet_diag_msg))
113 		+ inet_diag_msg_attrs_size()
114 		+ nla_total_size(sizeof(struct inet_diag_meminfo))
115 		+ nla_total_size(SK_MEMINFO_VARS * sizeof(u32))
116 		+ nla_total_size(TCP_CA_NAME_MAX)
117 		+ nla_total_size(sizeof(struct tcpvegas_info))
118 		+ aux
119 		+ 64;
120 }
121 
122 int inet_diag_msg_attrs_fill(struct sock *sk, struct sk_buff *skb,
123 			     struct inet_diag_msg *r, int ext,
124 			     struct user_namespace *user_ns,
125 			     bool net_admin)
126 {
127 	const struct inet_sock *inet = inet_sk(sk);
128 
129 	if (nla_put_u8(skb, INET_DIAG_SHUTDOWN, sk->sk_shutdown))
130 		goto errout;
131 
132 	/* IPv6 dual-stack sockets use inet->tos for IPv4 connections,
133 	 * hence this needs to be included regardless of socket family.
134 	 */
135 	if (ext & (1 << (INET_DIAG_TOS - 1)))
136 		if (nla_put_u8(skb, INET_DIAG_TOS, inet->tos) < 0)
137 			goto errout;
138 
139 #if IS_ENABLED(CONFIG_IPV6)
140 	if (r->idiag_family == AF_INET6) {
141 		if (ext & (1 << (INET_DIAG_TCLASS - 1)))
142 			if (nla_put_u8(skb, INET_DIAG_TCLASS,
143 				       inet6_sk(sk)->tclass) < 0)
144 				goto errout;
145 
146 		if (((1 << sk->sk_state) & (TCPF_LISTEN | TCPF_CLOSE)) &&
147 		    nla_put_u8(skb, INET_DIAG_SKV6ONLY, ipv6_only_sock(sk)))
148 			goto errout;
149 	}
150 #endif
151 
152 	if (net_admin && nla_put_u32(skb, INET_DIAG_MARK, sk->sk_mark))
153 		goto errout;
154 
155 	if (ext & (1 << (INET_DIAG_CLASS_ID - 1)) ||
156 	    ext & (1 << (INET_DIAG_TCLASS - 1))) {
157 		u32 classid = 0;
158 
159 #ifdef CONFIG_SOCK_CGROUP_DATA
160 		classid = sock_cgroup_classid(&sk->sk_cgrp_data);
161 #endif
162 		/* Fallback to socket priority if class id isn't set.
163 		 * Classful qdiscs use it as direct reference to class.
164 		 * For cgroup2 classid is always zero.
165 		 */
166 		if (!classid)
167 			classid = sk->sk_priority;
168 
169 		if (nla_put_u32(skb, INET_DIAG_CLASS_ID, classid))
170 			goto errout;
171 	}
172 
173 #ifdef CONFIG_SOCK_CGROUP_DATA
174 	if (nla_put_u64_64bit(skb, INET_DIAG_CGROUP_ID,
175 			      cgroup_id(sock_cgroup_ptr(&sk->sk_cgrp_data)),
176 			      INET_DIAG_PAD))
177 		goto errout;
178 #endif
179 
180 	r->idiag_uid = from_kuid_munged(user_ns, sock_i_uid(sk));
181 	r->idiag_inode = sock_i_ino(sk);
182 
183 	return 0;
184 errout:
185 	return 1;
186 }
187 EXPORT_SYMBOL_GPL(inet_diag_msg_attrs_fill);
188 
189 static void inet_diag_parse_attrs(const struct nlmsghdr *nlh, int hdrlen,
190 				  struct nlattr **req_nlas)
191 {
192 	struct nlattr *nla;
193 	int remaining;
194 
195 	nlmsg_for_each_attr(nla, nlh, hdrlen, remaining) {
196 		int type = nla_type(nla);
197 
198 		if (type < __INET_DIAG_REQ_MAX)
199 			req_nlas[type] = nla;
200 	}
201 }
202 
203 static int inet_diag_get_protocol(const struct inet_diag_req_v2 *req,
204 				  const struct inet_diag_dump_data *data)
205 {
206 	if (data->req_nlas[INET_DIAG_REQ_PROTOCOL])
207 		return nla_get_u32(data->req_nlas[INET_DIAG_REQ_PROTOCOL]);
208 	return req->sdiag_protocol;
209 }
210 
211 #define MAX_DUMP_ALLOC_SIZE (KMALLOC_MAX_SIZE - SKB_DATA_ALIGN(sizeof(struct skb_shared_info)))
212 
213 int inet_sk_diag_fill(struct sock *sk, struct inet_connection_sock *icsk,
214 		      struct sk_buff *skb, struct netlink_callback *cb,
215 		      const struct inet_diag_req_v2 *req,
216 		      u16 nlmsg_flags, bool net_admin)
217 {
218 	const struct tcp_congestion_ops *ca_ops;
219 	const struct inet_diag_handler *handler;
220 	struct inet_diag_dump_data *cb_data;
221 	int ext = req->idiag_ext;
222 	struct inet_diag_msg *r;
223 	struct nlmsghdr  *nlh;
224 	struct nlattr *attr;
225 	void *info = NULL;
226 
227 	cb_data = cb->data;
228 	handler = inet_diag_table[inet_diag_get_protocol(req, cb_data)];
229 	BUG_ON(!handler);
230 
231 	nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
232 			cb->nlh->nlmsg_type, sizeof(*r), nlmsg_flags);
233 	if (!nlh)
234 		return -EMSGSIZE;
235 
236 	r = nlmsg_data(nlh);
237 	BUG_ON(!sk_fullsock(sk));
238 
239 	inet_diag_msg_common_fill(r, sk);
240 	r->idiag_state = sk->sk_state;
241 	r->idiag_timer = 0;
242 	r->idiag_retrans = 0;
243 
244 	if (inet_diag_msg_attrs_fill(sk, skb, r, ext,
245 				     sk_user_ns(NETLINK_CB(cb->skb).sk),
246 				     net_admin))
247 		goto errout;
248 
249 	if (ext & (1 << (INET_DIAG_MEMINFO - 1))) {
250 		struct inet_diag_meminfo minfo = {
251 			.idiag_rmem = sk_rmem_alloc_get(sk),
252 			.idiag_wmem = READ_ONCE(sk->sk_wmem_queued),
253 			.idiag_fmem = sk->sk_forward_alloc,
254 			.idiag_tmem = sk_wmem_alloc_get(sk),
255 		};
256 
257 		if (nla_put(skb, INET_DIAG_MEMINFO, sizeof(minfo), &minfo) < 0)
258 			goto errout;
259 	}
260 
261 	if (ext & (1 << (INET_DIAG_SKMEMINFO - 1)))
262 		if (sock_diag_put_meminfo(sk, skb, INET_DIAG_SKMEMINFO))
263 			goto errout;
264 
265 	/*
266 	 * RAW sockets might have user-defined protocols assigned,
267 	 * so report the one supplied on socket creation.
268 	 */
269 	if (sk->sk_type == SOCK_RAW) {
270 		if (nla_put_u8(skb, INET_DIAG_PROTOCOL, sk->sk_protocol))
271 			goto errout;
272 	}
273 
274 	if (!icsk) {
275 		handler->idiag_get_info(sk, r, NULL);
276 		goto out;
277 	}
278 
279 	if (icsk->icsk_pending == ICSK_TIME_RETRANS ||
280 	    icsk->icsk_pending == ICSK_TIME_REO_TIMEOUT ||
281 	    icsk->icsk_pending == ICSK_TIME_LOSS_PROBE) {
282 		r->idiag_timer = 1;
283 		r->idiag_retrans = icsk->icsk_retransmits;
284 		r->idiag_expires =
285 			jiffies_delta_to_msecs(icsk->icsk_timeout - jiffies);
286 	} else if (icsk->icsk_pending == ICSK_TIME_PROBE0) {
287 		r->idiag_timer = 4;
288 		r->idiag_retrans = icsk->icsk_probes_out;
289 		r->idiag_expires =
290 			jiffies_delta_to_msecs(icsk->icsk_timeout - jiffies);
291 	} else if (timer_pending(&sk->sk_timer)) {
292 		r->idiag_timer = 2;
293 		r->idiag_retrans = icsk->icsk_probes_out;
294 		r->idiag_expires =
295 			jiffies_delta_to_msecs(sk->sk_timer.expires - jiffies);
296 	} else {
297 		r->idiag_timer = 0;
298 		r->idiag_expires = 0;
299 	}
300 
301 	if ((ext & (1 << (INET_DIAG_INFO - 1))) && handler->idiag_info_size) {
302 		attr = nla_reserve_64bit(skb, INET_DIAG_INFO,
303 					 handler->idiag_info_size,
304 					 INET_DIAG_PAD);
305 		if (!attr)
306 			goto errout;
307 
308 		info = nla_data(attr);
309 	}
310 
311 	if (ext & (1 << (INET_DIAG_CONG - 1))) {
312 		int err = 0;
313 
314 		rcu_read_lock();
315 		ca_ops = READ_ONCE(icsk->icsk_ca_ops);
316 		if (ca_ops)
317 			err = nla_put_string(skb, INET_DIAG_CONG, ca_ops->name);
318 		rcu_read_unlock();
319 		if (err < 0)
320 			goto errout;
321 	}
322 
323 	handler->idiag_get_info(sk, r, info);
324 
325 	if (ext & (1 << (INET_DIAG_INFO - 1)) && handler->idiag_get_aux)
326 		if (handler->idiag_get_aux(sk, net_admin, skb) < 0)
327 			goto errout;
328 
329 	if (sk->sk_state < TCP_TIME_WAIT) {
330 		union tcp_cc_info info;
331 		size_t sz = 0;
332 		int attr;
333 
334 		rcu_read_lock();
335 		ca_ops = READ_ONCE(icsk->icsk_ca_ops);
336 		if (ca_ops && ca_ops->get_info)
337 			sz = ca_ops->get_info(sk, ext, &attr, &info);
338 		rcu_read_unlock();
339 		if (sz && nla_put(skb, attr, sz, &info) < 0)
340 			goto errout;
341 	}
342 
343 	/* Keep it at the end for potential retry with a larger skb,
344 	 * or else do best-effort fitting, which is only done for the
345 	 * first_nlmsg.
346 	 */
347 	if (cb_data->bpf_stg_diag) {
348 		bool first_nlmsg = ((unsigned char *)nlh == skb->data);
349 		unsigned int prev_min_dump_alloc;
350 		unsigned int total_nla_size = 0;
351 		unsigned int msg_len;
352 		int err;
353 
354 		msg_len = skb_tail_pointer(skb) - (unsigned char *)nlh;
355 		err = bpf_sk_storage_diag_put(cb_data->bpf_stg_diag, sk, skb,
356 					      INET_DIAG_SK_BPF_STORAGES,
357 					      &total_nla_size);
358 
359 		if (!err)
360 			goto out;
361 
362 		total_nla_size += msg_len;
363 		prev_min_dump_alloc = cb->min_dump_alloc;
364 		if (total_nla_size > prev_min_dump_alloc)
365 			cb->min_dump_alloc = min_t(u32, total_nla_size,
366 						   MAX_DUMP_ALLOC_SIZE);
367 
368 		if (!first_nlmsg)
369 			goto errout;
370 
371 		if (cb->min_dump_alloc > prev_min_dump_alloc)
372 			/* Retry with pskb_expand_head() with
373 			 * __GFP_DIRECT_RECLAIM
374 			 */
375 			goto errout;
376 
377 		WARN_ON_ONCE(total_nla_size <= prev_min_dump_alloc);
378 
379 		/* Send what we have for this sk
380 		 * and move on to the next sk in the following
381 		 * dump()
382 		 */
383 	}
384 
385 out:
386 	nlmsg_end(skb, nlh);
387 	return 0;
388 
389 errout:
390 	nlmsg_cancel(skb, nlh);
391 	return -EMSGSIZE;
392 }
393 EXPORT_SYMBOL_GPL(inet_sk_diag_fill);
394 
395 static int inet_twsk_diag_fill(struct sock *sk,
396 			       struct sk_buff *skb,
397 			       struct netlink_callback *cb,
398 			       u16 nlmsg_flags)
399 {
400 	struct inet_timewait_sock *tw = inet_twsk(sk);
401 	struct inet_diag_msg *r;
402 	struct nlmsghdr *nlh;
403 	long tmo;
404 
405 	nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid,
406 			cb->nlh->nlmsg_seq, cb->nlh->nlmsg_type,
407 			sizeof(*r), nlmsg_flags);
408 	if (!nlh)
409 		return -EMSGSIZE;
410 
411 	r = nlmsg_data(nlh);
412 	BUG_ON(tw->tw_state != TCP_TIME_WAIT);
413 
414 	inet_diag_msg_common_fill(r, sk);
415 	r->idiag_retrans      = 0;
416 
417 	r->idiag_state	      = tw->tw_substate;
418 	r->idiag_timer	      = 3;
419 	tmo = tw->tw_timer.expires - jiffies;
420 	r->idiag_expires      = jiffies_delta_to_msecs(tmo);
421 	r->idiag_rqueue	      = 0;
422 	r->idiag_wqueue	      = 0;
423 	r->idiag_uid	      = 0;
424 	r->idiag_inode	      = 0;
425 
426 	nlmsg_end(skb, nlh);
427 	return 0;
428 }
429 
430 static int inet_req_diag_fill(struct sock *sk, struct sk_buff *skb,
431 			      struct netlink_callback *cb,
432 			      u16 nlmsg_flags, bool net_admin)
433 {
434 	struct request_sock *reqsk = inet_reqsk(sk);
435 	struct inet_diag_msg *r;
436 	struct nlmsghdr *nlh;
437 	long tmo;
438 
439 	nlh = nlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
440 			cb->nlh->nlmsg_type, sizeof(*r), nlmsg_flags);
441 	if (!nlh)
442 		return -EMSGSIZE;
443 
444 	r = nlmsg_data(nlh);
445 	inet_diag_msg_common_fill(r, sk);
446 	r->idiag_state = TCP_SYN_RECV;
447 	r->idiag_timer = 1;
448 	r->idiag_retrans = reqsk->num_retrans;
449 
450 	BUILD_BUG_ON(offsetof(struct inet_request_sock, ir_cookie) !=
451 		     offsetof(struct sock, sk_cookie));
452 
453 	tmo = inet_reqsk(sk)->rsk_timer.expires - jiffies;
454 	r->idiag_expires = jiffies_delta_to_msecs(tmo);
455 	r->idiag_rqueue	= 0;
456 	r->idiag_wqueue	= 0;
457 	r->idiag_uid	= 0;
458 	r->idiag_inode	= 0;
459 
460 	if (net_admin && nla_put_u32(skb, INET_DIAG_MARK,
461 				     inet_rsk(reqsk)->ir_mark))
462 		return -EMSGSIZE;
463 
464 	nlmsg_end(skb, nlh);
465 	return 0;
466 }
467 
468 static int sk_diag_fill(struct sock *sk, struct sk_buff *skb,
469 			struct netlink_callback *cb,
470 			const struct inet_diag_req_v2 *r,
471 			u16 nlmsg_flags, bool net_admin)
472 {
473 	if (sk->sk_state == TCP_TIME_WAIT)
474 		return inet_twsk_diag_fill(sk, skb, cb, nlmsg_flags);
475 
476 	if (sk->sk_state == TCP_NEW_SYN_RECV)
477 		return inet_req_diag_fill(sk, skb, cb, nlmsg_flags, net_admin);
478 
479 	return inet_sk_diag_fill(sk, inet_csk(sk), skb, cb, r, nlmsg_flags,
480 				 net_admin);
481 }
482 
483 struct sock *inet_diag_find_one_icsk(struct net *net,
484 				     struct inet_hashinfo *hashinfo,
485 				     const struct inet_diag_req_v2 *req)
486 {
487 	struct sock *sk;
488 
489 	rcu_read_lock();
490 	if (req->sdiag_family == AF_INET)
491 		sk = inet_lookup(net, hashinfo, NULL, 0, req->id.idiag_dst[0],
492 				 req->id.idiag_dport, req->id.idiag_src[0],
493 				 req->id.idiag_sport, req->id.idiag_if);
494 #if IS_ENABLED(CONFIG_IPV6)
495 	else if (req->sdiag_family == AF_INET6) {
496 		if (ipv6_addr_v4mapped((struct in6_addr *)req->id.idiag_dst) &&
497 		    ipv6_addr_v4mapped((struct in6_addr *)req->id.idiag_src))
498 			sk = inet_lookup(net, hashinfo, NULL, 0, req->id.idiag_dst[3],
499 					 req->id.idiag_dport, req->id.idiag_src[3],
500 					 req->id.idiag_sport, req->id.idiag_if);
501 		else
502 			sk = inet6_lookup(net, hashinfo, NULL, 0,
503 					  (struct in6_addr *)req->id.idiag_dst,
504 					  req->id.idiag_dport,
505 					  (struct in6_addr *)req->id.idiag_src,
506 					  req->id.idiag_sport,
507 					  req->id.idiag_if);
508 	}
509 #endif
510 	else {
511 		rcu_read_unlock();
512 		return ERR_PTR(-EINVAL);
513 	}
514 	rcu_read_unlock();
515 	if (!sk)
516 		return ERR_PTR(-ENOENT);
517 
518 	if (sock_diag_check_cookie(sk, req->id.idiag_cookie)) {
519 		sock_gen_put(sk);
520 		return ERR_PTR(-ENOENT);
521 	}
522 
523 	return sk;
524 }
525 EXPORT_SYMBOL_GPL(inet_diag_find_one_icsk);
526 
527 int inet_diag_dump_one_icsk(struct inet_hashinfo *hashinfo,
528 			    struct netlink_callback *cb,
529 			    const struct inet_diag_req_v2 *req)
530 {
531 	struct sk_buff *in_skb = cb->skb;
532 	bool net_admin = netlink_net_capable(in_skb, CAP_NET_ADMIN);
533 	struct net *net = sock_net(in_skb->sk);
534 	struct sk_buff *rep;
535 	struct sock *sk;
536 	int err;
537 
538 	sk = inet_diag_find_one_icsk(net, hashinfo, req);
539 	if (IS_ERR(sk))
540 		return PTR_ERR(sk);
541 
542 	rep = nlmsg_new(inet_sk_attr_size(sk, req, net_admin), GFP_KERNEL);
543 	if (!rep) {
544 		err = -ENOMEM;
545 		goto out;
546 	}
547 
548 	err = sk_diag_fill(sk, rep, cb, req, 0, net_admin);
549 	if (err < 0) {
550 		WARN_ON(err == -EMSGSIZE);
551 		nlmsg_free(rep);
552 		goto out;
553 	}
554 	err = netlink_unicast(net->diag_nlsk, rep, NETLINK_CB(in_skb).portid,
555 			      MSG_DONTWAIT);
556 	if (err > 0)
557 		err = 0;
558 
559 out:
560 	if (sk)
561 		sock_gen_put(sk);
562 
563 	return err;
564 }
565 EXPORT_SYMBOL_GPL(inet_diag_dump_one_icsk);
566 
567 static int inet_diag_cmd_exact(int cmd, struct sk_buff *in_skb,
568 			       const struct nlmsghdr *nlh,
569 			       int hdrlen,
570 			       const struct inet_diag_req_v2 *req)
571 {
572 	const struct inet_diag_handler *handler;
573 	struct inet_diag_dump_data dump_data;
574 	int err, protocol;
575 
576 	memset(&dump_data, 0, sizeof(dump_data));
577 	inet_diag_parse_attrs(nlh, hdrlen, dump_data.req_nlas);
578 	protocol = inet_diag_get_protocol(req, &dump_data);
579 
580 	handler = inet_diag_lock_handler(protocol);
581 	if (IS_ERR(handler)) {
582 		err = PTR_ERR(handler);
583 	} else if (cmd == SOCK_DIAG_BY_FAMILY) {
584 		struct netlink_callback cb = {
585 			.nlh = nlh,
586 			.skb = in_skb,
587 			.data = &dump_data,
588 		};
589 		err = handler->dump_one(&cb, req);
590 	} else if (cmd == SOCK_DESTROY && handler->destroy) {
591 		err = handler->destroy(in_skb, req);
592 	} else {
593 		err = -EOPNOTSUPP;
594 	}
595 	inet_diag_unlock_handler(handler);
596 
597 	return err;
598 }
599 
600 static int bitstring_match(const __be32 *a1, const __be32 *a2, int bits)
601 {
602 	int words = bits >> 5;
603 
604 	bits &= 0x1f;
605 
606 	if (words) {
607 		if (memcmp(a1, a2, words << 2))
608 			return 0;
609 	}
610 	if (bits) {
611 		__be32 w1, w2;
612 		__be32 mask;
613 
614 		w1 = a1[words];
615 		w2 = a2[words];
616 
617 		mask = htonl((0xffffffff) << (32 - bits));
618 
619 		if ((w1 ^ w2) & mask)
620 			return 0;
621 	}
622 
623 	return 1;
624 }
625 
626 static int inet_diag_bc_run(const struct nlattr *_bc,
627 			    const struct inet_diag_entry *entry)
628 {
629 	const void *bc = nla_data(_bc);
630 	int len = nla_len(_bc);
631 
632 	while (len > 0) {
633 		int yes = 1;
634 		const struct inet_diag_bc_op *op = bc;
635 
636 		switch (op->code) {
637 		case INET_DIAG_BC_NOP:
638 			break;
639 		case INET_DIAG_BC_JMP:
640 			yes = 0;
641 			break;
642 		case INET_DIAG_BC_S_EQ:
643 			yes = entry->sport == op[1].no;
644 			break;
645 		case INET_DIAG_BC_S_GE:
646 			yes = entry->sport >= op[1].no;
647 			break;
648 		case INET_DIAG_BC_S_LE:
649 			yes = entry->sport <= op[1].no;
650 			break;
651 		case INET_DIAG_BC_D_EQ:
652 			yes = entry->dport == op[1].no;
653 			break;
654 		case INET_DIAG_BC_D_GE:
655 			yes = entry->dport >= op[1].no;
656 			break;
657 		case INET_DIAG_BC_D_LE:
658 			yes = entry->dport <= op[1].no;
659 			break;
660 		case INET_DIAG_BC_AUTO:
661 			yes = !(entry->userlocks & SOCK_BINDPORT_LOCK);
662 			break;
663 		case INET_DIAG_BC_S_COND:
664 		case INET_DIAG_BC_D_COND: {
665 			const struct inet_diag_hostcond *cond;
666 			const __be32 *addr;
667 
668 			cond = (const struct inet_diag_hostcond *)(op + 1);
669 			if (cond->port != -1 &&
670 			    cond->port != (op->code == INET_DIAG_BC_S_COND ?
671 					     entry->sport : entry->dport)) {
672 				yes = 0;
673 				break;
674 			}
675 
676 			if (op->code == INET_DIAG_BC_S_COND)
677 				addr = entry->saddr;
678 			else
679 				addr = entry->daddr;
680 
681 			if (cond->family != AF_UNSPEC &&
682 			    cond->family != entry->family) {
683 				if (entry->family == AF_INET6 &&
684 				    cond->family == AF_INET) {
685 					if (addr[0] == 0 && addr[1] == 0 &&
686 					    addr[2] == htonl(0xffff) &&
687 					    bitstring_match(addr + 3,
688 							    cond->addr,
689 							    cond->prefix_len))
690 						break;
691 				}
692 				yes = 0;
693 				break;
694 			}
695 
696 			if (cond->prefix_len == 0)
697 				break;
698 			if (bitstring_match(addr, cond->addr,
699 					    cond->prefix_len))
700 				break;
701 			yes = 0;
702 			break;
703 		}
704 		case INET_DIAG_BC_DEV_COND: {
705 			u32 ifindex;
706 
707 			ifindex = *((const u32 *)(op + 1));
708 			if (ifindex != entry->ifindex)
709 				yes = 0;
710 			break;
711 		}
712 		case INET_DIAG_BC_MARK_COND: {
713 			struct inet_diag_markcond *cond;
714 
715 			cond = (struct inet_diag_markcond *)(op + 1);
716 			if ((entry->mark & cond->mask) != cond->mark)
717 				yes = 0;
718 			break;
719 		}
720 #ifdef CONFIG_SOCK_CGROUP_DATA
721 		case INET_DIAG_BC_CGROUP_COND: {
722 			u64 cgroup_id;
723 
724 			cgroup_id = get_unaligned((const u64 *)(op + 1));
725 			if (cgroup_id != entry->cgroup_id)
726 				yes = 0;
727 			break;
728 		}
729 #endif
730 		}
731 
732 		if (yes) {
733 			len -= op->yes;
734 			bc += op->yes;
735 		} else {
736 			len -= op->no;
737 			bc += op->no;
738 		}
739 	}
740 	return len == 0;
741 }
742 
743 /* This helper is available for all sockets (ESTABLISH, TIMEWAIT, SYN_RECV)
744  */
745 static void entry_fill_addrs(struct inet_diag_entry *entry,
746 			     const struct sock *sk)
747 {
748 #if IS_ENABLED(CONFIG_IPV6)
749 	if (sk->sk_family == AF_INET6) {
750 		entry->saddr = sk->sk_v6_rcv_saddr.s6_addr32;
751 		entry->daddr = sk->sk_v6_daddr.s6_addr32;
752 	} else
753 #endif
754 	{
755 		entry->saddr = &sk->sk_rcv_saddr;
756 		entry->daddr = &sk->sk_daddr;
757 	}
758 }
759 
760 int inet_diag_bc_sk(const struct nlattr *bc, struct sock *sk)
761 {
762 	struct inet_sock *inet = inet_sk(sk);
763 	struct inet_diag_entry entry;
764 
765 	if (!bc)
766 		return 1;
767 
768 	entry.family = sk->sk_family;
769 	entry_fill_addrs(&entry, sk);
770 	entry.sport = inet->inet_num;
771 	entry.dport = ntohs(inet->inet_dport);
772 	entry.ifindex = sk->sk_bound_dev_if;
773 	entry.userlocks = sk_fullsock(sk) ? sk->sk_userlocks : 0;
774 	if (sk_fullsock(sk))
775 		entry.mark = sk->sk_mark;
776 	else if (sk->sk_state == TCP_NEW_SYN_RECV)
777 		entry.mark = inet_rsk(inet_reqsk(sk))->ir_mark;
778 	else
779 		entry.mark = 0;
780 #ifdef CONFIG_SOCK_CGROUP_DATA
781 	entry.cgroup_id = sk_fullsock(sk) ?
782 		cgroup_id(sock_cgroup_ptr(&sk->sk_cgrp_data)) : 0;
783 #endif
784 
785 	return inet_diag_bc_run(bc, &entry);
786 }
787 EXPORT_SYMBOL_GPL(inet_diag_bc_sk);
788 
789 static int valid_cc(const void *bc, int len, int cc)
790 {
791 	while (len >= 0) {
792 		const struct inet_diag_bc_op *op = bc;
793 
794 		if (cc > len)
795 			return 0;
796 		if (cc == len)
797 			return 1;
798 		if (op->yes < 4 || op->yes & 3)
799 			return 0;
800 		len -= op->yes;
801 		bc  += op->yes;
802 	}
803 	return 0;
804 }
805 
806 /* data is u32 ifindex */
807 static bool valid_devcond(const struct inet_diag_bc_op *op, int len,
808 			  int *min_len)
809 {
810 	/* Check ifindex space. */
811 	*min_len += sizeof(u32);
812 	if (len < *min_len)
813 		return false;
814 
815 	return true;
816 }
817 /* Validate an inet_diag_hostcond. */
818 static bool valid_hostcond(const struct inet_diag_bc_op *op, int len,
819 			   int *min_len)
820 {
821 	struct inet_diag_hostcond *cond;
822 	int addr_len;
823 
824 	/* Check hostcond space. */
825 	*min_len += sizeof(struct inet_diag_hostcond);
826 	if (len < *min_len)
827 		return false;
828 	cond = (struct inet_diag_hostcond *)(op + 1);
829 
830 	/* Check address family and address length. */
831 	switch (cond->family) {
832 	case AF_UNSPEC:
833 		addr_len = 0;
834 		break;
835 	case AF_INET:
836 		addr_len = sizeof(struct in_addr);
837 		break;
838 	case AF_INET6:
839 		addr_len = sizeof(struct in6_addr);
840 		break;
841 	default:
842 		return false;
843 	}
844 	*min_len += addr_len;
845 	if (len < *min_len)
846 		return false;
847 
848 	/* Check prefix length (in bits) vs address length (in bytes). */
849 	if (cond->prefix_len > 8 * addr_len)
850 		return false;
851 
852 	return true;
853 }
854 
855 /* Validate a port comparison operator. */
856 static bool valid_port_comparison(const struct inet_diag_bc_op *op,
857 				  int len, int *min_len)
858 {
859 	/* Port comparisons put the port in a follow-on inet_diag_bc_op. */
860 	*min_len += sizeof(struct inet_diag_bc_op);
861 	if (len < *min_len)
862 		return false;
863 	return true;
864 }
865 
866 static bool valid_markcond(const struct inet_diag_bc_op *op, int len,
867 			   int *min_len)
868 {
869 	*min_len += sizeof(struct inet_diag_markcond);
870 	return len >= *min_len;
871 }
872 
873 #ifdef CONFIG_SOCK_CGROUP_DATA
874 static bool valid_cgroupcond(const struct inet_diag_bc_op *op, int len,
875 			     int *min_len)
876 {
877 	*min_len += sizeof(u64);
878 	return len >= *min_len;
879 }
880 #endif
881 
882 static int inet_diag_bc_audit(const struct nlattr *attr,
883 			      const struct sk_buff *skb)
884 {
885 	bool net_admin = netlink_net_capable(skb, CAP_NET_ADMIN);
886 	const void *bytecode, *bc;
887 	int bytecode_len, len;
888 
889 	if (!attr || nla_len(attr) < sizeof(struct inet_diag_bc_op))
890 		return -EINVAL;
891 
892 	bytecode = bc = nla_data(attr);
893 	len = bytecode_len = nla_len(attr);
894 
895 	while (len > 0) {
896 		int min_len = sizeof(struct inet_diag_bc_op);
897 		const struct inet_diag_bc_op *op = bc;
898 
899 		switch (op->code) {
900 		case INET_DIAG_BC_S_COND:
901 		case INET_DIAG_BC_D_COND:
902 			if (!valid_hostcond(bc, len, &min_len))
903 				return -EINVAL;
904 			break;
905 		case INET_DIAG_BC_DEV_COND:
906 			if (!valid_devcond(bc, len, &min_len))
907 				return -EINVAL;
908 			break;
909 		case INET_DIAG_BC_S_EQ:
910 		case INET_DIAG_BC_S_GE:
911 		case INET_DIAG_BC_S_LE:
912 		case INET_DIAG_BC_D_EQ:
913 		case INET_DIAG_BC_D_GE:
914 		case INET_DIAG_BC_D_LE:
915 			if (!valid_port_comparison(bc, len, &min_len))
916 				return -EINVAL;
917 			break;
918 		case INET_DIAG_BC_MARK_COND:
919 			if (!net_admin)
920 				return -EPERM;
921 			if (!valid_markcond(bc, len, &min_len))
922 				return -EINVAL;
923 			break;
924 #ifdef CONFIG_SOCK_CGROUP_DATA
925 		case INET_DIAG_BC_CGROUP_COND:
926 			if (!valid_cgroupcond(bc, len, &min_len))
927 				return -EINVAL;
928 			break;
929 #endif
930 		case INET_DIAG_BC_AUTO:
931 		case INET_DIAG_BC_JMP:
932 		case INET_DIAG_BC_NOP:
933 			break;
934 		default:
935 			return -EINVAL;
936 		}
937 
938 		if (op->code != INET_DIAG_BC_NOP) {
939 			if (op->no < min_len || op->no > len + 4 || op->no & 3)
940 				return -EINVAL;
941 			if (op->no < len &&
942 			    !valid_cc(bytecode, bytecode_len, len - op->no))
943 				return -EINVAL;
944 		}
945 
946 		if (op->yes < min_len || op->yes > len + 4 || op->yes & 3)
947 			return -EINVAL;
948 		bc  += op->yes;
949 		len -= op->yes;
950 	}
951 	return len == 0 ? 0 : -EINVAL;
952 }
953 
954 static void twsk_build_assert(void)
955 {
956 	BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_family) !=
957 		     offsetof(struct sock, sk_family));
958 
959 	BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_num) !=
960 		     offsetof(struct inet_sock, inet_num));
961 
962 	BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_dport) !=
963 		     offsetof(struct inet_sock, inet_dport));
964 
965 	BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_rcv_saddr) !=
966 		     offsetof(struct inet_sock, inet_rcv_saddr));
967 
968 	BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_daddr) !=
969 		     offsetof(struct inet_sock, inet_daddr));
970 
971 #if IS_ENABLED(CONFIG_IPV6)
972 	BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_v6_rcv_saddr) !=
973 		     offsetof(struct sock, sk_v6_rcv_saddr));
974 
975 	BUILD_BUG_ON(offsetof(struct inet_timewait_sock, tw_v6_daddr) !=
976 		     offsetof(struct sock, sk_v6_daddr));
977 #endif
978 }
979 
980 void inet_diag_dump_icsk(struct inet_hashinfo *hashinfo, struct sk_buff *skb,
981 			 struct netlink_callback *cb,
982 			 const struct inet_diag_req_v2 *r)
983 {
984 	bool net_admin = netlink_net_capable(cb->skb, CAP_NET_ADMIN);
985 	struct inet_diag_dump_data *cb_data = cb->data;
986 	struct net *net = sock_net(skb->sk);
987 	u32 idiag_states = r->idiag_states;
988 	int i, num, s_i, s_num;
989 	struct nlattr *bc;
990 	struct sock *sk;
991 
992 	bc = cb_data->inet_diag_nla_bc;
993 	if (idiag_states & TCPF_SYN_RECV)
994 		idiag_states |= TCPF_NEW_SYN_RECV;
995 	s_i = cb->args[1];
996 	s_num = num = cb->args[2];
997 
998 	if (cb->args[0] == 0) {
999 		if (!(idiag_states & TCPF_LISTEN) || r->id.idiag_dport)
1000 			goto skip_listen_ht;
1001 
1002 		for (i = s_i; i < INET_LHTABLE_SIZE; i++) {
1003 			struct inet_listen_hashbucket *ilb;
1004 			struct hlist_nulls_node *node;
1005 
1006 			num = 0;
1007 			ilb = &hashinfo->listening_hash[i];
1008 			spin_lock(&ilb->lock);
1009 			sk_nulls_for_each(sk, node, &ilb->nulls_head) {
1010 				struct inet_sock *inet = inet_sk(sk);
1011 
1012 				if (!net_eq(sock_net(sk), net))
1013 					continue;
1014 
1015 				if (num < s_num) {
1016 					num++;
1017 					continue;
1018 				}
1019 
1020 				if (r->sdiag_family != AF_UNSPEC &&
1021 				    sk->sk_family != r->sdiag_family)
1022 					goto next_listen;
1023 
1024 				if (r->id.idiag_sport != inet->inet_sport &&
1025 				    r->id.idiag_sport)
1026 					goto next_listen;
1027 
1028 				if (!inet_diag_bc_sk(bc, sk))
1029 					goto next_listen;
1030 
1031 				if (inet_sk_diag_fill(sk, inet_csk(sk), skb,
1032 						      cb, r, NLM_F_MULTI,
1033 						      net_admin) < 0) {
1034 					spin_unlock(&ilb->lock);
1035 					goto done;
1036 				}
1037 
1038 next_listen:
1039 				++num;
1040 			}
1041 			spin_unlock(&ilb->lock);
1042 
1043 			s_num = 0;
1044 		}
1045 skip_listen_ht:
1046 		cb->args[0] = 1;
1047 		s_i = num = s_num = 0;
1048 	}
1049 
1050 	if (!(idiag_states & ~TCPF_LISTEN))
1051 		goto out;
1052 
1053 #define SKARR_SZ 16
1054 	for (i = s_i; i <= hashinfo->ehash_mask; i++) {
1055 		struct inet_ehash_bucket *head = &hashinfo->ehash[i];
1056 		spinlock_t *lock = inet_ehash_lockp(hashinfo, i);
1057 		struct hlist_nulls_node *node;
1058 		struct sock *sk_arr[SKARR_SZ];
1059 		int num_arr[SKARR_SZ];
1060 		int idx, accum, res;
1061 
1062 		if (hlist_nulls_empty(&head->chain))
1063 			continue;
1064 
1065 		if (i > s_i)
1066 			s_num = 0;
1067 
1068 next_chunk:
1069 		num = 0;
1070 		accum = 0;
1071 		spin_lock_bh(lock);
1072 		sk_nulls_for_each(sk, node, &head->chain) {
1073 			int state;
1074 
1075 			if (!net_eq(sock_net(sk), net))
1076 				continue;
1077 			if (num < s_num)
1078 				goto next_normal;
1079 			state = (sk->sk_state == TCP_TIME_WAIT) ?
1080 				inet_twsk(sk)->tw_substate : sk->sk_state;
1081 			if (!(idiag_states & (1 << state)))
1082 				goto next_normal;
1083 			if (r->sdiag_family != AF_UNSPEC &&
1084 			    sk->sk_family != r->sdiag_family)
1085 				goto next_normal;
1086 			if (r->id.idiag_sport != htons(sk->sk_num) &&
1087 			    r->id.idiag_sport)
1088 				goto next_normal;
1089 			if (r->id.idiag_dport != sk->sk_dport &&
1090 			    r->id.idiag_dport)
1091 				goto next_normal;
1092 			twsk_build_assert();
1093 
1094 			if (!inet_diag_bc_sk(bc, sk))
1095 				goto next_normal;
1096 
1097 			if (!refcount_inc_not_zero(&sk->sk_refcnt))
1098 				goto next_normal;
1099 
1100 			num_arr[accum] = num;
1101 			sk_arr[accum] = sk;
1102 			if (++accum == SKARR_SZ)
1103 				break;
1104 next_normal:
1105 			++num;
1106 		}
1107 		spin_unlock_bh(lock);
1108 		res = 0;
1109 		for (idx = 0; idx < accum; idx++) {
1110 			if (res >= 0) {
1111 				res = sk_diag_fill(sk_arr[idx], skb, cb, r,
1112 						   NLM_F_MULTI, net_admin);
1113 				if (res < 0)
1114 					num = num_arr[idx];
1115 			}
1116 			sock_gen_put(sk_arr[idx]);
1117 		}
1118 		if (res < 0)
1119 			break;
1120 		cond_resched();
1121 		if (accum == SKARR_SZ) {
1122 			s_num = num + 1;
1123 			goto next_chunk;
1124 		}
1125 	}
1126 
1127 done:
1128 	cb->args[1] = i;
1129 	cb->args[2] = num;
1130 out:
1131 	;
1132 }
1133 EXPORT_SYMBOL_GPL(inet_diag_dump_icsk);
1134 
1135 static int __inet_diag_dump(struct sk_buff *skb, struct netlink_callback *cb,
1136 			    const struct inet_diag_req_v2 *r)
1137 {
1138 	struct inet_diag_dump_data *cb_data = cb->data;
1139 	const struct inet_diag_handler *handler;
1140 	u32 prev_min_dump_alloc;
1141 	int protocol, err = 0;
1142 
1143 	protocol = inet_diag_get_protocol(r, cb_data);
1144 
1145 again:
1146 	prev_min_dump_alloc = cb->min_dump_alloc;
1147 	handler = inet_diag_lock_handler(protocol);
1148 	if (!IS_ERR(handler))
1149 		handler->dump(skb, cb, r);
1150 	else
1151 		err = PTR_ERR(handler);
1152 	inet_diag_unlock_handler(handler);
1153 
1154 	/* The skb is not large enough to fit one sk info and
1155 	 * inet_sk_diag_fill() has requested for a larger skb.
1156 	 */
1157 	if (!skb->len && cb->min_dump_alloc > prev_min_dump_alloc) {
1158 		err = pskb_expand_head(skb, 0, cb->min_dump_alloc, GFP_KERNEL);
1159 		if (!err)
1160 			goto again;
1161 	}
1162 
1163 	return err ? : skb->len;
1164 }
1165 
1166 static int inet_diag_dump(struct sk_buff *skb, struct netlink_callback *cb)
1167 {
1168 	return __inet_diag_dump(skb, cb, nlmsg_data(cb->nlh));
1169 }
1170 
1171 static int __inet_diag_dump_start(struct netlink_callback *cb, int hdrlen)
1172 {
1173 	const struct nlmsghdr *nlh = cb->nlh;
1174 	struct inet_diag_dump_data *cb_data;
1175 	struct sk_buff *skb = cb->skb;
1176 	struct nlattr *nla;
1177 	int err;
1178 
1179 	cb_data = kzalloc(sizeof(*cb_data), GFP_KERNEL);
1180 	if (!cb_data)
1181 		return -ENOMEM;
1182 
1183 	inet_diag_parse_attrs(nlh, hdrlen, cb_data->req_nlas);
1184 
1185 	nla = cb_data->inet_diag_nla_bc;
1186 	if (nla) {
1187 		err = inet_diag_bc_audit(nla, skb);
1188 		if (err) {
1189 			kfree(cb_data);
1190 			return err;
1191 		}
1192 	}
1193 
1194 	nla = cb_data->inet_diag_nla_bpf_stgs;
1195 	if (nla) {
1196 		struct bpf_sk_storage_diag *bpf_stg_diag;
1197 
1198 		bpf_stg_diag = bpf_sk_storage_diag_alloc(nla);
1199 		if (IS_ERR(bpf_stg_diag)) {
1200 			kfree(cb_data);
1201 			return PTR_ERR(bpf_stg_diag);
1202 		}
1203 		cb_data->bpf_stg_diag = bpf_stg_diag;
1204 	}
1205 
1206 	cb->data = cb_data;
1207 	return 0;
1208 }
1209 
1210 static int inet_diag_dump_start(struct netlink_callback *cb)
1211 {
1212 	return __inet_diag_dump_start(cb, sizeof(struct inet_diag_req_v2));
1213 }
1214 
1215 static int inet_diag_dump_start_compat(struct netlink_callback *cb)
1216 {
1217 	return __inet_diag_dump_start(cb, sizeof(struct inet_diag_req));
1218 }
1219 
1220 static int inet_diag_dump_done(struct netlink_callback *cb)
1221 {
1222 	struct inet_diag_dump_data *cb_data = cb->data;
1223 
1224 	bpf_sk_storage_diag_free(cb_data->bpf_stg_diag);
1225 	kfree(cb->data);
1226 
1227 	return 0;
1228 }
1229 
1230 static int inet_diag_type2proto(int type)
1231 {
1232 	switch (type) {
1233 	case TCPDIAG_GETSOCK:
1234 		return IPPROTO_TCP;
1235 	case DCCPDIAG_GETSOCK:
1236 		return IPPROTO_DCCP;
1237 	default:
1238 		return 0;
1239 	}
1240 }
1241 
1242 static int inet_diag_dump_compat(struct sk_buff *skb,
1243 				 struct netlink_callback *cb)
1244 {
1245 	struct inet_diag_req *rc = nlmsg_data(cb->nlh);
1246 	struct inet_diag_req_v2 req;
1247 
1248 	req.sdiag_family = AF_UNSPEC; /* compatibility */
1249 	req.sdiag_protocol = inet_diag_type2proto(cb->nlh->nlmsg_type);
1250 	req.idiag_ext = rc->idiag_ext;
1251 	req.idiag_states = rc->idiag_states;
1252 	req.id = rc->id;
1253 
1254 	return __inet_diag_dump(skb, cb, &req);
1255 }
1256 
1257 static int inet_diag_get_exact_compat(struct sk_buff *in_skb,
1258 				      const struct nlmsghdr *nlh)
1259 {
1260 	struct inet_diag_req *rc = nlmsg_data(nlh);
1261 	struct inet_diag_req_v2 req;
1262 
1263 	req.sdiag_family = rc->idiag_family;
1264 	req.sdiag_protocol = inet_diag_type2proto(nlh->nlmsg_type);
1265 	req.idiag_ext = rc->idiag_ext;
1266 	req.idiag_states = rc->idiag_states;
1267 	req.id = rc->id;
1268 
1269 	return inet_diag_cmd_exact(SOCK_DIAG_BY_FAMILY, in_skb, nlh,
1270 				   sizeof(struct inet_diag_req), &req);
1271 }
1272 
1273 static int inet_diag_rcv_msg_compat(struct sk_buff *skb, struct nlmsghdr *nlh)
1274 {
1275 	int hdrlen = sizeof(struct inet_diag_req);
1276 	struct net *net = sock_net(skb->sk);
1277 
1278 	if (nlh->nlmsg_type >= INET_DIAG_GETSOCK_MAX ||
1279 	    nlmsg_len(nlh) < hdrlen)
1280 		return -EINVAL;
1281 
1282 	if (nlh->nlmsg_flags & NLM_F_DUMP) {
1283 		struct netlink_dump_control c = {
1284 			.start = inet_diag_dump_start_compat,
1285 			.done = inet_diag_dump_done,
1286 			.dump = inet_diag_dump_compat,
1287 		};
1288 		return netlink_dump_start(net->diag_nlsk, skb, nlh, &c);
1289 	}
1290 
1291 	return inet_diag_get_exact_compat(skb, nlh);
1292 }
1293 
1294 static int inet_diag_handler_cmd(struct sk_buff *skb, struct nlmsghdr *h)
1295 {
1296 	int hdrlen = sizeof(struct inet_diag_req_v2);
1297 	struct net *net = sock_net(skb->sk);
1298 
1299 	if (nlmsg_len(h) < hdrlen)
1300 		return -EINVAL;
1301 
1302 	if (h->nlmsg_type == SOCK_DIAG_BY_FAMILY &&
1303 	    h->nlmsg_flags & NLM_F_DUMP) {
1304 		struct netlink_dump_control c = {
1305 			.start = inet_diag_dump_start,
1306 			.done = inet_diag_dump_done,
1307 			.dump = inet_diag_dump,
1308 		};
1309 		return netlink_dump_start(net->diag_nlsk, skb, h, &c);
1310 	}
1311 
1312 	return inet_diag_cmd_exact(h->nlmsg_type, skb, h, hdrlen,
1313 				   nlmsg_data(h));
1314 }
1315 
1316 static
1317 int inet_diag_handler_get_info(struct sk_buff *skb, struct sock *sk)
1318 {
1319 	const struct inet_diag_handler *handler;
1320 	struct nlmsghdr *nlh;
1321 	struct nlattr *attr;
1322 	struct inet_diag_msg *r;
1323 	void *info = NULL;
1324 	int err = 0;
1325 
1326 	nlh = nlmsg_put(skb, 0, 0, SOCK_DIAG_BY_FAMILY, sizeof(*r), 0);
1327 	if (!nlh)
1328 		return -ENOMEM;
1329 
1330 	r = nlmsg_data(nlh);
1331 	memset(r, 0, sizeof(*r));
1332 	inet_diag_msg_common_fill(r, sk);
1333 	if (sk->sk_type == SOCK_DGRAM || sk->sk_type == SOCK_STREAM)
1334 		r->id.idiag_sport = inet_sk(sk)->inet_sport;
1335 	r->idiag_state = sk->sk_state;
1336 
1337 	if ((err = nla_put_u8(skb, INET_DIAG_PROTOCOL, sk->sk_protocol))) {
1338 		nlmsg_cancel(skb, nlh);
1339 		return err;
1340 	}
1341 
1342 	handler = inet_diag_lock_handler(sk->sk_protocol);
1343 	if (IS_ERR(handler)) {
1344 		inet_diag_unlock_handler(handler);
1345 		nlmsg_cancel(skb, nlh);
1346 		return PTR_ERR(handler);
1347 	}
1348 
1349 	attr = handler->idiag_info_size
1350 		? nla_reserve_64bit(skb, INET_DIAG_INFO,
1351 				    handler->idiag_info_size,
1352 				    INET_DIAG_PAD)
1353 		: NULL;
1354 	if (attr)
1355 		info = nla_data(attr);
1356 
1357 	handler->idiag_get_info(sk, r, info);
1358 	inet_diag_unlock_handler(handler);
1359 
1360 	nlmsg_end(skb, nlh);
1361 	return 0;
1362 }
1363 
1364 static const struct sock_diag_handler inet_diag_handler = {
1365 	.family = AF_INET,
1366 	.dump = inet_diag_handler_cmd,
1367 	.get_info = inet_diag_handler_get_info,
1368 	.destroy = inet_diag_handler_cmd,
1369 };
1370 
1371 static const struct sock_diag_handler inet6_diag_handler = {
1372 	.family = AF_INET6,
1373 	.dump = inet_diag_handler_cmd,
1374 	.get_info = inet_diag_handler_get_info,
1375 	.destroy = inet_diag_handler_cmd,
1376 };
1377 
1378 int inet_diag_register(const struct inet_diag_handler *h)
1379 {
1380 	const __u16 type = h->idiag_type;
1381 	int err = -EINVAL;
1382 
1383 	if (type >= IPPROTO_MAX)
1384 		goto out;
1385 
1386 	mutex_lock(&inet_diag_table_mutex);
1387 	err = -EEXIST;
1388 	if (!inet_diag_table[type]) {
1389 		inet_diag_table[type] = h;
1390 		err = 0;
1391 	}
1392 	mutex_unlock(&inet_diag_table_mutex);
1393 out:
1394 	return err;
1395 }
1396 EXPORT_SYMBOL_GPL(inet_diag_register);
1397 
1398 void inet_diag_unregister(const struct inet_diag_handler *h)
1399 {
1400 	const __u16 type = h->idiag_type;
1401 
1402 	if (type >= IPPROTO_MAX)
1403 		return;
1404 
1405 	mutex_lock(&inet_diag_table_mutex);
1406 	inet_diag_table[type] = NULL;
1407 	mutex_unlock(&inet_diag_table_mutex);
1408 }
1409 EXPORT_SYMBOL_GPL(inet_diag_unregister);
1410 
1411 static int __init inet_diag_init(void)
1412 {
1413 	const int inet_diag_table_size = (IPPROTO_MAX *
1414 					  sizeof(struct inet_diag_handler *));
1415 	int err = -ENOMEM;
1416 
1417 	inet_diag_table = kzalloc(inet_diag_table_size, GFP_KERNEL);
1418 	if (!inet_diag_table)
1419 		goto out;
1420 
1421 	err = sock_diag_register(&inet_diag_handler);
1422 	if (err)
1423 		goto out_free_nl;
1424 
1425 	err = sock_diag_register(&inet6_diag_handler);
1426 	if (err)
1427 		goto out_free_inet;
1428 
1429 	sock_diag_register_inet_compat(inet_diag_rcv_msg_compat);
1430 out:
1431 	return err;
1432 
1433 out_free_inet:
1434 	sock_diag_unregister(&inet_diag_handler);
1435 out_free_nl:
1436 	kfree(inet_diag_table);
1437 	goto out;
1438 }
1439 
1440 static void __exit inet_diag_exit(void)
1441 {
1442 	sock_diag_unregister(&inet6_diag_handler);
1443 	sock_diag_unregister(&inet_diag_handler);
1444 	sock_diag_unregister_inet_compat(inet_diag_rcv_msg_compat);
1445 	kfree(inet_diag_table);
1446 }
1447 
1448 module_init(inet_diag_init);
1449 module_exit(inet_diag_exit);
1450 MODULE_LICENSE("GPL");
1451 MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 2 /* AF_INET */);
1452 MODULE_ALIAS_NET_PF_PROTO_TYPE(PF_NETLINK, NETLINK_SOCK_DIAG, 10 /* AF_INET6 */);
1453