xref: /openbmc/linux/net/ipv4/ping.c (revision 2427f03f)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * INET		An implementation of the TCP/IP protocol suite for the LINUX
4  *		operating system.  INET is implemented using the  BSD Socket
5  *		interface as the means of communication with the user level.
6  *
7  *		"Ping" sockets
8  *
9  * Based on ipv4/udp.c code.
10  *
11  * Authors:	Vasiliy Kulikov / Openwall (for Linux 2.6),
12  *		Pavel Kankovsky (for Linux 2.4.32)
13  *
14  * Pavel gave all rights to bugs to Vasiliy,
15  * none of the bugs are Pavel's now.
16  */
17 
18 #include <linux/uaccess.h>
19 #include <linux/types.h>
20 #include <linux/fcntl.h>
21 #include <linux/socket.h>
22 #include <linux/sockios.h>
23 #include <linux/in.h>
24 #include <linux/errno.h>
25 #include <linux/timer.h>
26 #include <linux/mm.h>
27 #include <linux/inet.h>
28 #include <linux/netdevice.h>
29 #include <net/snmp.h>
30 #include <net/ip.h>
31 #include <net/icmp.h>
32 #include <net/protocol.h>
33 #include <linux/skbuff.h>
34 #include <linux/proc_fs.h>
35 #include <linux/export.h>
36 #include <net/sock.h>
37 #include <net/ping.h>
38 #include <net/udp.h>
39 #include <net/route.h>
40 #include <net/inet_common.h>
41 #include <net/checksum.h>
42 
43 #if IS_ENABLED(CONFIG_IPV6)
44 #include <linux/in6.h>
45 #include <linux/icmpv6.h>
46 #include <net/addrconf.h>
47 #include <net/ipv6.h>
48 #include <net/transp_v6.h>
49 #endif
50 
51 struct ping_table {
52 	struct hlist_nulls_head	hash[PING_HTABLE_SIZE];
53 	rwlock_t		lock;
54 };
55 
56 static struct ping_table ping_table;
57 struct pingv6_ops pingv6_ops;
58 EXPORT_SYMBOL_GPL(pingv6_ops);
59 
60 static u16 ping_port_rover;
61 
62 static inline u32 ping_hashfn(const struct net *net, u32 num, u32 mask)
63 {
64 	u32 res = (num + net_hash_mix(net)) & mask;
65 
66 	pr_debug("hash(%u) = %u\n", num, res);
67 	return res;
68 }
69 EXPORT_SYMBOL_GPL(ping_hash);
70 
71 static inline struct hlist_nulls_head *ping_hashslot(struct ping_table *table,
72 					     struct net *net, unsigned int num)
73 {
74 	return &table->hash[ping_hashfn(net, num, PING_HTABLE_MASK)];
75 }
76 
77 int ping_get_port(struct sock *sk, unsigned short ident)
78 {
79 	struct hlist_nulls_node *node;
80 	struct hlist_nulls_head *hlist;
81 	struct inet_sock *isk, *isk2;
82 	struct sock *sk2 = NULL;
83 
84 	isk = inet_sk(sk);
85 	write_lock_bh(&ping_table.lock);
86 	if (ident == 0) {
87 		u32 i;
88 		u16 result = ping_port_rover + 1;
89 
90 		for (i = 0; i < (1L << 16); i++, result++) {
91 			if (!result)
92 				result++; /* avoid zero */
93 			hlist = ping_hashslot(&ping_table, sock_net(sk),
94 					    result);
95 			ping_portaddr_for_each_entry(sk2, node, hlist) {
96 				isk2 = inet_sk(sk2);
97 
98 				if (isk2->inet_num == result)
99 					goto next_port;
100 			}
101 
102 			/* found */
103 			ping_port_rover = ident = result;
104 			break;
105 next_port:
106 			;
107 		}
108 		if (i >= (1L << 16))
109 			goto fail;
110 	} else {
111 		hlist = ping_hashslot(&ping_table, sock_net(sk), ident);
112 		ping_portaddr_for_each_entry(sk2, node, hlist) {
113 			isk2 = inet_sk(sk2);
114 
115 			/* BUG? Why is this reuse and not reuseaddr? ping.c
116 			 * doesn't turn off SO_REUSEADDR, and it doesn't expect
117 			 * that other ping processes can steal its packets.
118 			 */
119 			if ((isk2->inet_num == ident) &&
120 			    (sk2 != sk) &&
121 			    (!sk2->sk_reuse || !sk->sk_reuse))
122 				goto fail;
123 		}
124 	}
125 
126 	pr_debug("found port/ident = %d\n", ident);
127 	isk->inet_num = ident;
128 	if (sk_unhashed(sk)) {
129 		pr_debug("was not hashed\n");
130 		sock_hold(sk);
131 		hlist_nulls_add_head(&sk->sk_nulls_node, hlist);
132 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
133 	}
134 	write_unlock_bh(&ping_table.lock);
135 	return 0;
136 
137 fail:
138 	write_unlock_bh(&ping_table.lock);
139 	return 1;
140 }
141 EXPORT_SYMBOL_GPL(ping_get_port);
142 
143 int ping_hash(struct sock *sk)
144 {
145 	pr_debug("ping_hash(sk->port=%u)\n", inet_sk(sk)->inet_num);
146 	BUG(); /* "Please do not press this button again." */
147 
148 	return 0;
149 }
150 
151 void ping_unhash(struct sock *sk)
152 {
153 	struct inet_sock *isk = inet_sk(sk);
154 
155 	pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
156 	write_lock_bh(&ping_table.lock);
157 	if (sk_hashed(sk)) {
158 		hlist_nulls_del(&sk->sk_nulls_node);
159 		sk_nulls_node_init(&sk->sk_nulls_node);
160 		sock_put(sk);
161 		isk->inet_num = 0;
162 		isk->inet_sport = 0;
163 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
164 	}
165 	write_unlock_bh(&ping_table.lock);
166 }
167 EXPORT_SYMBOL_GPL(ping_unhash);
168 
169 static struct sock *ping_lookup(struct net *net, struct sk_buff *skb, u16 ident)
170 {
171 	struct hlist_nulls_head *hslot = ping_hashslot(&ping_table, net, ident);
172 	struct sock *sk = NULL;
173 	struct inet_sock *isk;
174 	struct hlist_nulls_node *hnode;
175 	int dif = skb->dev->ifindex;
176 
177 	if (skb->protocol == htons(ETH_P_IP)) {
178 		pr_debug("try to find: num = %d, daddr = %pI4, dif = %d\n",
179 			 (int)ident, &ip_hdr(skb)->daddr, dif);
180 #if IS_ENABLED(CONFIG_IPV6)
181 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
182 		pr_debug("try to find: num = %d, daddr = %pI6c, dif = %d\n",
183 			 (int)ident, &ipv6_hdr(skb)->daddr, dif);
184 #endif
185 	}
186 
187 	read_lock_bh(&ping_table.lock);
188 
189 	ping_portaddr_for_each_entry(sk, hnode, hslot) {
190 		isk = inet_sk(sk);
191 
192 		pr_debug("iterate\n");
193 		if (isk->inet_num != ident)
194 			continue;
195 
196 		if (skb->protocol == htons(ETH_P_IP) &&
197 		    sk->sk_family == AF_INET) {
198 			pr_debug("found: %p: num=%d, daddr=%pI4, dif=%d\n", sk,
199 				 (int) isk->inet_num, &isk->inet_rcv_saddr,
200 				 sk->sk_bound_dev_if);
201 
202 			if (isk->inet_rcv_saddr &&
203 			    isk->inet_rcv_saddr != ip_hdr(skb)->daddr)
204 				continue;
205 #if IS_ENABLED(CONFIG_IPV6)
206 		} else if (skb->protocol == htons(ETH_P_IPV6) &&
207 			   sk->sk_family == AF_INET6) {
208 
209 			pr_debug("found: %p: num=%d, daddr=%pI6c, dif=%d\n", sk,
210 				 (int) isk->inet_num,
211 				 &sk->sk_v6_rcv_saddr,
212 				 sk->sk_bound_dev_if);
213 
214 			if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr) &&
215 			    !ipv6_addr_equal(&sk->sk_v6_rcv_saddr,
216 					     &ipv6_hdr(skb)->daddr))
217 				continue;
218 #endif
219 		} else {
220 			continue;
221 		}
222 
223 		if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif &&
224 		    sk->sk_bound_dev_if != inet_sdif(skb))
225 			continue;
226 
227 		sock_hold(sk);
228 		goto exit;
229 	}
230 
231 	sk = NULL;
232 exit:
233 	read_unlock_bh(&ping_table.lock);
234 
235 	return sk;
236 }
237 
238 static void inet_get_ping_group_range_net(struct net *net, kgid_t *low,
239 					  kgid_t *high)
240 {
241 	kgid_t *data = net->ipv4.ping_group_range.range;
242 	unsigned int seq;
243 
244 	do {
245 		seq = read_seqbegin(&net->ipv4.ping_group_range.lock);
246 
247 		*low = data[0];
248 		*high = data[1];
249 	} while (read_seqretry(&net->ipv4.ping_group_range.lock, seq));
250 }
251 
252 
253 int ping_init_sock(struct sock *sk)
254 {
255 	struct net *net = sock_net(sk);
256 	kgid_t group = current_egid();
257 	struct group_info *group_info;
258 	int i;
259 	kgid_t low, high;
260 	int ret = 0;
261 
262 	if (sk->sk_family == AF_INET6)
263 		sk->sk_ipv6only = 1;
264 
265 	inet_get_ping_group_range_net(net, &low, &high);
266 	if (gid_lte(low, group) && gid_lte(group, high))
267 		return 0;
268 
269 	group_info = get_current_groups();
270 	for (i = 0; i < group_info->ngroups; i++) {
271 		kgid_t gid = group_info->gid[i];
272 
273 		if (gid_lte(low, gid) && gid_lte(gid, high))
274 			goto out_release_group;
275 	}
276 
277 	ret = -EACCES;
278 
279 out_release_group:
280 	put_group_info(group_info);
281 	return ret;
282 }
283 EXPORT_SYMBOL_GPL(ping_init_sock);
284 
285 void ping_close(struct sock *sk, long timeout)
286 {
287 	pr_debug("ping_close(sk=%p,sk->num=%u)\n",
288 		 inet_sk(sk), inet_sk(sk)->inet_num);
289 	pr_debug("isk->refcnt = %d\n", refcount_read(&sk->sk_refcnt));
290 
291 	sk_common_release(sk);
292 }
293 EXPORT_SYMBOL_GPL(ping_close);
294 
295 /* Checks the bind address and possibly modifies sk->sk_bound_dev_if. */
296 static int ping_check_bind_addr(struct sock *sk, struct inet_sock *isk,
297 				struct sockaddr *uaddr, int addr_len)
298 {
299 	struct net *net = sock_net(sk);
300 	if (sk->sk_family == AF_INET) {
301 		struct sockaddr_in *addr = (struct sockaddr_in *) uaddr;
302 		int chk_addr_ret;
303 
304 		if (addr_len < sizeof(*addr))
305 			return -EINVAL;
306 
307 		if (addr->sin_family != AF_INET &&
308 		    !(addr->sin_family == AF_UNSPEC &&
309 		      addr->sin_addr.s_addr == htonl(INADDR_ANY)))
310 			return -EAFNOSUPPORT;
311 
312 		pr_debug("ping_check_bind_addr(sk=%p,addr=%pI4,port=%d)\n",
313 			 sk, &addr->sin_addr.s_addr, ntohs(addr->sin_port));
314 
315 		chk_addr_ret = inet_addr_type(net, addr->sin_addr.s_addr);
316 
317 		if (!inet_addr_valid_or_nonlocal(net, inet_sk(sk),
318 					         addr->sin_addr.s_addr,
319 	                                         chk_addr_ret))
320 			return -EADDRNOTAVAIL;
321 
322 #if IS_ENABLED(CONFIG_IPV6)
323 	} else if (sk->sk_family == AF_INET6) {
324 		struct sockaddr_in6 *addr = (struct sockaddr_in6 *) uaddr;
325 		int addr_type, scoped, has_addr;
326 		struct net_device *dev = NULL;
327 
328 		if (addr_len < sizeof(*addr))
329 			return -EINVAL;
330 
331 		if (addr->sin6_family != AF_INET6)
332 			return -EAFNOSUPPORT;
333 
334 		pr_debug("ping_check_bind_addr(sk=%p,addr=%pI6c,port=%d)\n",
335 			 sk, addr->sin6_addr.s6_addr, ntohs(addr->sin6_port));
336 
337 		addr_type = ipv6_addr_type(&addr->sin6_addr);
338 		scoped = __ipv6_addr_needs_scope_id(addr_type);
339 		if ((addr_type != IPV6_ADDR_ANY &&
340 		     !(addr_type & IPV6_ADDR_UNICAST)) ||
341 		    (scoped && !addr->sin6_scope_id))
342 			return -EINVAL;
343 
344 		rcu_read_lock();
345 		if (addr->sin6_scope_id) {
346 			dev = dev_get_by_index_rcu(net, addr->sin6_scope_id);
347 			if (!dev) {
348 				rcu_read_unlock();
349 				return -ENODEV;
350 			}
351 		}
352 		has_addr = pingv6_ops.ipv6_chk_addr(net, &addr->sin6_addr, dev,
353 						    scoped);
354 		rcu_read_unlock();
355 
356 		if (!(ipv6_can_nonlocal_bind(net, isk) || has_addr ||
357 		      addr_type == IPV6_ADDR_ANY))
358 			return -EADDRNOTAVAIL;
359 
360 		if (scoped)
361 			sk->sk_bound_dev_if = addr->sin6_scope_id;
362 #endif
363 	} else {
364 		return -EAFNOSUPPORT;
365 	}
366 	return 0;
367 }
368 
369 static void ping_set_saddr(struct sock *sk, struct sockaddr *saddr)
370 {
371 	if (saddr->sa_family == AF_INET) {
372 		struct inet_sock *isk = inet_sk(sk);
373 		struct sockaddr_in *addr = (struct sockaddr_in *) saddr;
374 		isk->inet_rcv_saddr = isk->inet_saddr = addr->sin_addr.s_addr;
375 #if IS_ENABLED(CONFIG_IPV6)
376 	} else if (saddr->sa_family == AF_INET6) {
377 		struct sockaddr_in6 *addr = (struct sockaddr_in6 *) saddr;
378 		struct ipv6_pinfo *np = inet6_sk(sk);
379 		sk->sk_v6_rcv_saddr = np->saddr = addr->sin6_addr;
380 #endif
381 	}
382 }
383 
384 /*
385  * We need our own bind because there are no privileged id's == local ports.
386  * Moreover, we don't allow binding to multi- and broadcast addresses.
387  */
388 
389 int ping_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
390 {
391 	struct inet_sock *isk = inet_sk(sk);
392 	unsigned short snum;
393 	int err;
394 	int dif = sk->sk_bound_dev_if;
395 
396 	err = ping_check_bind_addr(sk, isk, uaddr, addr_len);
397 	if (err)
398 		return err;
399 
400 	lock_sock(sk);
401 
402 	err = -EINVAL;
403 	if (isk->inet_num != 0)
404 		goto out;
405 
406 	err = -EADDRINUSE;
407 	snum = ntohs(((struct sockaddr_in *)uaddr)->sin_port);
408 	if (ping_get_port(sk, snum) != 0) {
409 		/* Restore possibly modified sk->sk_bound_dev_if by ping_check_bind_addr(). */
410 		sk->sk_bound_dev_if = dif;
411 		goto out;
412 	}
413 	ping_set_saddr(sk, uaddr);
414 
415 	pr_debug("after bind(): num = %hu, dif = %d\n",
416 		 isk->inet_num,
417 		 sk->sk_bound_dev_if);
418 
419 	err = 0;
420 	if (sk->sk_family == AF_INET && isk->inet_rcv_saddr)
421 		sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
422 #if IS_ENABLED(CONFIG_IPV6)
423 	if (sk->sk_family == AF_INET6 && !ipv6_addr_any(&sk->sk_v6_rcv_saddr))
424 		sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
425 #endif
426 
427 	if (snum)
428 		sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
429 	isk->inet_sport = htons(isk->inet_num);
430 	isk->inet_daddr = 0;
431 	isk->inet_dport = 0;
432 
433 #if IS_ENABLED(CONFIG_IPV6)
434 	if (sk->sk_family == AF_INET6)
435 		memset(&sk->sk_v6_daddr, 0, sizeof(sk->sk_v6_daddr));
436 #endif
437 
438 	sk_dst_reset(sk);
439 out:
440 	release_sock(sk);
441 	pr_debug("ping_v4_bind -> %d\n", err);
442 	return err;
443 }
444 EXPORT_SYMBOL_GPL(ping_bind);
445 
446 /*
447  * Is this a supported type of ICMP message?
448  */
449 
450 static inline int ping_supported(int family, int type, int code)
451 {
452 	return (family == AF_INET && type == ICMP_ECHO && code == 0) ||
453 	       (family == AF_INET && type == ICMP_EXT_ECHO && code == 0) ||
454 	       (family == AF_INET6 && type == ICMPV6_ECHO_REQUEST && code == 0) ||
455 	       (family == AF_INET6 && type == ICMPV6_EXT_ECHO_REQUEST && code == 0);
456 }
457 
458 /*
459  * This routine is called by the ICMP module when it gets some
460  * sort of error condition.
461  */
462 
463 void ping_err(struct sk_buff *skb, int offset, u32 info)
464 {
465 	int family;
466 	struct icmphdr *icmph;
467 	struct inet_sock *inet_sock;
468 	int type;
469 	int code;
470 	struct net *net = dev_net(skb->dev);
471 	struct sock *sk;
472 	int harderr;
473 	int err;
474 
475 	if (skb->protocol == htons(ETH_P_IP)) {
476 		family = AF_INET;
477 		type = icmp_hdr(skb)->type;
478 		code = icmp_hdr(skb)->code;
479 		icmph = (struct icmphdr *)(skb->data + offset);
480 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
481 		family = AF_INET6;
482 		type = icmp6_hdr(skb)->icmp6_type;
483 		code = icmp6_hdr(skb)->icmp6_code;
484 		icmph = (struct icmphdr *) (skb->data + offset);
485 	} else {
486 		BUG();
487 	}
488 
489 	/* We assume the packet has already been checked by icmp_unreach */
490 
491 	if (!ping_supported(family, icmph->type, icmph->code))
492 		return;
493 
494 	pr_debug("ping_err(proto=0x%x,type=%d,code=%d,id=%04x,seq=%04x)\n",
495 		 skb->protocol, type, code, ntohs(icmph->un.echo.id),
496 		 ntohs(icmph->un.echo.sequence));
497 
498 	sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id));
499 	if (!sk) {
500 		pr_debug("no socket, dropping\n");
501 		return;	/* No socket for error */
502 	}
503 	pr_debug("err on socket %p\n", sk);
504 
505 	err = 0;
506 	harderr = 0;
507 	inet_sock = inet_sk(sk);
508 
509 	if (skb->protocol == htons(ETH_P_IP)) {
510 		switch (type) {
511 		default:
512 		case ICMP_TIME_EXCEEDED:
513 			err = EHOSTUNREACH;
514 			break;
515 		case ICMP_SOURCE_QUENCH:
516 			/* This is not a real error but ping wants to see it.
517 			 * Report it with some fake errno.
518 			 */
519 			err = EREMOTEIO;
520 			break;
521 		case ICMP_PARAMETERPROB:
522 			err = EPROTO;
523 			harderr = 1;
524 			break;
525 		case ICMP_DEST_UNREACH:
526 			if (code == ICMP_FRAG_NEEDED) { /* Path MTU discovery */
527 				ipv4_sk_update_pmtu(skb, sk, info);
528 				if (inet_sock->pmtudisc != IP_PMTUDISC_DONT) {
529 					err = EMSGSIZE;
530 					harderr = 1;
531 					break;
532 				}
533 				goto out;
534 			}
535 			err = EHOSTUNREACH;
536 			if (code <= NR_ICMP_UNREACH) {
537 				harderr = icmp_err_convert[code].fatal;
538 				err = icmp_err_convert[code].errno;
539 			}
540 			break;
541 		case ICMP_REDIRECT:
542 			/* See ICMP_SOURCE_QUENCH */
543 			ipv4_sk_redirect(skb, sk);
544 			err = EREMOTEIO;
545 			break;
546 		}
547 #if IS_ENABLED(CONFIG_IPV6)
548 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
549 		harderr = pingv6_ops.icmpv6_err_convert(type, code, &err);
550 #endif
551 	}
552 
553 	/*
554 	 *      RFC1122: OK.  Passes ICMP errors back to application, as per
555 	 *	4.1.3.3.
556 	 */
557 	if ((family == AF_INET && !inet_sock->recverr) ||
558 	    (family == AF_INET6 && !inet6_sk(sk)->recverr)) {
559 		if (!harderr || sk->sk_state != TCP_ESTABLISHED)
560 			goto out;
561 	} else {
562 		if (family == AF_INET) {
563 			ip_icmp_error(sk, skb, err, 0 /* no remote port */,
564 				      info, (u8 *)icmph);
565 #if IS_ENABLED(CONFIG_IPV6)
566 		} else if (family == AF_INET6) {
567 			pingv6_ops.ipv6_icmp_error(sk, skb, err, 0,
568 						   info, (u8 *)icmph);
569 #endif
570 		}
571 	}
572 	sk->sk_err = err;
573 	sk_error_report(sk);
574 out:
575 	sock_put(sk);
576 }
577 EXPORT_SYMBOL_GPL(ping_err);
578 
579 /*
580  *	Copy and checksum an ICMP Echo packet from user space into a buffer
581  *	starting from the payload.
582  */
583 
584 int ping_getfrag(void *from, char *to,
585 		 int offset, int fraglen, int odd, struct sk_buff *skb)
586 {
587 	struct pingfakehdr *pfh = (struct pingfakehdr *)from;
588 
589 	if (offset == 0) {
590 		fraglen -= sizeof(struct icmphdr);
591 		if (fraglen < 0)
592 			BUG();
593 		if (!csum_and_copy_from_iter_full(to + sizeof(struct icmphdr),
594 			    fraglen, &pfh->wcheck,
595 			    &pfh->msg->msg_iter))
596 			return -EFAULT;
597 	} else if (offset < sizeof(struct icmphdr)) {
598 			BUG();
599 	} else {
600 		if (!csum_and_copy_from_iter_full(to, fraglen, &pfh->wcheck,
601 					    &pfh->msg->msg_iter))
602 			return -EFAULT;
603 	}
604 
605 #if IS_ENABLED(CONFIG_IPV6)
606 	/* For IPv6, checksum each skb as we go along, as expected by
607 	 * icmpv6_push_pending_frames. For IPv4, accumulate the checksum in
608 	 * wcheck, it will be finalized in ping_v4_push_pending_frames.
609 	 */
610 	if (pfh->family == AF_INET6) {
611 		skb->csum = pfh->wcheck;
612 		skb->ip_summed = CHECKSUM_NONE;
613 		pfh->wcheck = 0;
614 	}
615 #endif
616 
617 	return 0;
618 }
619 EXPORT_SYMBOL_GPL(ping_getfrag);
620 
621 static int ping_v4_push_pending_frames(struct sock *sk, struct pingfakehdr *pfh,
622 				       struct flowi4 *fl4)
623 {
624 	struct sk_buff *skb = skb_peek(&sk->sk_write_queue);
625 
626 	if (!skb)
627 		return 0;
628 	pfh->wcheck = csum_partial((char *)&pfh->icmph,
629 		sizeof(struct icmphdr), pfh->wcheck);
630 	pfh->icmph.checksum = csum_fold(pfh->wcheck);
631 	memcpy(icmp_hdr(skb), &pfh->icmph, sizeof(struct icmphdr));
632 	skb->ip_summed = CHECKSUM_NONE;
633 	return ip_push_pending_frames(sk, fl4);
634 }
635 
636 int ping_common_sendmsg(int family, struct msghdr *msg, size_t len,
637 			void *user_icmph, size_t icmph_len)
638 {
639 	u8 type, code;
640 
641 	if (len > 0xFFFF)
642 		return -EMSGSIZE;
643 
644 	/* Must have at least a full ICMP header. */
645 	if (len < icmph_len)
646 		return -EINVAL;
647 
648 	/*
649 	 *	Check the flags.
650 	 */
651 
652 	/* Mirror BSD error message compatibility */
653 	if (msg->msg_flags & MSG_OOB)
654 		return -EOPNOTSUPP;
655 
656 	/*
657 	 *	Fetch the ICMP header provided by the userland.
658 	 *	iovec is modified! The ICMP header is consumed.
659 	 */
660 	if (memcpy_from_msg(user_icmph, msg, icmph_len))
661 		return -EFAULT;
662 
663 	if (family == AF_INET) {
664 		type = ((struct icmphdr *) user_icmph)->type;
665 		code = ((struct icmphdr *) user_icmph)->code;
666 #if IS_ENABLED(CONFIG_IPV6)
667 	} else if (family == AF_INET6) {
668 		type = ((struct icmp6hdr *) user_icmph)->icmp6_type;
669 		code = ((struct icmp6hdr *) user_icmph)->icmp6_code;
670 #endif
671 	} else {
672 		BUG();
673 	}
674 
675 	if (!ping_supported(family, type, code))
676 		return -EINVAL;
677 
678 	return 0;
679 }
680 EXPORT_SYMBOL_GPL(ping_common_sendmsg);
681 
682 static int ping_v4_sendmsg(struct sock *sk, struct msghdr *msg, size_t len)
683 {
684 	struct net *net = sock_net(sk);
685 	struct flowi4 fl4;
686 	struct inet_sock *inet = inet_sk(sk);
687 	struct ipcm_cookie ipc;
688 	struct icmphdr user_icmph;
689 	struct pingfakehdr pfh;
690 	struct rtable *rt = NULL;
691 	struct ip_options_data opt_copy;
692 	int free = 0;
693 	__be32 saddr, daddr, faddr;
694 	u8  tos;
695 	int err;
696 
697 	pr_debug("ping_v4_sendmsg(sk=%p,sk->num=%u)\n", inet, inet->inet_num);
698 
699 	err = ping_common_sendmsg(AF_INET, msg, len, &user_icmph,
700 				  sizeof(user_icmph));
701 	if (err)
702 		return err;
703 
704 	/*
705 	 *	Get and verify the address.
706 	 */
707 
708 	if (msg->msg_name) {
709 		DECLARE_SOCKADDR(struct sockaddr_in *, usin, msg->msg_name);
710 		if (msg->msg_namelen < sizeof(*usin))
711 			return -EINVAL;
712 		if (usin->sin_family != AF_INET)
713 			return -EAFNOSUPPORT;
714 		daddr = usin->sin_addr.s_addr;
715 		/* no remote port */
716 	} else {
717 		if (sk->sk_state != TCP_ESTABLISHED)
718 			return -EDESTADDRREQ;
719 		daddr = inet->inet_daddr;
720 		/* no remote port */
721 	}
722 
723 	ipcm_init_sk(&ipc, inet);
724 
725 	if (msg->msg_controllen) {
726 		err = ip_cmsg_send(sk, msg, &ipc, false);
727 		if (unlikely(err)) {
728 			kfree(ipc.opt);
729 			return err;
730 		}
731 		if (ipc.opt)
732 			free = 1;
733 	}
734 	if (!ipc.opt) {
735 		struct ip_options_rcu *inet_opt;
736 
737 		rcu_read_lock();
738 		inet_opt = rcu_dereference(inet->inet_opt);
739 		if (inet_opt) {
740 			memcpy(&opt_copy, inet_opt,
741 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
742 			ipc.opt = &opt_copy.opt;
743 		}
744 		rcu_read_unlock();
745 	}
746 
747 	saddr = ipc.addr;
748 	ipc.addr = faddr = daddr;
749 
750 	if (ipc.opt && ipc.opt->opt.srr) {
751 		if (!daddr) {
752 			err = -EINVAL;
753 			goto out_free;
754 		}
755 		faddr = ipc.opt->opt.faddr;
756 	}
757 	tos = get_rttos(&ipc, inet);
758 	if (sock_flag(sk, SOCK_LOCALROUTE) ||
759 	    (msg->msg_flags & MSG_DONTROUTE) ||
760 	    (ipc.opt && ipc.opt->opt.is_strictroute)) {
761 		tos |= RTO_ONLINK;
762 	}
763 
764 	if (ipv4_is_multicast(daddr)) {
765 		if (!ipc.oif || netif_index_is_l3_master(sock_net(sk), ipc.oif))
766 			ipc.oif = inet->mc_index;
767 		if (!saddr)
768 			saddr = inet->mc_addr;
769 	} else if (!ipc.oif)
770 		ipc.oif = inet->uc_index;
771 
772 	flowi4_init_output(&fl4, ipc.oif, ipc.sockc.mark, tos,
773 			   RT_SCOPE_UNIVERSE, sk->sk_protocol,
774 			   inet_sk_flowi_flags(sk), faddr, saddr, 0, 0,
775 			   sk->sk_uid);
776 
777 	fl4.fl4_icmp_type = user_icmph.type;
778 	fl4.fl4_icmp_code = user_icmph.code;
779 
780 	security_sk_classify_flow(sk, flowi4_to_flowi_common(&fl4));
781 	rt = ip_route_output_flow(net, &fl4, sk);
782 	if (IS_ERR(rt)) {
783 		err = PTR_ERR(rt);
784 		rt = NULL;
785 		if (err == -ENETUNREACH)
786 			IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
787 		goto out;
788 	}
789 
790 	err = -EACCES;
791 	if ((rt->rt_flags & RTCF_BROADCAST) &&
792 	    !sock_flag(sk, SOCK_BROADCAST))
793 		goto out;
794 
795 	if (msg->msg_flags & MSG_CONFIRM)
796 		goto do_confirm;
797 back_from_confirm:
798 
799 	if (!ipc.addr)
800 		ipc.addr = fl4.daddr;
801 
802 	lock_sock(sk);
803 
804 	pfh.icmph.type = user_icmph.type; /* already checked */
805 	pfh.icmph.code = user_icmph.code; /* ditto */
806 	pfh.icmph.checksum = 0;
807 	pfh.icmph.un.echo.id = inet->inet_sport;
808 	pfh.icmph.un.echo.sequence = user_icmph.un.echo.sequence;
809 	pfh.msg = msg;
810 	pfh.wcheck = 0;
811 	pfh.family = AF_INET;
812 
813 	err = ip_append_data(sk, &fl4, ping_getfrag, &pfh, len,
814 			0, &ipc, &rt, msg->msg_flags);
815 	if (err)
816 		ip_flush_pending_frames(sk);
817 	else
818 		err = ping_v4_push_pending_frames(sk, &pfh, &fl4);
819 	release_sock(sk);
820 
821 out:
822 	ip_rt_put(rt);
823 out_free:
824 	if (free)
825 		kfree(ipc.opt);
826 	if (!err) {
827 		icmp_out_count(sock_net(sk), user_icmph.type);
828 		return len;
829 	}
830 	return err;
831 
832 do_confirm:
833 	if (msg->msg_flags & MSG_PROBE)
834 		dst_confirm_neigh(&rt->dst, &fl4.daddr);
835 	if (!(msg->msg_flags & MSG_PROBE) || len)
836 		goto back_from_confirm;
837 	err = 0;
838 	goto out;
839 }
840 
841 int ping_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
842 		 int flags, int *addr_len)
843 {
844 	struct inet_sock *isk = inet_sk(sk);
845 	int family = sk->sk_family;
846 	struct sk_buff *skb;
847 	int copied, err;
848 
849 	pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
850 
851 	err = -EOPNOTSUPP;
852 	if (flags & MSG_OOB)
853 		goto out;
854 
855 	if (flags & MSG_ERRQUEUE)
856 		return inet_recv_error(sk, msg, len, addr_len);
857 
858 	skb = skb_recv_datagram(sk, flags, noblock, &err);
859 	if (!skb)
860 		goto out;
861 
862 	copied = skb->len;
863 	if (copied > len) {
864 		msg->msg_flags |= MSG_TRUNC;
865 		copied = len;
866 	}
867 
868 	/* Don't bother checking the checksum */
869 	err = skb_copy_datagram_msg(skb, 0, msg, copied);
870 	if (err)
871 		goto done;
872 
873 	sock_recv_timestamp(msg, sk, skb);
874 
875 	/* Copy the address and add cmsg data. */
876 	if (family == AF_INET) {
877 		DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
878 
879 		if (sin) {
880 			sin->sin_family = AF_INET;
881 			sin->sin_port = 0 /* skb->h.uh->source */;
882 			sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
883 			memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
884 			*addr_len = sizeof(*sin);
885 		}
886 
887 		if (isk->cmsg_flags)
888 			ip_cmsg_recv(msg, skb);
889 
890 #if IS_ENABLED(CONFIG_IPV6)
891 	} else if (family == AF_INET6) {
892 		struct ipv6_pinfo *np = inet6_sk(sk);
893 		struct ipv6hdr *ip6 = ipv6_hdr(skb);
894 		DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
895 
896 		if (sin6) {
897 			sin6->sin6_family = AF_INET6;
898 			sin6->sin6_port = 0;
899 			sin6->sin6_addr = ip6->saddr;
900 			sin6->sin6_flowinfo = 0;
901 			if (np->sndflow)
902 				sin6->sin6_flowinfo = ip6_flowinfo(ip6);
903 			sin6->sin6_scope_id =
904 				ipv6_iface_scope_id(&sin6->sin6_addr,
905 						    inet6_iif(skb));
906 			*addr_len = sizeof(*sin6);
907 		}
908 
909 		if (inet6_sk(sk)->rxopt.all)
910 			pingv6_ops.ip6_datagram_recv_common_ctl(sk, msg, skb);
911 		if (skb->protocol == htons(ETH_P_IPV6) &&
912 		    inet6_sk(sk)->rxopt.all)
913 			pingv6_ops.ip6_datagram_recv_specific_ctl(sk, msg, skb);
914 		else if (skb->protocol == htons(ETH_P_IP) && isk->cmsg_flags)
915 			ip_cmsg_recv(msg, skb);
916 #endif
917 	} else {
918 		BUG();
919 	}
920 
921 	err = copied;
922 
923 done:
924 	skb_free_datagram(sk, skb);
925 out:
926 	pr_debug("ping_recvmsg -> %d\n", err);
927 	return err;
928 }
929 EXPORT_SYMBOL_GPL(ping_recvmsg);
930 
931 int ping_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
932 {
933 	pr_debug("ping_queue_rcv_skb(sk=%p,sk->num=%d,skb=%p)\n",
934 		 inet_sk(sk), inet_sk(sk)->inet_num, skb);
935 	if (sock_queue_rcv_skb(sk, skb) < 0) {
936 		kfree_skb(skb);
937 		pr_debug("ping_queue_rcv_skb -> failed\n");
938 		return -1;
939 	}
940 	return 0;
941 }
942 EXPORT_SYMBOL_GPL(ping_queue_rcv_skb);
943 
944 
945 /*
946  *	All we need to do is get the socket.
947  */
948 
949 bool ping_rcv(struct sk_buff *skb)
950 {
951 	struct sock *sk;
952 	struct net *net = dev_net(skb->dev);
953 	struct icmphdr *icmph = icmp_hdr(skb);
954 	bool rc = false;
955 
956 	/* We assume the packet has already been checked by icmp_rcv */
957 
958 	pr_debug("ping_rcv(skb=%p,id=%04x,seq=%04x)\n",
959 		 skb, ntohs(icmph->un.echo.id), ntohs(icmph->un.echo.sequence));
960 
961 	/* Push ICMP header back */
962 	skb_push(skb, skb->data - (u8 *)icmph);
963 
964 	sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id));
965 	if (sk) {
966 		struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
967 
968 		pr_debug("rcv on socket %p\n", sk);
969 		if (skb2 && !ping_queue_rcv_skb(sk, skb2))
970 			rc = true;
971 		sock_put(sk);
972 	}
973 
974 	if (!rc)
975 		pr_debug("no socket, dropping\n");
976 
977 	return rc;
978 }
979 EXPORT_SYMBOL_GPL(ping_rcv);
980 
981 struct proto ping_prot = {
982 	.name =		"PING",
983 	.owner =	THIS_MODULE,
984 	.init =		ping_init_sock,
985 	.close =	ping_close,
986 	.connect =	ip4_datagram_connect,
987 	.disconnect =	__udp_disconnect,
988 	.setsockopt =	ip_setsockopt,
989 	.getsockopt =	ip_getsockopt,
990 	.sendmsg =	ping_v4_sendmsg,
991 	.recvmsg =	ping_recvmsg,
992 	.bind =		ping_bind,
993 	.backlog_rcv =	ping_queue_rcv_skb,
994 	.release_cb =	ip4_datagram_release_cb,
995 	.hash =		ping_hash,
996 	.unhash =	ping_unhash,
997 	.get_port =	ping_get_port,
998 	.put_port =	ping_unhash,
999 	.obj_size =	sizeof(struct inet_sock),
1000 };
1001 EXPORT_SYMBOL(ping_prot);
1002 
1003 #ifdef CONFIG_PROC_FS
1004 
1005 static struct sock *ping_get_first(struct seq_file *seq, int start)
1006 {
1007 	struct sock *sk;
1008 	struct ping_iter_state *state = seq->private;
1009 	struct net *net = seq_file_net(seq);
1010 
1011 	for (state->bucket = start; state->bucket < PING_HTABLE_SIZE;
1012 	     ++state->bucket) {
1013 		struct hlist_nulls_node *node;
1014 		struct hlist_nulls_head *hslot;
1015 
1016 		hslot = &ping_table.hash[state->bucket];
1017 
1018 		if (hlist_nulls_empty(hslot))
1019 			continue;
1020 
1021 		sk_nulls_for_each(sk, node, hslot) {
1022 			if (net_eq(sock_net(sk), net) &&
1023 			    sk->sk_family == state->family)
1024 				goto found;
1025 		}
1026 	}
1027 	sk = NULL;
1028 found:
1029 	return sk;
1030 }
1031 
1032 static struct sock *ping_get_next(struct seq_file *seq, struct sock *sk)
1033 {
1034 	struct ping_iter_state *state = seq->private;
1035 	struct net *net = seq_file_net(seq);
1036 
1037 	do {
1038 		sk = sk_nulls_next(sk);
1039 	} while (sk && (!net_eq(sock_net(sk), net)));
1040 
1041 	if (!sk)
1042 		return ping_get_first(seq, state->bucket + 1);
1043 	return sk;
1044 }
1045 
1046 static struct sock *ping_get_idx(struct seq_file *seq, loff_t pos)
1047 {
1048 	struct sock *sk = ping_get_first(seq, 0);
1049 
1050 	if (sk)
1051 		while (pos && (sk = ping_get_next(seq, sk)) != NULL)
1052 			--pos;
1053 	return pos ? NULL : sk;
1054 }
1055 
1056 void *ping_seq_start(struct seq_file *seq, loff_t *pos, sa_family_t family)
1057 	__acquires(ping_table.lock)
1058 {
1059 	struct ping_iter_state *state = seq->private;
1060 	state->bucket = 0;
1061 	state->family = family;
1062 
1063 	read_lock_bh(&ping_table.lock);
1064 
1065 	return *pos ? ping_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
1066 }
1067 EXPORT_SYMBOL_GPL(ping_seq_start);
1068 
1069 static void *ping_v4_seq_start(struct seq_file *seq, loff_t *pos)
1070 {
1071 	return ping_seq_start(seq, pos, AF_INET);
1072 }
1073 
1074 void *ping_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1075 {
1076 	struct sock *sk;
1077 
1078 	if (v == SEQ_START_TOKEN)
1079 		sk = ping_get_idx(seq, 0);
1080 	else
1081 		sk = ping_get_next(seq, v);
1082 
1083 	++*pos;
1084 	return sk;
1085 }
1086 EXPORT_SYMBOL_GPL(ping_seq_next);
1087 
1088 void ping_seq_stop(struct seq_file *seq, void *v)
1089 	__releases(ping_table.lock)
1090 {
1091 	read_unlock_bh(&ping_table.lock);
1092 }
1093 EXPORT_SYMBOL_GPL(ping_seq_stop);
1094 
1095 static void ping_v4_format_sock(struct sock *sp, struct seq_file *f,
1096 		int bucket)
1097 {
1098 	struct inet_sock *inet = inet_sk(sp);
1099 	__be32 dest = inet->inet_daddr;
1100 	__be32 src = inet->inet_rcv_saddr;
1101 	__u16 destp = ntohs(inet->inet_dport);
1102 	__u16 srcp = ntohs(inet->inet_sport);
1103 
1104 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
1105 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %u",
1106 		bucket, src, srcp, dest, destp, sp->sk_state,
1107 		sk_wmem_alloc_get(sp),
1108 		sk_rmem_alloc_get(sp),
1109 		0, 0L, 0,
1110 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
1111 		0, sock_i_ino(sp),
1112 		refcount_read(&sp->sk_refcnt), sp,
1113 		atomic_read(&sp->sk_drops));
1114 }
1115 
1116 static int ping_v4_seq_show(struct seq_file *seq, void *v)
1117 {
1118 	seq_setwidth(seq, 127);
1119 	if (v == SEQ_START_TOKEN)
1120 		seq_puts(seq, "  sl  local_address rem_address   st tx_queue "
1121 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
1122 			   "inode ref pointer drops");
1123 	else {
1124 		struct ping_iter_state *state = seq->private;
1125 
1126 		ping_v4_format_sock(v, seq, state->bucket);
1127 	}
1128 	seq_pad(seq, '\n');
1129 	return 0;
1130 }
1131 
1132 static const struct seq_operations ping_v4_seq_ops = {
1133 	.start		= ping_v4_seq_start,
1134 	.show		= ping_v4_seq_show,
1135 	.next		= ping_seq_next,
1136 	.stop		= ping_seq_stop,
1137 };
1138 
1139 static int __net_init ping_v4_proc_init_net(struct net *net)
1140 {
1141 	if (!proc_create_net("icmp", 0444, net->proc_net, &ping_v4_seq_ops,
1142 			sizeof(struct ping_iter_state)))
1143 		return -ENOMEM;
1144 	return 0;
1145 }
1146 
1147 static void __net_exit ping_v4_proc_exit_net(struct net *net)
1148 {
1149 	remove_proc_entry("icmp", net->proc_net);
1150 }
1151 
1152 static struct pernet_operations ping_v4_net_ops = {
1153 	.init = ping_v4_proc_init_net,
1154 	.exit = ping_v4_proc_exit_net,
1155 };
1156 
1157 int __init ping_proc_init(void)
1158 {
1159 	return register_pernet_subsys(&ping_v4_net_ops);
1160 }
1161 
1162 void ping_proc_exit(void)
1163 {
1164 	unregister_pernet_subsys(&ping_v4_net_ops);
1165 }
1166 
1167 #endif
1168 
1169 void __init ping_init(void)
1170 {
1171 	int i;
1172 
1173 	for (i = 0; i < PING_HTABLE_SIZE; i++)
1174 		INIT_HLIST_NULLS_HEAD(&ping_table.hash[i], i);
1175 	rwlock_init(&ping_table.lock);
1176 }
1177