Paranoid network.
[firefly-linux-kernel-4.4.55.git] / net / ipv4 / af_inet.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  *              PF_INET protocol family socket handler.
7  *
8  * Authors:     Ross Biro
9  *              Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10  *              Florian La Roche, <flla@stud.uni-sb.de>
11  *              Alan Cox, <A.Cox@swansea.ac.uk>
12  *
13  * Changes (see also sock.c)
14  *
15  *              piggy,
16  *              Karl Knutson    :       Socket protocol table
17  *              A.N.Kuznetsov   :       Socket death error in accept().
18  *              John Richardson :       Fix non blocking error in connect()
19  *                                      so sockets that fail to connect
20  *                                      don't return -EINPROGRESS.
21  *              Alan Cox        :       Asynchronous I/O support
22  *              Alan Cox        :       Keep correct socket pointer on sock
23  *                                      structures
24  *                                      when accept() ed
25  *              Alan Cox        :       Semantics of SO_LINGER aren't state
26  *                                      moved to close when you look carefully.
27  *                                      With this fixed and the accept bug fixed
28  *                                      some RPC stuff seems happier.
29  *              Niibe Yutaka    :       4.4BSD style write async I/O
30  *              Alan Cox,
31  *              Tony Gale       :       Fixed reuse semantics.
32  *              Alan Cox        :       bind() shouldn't abort existing but dead
33  *                                      sockets. Stops FTP netin:.. I hope.
34  *              Alan Cox        :       bind() works correctly for RAW sockets.
35  *                                      Note that FreeBSD at least was broken
36  *                                      in this respect so be careful with
37  *                                      compatibility tests...
38  *              Alan Cox        :       routing cache support
39  *              Alan Cox        :       memzero the socket structure for
40  *                                      compactness.
41  *              Matt Day        :       nonblock connect error handler
42  *              Alan Cox        :       Allow large numbers of pending sockets
43  *                                      (eg for big web sites), but only if
44  *                                      specifically application requested.
45  *              Alan Cox        :       New buffering throughout IP. Used
46  *                                      dumbly.
47  *              Alan Cox        :       New buffering now used smartly.
48  *              Alan Cox        :       BSD rather than common sense
49  *                                      interpretation of listen.
50  *              Germano Caronni :       Assorted small races.
51  *              Alan Cox        :       sendmsg/recvmsg basic support.
52  *              Alan Cox        :       Only sendmsg/recvmsg now supported.
53  *              Alan Cox        :       Locked down bind (see security list).
54  *              Alan Cox        :       Loosened bind a little.
55  *              Mike McLagan    :       ADD/DEL DLCI Ioctls
56  *      Willy Konynenberg       :       Transparent proxying support.
57  *              David S. Miller :       New socket lookup architecture.
58  *                                      Some other random speedups.
59  *              Cyrus Durgin    :       Cleaned up file for kmod hacks.
60  *              Andi Kleen      :       Fix inet_stream_connect TCP race.
61  *
62  *              This program is free software; you can redistribute it and/or
63  *              modify it under the terms of the GNU General Public License
64  *              as published by the Free Software Foundation; either version
65  *              2 of the License, or (at your option) any later version.
66  */
67
68 #define pr_fmt(fmt) "IPv4: " fmt
69
70 #include <linux/err.h>
71 #include <linux/errno.h>
72 #include <linux/types.h>
73 #include <linux/socket.h>
74 #include <linux/in.h>
75 #include <linux/kernel.h>
76 #include <linux/module.h>
77 #include <linux/sched.h>
78 #include <linux/timer.h>
79 #include <linux/string.h>
80 #include <linux/sockios.h>
81 #include <linux/net.h>
82 #include <linux/capability.h>
83 #include <linux/fcntl.h>
84 #include <linux/mm.h>
85 #include <linux/interrupt.h>
86 #include <linux/stat.h>
87 #include <linux/init.h>
88 #include <linux/poll.h>
89 #include <linux/netfilter_ipv4.h>
90 #include <linux/random.h>
91 #include <linux/slab.h>
92
93 #include <asm/uaccess.h>
94
95 #include <linux/inet.h>
96 #include <linux/igmp.h>
97 #include <linux/inetdevice.h>
98 #include <linux/netdevice.h>
99 #include <net/checksum.h>
100 #include <net/ip.h>
101 #include <net/protocol.h>
102 #include <net/arp.h>
103 #include <net/route.h>
104 #include <net/ip_fib.h>
105 #include <net/inet_connection_sock.h>
106 #include <net/tcp.h>
107 #include <net/udp.h>
108 #include <net/udplite.h>
109 #include <net/ping.h>
110 #include <linux/skbuff.h>
111 #include <net/sock.h>
112 #include <net/raw.h>
113 #include <net/icmp.h>
114 #include <net/inet_common.h>
115 #include <net/ip_tunnels.h>
116 #include <net/xfrm.h>
117 #include <net/net_namespace.h>
118 #include <net/secure_seq.h>
119 #ifdef CONFIG_IP_MROUTE
120 #include <linux/mroute.h>
121 #endif
122 #include <net/l3mdev.h>
123
124 #ifdef CONFIG_ANDROID_PARANOID_NETWORK
125 #include <linux/android_aid.h>
126 #endif
127
128 /* The inetsw table contains everything that inet_create needs to
129  * build a new socket.
130  */
131 static struct list_head inetsw[SOCK_MAX];
132 static DEFINE_SPINLOCK(inetsw_lock);
133
134 /* New destruction routine */
135
136 void inet_sock_destruct(struct sock *sk)
137 {
138         struct inet_sock *inet = inet_sk(sk);
139
140         __skb_queue_purge(&sk->sk_receive_queue);
141         __skb_queue_purge(&sk->sk_error_queue);
142
143         sk_mem_reclaim(sk);
144
145         if (sk->sk_type == SOCK_STREAM && sk->sk_state != TCP_CLOSE) {
146                 pr_err("Attempt to release TCP socket in state %d %p\n",
147                        sk->sk_state, sk);
148                 return;
149         }
150         if (!sock_flag(sk, SOCK_DEAD)) {
151                 pr_err("Attempt to release alive inet socket %p\n", sk);
152                 return;
153         }
154
155         WARN_ON(atomic_read(&sk->sk_rmem_alloc));
156         WARN_ON(atomic_read(&sk->sk_wmem_alloc));
157         WARN_ON(sk->sk_wmem_queued);
158         WARN_ON(sk->sk_forward_alloc);
159
160         kfree(rcu_dereference_protected(inet->inet_opt, 1));
161         dst_release(rcu_dereference_check(sk->sk_dst_cache, 1));
162         dst_release(sk->sk_rx_dst);
163         sk_refcnt_debug_dec(sk);
164 }
165 EXPORT_SYMBOL(inet_sock_destruct);
166
167 /*
168  *      The routines beyond this point handle the behaviour of an AF_INET
169  *      socket object. Mostly it punts to the subprotocols of IP to do
170  *      the work.
171  */
172
173 /*
174  *      Automatically bind an unbound socket.
175  */
176
177 static int inet_autobind(struct sock *sk)
178 {
179         struct inet_sock *inet;
180         /* We may need to bind the socket. */
181         lock_sock(sk);
182         inet = inet_sk(sk);
183         if (!inet->inet_num) {
184                 if (sk->sk_prot->get_port(sk, 0)) {
185                         release_sock(sk);
186                         return -EAGAIN;
187                 }
188                 inet->inet_sport = htons(inet->inet_num);
189         }
190         release_sock(sk);
191         return 0;
192 }
193
194 /*
195  *      Move a socket into listening state.
196  */
197 int inet_listen(struct socket *sock, int backlog)
198 {
199         struct sock *sk = sock->sk;
200         unsigned char old_state;
201         int err;
202
203         lock_sock(sk);
204
205         err = -EINVAL;
206         if (sock->state != SS_UNCONNECTED || sock->type != SOCK_STREAM)
207                 goto out;
208
209         old_state = sk->sk_state;
210         if (!((1 << old_state) & (TCPF_CLOSE | TCPF_LISTEN)))
211                 goto out;
212
213         /* Really, if the socket is already in listen state
214          * we can only allow the backlog to be adjusted.
215          */
216         if (old_state != TCP_LISTEN) {
217                 /* Check special setups for testing purpose to enable TFO w/o
218                  * requiring TCP_FASTOPEN sockopt.
219                  * Note that only TCP sockets (SOCK_STREAM) will reach here.
220                  * Also fastopenq may already been allocated because this
221                  * socket was in TCP_LISTEN state previously but was
222                  * shutdown() (rather than close()).
223                  */
224                 if ((sysctl_tcp_fastopen & TFO_SERVER_ENABLE) != 0 &&
225                     !inet_csk(sk)->icsk_accept_queue.fastopenq.max_qlen) {
226                         if ((sysctl_tcp_fastopen & TFO_SERVER_WO_SOCKOPT1) != 0)
227                                 fastopen_queue_tune(sk, backlog);
228                         else if ((sysctl_tcp_fastopen &
229                                   TFO_SERVER_WO_SOCKOPT2) != 0)
230                                 fastopen_queue_tune(sk,
231                                     ((uint)sysctl_tcp_fastopen) >> 16);
232
233                         tcp_fastopen_init_key_once(true);
234                 }
235                 err = inet_csk_listen_start(sk, backlog);
236                 if (err)
237                         goto out;
238         }
239         sk->sk_max_ack_backlog = backlog;
240         err = 0;
241
242 out:
243         release_sock(sk);
244         return err;
245 }
246 EXPORT_SYMBOL(inet_listen);
247
248 #ifdef CONFIG_ANDROID_PARANOID_NETWORK
249 static inline int current_has_network(void)
250 {
251         return (!current_euid() || in_egroup_p(AID_INET) ||
252                 in_egroup_p(AID_NET_RAW));
253 }
254 static inline int current_has_cap(struct net *net, int cap)
255 {
256         if (cap == CAP_NET_RAW && in_egroup_p(AID_NET_RAW))
257                 return 1;
258         return ns_capable(net->user_ns, cap);
259 }
260 # else
261 static inline int current_has_network(void)
262 {
263         return 1;
264 }
265 static inline int current_has_cap(struct net *net, int cap)
266 {
267         return ns_capable(net->user_ns, cap);
268 }
269 #endif
270
271 /*
272  *      Create an inet socket.
273  */
274
275 static int inet_create(struct net *net, struct socket *sock, int protocol,
276                        int kern)
277 {
278         struct sock *sk;
279         struct inet_protosw *answer;
280         struct inet_sock *inet;
281         struct proto *answer_prot;
282         unsigned char answer_flags;
283         int try_loading_module = 0;
284         int err;
285
286         if (protocol < 0 || protocol >= IPPROTO_MAX)
287                 return -EINVAL;
288
289         if (!current_has_network())
290                 return -EACCES;
291
292         sock->state = SS_UNCONNECTED;
293
294         /* Look for the requested type/protocol pair. */
295 lookup_protocol:
296         err = -ESOCKTNOSUPPORT;
297         rcu_read_lock();
298         list_for_each_entry_rcu(answer, &inetsw[sock->type], list) {
299
300                 err = 0;
301                 /* Check the non-wild match. */
302                 if (protocol == answer->protocol) {
303                         if (protocol != IPPROTO_IP)
304                                 break;
305                 } else {
306                         /* Check for the two wild cases. */
307                         if (IPPROTO_IP == protocol) {
308                                 protocol = answer->protocol;
309                                 break;
310                         }
311                         if (IPPROTO_IP == answer->protocol)
312                                 break;
313                 }
314                 err = -EPROTONOSUPPORT;
315         }
316
317         if (unlikely(err)) {
318                 if (try_loading_module < 2) {
319                         rcu_read_unlock();
320                         /*
321                          * Be more specific, e.g. net-pf-2-proto-132-type-1
322                          * (net-pf-PF_INET-proto-IPPROTO_SCTP-type-SOCK_STREAM)
323                          */
324                         if (++try_loading_module == 1)
325                                 request_module("net-pf-%d-proto-%d-type-%d",
326                                                PF_INET, protocol, sock->type);
327                         /*
328                          * Fall back to generic, e.g. net-pf-2-proto-132
329                          * (net-pf-PF_INET-proto-IPPROTO_SCTP)
330                          */
331                         else
332                                 request_module("net-pf-%d-proto-%d",
333                                                PF_INET, protocol);
334                         goto lookup_protocol;
335                 } else
336                         goto out_rcu_unlock;
337         }
338
339         err = -EPERM;
340         if (sock->type == SOCK_RAW && !kern &&
341             !current_has_cap(net, CAP_NET_RAW))
342                 goto out_rcu_unlock;
343
344         sock->ops = answer->ops;
345         answer_prot = answer->prot;
346         answer_flags = answer->flags;
347         rcu_read_unlock();
348
349         WARN_ON(!answer_prot->slab);
350
351         err = -ENOBUFS;
352         sk = sk_alloc(net, PF_INET, GFP_KERNEL, answer_prot, kern);
353         if (!sk)
354                 goto out;
355
356         err = 0;
357         if (INET_PROTOSW_REUSE & answer_flags)
358                 sk->sk_reuse = SK_CAN_REUSE;
359
360         inet = inet_sk(sk);
361         inet->is_icsk = (INET_PROTOSW_ICSK & answer_flags) != 0;
362
363         inet->nodefrag = 0;
364
365         if (SOCK_RAW == sock->type) {
366                 inet->inet_num = protocol;
367                 if (IPPROTO_RAW == protocol)
368                         inet->hdrincl = 1;
369         }
370
371         if (net->ipv4.sysctl_ip_no_pmtu_disc)
372                 inet->pmtudisc = IP_PMTUDISC_DONT;
373         else
374                 inet->pmtudisc = IP_PMTUDISC_WANT;
375
376         inet->inet_id = 0;
377
378         sock_init_data(sock, sk);
379
380         sk->sk_destruct    = inet_sock_destruct;
381         sk->sk_protocol    = protocol;
382         sk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
383
384         inet->uc_ttl    = -1;
385         inet->mc_loop   = 1;
386         inet->mc_ttl    = 1;
387         inet->mc_all    = 1;
388         inet->mc_index  = 0;
389         inet->mc_list   = NULL;
390         inet->rcv_tos   = 0;
391
392         sk_refcnt_debug_inc(sk);
393
394         if (inet->inet_num) {
395                 /* It assumes that any protocol which allows
396                  * the user to assign a number at socket
397                  * creation time automatically
398                  * shares.
399                  */
400                 inet->inet_sport = htons(inet->inet_num);
401                 /* Add to protocol hash chains. */
402                 sk->sk_prot->hash(sk);
403         }
404
405         if (sk->sk_prot->init) {
406                 err = sk->sk_prot->init(sk);
407                 if (err)
408                         sk_common_release(sk);
409         }
410 out:
411         return err;
412 out_rcu_unlock:
413         rcu_read_unlock();
414         goto out;
415 }
416
417
418 /*
419  *      The peer socket should always be NULL (or else). When we call this
420  *      function we are destroying the object and from then on nobody
421  *      should refer to it.
422  */
423 int inet_release(struct socket *sock)
424 {
425         struct sock *sk = sock->sk;
426
427         if (sk) {
428                 long timeout;
429
430                 /* Applications forget to leave groups before exiting */
431                 ip_mc_drop_socket(sk);
432
433                 /* If linger is set, we don't return until the close
434                  * is complete.  Otherwise we return immediately. The
435                  * actually closing is done the same either way.
436                  *
437                  * If the close is due to the process exiting, we never
438                  * linger..
439                  */
440                 timeout = 0;
441                 if (sock_flag(sk, SOCK_LINGER) &&
442                     !(current->flags & PF_EXITING))
443                         timeout = sk->sk_lingertime;
444                 sock->sk = NULL;
445                 sk->sk_prot->close(sk, timeout);
446         }
447         return 0;
448 }
449 EXPORT_SYMBOL(inet_release);
450
451 int inet_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
452 {
453         struct sockaddr_in *addr = (struct sockaddr_in *)uaddr;
454         struct sock *sk = sock->sk;
455         struct inet_sock *inet = inet_sk(sk);
456         struct net *net = sock_net(sk);
457         unsigned short snum;
458         int chk_addr_ret;
459         u32 tb_id = RT_TABLE_LOCAL;
460         int err;
461
462         /* If the socket has its own bind function then use it. (RAW) */
463         if (sk->sk_prot->bind) {
464                 err = sk->sk_prot->bind(sk, uaddr, addr_len);
465                 goto out;
466         }
467         err = -EINVAL;
468         if (addr_len < sizeof(struct sockaddr_in))
469                 goto out;
470
471         if (addr->sin_family != AF_INET) {
472                 /* Compatibility games : accept AF_UNSPEC (mapped to AF_INET)
473                  * only if s_addr is INADDR_ANY.
474                  */
475                 err = -EAFNOSUPPORT;
476                 if (addr->sin_family != AF_UNSPEC ||
477                     addr->sin_addr.s_addr != htonl(INADDR_ANY))
478                         goto out;
479         }
480
481         tb_id = l3mdev_fib_table_by_index(net, sk->sk_bound_dev_if) ? : tb_id;
482         chk_addr_ret = inet_addr_type_table(net, addr->sin_addr.s_addr, tb_id);
483
484         /* Not specified by any standard per-se, however it breaks too
485          * many applications when removed.  It is unfortunate since
486          * allowing applications to make a non-local bind solves
487          * several problems with systems using dynamic addressing.
488          * (ie. your servers still start up even if your ISDN link
489          *  is temporarily down)
490          */
491         err = -EADDRNOTAVAIL;
492         if (!net->ipv4.sysctl_ip_nonlocal_bind &&
493             !(inet->freebind || inet->transparent) &&
494             addr->sin_addr.s_addr != htonl(INADDR_ANY) &&
495             chk_addr_ret != RTN_LOCAL &&
496             chk_addr_ret != RTN_MULTICAST &&
497             chk_addr_ret != RTN_BROADCAST)
498                 goto out;
499
500         snum = ntohs(addr->sin_port);
501         err = -EACCES;
502         if (snum && snum < PROT_SOCK &&
503             !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
504                 goto out;
505
506         /*      We keep a pair of addresses. rcv_saddr is the one
507          *      used by hash lookups, and saddr is used for transmit.
508          *
509          *      In the BSD API these are the same except where it
510          *      would be illegal to use them (multicast/broadcast) in
511          *      which case the sending device address is used.
512          */
513         lock_sock(sk);
514
515         /* Check these errors (active socket, double bind). */
516         err = -EINVAL;
517         if (sk->sk_state != TCP_CLOSE || inet->inet_num)
518                 goto out_release_sock;
519
520         inet->inet_rcv_saddr = inet->inet_saddr = addr->sin_addr.s_addr;
521         if (chk_addr_ret == RTN_MULTICAST || chk_addr_ret == RTN_BROADCAST)
522                 inet->inet_saddr = 0;  /* Use device */
523
524         /* Make sure we are allowed to bind here. */
525         if ((snum || !inet->bind_address_no_port) &&
526             sk->sk_prot->get_port(sk, snum)) {
527                 inet->inet_saddr = inet->inet_rcv_saddr = 0;
528                 err = -EADDRINUSE;
529                 goto out_release_sock;
530         }
531
532         if (inet->inet_rcv_saddr)
533                 sk->sk_userlocks |= SOCK_BINDADDR_LOCK;
534         if (snum)
535                 sk->sk_userlocks |= SOCK_BINDPORT_LOCK;
536         inet->inet_sport = htons(inet->inet_num);
537         inet->inet_daddr = 0;
538         inet->inet_dport = 0;
539         sk_dst_reset(sk);
540         err = 0;
541 out_release_sock:
542         release_sock(sk);
543 out:
544         return err;
545 }
546 EXPORT_SYMBOL(inet_bind);
547
548 int inet_dgram_connect(struct socket *sock, struct sockaddr *uaddr,
549                        int addr_len, int flags)
550 {
551         struct sock *sk = sock->sk;
552
553         if (addr_len < sizeof(uaddr->sa_family))
554                 return -EINVAL;
555         if (uaddr->sa_family == AF_UNSPEC)
556                 return sk->sk_prot->disconnect(sk, flags);
557
558         if (!inet_sk(sk)->inet_num && inet_autobind(sk))
559                 return -EAGAIN;
560         return sk->sk_prot->connect(sk, uaddr, addr_len);
561 }
562 EXPORT_SYMBOL(inet_dgram_connect);
563
564 static long inet_wait_for_connect(struct sock *sk, long timeo, int writebias)
565 {
566         DEFINE_WAIT(wait);
567
568         prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
569         sk->sk_write_pending += writebias;
570
571         /* Basic assumption: if someone sets sk->sk_err, he _must_
572          * change state of the socket from TCP_SYN_*.
573          * Connect() does not allow to get error notifications
574          * without closing the socket.
575          */
576         while ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
577                 release_sock(sk);
578                 timeo = schedule_timeout(timeo);
579                 lock_sock(sk);
580                 if (signal_pending(current) || !timeo)
581                         break;
582                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
583         }
584         finish_wait(sk_sleep(sk), &wait);
585         sk->sk_write_pending -= writebias;
586         return timeo;
587 }
588
589 /*
590  *      Connect to a remote host. There is regrettably still a little
591  *      TCP 'magic' in here.
592  */
593 int __inet_stream_connect(struct socket *sock, struct sockaddr *uaddr,
594                           int addr_len, int flags)
595 {
596         struct sock *sk = sock->sk;
597         int err;
598         long timeo;
599
600         if (addr_len < sizeof(uaddr->sa_family))
601                 return -EINVAL;
602
603         if (uaddr->sa_family == AF_UNSPEC) {
604                 err = sk->sk_prot->disconnect(sk, flags);
605                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
606                 goto out;
607         }
608
609         switch (sock->state) {
610         default:
611                 err = -EINVAL;
612                 goto out;
613         case SS_CONNECTED:
614                 err = -EISCONN;
615                 goto out;
616         case SS_CONNECTING:
617                 err = -EALREADY;
618                 /* Fall out of switch with err, set for this state */
619                 break;
620         case SS_UNCONNECTED:
621                 err = -EISCONN;
622                 if (sk->sk_state != TCP_CLOSE)
623                         goto out;
624
625                 err = sk->sk_prot->connect(sk, uaddr, addr_len);
626                 if (err < 0)
627                         goto out;
628
629                 sock->state = SS_CONNECTING;
630
631                 /* Just entered SS_CONNECTING state; the only
632                  * difference is that return value in non-blocking
633                  * case is EINPROGRESS, rather than EALREADY.
634                  */
635                 err = -EINPROGRESS;
636                 break;
637         }
638
639         timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
640
641         if ((1 << sk->sk_state) & (TCPF_SYN_SENT | TCPF_SYN_RECV)) {
642                 int writebias = (sk->sk_protocol == IPPROTO_TCP) &&
643                                 tcp_sk(sk)->fastopen_req &&
644                                 tcp_sk(sk)->fastopen_req->data ? 1 : 0;
645
646                 /* Error code is set above */
647                 if (!timeo || !inet_wait_for_connect(sk, timeo, writebias))
648                         goto out;
649
650                 err = sock_intr_errno(timeo);
651                 if (signal_pending(current))
652                         goto out;
653         }
654
655         /* Connection was closed by RST, timeout, ICMP error
656          * or another process disconnected us.
657          */
658         if (sk->sk_state == TCP_CLOSE)
659                 goto sock_error;
660
661         /* sk->sk_err may be not zero now, if RECVERR was ordered by user
662          * and error was received after socket entered established state.
663          * Hence, it is handled normally after connect() return successfully.
664          */
665
666         sock->state = SS_CONNECTED;
667         err = 0;
668 out:
669         return err;
670
671 sock_error:
672         err = sock_error(sk) ? : -ECONNABORTED;
673         sock->state = SS_UNCONNECTED;
674         if (sk->sk_prot->disconnect(sk, flags))
675                 sock->state = SS_DISCONNECTING;
676         goto out;
677 }
678 EXPORT_SYMBOL(__inet_stream_connect);
679
680 int inet_stream_connect(struct socket *sock, struct sockaddr *uaddr,
681                         int addr_len, int flags)
682 {
683         int err;
684
685         lock_sock(sock->sk);
686         err = __inet_stream_connect(sock, uaddr, addr_len, flags);
687         release_sock(sock->sk);
688         return err;
689 }
690 EXPORT_SYMBOL(inet_stream_connect);
691
692 /*
693  *      Accept a pending connection. The TCP layer now gives BSD semantics.
694  */
695
696 int inet_accept(struct socket *sock, struct socket *newsock, int flags)
697 {
698         struct sock *sk1 = sock->sk;
699         int err = -EINVAL;
700         struct sock *sk2 = sk1->sk_prot->accept(sk1, flags, &err);
701
702         if (!sk2)
703                 goto do_err;
704
705         lock_sock(sk2);
706
707         sock_rps_record_flow(sk2);
708         WARN_ON(!((1 << sk2->sk_state) &
709                   (TCPF_ESTABLISHED | TCPF_SYN_RECV |
710                   TCPF_CLOSE_WAIT | TCPF_CLOSE)));
711
712         sock_graft(sk2, newsock);
713
714         newsock->state = SS_CONNECTED;
715         err = 0;
716         release_sock(sk2);
717 do_err:
718         return err;
719 }
720 EXPORT_SYMBOL(inet_accept);
721
722
723 /*
724  *      This does both peername and sockname.
725  */
726 int inet_getname(struct socket *sock, struct sockaddr *uaddr,
727                         int *uaddr_len, int peer)
728 {
729         struct sock *sk         = sock->sk;
730         struct inet_sock *inet  = inet_sk(sk);
731         DECLARE_SOCKADDR(struct sockaddr_in *, sin, uaddr);
732
733         sin->sin_family = AF_INET;
734         if (peer) {
735                 if (!inet->inet_dport ||
736                     (((1 << sk->sk_state) & (TCPF_CLOSE | TCPF_SYN_SENT)) &&
737                      peer == 1))
738                         return -ENOTCONN;
739                 sin->sin_port = inet->inet_dport;
740                 sin->sin_addr.s_addr = inet->inet_daddr;
741         } else {
742                 __be32 addr = inet->inet_rcv_saddr;
743                 if (!addr)
744                         addr = inet->inet_saddr;
745                 sin->sin_port = inet->inet_sport;
746                 sin->sin_addr.s_addr = addr;
747         }
748         memset(sin->sin_zero, 0, sizeof(sin->sin_zero));
749         *uaddr_len = sizeof(*sin);
750         return 0;
751 }
752 EXPORT_SYMBOL(inet_getname);
753
754 int inet_sendmsg(struct socket *sock, struct msghdr *msg, size_t size)
755 {
756         struct sock *sk = sock->sk;
757
758         sock_rps_record_flow(sk);
759
760         /* We may need to bind the socket. */
761         if (!inet_sk(sk)->inet_num && !sk->sk_prot->no_autobind &&
762             inet_autobind(sk))
763                 return -EAGAIN;
764
765         return sk->sk_prot->sendmsg(sk, msg, size);
766 }
767 EXPORT_SYMBOL(inet_sendmsg);
768
769 ssize_t inet_sendpage(struct socket *sock, struct page *page, int offset,
770                       size_t size, int flags)
771 {
772         struct sock *sk = sock->sk;
773
774         sock_rps_record_flow(sk);
775
776         /* We may need to bind the socket. */
777         if (!inet_sk(sk)->inet_num && !sk->sk_prot->no_autobind &&
778             inet_autobind(sk))
779                 return -EAGAIN;
780
781         if (sk->sk_prot->sendpage)
782                 return sk->sk_prot->sendpage(sk, page, offset, size, flags);
783         return sock_no_sendpage(sock, page, offset, size, flags);
784 }
785 EXPORT_SYMBOL(inet_sendpage);
786
787 int inet_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
788                  int flags)
789 {
790         struct sock *sk = sock->sk;
791         int addr_len = 0;
792         int err;
793
794         sock_rps_record_flow(sk);
795
796         err = sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
797                                    flags & ~MSG_DONTWAIT, &addr_len);
798         if (err >= 0)
799                 msg->msg_namelen = addr_len;
800         return err;
801 }
802 EXPORT_SYMBOL(inet_recvmsg);
803
804 int inet_shutdown(struct socket *sock, int how)
805 {
806         struct sock *sk = sock->sk;
807         int err = 0;
808
809         /* This should really check to make sure
810          * the socket is a TCP socket. (WHY AC...)
811          */
812         how++; /* maps 0->1 has the advantage of making bit 1 rcvs and
813                        1->2 bit 2 snds.
814                        2->3 */
815         if ((how & ~SHUTDOWN_MASK) || !how)     /* MAXINT->0 */
816                 return -EINVAL;
817
818         lock_sock(sk);
819         if (sock->state == SS_CONNECTING) {
820                 if ((1 << sk->sk_state) &
821                     (TCPF_SYN_SENT | TCPF_SYN_RECV | TCPF_CLOSE))
822                         sock->state = SS_DISCONNECTING;
823                 else
824                         sock->state = SS_CONNECTED;
825         }
826
827         switch (sk->sk_state) {
828         case TCP_CLOSE:
829                 err = -ENOTCONN;
830                 /* Hack to wake up other listeners, who can poll for
831                    POLLHUP, even on eg. unconnected UDP sockets -- RR */
832         default:
833                 sk->sk_shutdown |= how;
834                 if (sk->sk_prot->shutdown)
835                         sk->sk_prot->shutdown(sk, how);
836                 break;
837
838         /* Remaining two branches are temporary solution for missing
839          * close() in multithreaded environment. It is _not_ a good idea,
840          * but we have no choice until close() is repaired at VFS level.
841          */
842         case TCP_LISTEN:
843                 if (!(how & RCV_SHUTDOWN))
844                         break;
845                 /* Fall through */
846         case TCP_SYN_SENT:
847                 err = sk->sk_prot->disconnect(sk, O_NONBLOCK);
848                 sock->state = err ? SS_DISCONNECTING : SS_UNCONNECTED;
849                 break;
850         }
851
852         /* Wake up anyone sleeping in poll. */
853         sk->sk_state_change(sk);
854         release_sock(sk);
855         return err;
856 }
857 EXPORT_SYMBOL(inet_shutdown);
858
859 /*
860  *      ioctl() calls you can issue on an INET socket. Most of these are
861  *      device configuration and stuff and very rarely used. Some ioctls
862  *      pass on to the socket itself.
863  *
864  *      NOTE: I like the idea of a module for the config stuff. ie ifconfig
865  *      loads the devconfigure module does its configuring and unloads it.
866  *      There's a good 20K of config code hanging around the kernel.
867  */
868
869 int inet_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
870 {
871         struct sock *sk = sock->sk;
872         int err = 0;
873         struct net *net = sock_net(sk);
874
875         switch (cmd) {
876         case SIOCGSTAMP:
877                 err = sock_get_timestamp(sk, (struct timeval __user *)arg);
878                 break;
879         case SIOCGSTAMPNS:
880                 err = sock_get_timestampns(sk, (struct timespec __user *)arg);
881                 break;
882         case SIOCADDRT:
883         case SIOCDELRT:
884         case SIOCRTMSG:
885                 err = ip_rt_ioctl(net, cmd, (void __user *)arg);
886                 break;
887         case SIOCDARP:
888         case SIOCGARP:
889         case SIOCSARP:
890                 err = arp_ioctl(net, cmd, (void __user *)arg);
891                 break;
892         case SIOCGIFADDR:
893         case SIOCSIFADDR:
894         case SIOCGIFBRDADDR:
895         case SIOCSIFBRDADDR:
896         case SIOCGIFNETMASK:
897         case SIOCSIFNETMASK:
898         case SIOCGIFDSTADDR:
899         case SIOCSIFDSTADDR:
900         case SIOCSIFPFLAGS:
901         case SIOCGIFPFLAGS:
902         case SIOCSIFFLAGS:
903                 err = devinet_ioctl(net, cmd, (void __user *)arg);
904                 break;
905         default:
906                 if (sk->sk_prot->ioctl)
907                         err = sk->sk_prot->ioctl(sk, cmd, arg);
908                 else
909                         err = -ENOIOCTLCMD;
910                 break;
911         }
912         return err;
913 }
914 EXPORT_SYMBOL(inet_ioctl);
915
916 #ifdef CONFIG_COMPAT
917 static int inet_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
918 {
919         struct sock *sk = sock->sk;
920         int err = -ENOIOCTLCMD;
921
922         if (sk->sk_prot->compat_ioctl)
923                 err = sk->sk_prot->compat_ioctl(sk, cmd, arg);
924
925         return err;
926 }
927 #endif
928
929 const struct proto_ops inet_stream_ops = {
930         .family            = PF_INET,
931         .owner             = THIS_MODULE,
932         .release           = inet_release,
933         .bind              = inet_bind,
934         .connect           = inet_stream_connect,
935         .socketpair        = sock_no_socketpair,
936         .accept            = inet_accept,
937         .getname           = inet_getname,
938         .poll              = tcp_poll,
939         .ioctl             = inet_ioctl,
940         .listen            = inet_listen,
941         .shutdown          = inet_shutdown,
942         .setsockopt        = sock_common_setsockopt,
943         .getsockopt        = sock_common_getsockopt,
944         .sendmsg           = inet_sendmsg,
945         .recvmsg           = inet_recvmsg,
946         .mmap              = sock_no_mmap,
947         .sendpage          = inet_sendpage,
948         .splice_read       = tcp_splice_read,
949 #ifdef CONFIG_COMPAT
950         .compat_setsockopt = compat_sock_common_setsockopt,
951         .compat_getsockopt = compat_sock_common_getsockopt,
952         .compat_ioctl      = inet_compat_ioctl,
953 #endif
954 };
955 EXPORT_SYMBOL(inet_stream_ops);
956
957 const struct proto_ops inet_dgram_ops = {
958         .family            = PF_INET,
959         .owner             = THIS_MODULE,
960         .release           = inet_release,
961         .bind              = inet_bind,
962         .connect           = inet_dgram_connect,
963         .socketpair        = sock_no_socketpair,
964         .accept            = sock_no_accept,
965         .getname           = inet_getname,
966         .poll              = udp_poll,
967         .ioctl             = inet_ioctl,
968         .listen            = sock_no_listen,
969         .shutdown          = inet_shutdown,
970         .setsockopt        = sock_common_setsockopt,
971         .getsockopt        = sock_common_getsockopt,
972         .sendmsg           = inet_sendmsg,
973         .recvmsg           = inet_recvmsg,
974         .mmap              = sock_no_mmap,
975         .sendpage          = inet_sendpage,
976 #ifdef CONFIG_COMPAT
977         .compat_setsockopt = compat_sock_common_setsockopt,
978         .compat_getsockopt = compat_sock_common_getsockopt,
979         .compat_ioctl      = inet_compat_ioctl,
980 #endif
981 };
982 EXPORT_SYMBOL(inet_dgram_ops);
983
984 /*
985  * For SOCK_RAW sockets; should be the same as inet_dgram_ops but without
986  * udp_poll
987  */
988 static const struct proto_ops inet_sockraw_ops = {
989         .family            = PF_INET,
990         .owner             = THIS_MODULE,
991         .release           = inet_release,
992         .bind              = inet_bind,
993         .connect           = inet_dgram_connect,
994         .socketpair        = sock_no_socketpair,
995         .accept            = sock_no_accept,
996         .getname           = inet_getname,
997         .poll              = datagram_poll,
998         .ioctl             = inet_ioctl,
999         .listen            = sock_no_listen,
1000         .shutdown          = inet_shutdown,
1001         .setsockopt        = sock_common_setsockopt,
1002         .getsockopt        = sock_common_getsockopt,
1003         .sendmsg           = inet_sendmsg,
1004         .recvmsg           = inet_recvmsg,
1005         .mmap              = sock_no_mmap,
1006         .sendpage          = inet_sendpage,
1007 #ifdef CONFIG_COMPAT
1008         .compat_setsockopt = compat_sock_common_setsockopt,
1009         .compat_getsockopt = compat_sock_common_getsockopt,
1010         .compat_ioctl      = inet_compat_ioctl,
1011 #endif
1012 };
1013
1014 static const struct net_proto_family inet_family_ops = {
1015         .family = PF_INET,
1016         .create = inet_create,
1017         .owner  = THIS_MODULE,
1018 };
1019
1020 /* Upon startup we insert all the elements in inetsw_array[] into
1021  * the linked list inetsw.
1022  */
1023 static struct inet_protosw inetsw_array[] =
1024 {
1025         {
1026                 .type =       SOCK_STREAM,
1027                 .protocol =   IPPROTO_TCP,
1028                 .prot =       &tcp_prot,
1029                 .ops =        &inet_stream_ops,
1030                 .flags =      INET_PROTOSW_PERMANENT |
1031                               INET_PROTOSW_ICSK,
1032         },
1033
1034         {
1035                 .type =       SOCK_DGRAM,
1036                 .protocol =   IPPROTO_UDP,
1037                 .prot =       &udp_prot,
1038                 .ops =        &inet_dgram_ops,
1039                 .flags =      INET_PROTOSW_PERMANENT,
1040        },
1041
1042        {
1043                 .type =       SOCK_DGRAM,
1044                 .protocol =   IPPROTO_ICMP,
1045                 .prot =       &ping_prot,
1046                 .ops =        &inet_dgram_ops,
1047                 .flags =      INET_PROTOSW_REUSE,
1048        },
1049
1050        {
1051                .type =       SOCK_RAW,
1052                .protocol =   IPPROTO_IP,        /* wild card */
1053                .prot =       &raw_prot,
1054                .ops =        &inet_sockraw_ops,
1055                .flags =      INET_PROTOSW_REUSE,
1056        }
1057 };
1058
1059 #define INETSW_ARRAY_LEN ARRAY_SIZE(inetsw_array)
1060
1061 void inet_register_protosw(struct inet_protosw *p)
1062 {
1063         struct list_head *lh;
1064         struct inet_protosw *answer;
1065         int protocol = p->protocol;
1066         struct list_head *last_perm;
1067
1068         spin_lock_bh(&inetsw_lock);
1069
1070         if (p->type >= SOCK_MAX)
1071                 goto out_illegal;
1072
1073         /* If we are trying to override a permanent protocol, bail. */
1074         last_perm = &inetsw[p->type];
1075         list_for_each(lh, &inetsw[p->type]) {
1076                 answer = list_entry(lh, struct inet_protosw, list);
1077                 /* Check only the non-wild match. */
1078                 if ((INET_PROTOSW_PERMANENT & answer->flags) == 0)
1079                         break;
1080                 if (protocol == answer->protocol)
1081                         goto out_permanent;
1082                 last_perm = lh;
1083         }
1084
1085         /* Add the new entry after the last permanent entry if any, so that
1086          * the new entry does not override a permanent entry when matched with
1087          * a wild-card protocol. But it is allowed to override any existing
1088          * non-permanent entry.  This means that when we remove this entry, the
1089          * system automatically returns to the old behavior.
1090          */
1091         list_add_rcu(&p->list, last_perm);
1092 out:
1093         spin_unlock_bh(&inetsw_lock);
1094
1095         return;
1096
1097 out_permanent:
1098         pr_err("Attempt to override permanent protocol %d\n", protocol);
1099         goto out;
1100
1101 out_illegal:
1102         pr_err("Ignoring attempt to register invalid socket type %d\n",
1103                p->type);
1104         goto out;
1105 }
1106 EXPORT_SYMBOL(inet_register_protosw);
1107
1108 void inet_unregister_protosw(struct inet_protosw *p)
1109 {
1110         if (INET_PROTOSW_PERMANENT & p->flags) {
1111                 pr_err("Attempt to unregister permanent protocol %d\n",
1112                        p->protocol);
1113         } else {
1114                 spin_lock_bh(&inetsw_lock);
1115                 list_del_rcu(&p->list);
1116                 spin_unlock_bh(&inetsw_lock);
1117
1118                 synchronize_net();
1119         }
1120 }
1121 EXPORT_SYMBOL(inet_unregister_protosw);
1122
1123 /*
1124  *      Shall we try to damage output packets if routing dev changes?
1125  */
1126
1127 int sysctl_ip_dynaddr __read_mostly;
1128
1129 static int inet_sk_reselect_saddr(struct sock *sk)
1130 {
1131         struct inet_sock *inet = inet_sk(sk);
1132         __be32 old_saddr = inet->inet_saddr;
1133         __be32 daddr = inet->inet_daddr;
1134         struct flowi4 *fl4;
1135         struct rtable *rt;
1136         __be32 new_saddr;
1137         struct ip_options_rcu *inet_opt;
1138
1139         inet_opt = rcu_dereference_protected(inet->inet_opt,
1140                                              sock_owned_by_user(sk));
1141         if (inet_opt && inet_opt->opt.srr)
1142                 daddr = inet_opt->opt.faddr;
1143
1144         /* Query new route. */
1145         fl4 = &inet->cork.fl.u.ip4;
1146         rt = ip_route_connect(fl4, daddr, 0, RT_CONN_FLAGS(sk),
1147                               sk->sk_bound_dev_if, sk->sk_protocol,
1148                               inet->inet_sport, inet->inet_dport, sk);
1149         if (IS_ERR(rt))
1150                 return PTR_ERR(rt);
1151
1152         sk_setup_caps(sk, &rt->dst);
1153
1154         new_saddr = fl4->saddr;
1155
1156         if (new_saddr == old_saddr)
1157                 return 0;
1158
1159         if (sysctl_ip_dynaddr > 1) {
1160                 pr_info("%s(): shifting inet->saddr from %pI4 to %pI4\n",
1161                         __func__, &old_saddr, &new_saddr);
1162         }
1163
1164         inet->inet_saddr = inet->inet_rcv_saddr = new_saddr;
1165
1166         /*
1167          * XXX The only one ugly spot where we need to
1168          * XXX really change the sockets identity after
1169          * XXX it has entered the hashes. -DaveM
1170          *
1171          * Besides that, it does not check for connection
1172          * uniqueness. Wait for troubles.
1173          */
1174         __sk_prot_rehash(sk);
1175         return 0;
1176 }
1177
1178 int inet_sk_rebuild_header(struct sock *sk)
1179 {
1180         struct inet_sock *inet = inet_sk(sk);
1181         struct rtable *rt = (struct rtable *)__sk_dst_check(sk, 0);
1182         __be32 daddr;
1183         struct ip_options_rcu *inet_opt;
1184         struct flowi4 *fl4;
1185         int err;
1186
1187         /* Route is OK, nothing to do. */
1188         if (rt)
1189                 return 0;
1190
1191         /* Reroute. */
1192         rcu_read_lock();
1193         inet_opt = rcu_dereference(inet->inet_opt);
1194         daddr = inet->inet_daddr;
1195         if (inet_opt && inet_opt->opt.srr)
1196                 daddr = inet_opt->opt.faddr;
1197         rcu_read_unlock();
1198         fl4 = &inet->cork.fl.u.ip4;
1199         rt = ip_route_output_ports(sock_net(sk), fl4, sk, daddr, inet->inet_saddr,
1200                                    inet->inet_dport, inet->inet_sport,
1201                                    sk->sk_protocol, RT_CONN_FLAGS(sk),
1202                                    sk->sk_bound_dev_if);
1203         if (!IS_ERR(rt)) {
1204                 err = 0;
1205                 sk_setup_caps(sk, &rt->dst);
1206         } else {
1207                 err = PTR_ERR(rt);
1208
1209                 /* Routing failed... */
1210                 sk->sk_route_caps = 0;
1211                 /*
1212                  * Other protocols have to map its equivalent state to TCP_SYN_SENT.
1213                  * DCCP maps its DCCP_REQUESTING state to TCP_SYN_SENT. -acme
1214                  */
1215                 if (!sysctl_ip_dynaddr ||
1216                     sk->sk_state != TCP_SYN_SENT ||
1217                     (sk->sk_userlocks & SOCK_BINDADDR_LOCK) ||
1218                     (err = inet_sk_reselect_saddr(sk)) != 0)
1219                         sk->sk_err_soft = -err;
1220         }
1221
1222         return err;
1223 }
1224 EXPORT_SYMBOL(inet_sk_rebuild_header);
1225
1226 static struct sk_buff *inet_gso_segment(struct sk_buff *skb,
1227                                         netdev_features_t features)
1228 {
1229         struct sk_buff *segs = ERR_PTR(-EINVAL);
1230         const struct net_offload *ops;
1231         unsigned int offset = 0;
1232         bool udpfrag, encap;
1233         struct iphdr *iph;
1234         int proto;
1235         int nhoff;
1236         int ihl;
1237         int id;
1238
1239         if (unlikely(skb_shinfo(skb)->gso_type &
1240                      ~(SKB_GSO_TCPV4 |
1241                        SKB_GSO_UDP |
1242                        SKB_GSO_DODGY |
1243                        SKB_GSO_TCP_ECN |
1244                        SKB_GSO_GRE |
1245                        SKB_GSO_GRE_CSUM |
1246                        SKB_GSO_IPIP |
1247                        SKB_GSO_SIT |
1248                        SKB_GSO_TCPV6 |
1249                        SKB_GSO_UDP_TUNNEL |
1250                        SKB_GSO_UDP_TUNNEL_CSUM |
1251                        SKB_GSO_TUNNEL_REMCSUM |
1252                        0)))
1253                 goto out;
1254
1255         skb_reset_network_header(skb);
1256         nhoff = skb_network_header(skb) - skb_mac_header(skb);
1257         if (unlikely(!pskb_may_pull(skb, sizeof(*iph))))
1258                 goto out;
1259
1260         iph = ip_hdr(skb);
1261         ihl = iph->ihl * 4;
1262         if (ihl < sizeof(*iph))
1263                 goto out;
1264
1265         id = ntohs(iph->id);
1266         proto = iph->protocol;
1267
1268         /* Warning: after this point, iph might be no longer valid */
1269         if (unlikely(!pskb_may_pull(skb, ihl)))
1270                 goto out;
1271         __skb_pull(skb, ihl);
1272
1273         encap = SKB_GSO_CB(skb)->encap_level > 0;
1274         if (encap)
1275                 features &= skb->dev->hw_enc_features;
1276         SKB_GSO_CB(skb)->encap_level += ihl;
1277
1278         skb_reset_transport_header(skb);
1279
1280         segs = ERR_PTR(-EPROTONOSUPPORT);
1281
1282         if (skb->encapsulation &&
1283             skb_shinfo(skb)->gso_type & (SKB_GSO_SIT|SKB_GSO_IPIP))
1284                 udpfrag = proto == IPPROTO_UDP && encap;
1285         else
1286                 udpfrag = proto == IPPROTO_UDP && !skb->encapsulation;
1287
1288         ops = rcu_dereference(inet_offloads[proto]);
1289         if (likely(ops && ops->callbacks.gso_segment))
1290                 segs = ops->callbacks.gso_segment(skb, features);
1291
1292         if (IS_ERR_OR_NULL(segs))
1293                 goto out;
1294
1295         skb = segs;
1296         do {
1297                 iph = (struct iphdr *)(skb_mac_header(skb) + nhoff);
1298                 if (udpfrag) {
1299                         iph->id = htons(id);
1300                         iph->frag_off = htons(offset >> 3);
1301                         if (skb->next)
1302                                 iph->frag_off |= htons(IP_MF);
1303                         offset += skb->len - nhoff - ihl;
1304                 } else {
1305                         iph->id = htons(id++);
1306                 }
1307                 iph->tot_len = htons(skb->len - nhoff);
1308                 ip_send_check(iph);
1309                 if (encap)
1310                         skb_reset_inner_headers(skb);
1311                 skb->network_header = (u8 *)iph - skb->head;
1312         } while ((skb = skb->next));
1313
1314 out:
1315         return segs;
1316 }
1317
1318 static struct sk_buff **inet_gro_receive(struct sk_buff **head,
1319                                          struct sk_buff *skb)
1320 {
1321         const struct net_offload *ops;
1322         struct sk_buff **pp = NULL;
1323         struct sk_buff *p;
1324         const struct iphdr *iph;
1325         unsigned int hlen;
1326         unsigned int off;
1327         unsigned int id;
1328         int flush = 1;
1329         int proto;
1330
1331         off = skb_gro_offset(skb);
1332         hlen = off + sizeof(*iph);
1333         iph = skb_gro_header_fast(skb, off);
1334         if (skb_gro_header_hard(skb, hlen)) {
1335                 iph = skb_gro_header_slow(skb, hlen, off);
1336                 if (unlikely(!iph))
1337                         goto out;
1338         }
1339
1340         proto = iph->protocol;
1341
1342         rcu_read_lock();
1343         ops = rcu_dereference(inet_offloads[proto]);
1344         if (!ops || !ops->callbacks.gro_receive)
1345                 goto out_unlock;
1346
1347         if (*(u8 *)iph != 0x45)
1348                 goto out_unlock;
1349
1350         if (unlikely(ip_fast_csum((u8 *)iph, 5)))
1351                 goto out_unlock;
1352
1353         id = ntohl(*(__be32 *)&iph->id);
1354         flush = (u16)((ntohl(*(__be32 *)iph) ^ skb_gro_len(skb)) | (id & ~IP_DF));
1355         id >>= 16;
1356
1357         for (p = *head; p; p = p->next) {
1358                 struct iphdr *iph2;
1359
1360                 if (!NAPI_GRO_CB(p)->same_flow)
1361                         continue;
1362
1363                 iph2 = (struct iphdr *)(p->data + off);
1364                 /* The above works because, with the exception of the top
1365                  * (inner most) layer, we only aggregate pkts with the same
1366                  * hdr length so all the hdrs we'll need to verify will start
1367                  * at the same offset.
1368                  */
1369                 if ((iph->protocol ^ iph2->protocol) |
1370                     ((__force u32)iph->saddr ^ (__force u32)iph2->saddr) |
1371                     ((__force u32)iph->daddr ^ (__force u32)iph2->daddr)) {
1372                         NAPI_GRO_CB(p)->same_flow = 0;
1373                         continue;
1374                 }
1375
1376                 /* All fields must match except length and checksum. */
1377                 NAPI_GRO_CB(p)->flush |=
1378                         (iph->ttl ^ iph2->ttl) |
1379                         (iph->tos ^ iph2->tos) |
1380                         ((iph->frag_off ^ iph2->frag_off) & htons(IP_DF));
1381
1382                 /* Save the IP ID check to be included later when we get to
1383                  * the transport layer so only the inner most IP ID is checked.
1384                  * This is because some GSO/TSO implementations do not
1385                  * correctly increment the IP ID for the outer hdrs.
1386                  */
1387                 NAPI_GRO_CB(p)->flush_id =
1388                             ((u16)(ntohs(iph2->id) + NAPI_GRO_CB(p)->count) ^ id);
1389                 NAPI_GRO_CB(p)->flush |= flush;
1390         }
1391
1392         NAPI_GRO_CB(skb)->flush |= flush;
1393         skb_set_network_header(skb, off);
1394         /* The above will be needed by the transport layer if there is one
1395          * immediately following this IP hdr.
1396          */
1397
1398         /* Note : No need to call skb_gro_postpull_rcsum() here,
1399          * as we already checked checksum over ipv4 header was 0
1400          */
1401         skb_gro_pull(skb, sizeof(*iph));
1402         skb_set_transport_header(skb, skb_gro_offset(skb));
1403
1404         pp = ops->callbacks.gro_receive(head, skb);
1405
1406 out_unlock:
1407         rcu_read_unlock();
1408
1409 out:
1410         NAPI_GRO_CB(skb)->flush |= flush;
1411
1412         return pp;
1413 }
1414
1415 int inet_recv_error(struct sock *sk, struct msghdr *msg, int len, int *addr_len)
1416 {
1417         if (sk->sk_family == AF_INET)
1418                 return ip_recv_error(sk, msg, len, addr_len);
1419 #if IS_ENABLED(CONFIG_IPV6)
1420         if (sk->sk_family == AF_INET6)
1421                 return pingv6_ops.ipv6_recv_error(sk, msg, len, addr_len);
1422 #endif
1423         return -EINVAL;
1424 }
1425
1426 static int inet_gro_complete(struct sk_buff *skb, int nhoff)
1427 {
1428         __be16 newlen = htons(skb->len - nhoff);
1429         struct iphdr *iph = (struct iphdr *)(skb->data + nhoff);
1430         const struct net_offload *ops;
1431         int proto = iph->protocol;
1432         int err = -ENOSYS;
1433
1434         if (skb->encapsulation)
1435                 skb_set_inner_network_header(skb, nhoff);
1436
1437         csum_replace2(&iph->check, iph->tot_len, newlen);
1438         iph->tot_len = newlen;
1439
1440         rcu_read_lock();
1441         ops = rcu_dereference(inet_offloads[proto]);
1442         if (WARN_ON(!ops || !ops->callbacks.gro_complete))
1443                 goto out_unlock;
1444
1445         /* Only need to add sizeof(*iph) to get to the next hdr below
1446          * because any hdr with option will have been flushed in
1447          * inet_gro_receive().
1448          */
1449         err = ops->callbacks.gro_complete(skb, nhoff + sizeof(*iph));
1450
1451 out_unlock:
1452         rcu_read_unlock();
1453
1454         return err;
1455 }
1456
1457 int inet_ctl_sock_create(struct sock **sk, unsigned short family,
1458                          unsigned short type, unsigned char protocol,
1459                          struct net *net)
1460 {
1461         struct socket *sock;
1462         int rc = sock_create_kern(net, family, type, protocol, &sock);
1463
1464         if (rc == 0) {
1465                 *sk = sock->sk;
1466                 (*sk)->sk_allocation = GFP_ATOMIC;
1467                 /*
1468                  * Unhash it so that IP input processing does not even see it,
1469                  * we do not wish this socket to see incoming packets.
1470                  */
1471                 (*sk)->sk_prot->unhash(*sk);
1472         }
1473         return rc;
1474 }
1475 EXPORT_SYMBOL_GPL(inet_ctl_sock_create);
1476
1477 u64 snmp_get_cpu_field(void __percpu *mib, int cpu, int offt)
1478 {
1479         return  *(((unsigned long *)per_cpu_ptr(mib, cpu)) + offt);
1480 }
1481 EXPORT_SYMBOL_GPL(snmp_get_cpu_field);
1482
1483 unsigned long snmp_fold_field(void __percpu *mib, int offt)
1484 {
1485         unsigned long res = 0;
1486         int i;
1487
1488         for_each_possible_cpu(i)
1489                 res += snmp_get_cpu_field(mib, i, offt);
1490         return res;
1491 }
1492 EXPORT_SYMBOL_GPL(snmp_fold_field);
1493
1494 #if BITS_PER_LONG==32
1495
1496 u64 snmp_get_cpu_field64(void __percpu *mib, int cpu, int offt,
1497                          size_t syncp_offset)
1498 {
1499         void *bhptr;
1500         struct u64_stats_sync *syncp;
1501         u64 v;
1502         unsigned int start;
1503
1504         bhptr = per_cpu_ptr(mib, cpu);
1505         syncp = (struct u64_stats_sync *)(bhptr + syncp_offset);
1506         do {
1507                 start = u64_stats_fetch_begin_irq(syncp);
1508                 v = *(((u64 *)bhptr) + offt);
1509         } while (u64_stats_fetch_retry_irq(syncp, start));
1510
1511         return v;
1512 }
1513 EXPORT_SYMBOL_GPL(snmp_get_cpu_field64);
1514
1515 u64 snmp_fold_field64(void __percpu *mib, int offt, size_t syncp_offset)
1516 {
1517         u64 res = 0;
1518         int cpu;
1519
1520         for_each_possible_cpu(cpu) {
1521                 res += snmp_get_cpu_field64(mib, cpu, offt, syncp_offset);
1522         }
1523         return res;
1524 }
1525 EXPORT_SYMBOL_GPL(snmp_fold_field64);
1526 #endif
1527
1528 #ifdef CONFIG_IP_MULTICAST
1529 static const struct net_protocol igmp_protocol = {
1530         .handler =      igmp_rcv,
1531         .netns_ok =     1,
1532 };
1533 #endif
1534
1535 static const struct net_protocol tcp_protocol = {
1536         .early_demux    =       tcp_v4_early_demux,
1537         .handler        =       tcp_v4_rcv,
1538         .err_handler    =       tcp_v4_err,
1539         .no_policy      =       1,
1540         .netns_ok       =       1,
1541         .icmp_strict_tag_validation = 1,
1542 };
1543
1544 static const struct net_protocol udp_protocol = {
1545         .early_demux =  udp_v4_early_demux,
1546         .handler =      udp_rcv,
1547         .err_handler =  udp_err,
1548         .no_policy =    1,
1549         .netns_ok =     1,
1550 };
1551
1552 static const struct net_protocol icmp_protocol = {
1553         .handler =      icmp_rcv,
1554         .err_handler =  icmp_err,
1555         .no_policy =    1,
1556         .netns_ok =     1,
1557 };
1558
1559 static __net_init int ipv4_mib_init_net(struct net *net)
1560 {
1561         int i;
1562
1563         net->mib.tcp_statistics = alloc_percpu(struct tcp_mib);
1564         if (!net->mib.tcp_statistics)
1565                 goto err_tcp_mib;
1566         net->mib.ip_statistics = alloc_percpu(struct ipstats_mib);
1567         if (!net->mib.ip_statistics)
1568                 goto err_ip_mib;
1569
1570         for_each_possible_cpu(i) {
1571                 struct ipstats_mib *af_inet_stats;
1572                 af_inet_stats = per_cpu_ptr(net->mib.ip_statistics, i);
1573                 u64_stats_init(&af_inet_stats->syncp);
1574         }
1575
1576         net->mib.net_statistics = alloc_percpu(struct linux_mib);
1577         if (!net->mib.net_statistics)
1578                 goto err_net_mib;
1579         net->mib.udp_statistics = alloc_percpu(struct udp_mib);
1580         if (!net->mib.udp_statistics)
1581                 goto err_udp_mib;
1582         net->mib.udplite_statistics = alloc_percpu(struct udp_mib);
1583         if (!net->mib.udplite_statistics)
1584                 goto err_udplite_mib;
1585         net->mib.icmp_statistics = alloc_percpu(struct icmp_mib);
1586         if (!net->mib.icmp_statistics)
1587                 goto err_icmp_mib;
1588         net->mib.icmpmsg_statistics = kzalloc(sizeof(struct icmpmsg_mib),
1589                                               GFP_KERNEL);
1590         if (!net->mib.icmpmsg_statistics)
1591                 goto err_icmpmsg_mib;
1592
1593         tcp_mib_init(net);
1594         return 0;
1595
1596 err_icmpmsg_mib:
1597         free_percpu(net->mib.icmp_statistics);
1598 err_icmp_mib:
1599         free_percpu(net->mib.udplite_statistics);
1600 err_udplite_mib:
1601         free_percpu(net->mib.udp_statistics);
1602 err_udp_mib:
1603         free_percpu(net->mib.net_statistics);
1604 err_net_mib:
1605         free_percpu(net->mib.ip_statistics);
1606 err_ip_mib:
1607         free_percpu(net->mib.tcp_statistics);
1608 err_tcp_mib:
1609         return -ENOMEM;
1610 }
1611
1612 static __net_exit void ipv4_mib_exit_net(struct net *net)
1613 {
1614         kfree(net->mib.icmpmsg_statistics);
1615         free_percpu(net->mib.icmp_statistics);
1616         free_percpu(net->mib.udplite_statistics);
1617         free_percpu(net->mib.udp_statistics);
1618         free_percpu(net->mib.net_statistics);
1619         free_percpu(net->mib.ip_statistics);
1620         free_percpu(net->mib.tcp_statistics);
1621 }
1622
1623 static __net_initdata struct pernet_operations ipv4_mib_ops = {
1624         .init = ipv4_mib_init_net,
1625         .exit = ipv4_mib_exit_net,
1626 };
1627
1628 static int __init init_ipv4_mibs(void)
1629 {
1630         return register_pernet_subsys(&ipv4_mib_ops);
1631 }
1632
1633 static __net_init int inet_init_net(struct net *net)
1634 {
1635         /*
1636          * Set defaults for local port range
1637          */
1638         seqlock_init(&net->ipv4.ip_local_ports.lock);
1639         net->ipv4.ip_local_ports.range[0] =  32768;
1640         net->ipv4.ip_local_ports.range[1] =  60999;
1641
1642         seqlock_init(&net->ipv4.ping_group_range.lock);
1643         /*
1644          * Sane defaults - nobody may create ping sockets.
1645          * Boot scripts should set this to distro-specific group.
1646          */
1647         net->ipv4.ping_group_range.range[0] = make_kgid(&init_user_ns, 1);
1648         net->ipv4.ping_group_range.range[1] = make_kgid(&init_user_ns, 0);
1649         return 0;
1650 }
1651
1652 static __net_exit void inet_exit_net(struct net *net)
1653 {
1654 }
1655
1656 static __net_initdata struct pernet_operations af_inet_ops = {
1657         .init = inet_init_net,
1658         .exit = inet_exit_net,
1659 };
1660
1661 static int __init init_inet_pernet_ops(void)
1662 {
1663         return register_pernet_subsys(&af_inet_ops);
1664 }
1665
1666 static int ipv4_proc_init(void);
1667
1668 /*
1669  *      IP protocol layer initialiser
1670  */
1671
1672 static struct packet_offload ip_packet_offload __read_mostly = {
1673         .type = cpu_to_be16(ETH_P_IP),
1674         .callbacks = {
1675                 .gso_segment = inet_gso_segment,
1676                 .gro_receive = inet_gro_receive,
1677                 .gro_complete = inet_gro_complete,
1678         },
1679 };
1680
1681 static const struct net_offload ipip_offload = {
1682         .callbacks = {
1683                 .gso_segment    = inet_gso_segment,
1684                 .gro_receive    = inet_gro_receive,
1685                 .gro_complete   = inet_gro_complete,
1686         },
1687 };
1688
1689 static int __init ipv4_offload_init(void)
1690 {
1691         /*
1692          * Add offloads
1693          */
1694         if (udpv4_offload_init() < 0)
1695                 pr_crit("%s: Cannot add UDP protocol offload\n", __func__);
1696         if (tcpv4_offload_init() < 0)
1697                 pr_crit("%s: Cannot add TCP protocol offload\n", __func__);
1698
1699         dev_add_offload(&ip_packet_offload);
1700         inet_add_offload(&ipip_offload, IPPROTO_IPIP);
1701         return 0;
1702 }
1703
1704 fs_initcall(ipv4_offload_init);
1705
1706 static struct packet_type ip_packet_type __read_mostly = {
1707         .type = cpu_to_be16(ETH_P_IP),
1708         .func = ip_rcv,
1709 };
1710
1711 static int __init inet_init(void)
1712 {
1713         struct inet_protosw *q;
1714         struct list_head *r;
1715         int rc = -EINVAL;
1716
1717         sock_skb_cb_check_size(sizeof(struct inet_skb_parm));
1718
1719         rc = proto_register(&tcp_prot, 1);
1720         if (rc)
1721                 goto out;
1722
1723         rc = proto_register(&udp_prot, 1);
1724         if (rc)
1725                 goto out_unregister_tcp_proto;
1726
1727         rc = proto_register(&raw_prot, 1);
1728         if (rc)
1729                 goto out_unregister_udp_proto;
1730
1731         rc = proto_register(&ping_prot, 1);
1732         if (rc)
1733                 goto out_unregister_raw_proto;
1734
1735         /*
1736          *      Tell SOCKET that we are alive...
1737          */
1738
1739         (void)sock_register(&inet_family_ops);
1740
1741 #ifdef CONFIG_SYSCTL
1742         ip_static_sysctl_init();
1743 #endif
1744
1745         /*
1746          *      Add all the base protocols.
1747          */
1748
1749         if (inet_add_protocol(&icmp_protocol, IPPROTO_ICMP) < 0)
1750                 pr_crit("%s: Cannot add ICMP protocol\n", __func__);
1751         if (inet_add_protocol(&udp_protocol, IPPROTO_UDP) < 0)
1752                 pr_crit("%s: Cannot add UDP protocol\n", __func__);
1753         if (inet_add_protocol(&tcp_protocol, IPPROTO_TCP) < 0)
1754                 pr_crit("%s: Cannot add TCP protocol\n", __func__);
1755 #ifdef CONFIG_IP_MULTICAST
1756         if (inet_add_protocol(&igmp_protocol, IPPROTO_IGMP) < 0)
1757                 pr_crit("%s: Cannot add IGMP protocol\n", __func__);
1758 #endif
1759
1760         /* Register the socket-side information for inet_create. */
1761         for (r = &inetsw[0]; r < &inetsw[SOCK_MAX]; ++r)
1762                 INIT_LIST_HEAD(r);
1763
1764         for (q = inetsw_array; q < &inetsw_array[INETSW_ARRAY_LEN]; ++q)
1765                 inet_register_protosw(q);
1766
1767         /*
1768          *      Set the ARP module up
1769          */
1770
1771         arp_init();
1772
1773         /*
1774          *      Set the IP module up
1775          */
1776
1777         ip_init();
1778
1779         tcp_v4_init();
1780
1781         /* Setup TCP slab cache for open requests. */
1782         tcp_init();
1783
1784         /* Setup UDP memory threshold */
1785         udp_init();
1786
1787         /* Add UDP-Lite (RFC 3828) */
1788         udplite4_register();
1789
1790         ping_init();
1791
1792         /*
1793          *      Set the ICMP layer up
1794          */
1795
1796         if (icmp_init() < 0)
1797                 panic("Failed to create the ICMP control socket.\n");
1798
1799         /*
1800          *      Initialise the multicast router
1801          */
1802 #if defined(CONFIG_IP_MROUTE)
1803         if (ip_mr_init())
1804                 pr_crit("%s: Cannot init ipv4 mroute\n", __func__);
1805 #endif
1806
1807         if (init_inet_pernet_ops())
1808                 pr_crit("%s: Cannot init ipv4 inet pernet ops\n", __func__);
1809         /*
1810          *      Initialise per-cpu ipv4 mibs
1811          */
1812
1813         if (init_ipv4_mibs())
1814                 pr_crit("%s: Cannot init ipv4 mibs\n", __func__);
1815
1816         ipv4_proc_init();
1817
1818         ipfrag_init();
1819
1820         dev_add_pack(&ip_packet_type);
1821
1822         ip_tunnel_core_init();
1823
1824         rc = 0;
1825 out:
1826         return rc;
1827 out_unregister_raw_proto:
1828         proto_unregister(&raw_prot);
1829 out_unregister_udp_proto:
1830         proto_unregister(&udp_prot);
1831 out_unregister_tcp_proto:
1832         proto_unregister(&tcp_prot);
1833         goto out;
1834 }
1835
1836 fs_initcall(inet_init);
1837
1838 /* ------------------------------------------------------------------------ */
1839
1840 #ifdef CONFIG_PROC_FS
1841 static int __init ipv4_proc_init(void)
1842 {
1843         int rc = 0;
1844
1845         if (raw_proc_init())
1846                 goto out_raw;
1847         if (tcp4_proc_init())
1848                 goto out_tcp;
1849         if (udp4_proc_init())
1850                 goto out_udp;
1851         if (ping_proc_init())
1852                 goto out_ping;
1853         if (ip_misc_proc_init())
1854                 goto out_misc;
1855 out:
1856         return rc;
1857 out_misc:
1858         ping_proc_exit();
1859 out_ping:
1860         udp4_proc_exit();
1861 out_udp:
1862         tcp4_proc_exit();
1863 out_tcp:
1864         raw_proc_exit();
1865 out_raw:
1866         rc = -ENOMEM;
1867         goto out;
1868 }
1869
1870 #else /* CONFIG_PROC_FS */
1871 static int __init ipv4_proc_init(void)
1872 {
1873         return 0;
1874 }
1875 #endif /* CONFIG_PROC_FS */
1876
1877 MODULE_ALIAS_NETPROTO(PF_INET);
1878