xref: /linux/net/ipv4/ping.c (revision 2d87650a3bf1b80f7d0d150ee1af3f8a89e5b7aa)
1 /*
2  * INET		An implementation of the TCP/IP protocol suite for the LINUX
3  *		operating system.  INET is implemented using the  BSD Socket
4  *		interface as the means of communication with the user level.
5  *
6  *		"Ping" sockets
7  *
8  *		This program is free software; you can redistribute it and/or
9  *		modify it under the terms of the GNU General Public License
10  *		as published by the Free Software Foundation; either version
11  *		2 of the License, or (at your option) any later version.
12  *
13  * Based on ipv4/udp.c code.
14  *
15  * Authors:	Vasiliy Kulikov / Openwall (for Linux 2.6),
16  *		Pavel Kankovsky (for Linux 2.4.32)
17  *
18  * Pavel gave all rights to bugs to Vasiliy,
19  * none of the bugs are Pavel's now.
20  *
21  */
22 
23 #include <linux/uaccess.h>
24 #include <linux/types.h>
25 #include <linux/fcntl.h>
26 #include <linux/socket.h>
27 #include <linux/sockios.h>
28 #include <linux/in.h>
29 #include <linux/errno.h>
30 #include <linux/timer.h>
31 #include <linux/mm.h>
32 #include <linux/inet.h>
33 #include <linux/netdevice.h>
34 #include <net/snmp.h>
35 #include <net/ip.h>
36 #include <net/icmp.h>
37 #include <net/protocol.h>
38 #include <linux/skbuff.h>
39 #include <linux/proc_fs.h>
40 #include <linux/export.h>
41 #include <net/sock.h>
42 #include <net/ping.h>
43 #include <net/udp.h>
44 #include <net/route.h>
45 #include <net/inet_common.h>
46 #include <net/checksum.h>
47 
48 #if IS_ENABLED(CONFIG_IPV6)
49 #include <linux/in6.h>
50 #include <linux/icmpv6.h>
51 #include <net/addrconf.h>
52 #include <net/ipv6.h>
53 #include <net/transp_v6.h>
54 #endif
55 
56 struct ping_table {
57 	struct hlist_nulls_head	hash[PING_HTABLE_SIZE];
58 	rwlock_t		lock;
59 };
60 
61 static struct ping_table ping_table;
62 struct pingv6_ops pingv6_ops;
63 EXPORT_SYMBOL_GPL(pingv6_ops);
64 
65 static u16 ping_port_rover;
66 
67 static inline int ping_hashfn(struct net *net, unsigned int num, unsigned int mask)
68 {
69 	int res = (num + net_hash_mix(net)) & mask;
70 
71 	pr_debug("hash(%d) = %d\n", num, res);
72 	return res;
73 }
74 EXPORT_SYMBOL_GPL(ping_hash);
75 
76 static inline struct hlist_nulls_head *ping_hashslot(struct ping_table *table,
77 					     struct net *net, unsigned int num)
78 {
79 	return &table->hash[ping_hashfn(net, num, PING_HTABLE_MASK)];
80 }
81 
82 int ping_get_port(struct sock *sk, unsigned short ident)
83 {
84 	struct hlist_nulls_node *node;
85 	struct hlist_nulls_head *hlist;
86 	struct inet_sock *isk, *isk2;
87 	struct sock *sk2 = NULL;
88 
89 	isk = inet_sk(sk);
90 	write_lock_bh(&ping_table.lock);
91 	if (ident == 0) {
92 		u32 i;
93 		u16 result = ping_port_rover + 1;
94 
95 		for (i = 0; i < (1L << 16); i++, result++) {
96 			if (!result)
97 				result++; /* avoid zero */
98 			hlist = ping_hashslot(&ping_table, sock_net(sk),
99 					    result);
100 			ping_portaddr_for_each_entry(sk2, node, hlist) {
101 				isk2 = inet_sk(sk2);
102 
103 				if (isk2->inet_num == result)
104 					goto next_port;
105 			}
106 
107 			/* found */
108 			ping_port_rover = ident = result;
109 			break;
110 next_port:
111 			;
112 		}
113 		if (i >= (1L << 16))
114 			goto fail;
115 	} else {
116 		hlist = ping_hashslot(&ping_table, sock_net(sk), ident);
117 		ping_portaddr_for_each_entry(sk2, node, hlist) {
118 			isk2 = inet_sk(sk2);
119 
120 			/* BUG? Why is this reuse and not reuseaddr? ping.c
121 			 * doesn't turn off SO_REUSEADDR, and it doesn't expect
122 			 * that other ping processes can steal its packets.
123 			 */
124 			if ((isk2->inet_num == ident) &&
125 			    (sk2 != sk) &&
126 			    (!sk2->sk_reuse || !sk->sk_reuse))
127 				goto fail;
128 		}
129 	}
130 
131 	pr_debug("found port/ident = %d\n", ident);
132 	isk->inet_num = ident;
133 	if (sk_unhashed(sk)) {
134 		pr_debug("was not hashed\n");
135 		sock_hold(sk);
136 		hlist_nulls_add_head(&sk->sk_nulls_node, hlist);
137 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
138 	}
139 	write_unlock_bh(&ping_table.lock);
140 	return 0;
141 
142 fail:
143 	write_unlock_bh(&ping_table.lock);
144 	return 1;
145 }
146 EXPORT_SYMBOL_GPL(ping_get_port);
147 
148 void ping_hash(struct sock *sk)
149 {
150 	pr_debug("ping_hash(sk->port=%u)\n", inet_sk(sk)->inet_num);
151 	BUG(); /* "Please do not press this button again." */
152 }
153 
154 void ping_unhash(struct sock *sk)
155 {
156 	struct inet_sock *isk = inet_sk(sk);
157 	pr_debug("ping_unhash(isk=%p,isk->num=%u)\n", isk, isk->inet_num);
158 	if (sk_hashed(sk)) {
159 		write_lock_bh(&ping_table.lock);
160 		hlist_nulls_del(&sk->sk_nulls_node);
161 		sock_put(sk);
162 		isk->inet_num = 0;
163 		isk->inet_sport = 0;
164 		sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
165 		write_unlock_bh(&ping_table.lock);
166 	}
167 }
168 EXPORT_SYMBOL_GPL(ping_unhash);
169 
170 static struct sock *ping_lookup(struct net *net, struct sk_buff *skb, u16 ident)
171 {
172 	struct hlist_nulls_head *hslot = ping_hashslot(&ping_table, net, ident);
173 	struct sock *sk = NULL;
174 	struct inet_sock *isk;
175 	struct hlist_nulls_node *hnode;
176 	int dif = skb->dev->ifindex;
177 
178 	if (skb->protocol == htons(ETH_P_IP)) {
179 		pr_debug("try to find: num = %d, daddr = %pI4, dif = %d\n",
180 			 (int)ident, &ip_hdr(skb)->daddr, dif);
181 #if IS_ENABLED(CONFIG_IPV6)
182 	} else if (skb->protocol == htons(ETH_P_IPV6)) {
183 		pr_debug("try to find: num = %d, daddr = %pI6c, dif = %d\n",
184 			 (int)ident, &ipv6_hdr(skb)->daddr, dif);
185 #endif
186 	}
187 
188 	read_lock_bh(&ping_table.lock);
189 
190 	ping_portaddr_for_each_entry(sk, hnode, hslot) {
191 		isk = inet_sk(sk);
192 
193 		pr_debug("iterate\n");
194 		if (isk->inet_num != ident)
195 			continue;
196 
197 		if (skb->protocol == htons(ETH_P_IP) &&
198 		    sk->sk_family == AF_INET) {
199 			pr_debug("found: %p: num=%d, daddr=%pI4, dif=%d\n", sk,
200 				 (int) isk->inet_num, &isk->inet_rcv_saddr,
201 				 sk->sk_bound_dev_if);
202 
203 			if (isk->inet_rcv_saddr &&
204 			    isk->inet_rcv_saddr != ip_hdr(skb)->daddr)
205 				continue;
206 #if IS_ENABLED(CONFIG_IPV6)
207 		} else if (skb->protocol == htons(ETH_P_IPV6) &&
208 			   sk->sk_family == AF_INET6) {
209 
210 			pr_debug("found: %p: num=%d, daddr=%pI6c, dif=%d\n", sk,
211 				 (int) isk->inet_num,
212 				 &sk->sk_v6_rcv_saddr,
213 				 sk->sk_bound_dev_if);
214 
215 			if (!ipv6_addr_any(&sk->sk_v6_rcv_saddr) &&
216 			    !ipv6_addr_equal(&sk->sk_v6_rcv_saddr,
217 					     &ipv6_hdr(skb)->daddr))
218 				continue;
219 #endif
220 		}
221 
222 		if (sk->sk_bound_dev_if && sk->sk_bound_dev_if != dif)
223 			continue;
224 
225 		sock_hold(sk);
226 		goto exit;
227 	}
228 
229 	sk = NULL;
230 exit:
231 	read_unlock_bh(&ping_table.lock);
232 
233 	return sk;
234 }
235 
236 static void inet_get_ping_group_range_net(struct net *net, kgid_t *low,
237 					  kgid_t *high)
238 {
239 	kgid_t *data = net->ipv4.sysctl_ping_group_range;
240 	unsigned int seq;
241 
242 	do {
243 		seq = read_seqbegin(&net->ipv4.sysctl_local_ports.lock);
244 
245 		*low = data[0];
246 		*high = data[1];
247 	} while (read_seqretry(&net->ipv4.sysctl_local_ports.lock, seq));
248 }
249 
250 
251 int ping_init_sock(struct sock *sk)
252 {
253 	struct net *net = sock_net(sk);
254 	kgid_t group = current_egid();
255 	struct group_info *group_info = get_current_groups();
256 	int i, j, count = group_info->ngroups;
257 	kgid_t low, high;
258 
259 	inet_get_ping_group_range_net(net, &low, &high);
260 	if (gid_lte(low, group) && gid_lte(group, high))
261 		return 0;
262 
263 	for (i = 0; i < group_info->nblocks; i++) {
264 		int cp_count = min_t(int, NGROUPS_PER_BLOCK, count);
265 		for (j = 0; j < cp_count; j++) {
266 			kgid_t gid = group_info->blocks[i][j];
267 			if (gid_lte(low, gid) && gid_lte(gid, high))
268 				return 0;
269 		}
270 
271 		count -= cp_count;
272 	}
273 
274 	return -EACCES;
275 }
276 EXPORT_SYMBOL_GPL(ping_init_sock);
277 
278 void ping_close(struct sock *sk, long timeout)
279 {
280 	pr_debug("ping_close(sk=%p,sk->num=%u)\n",
281 		 inet_sk(sk), inet_sk(sk)->inet_num);
282 	pr_debug("isk->refcnt = %d\n", sk->sk_refcnt.counter);
283 
284 	sk_common_release(sk);
285 }
286 EXPORT_SYMBOL_GPL(ping_close);
287 
288 /* Checks the bind address and possibly modifies sk->sk_bound_dev_if. */
289 static int ping_check_bind_addr(struct sock *sk, struct inet_sock *isk,
290 				struct sockaddr *uaddr, int addr_len) {
291 	struct net *net = sock_net(sk);
292 	if (sk->sk_family == AF_INET) {
293 		struct sockaddr_in *addr = (struct sockaddr_in *) uaddr;
294 		int chk_addr_ret;
295 
296 		if (addr_len < sizeof(*addr))
297 			return -EINVAL;
298 
299 		pr_debug("ping_check_bind_addr(sk=%p,addr=%pI4,port=%d)\n",
300 			 sk, &addr->sin_addr.s_addr, ntohs(addr->sin_port));
301 
302 		chk_addr_ret = inet_addr_type(net, addr->sin_addr.s_addr);
303 
304 		if (addr->sin_addr.s_addr == htonl(INADDR_ANY))
305 			chk_addr_ret = RTN_LOCAL;
306 
307 		if ((sysctl_ip_nonlocal_bind == 0 &&
308 		    isk->freebind == 0 && isk->transparent == 0 &&
309 		     chk_addr_ret != RTN_LOCAL) ||
310 		    chk_addr_ret == RTN_MULTICAST ||
311 		    chk_addr_ret == RTN_BROADCAST)
312 			return -EADDRNOTAVAIL;
313 
314 #if IS_ENABLED(CONFIG_IPV6)
315 	} else if (sk->sk_family == AF_INET6) {
316 		struct sockaddr_in6 *addr = (struct sockaddr_in6 *) uaddr;
317 		int addr_type, scoped, has_addr;
318 		struct net_device *dev = NULL;
319 
320 		if (addr_len < sizeof(*addr))
321 			return -EINVAL;
322 
323 		pr_debug("ping_check_bind_addr(sk=%p,addr=%pI6c,port=%d)\n",
324 			 sk, addr->sin6_addr.s6_addr, ntohs(addr->sin6_port));
325 
326 		addr_type = ipv6_addr_type(&addr->sin6_addr);
327 		scoped = __ipv6_addr_needs_scope_id(addr_type);
328 		if ((addr_type != IPV6_ADDR_ANY &&
329 		     !(addr_type & IPV6_ADDR_UNICAST)) ||
330 		    (scoped && !addr->sin6_scope_id))
331 			return -EINVAL;
332 
333 		rcu_read_lock();
334 		if (addr->sin6_scope_id) {
335 			dev = dev_get_by_index_rcu(net, addr->sin6_scope_id);
336 			if (!dev) {
337 				rcu_read_unlock();
338 				return -ENODEV;
339 			}
340 		}
341 		has_addr = pingv6_ops.ipv6_chk_addr(net, &addr->sin6_addr, dev,
342 						    scoped);
343 		rcu_read_unlock();
344 
345 		if (!(isk->freebind || isk->transparent || has_addr ||
346 		      addr_type == IPV6_ADDR_ANY))
347 			return -EADDRNOTAVAIL;
348 
349 		if (scoped)
350 			sk->sk_bound_dev_if = addr->sin6_scope_id;
351 #endif
352 	} else {
353 		return -EAFNOSUPPORT;
354 	}
355 	return 0;
356 }
357 
358 static void ping_set_saddr(struct sock *sk, struct sockaddr *saddr)
359 {
360 	if (saddr->sa_family == AF_INET) {
361 		struct inet_sock *isk = inet_sk(sk);
362 		struct sockaddr_in *addr = (struct sockaddr_in *) saddr;
363 		isk->inet_rcv_saddr = isk->inet_saddr = addr->sin_addr.s_addr;
364 #if IS_ENABLED(CONFIG_IPV6)
365 	} else if (saddr->sa_family == AF_INET6) {
366 		struct sockaddr_in6 *addr = (struct sockaddr_in6 *) saddr;
367 		struct ipv6_pinfo *np = inet6_sk(sk);
368 		sk->sk_v6_rcv_saddr = np->saddr = addr->sin6_addr;
369 #endif
370 	}
371 }
372 
373 static void ping_clear_saddr(struct sock *sk, int dif)
374 {
375 	sk->sk_bound_dev_if = dif;
376 	if (sk->sk_family == AF_INET) {
377 		struct inet_sock *isk = inet_sk(sk);
378 		isk->inet_rcv_saddr = isk->inet_saddr = 0;
379 #if IS_ENABLED(CONFIG_IPV6)
380 	} else if (sk->sk_family == AF_INET6) {
381 		struct ipv6_pinfo *np = inet6_sk(sk);
382 		memset(&sk->sk_v6_rcv_saddr, 0, sizeof(sk->sk_v6_rcv_saddr));
383 		memset(&np->saddr, 0, sizeof(np->saddr));
384 #endif
385 	}
386 }
387 /*
388  * We need our own bind because there are no privileged id's == local ports.
389  * Moreover, we don't allow binding to multi- and broadcast addresses.
390  */
391 
392 int ping_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
393 {
394 	struct inet_sock *isk = inet_sk(sk);
395 	unsigned short snum;
396 	int err;
397 	int dif = sk->sk_bound_dev_if;
398 
399 	err = ping_check_bind_addr(sk, isk, uaddr, addr_len);
400 	if (err)
401 		return err;
402 
403 	lock_sock(sk);
404 
405 	err = -EINVAL;
406 	if (isk->inet_num != 0)
407 		goto out;
408 
409 	err = -EADDRINUSE;
410 	ping_set_saddr(sk, uaddr);
411 	snum = ntohs(((struct sockaddr_in *)uaddr)->sin_port);
412 	if (ping_get_port(sk, snum) != 0) {
413 		ping_clear_saddr(sk, dif);
414 		goto out;
415 	}
416 
417 	pr_debug("after bind(): num = %d, dif = %d\n",
418 		 (int)isk->inet_num,
419 		 (int)sk->sk_bound_dev_if);
420 
421 	err = 0;
422 	if (sk->sk_family == AF_INET && isk->inet_rcv_saddr)
423 		sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
424 #if IS_ENABLED(CONFIG_IPV6)
425 	if (sk->sk_family == AF_INET6 && !ipv6_addr_any(&sk->sk_v6_rcv_saddr))
426 		sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
427 #endif
428 
429 	if (snum)
430 		sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
431 	isk->inet_sport = htons(isk->inet_num);
432 	isk->inet_daddr = 0;
433 	isk->inet_dport = 0;
434 
435 #if IS_ENABLED(CONFIG_IPV6)
436 	if (sk->sk_family == AF_INET6)
437 		memset(&sk->sk_v6_daddr, 0, sizeof(sk->sk_v6_daddr));
438 #endif
439 
440 	sk_dst_reset(sk);
441 out:
442 	release_sock(sk);
443 	pr_debug("ping_v4_bind -> %d\n", err);
444 	return err;
445 }
446 EXPORT_SYMBOL_GPL(ping_bind);
447 
448 /*
449  * Is this a supported type of ICMP message?
450  */
451 
452 static inline int ping_supported(int family, int type, int code)
453 {
454 	return (family == AF_INET && type == ICMP_ECHO && code == 0) ||
455 	       (family == AF_INET6 && type == ICMPV6_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 == NULL) {
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->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 		if (fraglen < sizeof(struct icmphdr))
591 			BUG();
592 		if (csum_partial_copy_fromiovecend(to + sizeof(struct icmphdr),
593 			    pfh->iov, 0, fraglen - sizeof(struct icmphdr),
594 			    &pfh->wcheck))
595 			return -EFAULT;
596 	} else if (offset < sizeof(struct icmphdr)) {
597 			BUG();
598 	} else {
599 		if (csum_partial_copy_fromiovecend
600 				(to, pfh->iov, offset - sizeof(struct icmphdr),
601 				 fraglen, &pfh->wcheck))
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 	pfh->wcheck = csum_partial((char *)&pfh->icmph,
627 		sizeof(struct icmphdr), pfh->wcheck);
628 	pfh->icmph.checksum = csum_fold(pfh->wcheck);
629 	memcpy(icmp_hdr(skb), &pfh->icmph, sizeof(struct icmphdr));
630 	skb->ip_summed = CHECKSUM_NONE;
631 	return ip_push_pending_frames(sk, fl4);
632 }
633 
634 int ping_common_sendmsg(int family, struct msghdr *msg, size_t len,
635 			void *user_icmph, size_t icmph_len) {
636 	u8 type, code;
637 
638 	if (len > 0xFFFF)
639 		return -EMSGSIZE;
640 
641 	/*
642 	 *	Check the flags.
643 	 */
644 
645 	/* Mirror BSD error message compatibility */
646 	if (msg->msg_flags & MSG_OOB)
647 		return -EOPNOTSUPP;
648 
649 	/*
650 	 *	Fetch the ICMP header provided by the userland.
651 	 *	iovec is modified! The ICMP header is consumed.
652 	 */
653 	if (memcpy_fromiovec(user_icmph, msg->msg_iov, icmph_len))
654 		return -EFAULT;
655 
656 	if (family == AF_INET) {
657 		type = ((struct icmphdr *) user_icmph)->type;
658 		code = ((struct icmphdr *) user_icmph)->code;
659 #if IS_ENABLED(CONFIG_IPV6)
660 	} else if (family == AF_INET6) {
661 		type = ((struct icmp6hdr *) user_icmph)->icmp6_type;
662 		code = ((struct icmp6hdr *) user_icmph)->icmp6_code;
663 #endif
664 	} else {
665 		BUG();
666 	}
667 
668 	if (!ping_supported(family, type, code))
669 		return -EINVAL;
670 
671 	return 0;
672 }
673 EXPORT_SYMBOL_GPL(ping_common_sendmsg);
674 
675 static int ping_v4_sendmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
676 			   size_t len)
677 {
678 	struct net *net = sock_net(sk);
679 	struct flowi4 fl4;
680 	struct inet_sock *inet = inet_sk(sk);
681 	struct ipcm_cookie ipc;
682 	struct icmphdr user_icmph;
683 	struct pingfakehdr pfh;
684 	struct rtable *rt = NULL;
685 	struct ip_options_data opt_copy;
686 	int free = 0;
687 	__be32 saddr, daddr, faddr;
688 	u8  tos;
689 	int err;
690 
691 	pr_debug("ping_v4_sendmsg(sk=%p,sk->num=%u)\n", inet, inet->inet_num);
692 
693 	err = ping_common_sendmsg(AF_INET, msg, len, &user_icmph,
694 				  sizeof(user_icmph));
695 	if (err)
696 		return err;
697 
698 	/*
699 	 *	Get and verify the address.
700 	 */
701 
702 	if (msg->msg_name) {
703 		struct sockaddr_in *usin = (struct sockaddr_in *)msg->msg_name;
704 		if (msg->msg_namelen < sizeof(*usin))
705 			return -EINVAL;
706 		if (usin->sin_family != AF_INET)
707 			return -EINVAL;
708 		daddr = usin->sin_addr.s_addr;
709 		/* no remote port */
710 	} else {
711 		if (sk->sk_state != TCP_ESTABLISHED)
712 			return -EDESTADDRREQ;
713 		daddr = inet->inet_daddr;
714 		/* no remote port */
715 	}
716 
717 	ipc.addr = inet->inet_saddr;
718 	ipc.opt = NULL;
719 	ipc.oif = sk->sk_bound_dev_if;
720 	ipc.tx_flags = 0;
721 	ipc.ttl = 0;
722 	ipc.tos = -1;
723 
724 	sock_tx_timestamp(sk, &ipc.tx_flags);
725 
726 	if (msg->msg_controllen) {
727 		err = ip_cmsg_send(sock_net(sk), msg, &ipc);
728 		if (err)
729 			return err;
730 		if (ipc.opt)
731 			free = 1;
732 	}
733 	if (!ipc.opt) {
734 		struct ip_options_rcu *inet_opt;
735 
736 		rcu_read_lock();
737 		inet_opt = rcu_dereference(inet->inet_opt);
738 		if (inet_opt) {
739 			memcpy(&opt_copy, inet_opt,
740 			       sizeof(*inet_opt) + inet_opt->opt.optlen);
741 			ipc.opt = &opt_copy.opt;
742 		}
743 		rcu_read_unlock();
744 	}
745 
746 	saddr = ipc.addr;
747 	ipc.addr = faddr = daddr;
748 
749 	if (ipc.opt && ipc.opt->opt.srr) {
750 		if (!daddr)
751 			return -EINVAL;
752 		faddr = ipc.opt->opt.faddr;
753 	}
754 	tos = get_rttos(&ipc, inet);
755 	if (sock_flag(sk, SOCK_LOCALROUTE) ||
756 	    (msg->msg_flags & MSG_DONTROUTE) ||
757 	    (ipc.opt && ipc.opt->opt.is_strictroute)) {
758 		tos |= RTO_ONLINK;
759 	}
760 
761 	if (ipv4_is_multicast(daddr)) {
762 		if (!ipc.oif)
763 			ipc.oif = inet->mc_index;
764 		if (!saddr)
765 			saddr = inet->mc_addr;
766 	} else if (!ipc.oif)
767 		ipc.oif = inet->uc_index;
768 
769 	flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
770 			   RT_SCOPE_UNIVERSE, sk->sk_protocol,
771 			   inet_sk_flowi_flags(sk), faddr, saddr, 0, 0);
772 
773 	security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
774 	rt = ip_route_output_flow(net, &fl4, sk);
775 	if (IS_ERR(rt)) {
776 		err = PTR_ERR(rt);
777 		rt = NULL;
778 		if (err == -ENETUNREACH)
779 			IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
780 		goto out;
781 	}
782 
783 	err = -EACCES;
784 	if ((rt->rt_flags & RTCF_BROADCAST) &&
785 	    !sock_flag(sk, SOCK_BROADCAST))
786 		goto out;
787 
788 	if (msg->msg_flags & MSG_CONFIRM)
789 		goto do_confirm;
790 back_from_confirm:
791 
792 	if (!ipc.addr)
793 		ipc.addr = fl4.daddr;
794 
795 	lock_sock(sk);
796 
797 	pfh.icmph.type = user_icmph.type; /* already checked */
798 	pfh.icmph.code = user_icmph.code; /* ditto */
799 	pfh.icmph.checksum = 0;
800 	pfh.icmph.un.echo.id = inet->inet_sport;
801 	pfh.icmph.un.echo.sequence = user_icmph.un.echo.sequence;
802 	pfh.iov = msg->msg_iov;
803 	pfh.wcheck = 0;
804 	pfh.family = AF_INET;
805 
806 	err = ip_append_data(sk, &fl4, ping_getfrag, &pfh, len,
807 			0, &ipc, &rt, msg->msg_flags);
808 	if (err)
809 		ip_flush_pending_frames(sk);
810 	else
811 		err = ping_v4_push_pending_frames(sk, &pfh, &fl4);
812 	release_sock(sk);
813 
814 out:
815 	ip_rt_put(rt);
816 	if (free)
817 		kfree(ipc.opt);
818 	if (!err) {
819 		icmp_out_count(sock_net(sk), user_icmph.type);
820 		return len;
821 	}
822 	return err;
823 
824 do_confirm:
825 	dst_confirm(&rt->dst);
826 	if (!(msg->msg_flags & MSG_PROBE) || len)
827 		goto back_from_confirm;
828 	err = 0;
829 	goto out;
830 }
831 
832 int ping_recvmsg(struct kiocb *iocb, struct sock *sk, struct msghdr *msg,
833 		 size_t len, int noblock, int flags, int *addr_len)
834 {
835 	struct inet_sock *isk = inet_sk(sk);
836 	int family = sk->sk_family;
837 	struct sk_buff *skb;
838 	int copied, err;
839 
840 	pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
841 
842 	err = -EOPNOTSUPP;
843 	if (flags & MSG_OOB)
844 		goto out;
845 
846 	if (flags & MSG_ERRQUEUE) {
847 		if (family == AF_INET) {
848 			return ip_recv_error(sk, msg, len, addr_len);
849 #if IS_ENABLED(CONFIG_IPV6)
850 		} else if (family == AF_INET6) {
851 			return pingv6_ops.ipv6_recv_error(sk, msg, len,
852 							  addr_len);
853 #endif
854 		}
855 	}
856 
857 	skb = skb_recv_datagram(sk, flags, noblock, &err);
858 	if (!skb)
859 		goto out;
860 
861 	copied = skb->len;
862 	if (copied > len) {
863 		msg->msg_flags |= MSG_TRUNC;
864 		copied = len;
865 	}
866 
867 	/* Don't bother checking the checksum */
868 	err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
869 	if (err)
870 		goto done;
871 
872 	sock_recv_timestamp(msg, sk, skb);
873 
874 	/* Copy the address and add cmsg data. */
875 	if (family == AF_INET) {
876 		struct sockaddr_in *sin = (struct sockaddr_in *)msg->msg_name;
877 
878 		if (sin) {
879 			sin->sin_family = AF_INET;
880 			sin->sin_port = 0 /* skb->h.uh->source */;
881 			sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
882 			memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
883 			*addr_len = sizeof(*sin);
884 		}
885 
886 		if (isk->cmsg_flags)
887 			ip_cmsg_recv(msg, skb);
888 
889 #if IS_ENABLED(CONFIG_IPV6)
890 	} else if (family == AF_INET6) {
891 		struct ipv6_pinfo *np = inet6_sk(sk);
892 		struct ipv6hdr *ip6 = ipv6_hdr(skb);
893 		struct sockaddr_in6 *sin6 =
894 			(struct sockaddr_in6 *)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 						    IP6CB(skb)->iif);
906 			*addr_len = sizeof(*sin6);
907 		}
908 
909 		if (inet6_sk(sk)->rxopt.all)
910 			pingv6_ops.ip6_datagram_recv_ctl(sk, msg, skb);
911 #endif
912 	} else {
913 		BUG();
914 	}
915 
916 	err = copied;
917 
918 done:
919 	skb_free_datagram(sk, skb);
920 out:
921 	pr_debug("ping_recvmsg -> %d\n", err);
922 	return err;
923 }
924 EXPORT_SYMBOL_GPL(ping_recvmsg);
925 
926 int ping_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
927 {
928 	pr_debug("ping_queue_rcv_skb(sk=%p,sk->num=%d,skb=%p)\n",
929 		 inet_sk(sk), inet_sk(sk)->inet_num, skb);
930 	if (sock_queue_rcv_skb(sk, skb) < 0) {
931 		kfree_skb(skb);
932 		pr_debug("ping_queue_rcv_skb -> failed\n");
933 		return -1;
934 	}
935 	return 0;
936 }
937 EXPORT_SYMBOL_GPL(ping_queue_rcv_skb);
938 
939 
940 /*
941  *	All we need to do is get the socket.
942  */
943 
944 void ping_rcv(struct sk_buff *skb)
945 {
946 	struct sock *sk;
947 	struct net *net = dev_net(skb->dev);
948 	struct icmphdr *icmph = icmp_hdr(skb);
949 
950 	/* We assume the packet has already been checked by icmp_rcv */
951 
952 	pr_debug("ping_rcv(skb=%p,id=%04x,seq=%04x)\n",
953 		 skb, ntohs(icmph->un.echo.id), ntohs(icmph->un.echo.sequence));
954 
955 	/* Push ICMP header back */
956 	skb_push(skb, skb->data - (u8 *)icmph);
957 
958 	sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id));
959 	if (sk != NULL) {
960 		pr_debug("rcv on socket %p\n", sk);
961 		ping_queue_rcv_skb(sk, skb_get(skb));
962 		sock_put(sk);
963 		return;
964 	}
965 	pr_debug("no socket, dropping\n");
966 
967 	/* We're called from icmp_rcv(). kfree_skb() is done there. */
968 }
969 EXPORT_SYMBOL_GPL(ping_rcv);
970 
971 struct proto ping_prot = {
972 	.name =		"PING",
973 	.owner =	THIS_MODULE,
974 	.init =		ping_init_sock,
975 	.close =	ping_close,
976 	.connect =	ip4_datagram_connect,
977 	.disconnect =	udp_disconnect,
978 	.setsockopt =	ip_setsockopt,
979 	.getsockopt =	ip_getsockopt,
980 	.sendmsg =	ping_v4_sendmsg,
981 	.recvmsg =	ping_recvmsg,
982 	.bind =		ping_bind,
983 	.backlog_rcv =	ping_queue_rcv_skb,
984 	.release_cb =	ip4_datagram_release_cb,
985 	.hash =		ping_hash,
986 	.unhash =	ping_unhash,
987 	.get_port =	ping_get_port,
988 	.obj_size =	sizeof(struct inet_sock),
989 };
990 EXPORT_SYMBOL(ping_prot);
991 
992 #ifdef CONFIG_PROC_FS
993 
994 static struct sock *ping_get_first(struct seq_file *seq, int start)
995 {
996 	struct sock *sk;
997 	struct ping_iter_state *state = seq->private;
998 	struct net *net = seq_file_net(seq);
999 
1000 	for (state->bucket = start; state->bucket < PING_HTABLE_SIZE;
1001 	     ++state->bucket) {
1002 		struct hlist_nulls_node *node;
1003 		struct hlist_nulls_head *hslot;
1004 
1005 		hslot = &ping_table.hash[state->bucket];
1006 
1007 		if (hlist_nulls_empty(hslot))
1008 			continue;
1009 
1010 		sk_nulls_for_each(sk, node, hslot) {
1011 			if (net_eq(sock_net(sk), net) &&
1012 			    sk->sk_family == state->family)
1013 				goto found;
1014 		}
1015 	}
1016 	sk = NULL;
1017 found:
1018 	return sk;
1019 }
1020 
1021 static struct sock *ping_get_next(struct seq_file *seq, struct sock *sk)
1022 {
1023 	struct ping_iter_state *state = seq->private;
1024 	struct net *net = seq_file_net(seq);
1025 
1026 	do {
1027 		sk = sk_nulls_next(sk);
1028 	} while (sk && (!net_eq(sock_net(sk), net)));
1029 
1030 	if (!sk)
1031 		return ping_get_first(seq, state->bucket + 1);
1032 	return sk;
1033 }
1034 
1035 static struct sock *ping_get_idx(struct seq_file *seq, loff_t pos)
1036 {
1037 	struct sock *sk = ping_get_first(seq, 0);
1038 
1039 	if (sk)
1040 		while (pos && (sk = ping_get_next(seq, sk)) != NULL)
1041 			--pos;
1042 	return pos ? NULL : sk;
1043 }
1044 
1045 void *ping_seq_start(struct seq_file *seq, loff_t *pos, sa_family_t family)
1046 {
1047 	struct ping_iter_state *state = seq->private;
1048 	state->bucket = 0;
1049 	state->family = family;
1050 
1051 	read_lock_bh(&ping_table.lock);
1052 
1053 	return *pos ? ping_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
1054 }
1055 EXPORT_SYMBOL_GPL(ping_seq_start);
1056 
1057 static void *ping_v4_seq_start(struct seq_file *seq, loff_t *pos)
1058 {
1059 	return ping_seq_start(seq, pos, AF_INET);
1060 }
1061 
1062 void *ping_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1063 {
1064 	struct sock *sk;
1065 
1066 	if (v == SEQ_START_TOKEN)
1067 		sk = ping_get_idx(seq, 0);
1068 	else
1069 		sk = ping_get_next(seq, v);
1070 
1071 	++*pos;
1072 	return sk;
1073 }
1074 EXPORT_SYMBOL_GPL(ping_seq_next);
1075 
1076 void ping_seq_stop(struct seq_file *seq, void *v)
1077 {
1078 	read_unlock_bh(&ping_table.lock);
1079 }
1080 EXPORT_SYMBOL_GPL(ping_seq_stop);
1081 
1082 static void ping_v4_format_sock(struct sock *sp, struct seq_file *f,
1083 		int bucket)
1084 {
1085 	struct inet_sock *inet = inet_sk(sp);
1086 	__be32 dest = inet->inet_daddr;
1087 	__be32 src = inet->inet_rcv_saddr;
1088 	__u16 destp = ntohs(inet->inet_dport);
1089 	__u16 srcp = ntohs(inet->inet_sport);
1090 
1091 	seq_printf(f, "%5d: %08X:%04X %08X:%04X"
1092 		" %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d",
1093 		bucket, src, srcp, dest, destp, sp->sk_state,
1094 		sk_wmem_alloc_get(sp),
1095 		sk_rmem_alloc_get(sp),
1096 		0, 0L, 0,
1097 		from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
1098 		0, sock_i_ino(sp),
1099 		atomic_read(&sp->sk_refcnt), sp,
1100 		atomic_read(&sp->sk_drops));
1101 }
1102 
1103 static int ping_v4_seq_show(struct seq_file *seq, void *v)
1104 {
1105 	seq_setwidth(seq, 127);
1106 	if (v == SEQ_START_TOKEN)
1107 		seq_puts(seq, "  sl  local_address rem_address   st tx_queue "
1108 			   "rx_queue tr tm->when retrnsmt   uid  timeout "
1109 			   "inode ref pointer drops");
1110 	else {
1111 		struct ping_iter_state *state = seq->private;
1112 
1113 		ping_v4_format_sock(v, seq, state->bucket);
1114 	}
1115 	seq_pad(seq, '\n');
1116 	return 0;
1117 }
1118 
1119 static const struct seq_operations ping_v4_seq_ops = {
1120 	.show		= ping_v4_seq_show,
1121 	.start		= ping_v4_seq_start,
1122 	.next		= ping_seq_next,
1123 	.stop		= ping_seq_stop,
1124 };
1125 
1126 static int ping_seq_open(struct inode *inode, struct file *file)
1127 {
1128 	struct ping_seq_afinfo *afinfo = PDE_DATA(inode);
1129 	return seq_open_net(inode, file, &afinfo->seq_ops,
1130 			   sizeof(struct ping_iter_state));
1131 }
1132 
1133 const struct file_operations ping_seq_fops = {
1134 	.open		= ping_seq_open,
1135 	.read		= seq_read,
1136 	.llseek		= seq_lseek,
1137 	.release	= seq_release_net,
1138 };
1139 EXPORT_SYMBOL_GPL(ping_seq_fops);
1140 
1141 static struct ping_seq_afinfo ping_v4_seq_afinfo = {
1142 	.name		= "icmp",
1143 	.family		= AF_INET,
1144 	.seq_fops	= &ping_seq_fops,
1145 	.seq_ops	= {
1146 		.start		= ping_v4_seq_start,
1147 		.show		= ping_v4_seq_show,
1148 		.next		= ping_seq_next,
1149 		.stop		= ping_seq_stop,
1150 	},
1151 };
1152 
1153 int ping_proc_register(struct net *net, struct ping_seq_afinfo *afinfo)
1154 {
1155 	struct proc_dir_entry *p;
1156 	p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
1157 			     afinfo->seq_fops, afinfo);
1158 	if (!p)
1159 		return -ENOMEM;
1160 	return 0;
1161 }
1162 EXPORT_SYMBOL_GPL(ping_proc_register);
1163 
1164 void ping_proc_unregister(struct net *net, struct ping_seq_afinfo *afinfo)
1165 {
1166 	remove_proc_entry(afinfo->name, net->proc_net);
1167 }
1168 EXPORT_SYMBOL_GPL(ping_proc_unregister);
1169 
1170 static int __net_init ping_v4_proc_init_net(struct net *net)
1171 {
1172 	return ping_proc_register(net, &ping_v4_seq_afinfo);
1173 }
1174 
1175 static void __net_exit ping_v4_proc_exit_net(struct net *net)
1176 {
1177 	ping_proc_unregister(net, &ping_v4_seq_afinfo);
1178 }
1179 
1180 static struct pernet_operations ping_v4_net_ops = {
1181 	.init = ping_v4_proc_init_net,
1182 	.exit = ping_v4_proc_exit_net,
1183 };
1184 
1185 int __init ping_proc_init(void)
1186 {
1187 	return register_pernet_subsys(&ping_v4_net_ops);
1188 }
1189 
1190 void ping_proc_exit(void)
1191 {
1192 	unregister_pernet_subsys(&ping_v4_net_ops);
1193 }
1194 
1195 #endif
1196 
1197 void __init ping_init(void)
1198 {
1199 	int i;
1200 
1201 	for (i = 0; i < PING_HTABLE_SIZE; i++)
1202 		INIT_HLIST_NULLS_HEAD(&ping_table.hash[i], i);
1203 	rwlock_init(&ping_table.lock);
1204 }
1205