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