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