Merge branch 'linux-linaro-lsk-v4.4' into linux-linaro-lsk-v4.4-android
[firefly-linux-kernel-4.4.55.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                         return -EINVAL;
782                 faddr = ipc.opt->opt.faddr;
783         }
784         tos = get_rttos(&ipc, inet);
785         if (sock_flag(sk, SOCK_LOCALROUTE) ||
786             (msg->msg_flags & MSG_DONTROUTE) ||
787             (ipc.opt && ipc.opt->opt.is_strictroute)) {
788                 tos |= RTO_ONLINK;
789         }
790
791         if (ipv4_is_multicast(daddr)) {
792                 if (!ipc.oif)
793                         ipc.oif = inet->mc_index;
794                 if (!saddr)
795                         saddr = inet->mc_addr;
796         } else if (!ipc.oif)
797                 ipc.oif = inet->uc_index;
798
799         flowi4_init_output(&fl4, ipc.oif, sk->sk_mark, tos,
800                            RT_SCOPE_UNIVERSE, sk->sk_protocol,
801                            inet_sk_flowi_flags(sk), faddr, saddr, 0, 0,
802                            sk->sk_uid);
803
804         security_sk_classify_flow(sk, flowi4_to_flowi(&fl4));
805         rt = ip_route_output_flow(net, &fl4, sk);
806         if (IS_ERR(rt)) {
807                 err = PTR_ERR(rt);
808                 rt = NULL;
809                 if (err == -ENETUNREACH)
810                         IP_INC_STATS(net, IPSTATS_MIB_OUTNOROUTES);
811                 goto out;
812         }
813
814         err = -EACCES;
815         if ((rt->rt_flags & RTCF_BROADCAST) &&
816             !sock_flag(sk, SOCK_BROADCAST))
817                 goto out;
818
819         if (msg->msg_flags & MSG_CONFIRM)
820                 goto do_confirm;
821 back_from_confirm:
822
823         if (!ipc.addr)
824                 ipc.addr = fl4.daddr;
825
826         lock_sock(sk);
827
828         pfh.icmph.type = user_icmph.type; /* already checked */
829         pfh.icmph.code = user_icmph.code; /* ditto */
830         pfh.icmph.checksum = 0;
831         pfh.icmph.un.echo.id = inet->inet_sport;
832         pfh.icmph.un.echo.sequence = user_icmph.un.echo.sequence;
833         pfh.msg = msg;
834         pfh.wcheck = 0;
835         pfh.family = AF_INET;
836
837         err = ip_append_data(sk, &fl4, ping_getfrag, &pfh, len,
838                         0, &ipc, &rt, msg->msg_flags);
839         if (err)
840                 ip_flush_pending_frames(sk);
841         else
842                 err = ping_v4_push_pending_frames(sk, &pfh, &fl4);
843         release_sock(sk);
844
845 out:
846         ip_rt_put(rt);
847         if (free)
848                 kfree(ipc.opt);
849         if (!err) {
850                 icmp_out_count(sock_net(sk), user_icmph.type);
851                 return len;
852         }
853         return err;
854
855 do_confirm:
856         dst_confirm(&rt->dst);
857         if (!(msg->msg_flags & MSG_PROBE) || len)
858                 goto back_from_confirm;
859         err = 0;
860         goto out;
861 }
862
863 int ping_recvmsg(struct sock *sk, struct msghdr *msg, size_t len, int noblock,
864                  int flags, int *addr_len)
865 {
866         struct inet_sock *isk = inet_sk(sk);
867         int family = sk->sk_family;
868         struct sk_buff *skb;
869         int copied, err;
870
871         pr_debug("ping_recvmsg(sk=%p,sk->num=%u)\n", isk, isk->inet_num);
872
873         err = -EOPNOTSUPP;
874         if (flags & MSG_OOB)
875                 goto out;
876
877         if (flags & MSG_ERRQUEUE)
878                 return inet_recv_error(sk, msg, len, addr_len);
879
880         skb = skb_recv_datagram(sk, flags, noblock, &err);
881         if (!skb)
882                 goto out;
883
884         copied = skb->len;
885         if (copied > len) {
886                 msg->msg_flags |= MSG_TRUNC;
887                 copied = len;
888         }
889
890         /* Don't bother checking the checksum */
891         err = skb_copy_datagram_msg(skb, 0, msg, copied);
892         if (err)
893                 goto done;
894
895         sock_recv_timestamp(msg, sk, skb);
896
897         /* Copy the address and add cmsg data. */
898         if (family == AF_INET) {
899                 DECLARE_SOCKADDR(struct sockaddr_in *, sin, msg->msg_name);
900
901                 if (sin) {
902                         sin->sin_family = AF_INET;
903                         sin->sin_port = 0 /* skb->h.uh->source */;
904                         sin->sin_addr.s_addr = ip_hdr(skb)->saddr;
905                         memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
906                         *addr_len = sizeof(*sin);
907                 }
908
909                 if (isk->cmsg_flags)
910                         ip_cmsg_recv(msg, skb);
911
912 #if IS_ENABLED(CONFIG_IPV6)
913         } else if (family == AF_INET6) {
914                 struct ipv6_pinfo *np = inet6_sk(sk);
915                 struct ipv6hdr *ip6 = ipv6_hdr(skb);
916                 DECLARE_SOCKADDR(struct sockaddr_in6 *, sin6, msg->msg_name);
917
918                 if (sin6) {
919                         sin6->sin6_family = AF_INET6;
920                         sin6->sin6_port = 0;
921                         sin6->sin6_addr = ip6->saddr;
922                         sin6->sin6_flowinfo = 0;
923                         if (np->sndflow)
924                                 sin6->sin6_flowinfo = ip6_flowinfo(ip6);
925                         sin6->sin6_scope_id =
926                                 ipv6_iface_scope_id(&sin6->sin6_addr,
927                                                     inet6_iif(skb));
928                         *addr_len = sizeof(*sin6);
929                 }
930
931                 if (inet6_sk(sk)->rxopt.all)
932                         pingv6_ops.ip6_datagram_recv_common_ctl(sk, msg, skb);
933                 if (skb->protocol == htons(ETH_P_IPV6) &&
934                     inet6_sk(sk)->rxopt.all)
935                         pingv6_ops.ip6_datagram_recv_specific_ctl(sk, msg, skb);
936                 else if (skb->protocol == htons(ETH_P_IP) && isk->cmsg_flags)
937                         ip_cmsg_recv(msg, skb);
938 #endif
939         } else {
940                 BUG();
941         }
942
943         err = copied;
944
945 done:
946         skb_free_datagram(sk, skb);
947 out:
948         pr_debug("ping_recvmsg -> %d\n", err);
949         return err;
950 }
951 EXPORT_SYMBOL_GPL(ping_recvmsg);
952
953 int ping_queue_rcv_skb(struct sock *sk, struct sk_buff *skb)
954 {
955         pr_debug("ping_queue_rcv_skb(sk=%p,sk->num=%d,skb=%p)\n",
956                  inet_sk(sk), inet_sk(sk)->inet_num, skb);
957         if (sock_queue_rcv_skb(sk, skb) < 0) {
958                 kfree_skb(skb);
959                 pr_debug("ping_queue_rcv_skb -> failed\n");
960                 return -1;
961         }
962         return 0;
963 }
964 EXPORT_SYMBOL_GPL(ping_queue_rcv_skb);
965
966
967 /*
968  *      All we need to do is get the socket.
969  */
970
971 bool ping_rcv(struct sk_buff *skb)
972 {
973         struct sock *sk;
974         struct net *net = dev_net(skb->dev);
975         struct icmphdr *icmph = icmp_hdr(skb);
976
977         /* We assume the packet has already been checked by icmp_rcv */
978
979         pr_debug("ping_rcv(skb=%p,id=%04x,seq=%04x)\n",
980                  skb, ntohs(icmph->un.echo.id), ntohs(icmph->un.echo.sequence));
981
982         /* Push ICMP header back */
983         skb_push(skb, skb->data - (u8 *)icmph);
984
985         sk = ping_lookup(net, skb, ntohs(icmph->un.echo.id));
986         if (sk) {
987                 struct sk_buff *skb2 = skb_clone(skb, GFP_ATOMIC);
988
989                 pr_debug("rcv on socket %p\n", sk);
990                 if (skb2)
991                         ping_queue_rcv_skb(sk, skb2);
992                 sock_put(sk);
993                 return true;
994         }
995         pr_debug("no socket, dropping\n");
996
997         return false;
998 }
999 EXPORT_SYMBOL_GPL(ping_rcv);
1000
1001 struct proto ping_prot = {
1002         .name =         "PING",
1003         .owner =        THIS_MODULE,
1004         .init =         ping_init_sock,
1005         .close =        ping_close,
1006         .connect =      ip4_datagram_connect,
1007         .disconnect =   udp_disconnect,
1008         .setsockopt =   ip_setsockopt,
1009         .getsockopt =   ip_getsockopt,
1010         .sendmsg =      ping_v4_sendmsg,
1011         .recvmsg =      ping_recvmsg,
1012         .bind =         ping_bind,
1013         .backlog_rcv =  ping_queue_rcv_skb,
1014         .release_cb =   ip4_datagram_release_cb,
1015         .hash =         ping_hash,
1016         .unhash =       ping_unhash,
1017         .get_port =     ping_get_port,
1018         .obj_size =     sizeof(struct inet_sock),
1019 };
1020 EXPORT_SYMBOL(ping_prot);
1021
1022 #ifdef CONFIG_PROC_FS
1023
1024 static struct sock *ping_get_first(struct seq_file *seq, int start)
1025 {
1026         struct sock *sk;
1027         struct ping_iter_state *state = seq->private;
1028         struct net *net = seq_file_net(seq);
1029
1030         for (state->bucket = start; state->bucket < PING_HTABLE_SIZE;
1031              ++state->bucket) {
1032                 struct hlist_nulls_node *node;
1033                 struct hlist_nulls_head *hslot;
1034
1035                 hslot = &ping_table.hash[state->bucket];
1036
1037                 if (hlist_nulls_empty(hslot))
1038                         continue;
1039
1040                 sk_nulls_for_each(sk, node, hslot) {
1041                         if (net_eq(sock_net(sk), net) &&
1042                             sk->sk_family == state->family)
1043                                 goto found;
1044                 }
1045         }
1046         sk = NULL;
1047 found:
1048         return sk;
1049 }
1050
1051 static struct sock *ping_get_next(struct seq_file *seq, struct sock *sk)
1052 {
1053         struct ping_iter_state *state = seq->private;
1054         struct net *net = seq_file_net(seq);
1055
1056         do {
1057                 sk = sk_nulls_next(sk);
1058         } while (sk && (!net_eq(sock_net(sk), net)));
1059
1060         if (!sk)
1061                 return ping_get_first(seq, state->bucket + 1);
1062         return sk;
1063 }
1064
1065 static struct sock *ping_get_idx(struct seq_file *seq, loff_t pos)
1066 {
1067         struct sock *sk = ping_get_first(seq, 0);
1068
1069         if (sk)
1070                 while (pos && (sk = ping_get_next(seq, sk)) != NULL)
1071                         --pos;
1072         return pos ? NULL : sk;
1073 }
1074
1075 void *ping_seq_start(struct seq_file *seq, loff_t *pos, sa_family_t family)
1076 {
1077         struct ping_iter_state *state = seq->private;
1078         state->bucket = 0;
1079         state->family = family;
1080
1081         read_lock_bh(&ping_table.lock);
1082
1083         return *pos ? ping_get_idx(seq, *pos-1) : SEQ_START_TOKEN;
1084 }
1085 EXPORT_SYMBOL_GPL(ping_seq_start);
1086
1087 static void *ping_v4_seq_start(struct seq_file *seq, loff_t *pos)
1088 {
1089         return ping_seq_start(seq, pos, AF_INET);
1090 }
1091
1092 void *ping_seq_next(struct seq_file *seq, void *v, loff_t *pos)
1093 {
1094         struct sock *sk;
1095
1096         if (v == SEQ_START_TOKEN)
1097                 sk = ping_get_idx(seq, 0);
1098         else
1099                 sk = ping_get_next(seq, v);
1100
1101         ++*pos;
1102         return sk;
1103 }
1104 EXPORT_SYMBOL_GPL(ping_seq_next);
1105
1106 void ping_seq_stop(struct seq_file *seq, void *v)
1107 {
1108         read_unlock_bh(&ping_table.lock);
1109 }
1110 EXPORT_SYMBOL_GPL(ping_seq_stop);
1111
1112 static void ping_v4_format_sock(struct sock *sp, struct seq_file *f,
1113                 int bucket)
1114 {
1115         struct inet_sock *inet = inet_sk(sp);
1116         __be32 dest = inet->inet_daddr;
1117         __be32 src = inet->inet_rcv_saddr;
1118         __u16 destp = ntohs(inet->inet_dport);
1119         __u16 srcp = ntohs(inet->inet_sport);
1120
1121         seq_printf(f, "%5d: %08X:%04X %08X:%04X"
1122                 " %02X %08X:%08X %02X:%08lX %08X %5u %8d %lu %d %pK %d",
1123                 bucket, src, srcp, dest, destp, sp->sk_state,
1124                 sk_wmem_alloc_get(sp),
1125                 sk_rmem_alloc_get(sp),
1126                 0, 0L, 0,
1127                 from_kuid_munged(seq_user_ns(f), sock_i_uid(sp)),
1128                 0, sock_i_ino(sp),
1129                 atomic_read(&sp->sk_refcnt), sp,
1130                 atomic_read(&sp->sk_drops));
1131 }
1132
1133 static int ping_v4_seq_show(struct seq_file *seq, void *v)
1134 {
1135         seq_setwidth(seq, 127);
1136         if (v == SEQ_START_TOKEN)
1137                 seq_puts(seq, "  sl  local_address rem_address   st tx_queue "
1138                            "rx_queue tr tm->when retrnsmt   uid  timeout "
1139                            "inode ref pointer drops");
1140         else {
1141                 struct ping_iter_state *state = seq->private;
1142
1143                 ping_v4_format_sock(v, seq, state->bucket);
1144         }
1145         seq_pad(seq, '\n');
1146         return 0;
1147 }
1148
1149 static const struct seq_operations ping_v4_seq_ops = {
1150         .show           = ping_v4_seq_show,
1151         .start          = ping_v4_seq_start,
1152         .next           = ping_seq_next,
1153         .stop           = ping_seq_stop,
1154 };
1155
1156 static int ping_seq_open(struct inode *inode, struct file *file)
1157 {
1158         struct ping_seq_afinfo *afinfo = PDE_DATA(inode);
1159         return seq_open_net(inode, file, &afinfo->seq_ops,
1160                            sizeof(struct ping_iter_state));
1161 }
1162
1163 const struct file_operations ping_seq_fops = {
1164         .open           = ping_seq_open,
1165         .read           = seq_read,
1166         .llseek         = seq_lseek,
1167         .release        = seq_release_net,
1168 };
1169 EXPORT_SYMBOL_GPL(ping_seq_fops);
1170
1171 static struct ping_seq_afinfo ping_v4_seq_afinfo = {
1172         .name           = "icmp",
1173         .family         = AF_INET,
1174         .seq_fops       = &ping_seq_fops,
1175         .seq_ops        = {
1176                 .start          = ping_v4_seq_start,
1177                 .show           = ping_v4_seq_show,
1178                 .next           = ping_seq_next,
1179                 .stop           = ping_seq_stop,
1180         },
1181 };
1182
1183 int ping_proc_register(struct net *net, struct ping_seq_afinfo *afinfo)
1184 {
1185         struct proc_dir_entry *p;
1186         p = proc_create_data(afinfo->name, S_IRUGO, net->proc_net,
1187                              afinfo->seq_fops, afinfo);
1188         if (!p)
1189                 return -ENOMEM;
1190         return 0;
1191 }
1192 EXPORT_SYMBOL_GPL(ping_proc_register);
1193
1194 void ping_proc_unregister(struct net *net, struct ping_seq_afinfo *afinfo)
1195 {
1196         remove_proc_entry(afinfo->name, net->proc_net);
1197 }
1198 EXPORT_SYMBOL_GPL(ping_proc_unregister);
1199
1200 static int __net_init ping_v4_proc_init_net(struct net *net)
1201 {
1202         return ping_proc_register(net, &ping_v4_seq_afinfo);
1203 }
1204
1205 static void __net_exit ping_v4_proc_exit_net(struct net *net)
1206 {
1207         ping_proc_unregister(net, &ping_v4_seq_afinfo);
1208 }
1209
1210 static struct pernet_operations ping_v4_net_ops = {
1211         .init = ping_v4_proc_init_net,
1212         .exit = ping_v4_proc_exit_net,
1213 };
1214
1215 int __init ping_proc_init(void)
1216 {
1217         return register_pernet_subsys(&ping_v4_net_ops);
1218 }
1219
1220 void ping_proc_exit(void)
1221 {
1222         unregister_pernet_subsys(&ping_v4_net_ops);
1223 }
1224
1225 #endif
1226
1227 void __init ping_init(void)
1228 {
1229         int i;
1230
1231         for (i = 0; i < PING_HTABLE_SIZE; i++)
1232                 INIT_HLIST_NULLS_HEAD(&ping_table.hash[i], i);
1233         rwlock_init(&ping_table.lock);
1234 }