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