xref: /linux/net/socket.c (revision ff8747aacaff8266dd751b8a8648fb728dcc3b21)
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NET		An implementation of the SOCKET network access protocol.
4  *
5  * Version:	@(#)socket.c	1.1.93	18/02/95
6  *
7  * Authors:	Orest Zborowski, <obz@Kodak.COM>
8  *		Ross Biro
9  *		Fred N. van Kempen, <waltje@uWalt.NL.Mugnet.ORG>
10  *
11  * Fixes:
12  *		Anonymous	:	NOTSOCK/BADF cleanup. Error fix in
13  *					shutdown()
14  *		Alan Cox	:	verify_area() fixes
15  *		Alan Cox	:	Removed DDI
16  *		Jonathan Kamens	:	SOCK_DGRAM reconnect bug
17  *		Alan Cox	:	Moved a load of checks to the very
18  *					top level.
19  *		Alan Cox	:	Move address structures to/from user
20  *					mode above the protocol layers.
21  *		Rob Janssen	:	Allow 0 length sends.
22  *		Alan Cox	:	Asynchronous I/O support (cribbed from the
23  *					tty drivers).
24  *		Niibe Yutaka	:	Asynchronous I/O for writes (4.4BSD style)
25  *		Jeff Uphoff	:	Made max number of sockets command-line
26  *					configurable.
27  *		Matti Aarnio	:	Made the number of sockets dynamic,
28  *					to be allocated when needed, and mr.
29  *					Uphoff's max is used as max to be
30  *					allowed to allocate.
31  *		Linus		:	Argh. removed all the socket allocation
32  *					altogether: it's in the inode now.
33  *		Alan Cox	:	Made sock_alloc()/sock_release() public
34  *					for NetROM and future kernel nfsd type
35  *					stuff.
36  *		Alan Cox	:	sendmsg/recvmsg basics.
37  *		Tom Dyas	:	Export net symbols.
38  *		Marcin Dalecki	:	Fixed problems with CONFIG_NET="n".
39  *		Alan Cox	:	Added thread locking to sys_* calls
40  *					for sockets. May have errors at the
41  *					moment.
42  *		Kevin Buhr	:	Fixed the dumb errors in the above.
43  *		Andi Kleen	:	Some small cleanups, optimizations,
44  *					and fixed a copy_from_user() bug.
45  *		Tigran Aivazian	:	sys_send(args) calls sys_sendto(args, NULL, 0)
46  *		Tigran Aivazian	:	Made listen(2) backlog sanity checks
47  *					protocol-independent
48  *
49  *	This module is effectively the top level interface to the BSD socket
50  *	paradigm.
51  *
52  *	Based upon Swansea University Computer Society NET3.039
53  */
54 
55 #include <linux/bpf-cgroup.h>
56 #include <linux/ethtool.h>
57 #include <linux/mm.h>
58 #include <linux/socket.h>
59 #include <linux/file.h>
60 #include <linux/splice.h>
61 #include <linux/net.h>
62 #include <linux/interrupt.h>
63 #include <linux/thread_info.h>
64 #include <linux/rcupdate.h>
65 #include <linux/netdevice.h>
66 #include <linux/proc_fs.h>
67 #include <linux/seq_file.h>
68 #include <linux/mutex.h>
69 #include <linux/if_bridge.h>
70 #include <linux/if_vlan.h>
71 #include <linux/ptp_classify.h>
72 #include <linux/init.h>
73 #include <linux/poll.h>
74 #include <linux/cache.h>
75 #include <linux/module.h>
76 #include <linux/highmem.h>
77 #include <linux/mount.h>
78 #include <linux/pseudo_fs.h>
79 #include <linux/security.h>
80 #include <linux/uio.h>
81 #include <linux/syscalls.h>
82 #include <linux/compat.h>
83 #include <linux/kmod.h>
84 #include <linux/audit.h>
85 #include <linux/wireless.h>
86 #include <linux/nsproxy.h>
87 #include <linux/magic.h>
88 #include <linux/slab.h>
89 #include <linux/xattr.h>
90 #include <linux/nospec.h>
91 #include <linux/indirect_call_wrapper.h>
92 #include <linux/io_uring/net.h>
93 
94 #include <linux/uaccess.h>
95 #include <asm/unistd.h>
96 
97 #include <net/compat.h>
98 #include <net/wext.h>
99 #include <net/cls_cgroup.h>
100 
101 #include <net/sock.h>
102 #include <linux/netfilter.h>
103 
104 #include <linux/if_tun.h>
105 #include <linux/ipv6_route.h>
106 #include <linux/route.h>
107 #include <linux/termios.h>
108 #include <linux/sockios.h>
109 #include <net/busy_poll.h>
110 #include <linux/errqueue.h>
111 #include <linux/ptp_clock_kernel.h>
112 #include <trace/events/sock.h>
113 
114 #include "core/dev.h"
115 
116 #ifdef CONFIG_NET_RX_BUSY_POLL
117 unsigned int sysctl_net_busy_read __read_mostly;
118 unsigned int sysctl_net_busy_poll __read_mostly;
119 #endif
120 
121 static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to);
122 static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from);
123 static int sock_mmap(struct file *file, struct vm_area_struct *vma);
124 
125 static int sock_close(struct inode *inode, struct file *file);
126 static __poll_t sock_poll(struct file *file,
127 			      struct poll_table_struct *wait);
128 static long sock_ioctl(struct file *file, unsigned int cmd, unsigned long arg);
129 #ifdef CONFIG_COMPAT
130 static long compat_sock_ioctl(struct file *file,
131 			      unsigned int cmd, unsigned long arg);
132 #endif
133 static int sock_fasync(int fd, struct file *filp, int on);
134 static ssize_t sock_splice_read(struct file *file, loff_t *ppos,
135 				struct pipe_inode_info *pipe, size_t len,
136 				unsigned int flags);
137 static void sock_splice_eof(struct file *file);
138 
139 #ifdef CONFIG_PROC_FS
140 static void sock_show_fdinfo(struct seq_file *m, struct file *f)
141 {
142 	struct socket *sock = f->private_data;
143 	const struct proto_ops *ops = READ_ONCE(sock->ops);
144 
145 	if (ops->show_fdinfo)
146 		ops->show_fdinfo(m, sock);
147 }
148 #else
149 #define sock_show_fdinfo NULL
150 #endif
151 
152 /*
153  *	Socket files have a set of 'special' operations as well as the generic file ones. These don't appear
154  *	in the operation structures but are done directly via the socketcall() multiplexor.
155  */
156 
157 static const struct file_operations socket_file_ops = {
158 	.owner =	THIS_MODULE,
159 	.read_iter =	sock_read_iter,
160 	.write_iter =	sock_write_iter,
161 	.poll =		sock_poll,
162 	.unlocked_ioctl = sock_ioctl,
163 #ifdef CONFIG_COMPAT
164 	.compat_ioctl = compat_sock_ioctl,
165 #endif
166 	.uring_cmd =    io_uring_cmd_sock,
167 	.mmap =		sock_mmap,
168 	.release =	sock_close,
169 	.fasync =	sock_fasync,
170 	.splice_write = splice_to_socket,
171 	.splice_read =	sock_splice_read,
172 	.splice_eof =	sock_splice_eof,
173 	.show_fdinfo =	sock_show_fdinfo,
174 };
175 
176 static const char * const pf_family_names[] = {
177 	[PF_UNSPEC]	= "PF_UNSPEC",
178 	[PF_UNIX]	= "PF_UNIX/PF_LOCAL",
179 	[PF_INET]	= "PF_INET",
180 	[PF_AX25]	= "PF_AX25",
181 	[PF_IPX]	= "PF_IPX",
182 	[PF_APPLETALK]	= "PF_APPLETALK",
183 	[PF_NETROM]	= "PF_NETROM",
184 	[PF_BRIDGE]	= "PF_BRIDGE",
185 	[PF_ATMPVC]	= "PF_ATMPVC",
186 	[PF_X25]	= "PF_X25",
187 	[PF_INET6]	= "PF_INET6",
188 	[PF_ROSE]	= "PF_ROSE",
189 	[PF_DECnet]	= "PF_DECnet",
190 	[PF_NETBEUI]	= "PF_NETBEUI",
191 	[PF_SECURITY]	= "PF_SECURITY",
192 	[PF_KEY]	= "PF_KEY",
193 	[PF_NETLINK]	= "PF_NETLINK/PF_ROUTE",
194 	[PF_PACKET]	= "PF_PACKET",
195 	[PF_ASH]	= "PF_ASH",
196 	[PF_ECONET]	= "PF_ECONET",
197 	[PF_ATMSVC]	= "PF_ATMSVC",
198 	[PF_RDS]	= "PF_RDS",
199 	[PF_SNA]	= "PF_SNA",
200 	[PF_IRDA]	= "PF_IRDA",
201 	[PF_PPPOX]	= "PF_PPPOX",
202 	[PF_WANPIPE]	= "PF_WANPIPE",
203 	[PF_LLC]	= "PF_LLC",
204 	[PF_IB]		= "PF_IB",
205 	[PF_MPLS]	= "PF_MPLS",
206 	[PF_CAN]	= "PF_CAN",
207 	[PF_TIPC]	= "PF_TIPC",
208 	[PF_BLUETOOTH]	= "PF_BLUETOOTH",
209 	[PF_IUCV]	= "PF_IUCV",
210 	[PF_RXRPC]	= "PF_RXRPC",
211 	[PF_ISDN]	= "PF_ISDN",
212 	[PF_PHONET]	= "PF_PHONET",
213 	[PF_IEEE802154]	= "PF_IEEE802154",
214 	[PF_CAIF]	= "PF_CAIF",
215 	[PF_ALG]	= "PF_ALG",
216 	[PF_NFC]	= "PF_NFC",
217 	[PF_VSOCK]	= "PF_VSOCK",
218 	[PF_KCM]	= "PF_KCM",
219 	[PF_QIPCRTR]	= "PF_QIPCRTR",
220 	[PF_SMC]	= "PF_SMC",
221 	[PF_XDP]	= "PF_XDP",
222 	[PF_MCTP]	= "PF_MCTP",
223 };
224 
225 /*
226  *	The protocol list. Each protocol is registered in here.
227  */
228 
229 static DEFINE_SPINLOCK(net_family_lock);
230 static const struct net_proto_family __rcu *net_families[NPROTO] __read_mostly;
231 
232 /*
233  * Support routines.
234  * Move socket addresses back and forth across the kernel/user
235  * divide and look after the messy bits.
236  */
237 
238 /**
239  *	move_addr_to_kernel	-	copy a socket address into kernel space
240  *	@uaddr: Address in user space
241  *	@kaddr: Address in kernel space
242  *	@ulen: Length in user space
243  *
244  *	The address is copied into kernel space. If the provided address is
245  *	too long an error code of -EINVAL is returned. If the copy gives
246  *	invalid addresses -EFAULT is returned. On a success 0 is returned.
247  */
248 
249 int move_addr_to_kernel(void __user *uaddr, int ulen, struct sockaddr_storage *kaddr)
250 {
251 	if (ulen < 0 || ulen > sizeof(struct sockaddr_storage))
252 		return -EINVAL;
253 	if (ulen == 0)
254 		return 0;
255 	if (copy_from_user(kaddr, uaddr, ulen))
256 		return -EFAULT;
257 	return audit_sockaddr(ulen, kaddr);
258 }
259 
260 /**
261  *	move_addr_to_user	-	copy an address to user space
262  *	@kaddr: kernel space address
263  *	@klen: length of address in kernel
264  *	@uaddr: user space address
265  *	@ulen: pointer to user length field
266  *
267  *	The value pointed to by ulen on entry is the buffer length available.
268  *	This is overwritten with the buffer space used. -EINVAL is returned
269  *	if an overlong buffer is specified or a negative buffer size. -EFAULT
270  *	is returned if either the buffer or the length field are not
271  *	accessible.
272  *	After copying the data up to the limit the user specifies, the true
273  *	length of the data is written over the length limit the user
274  *	specified. Zero is returned for a success.
275  */
276 
277 static int move_addr_to_user(struct sockaddr_storage *kaddr, int klen,
278 			     void __user *uaddr, int __user *ulen)
279 {
280 	int len;
281 
282 	BUG_ON(klen > sizeof(struct sockaddr_storage));
283 
284 	scoped_user_rw_access_size(ulen, 4, efault_end) {
285 		unsafe_get_user(len, ulen, efault_end);
286 
287 		if (len > klen)
288 			len = klen;
289 		/*
290 		 *      "fromlen shall refer to the value before truncation.."
291 		 *                      1003.1g
292 		 */
293 		if (len >= 0)
294 			unsafe_put_user(klen, ulen, efault_end);
295 	}
296 
297 	if (len) {
298 		if (len < 0)
299 			return -EINVAL;
300 		if (audit_sockaddr(klen, kaddr))
301 			return -ENOMEM;
302 		if (copy_to_user(uaddr, kaddr, len))
303 			return -EFAULT;
304 	}
305 	return 0;
306 
307 efault_end:
308 	return -EFAULT;
309 }
310 
311 static struct kmem_cache *sock_inode_cachep __ro_after_init;
312 
313 static struct simple_xattr_cache sockfs_xa_cache;
314 
315 struct sockfs_inode {
316 	struct list_head xattrs;
317 	struct simple_xattr_limits xattr_limits;
318 	struct socket_alloc;
319 };
320 
321 static struct sockfs_inode *SOCKFS_I(struct inode *inode)
322 {
323 	return container_of(inode, struct sockfs_inode, vfs_inode);
324 }
325 
326 static struct inode *sock_alloc_inode(struct super_block *sb)
327 {
328 	struct sockfs_inode *si;
329 
330 	si = alloc_inode_sb(sb, sock_inode_cachep, GFP_KERNEL);
331 	if (!si)
332 		return NULL;
333 	INIT_LIST_HEAD_RCU(&si->xattrs);
334 	simple_xattr_limits_init(&si->xattr_limits);
335 
336 	init_waitqueue_head(&si->socket.wq.wait);
337 	si->socket.wq.fasync_list = NULL;
338 	si->socket.wq.flags = 0;
339 
340 	si->socket.state = SS_UNCONNECTED;
341 	si->socket.flags = 0;
342 	si->socket.ops = NULL;
343 	si->socket.sk = NULL;
344 	si->socket.file = NULL;
345 
346 	return &si->vfs_inode;
347 }
348 
349 static void sock_evict_inode(struct inode *inode)
350 {
351 	struct sockfs_inode *si = SOCKFS_I(inode);
352 
353 	simple_xattrs_free(&sockfs_xa_cache, &si->xattrs, NULL);
354 	clear_inode(inode);
355 }
356 
357 static void sock_free_inode(struct inode *inode)
358 {
359 	struct sockfs_inode *si = SOCKFS_I(inode);
360 
361 	kmem_cache_free(sock_inode_cachep, si);
362 }
363 
364 static void init_once(void *foo)
365 {
366 	struct sockfs_inode *si = (struct sockfs_inode *)foo;
367 
368 	inode_init_once(&si->vfs_inode);
369 }
370 
371 static void init_inodecache(void)
372 {
373 	sock_inode_cachep = kmem_cache_create("sock_inode_cache",
374 					      sizeof(struct sockfs_inode),
375 					      0,
376 					      (SLAB_HWCACHE_ALIGN |
377 					       SLAB_RECLAIM_ACCOUNT |
378 					       SLAB_ACCOUNT),
379 					      init_once);
380 	BUG_ON(sock_inode_cachep == NULL);
381 }
382 
383 static const struct super_operations sockfs_ops = {
384 	.alloc_inode	= sock_alloc_inode,
385 	.free_inode	= sock_free_inode,
386 	.evict_inode	= sock_evict_inode,
387 	.statfs		= simple_statfs,
388 };
389 
390 /*
391  * sockfs_dname() is called from d_path().
392  */
393 static char *sockfs_dname(struct dentry *dentry, char *buffer, int buflen)
394 {
395 	return dynamic_dname(buffer, buflen, "socket:[%llu]",
396 				d_inode(dentry)->i_ino);
397 }
398 
399 static const struct dentry_operations sockfs_dentry_operations = {
400 	.d_dname  = sockfs_dname,
401 };
402 
403 static int sockfs_xattr_get(const struct xattr_handler *handler,
404 			    struct dentry *dentry, struct inode *inode,
405 			    const char *suffix, void *value, size_t size)
406 {
407 	if (value) {
408 		if (dentry->d_name.len + 1 > size)
409 			return -ERANGE;
410 		memcpy(value, dentry->d_name.name, dentry->d_name.len + 1);
411 	}
412 	return dentry->d_name.len + 1;
413 }
414 
415 #define XATTR_SOCKPROTONAME_SUFFIX "sockprotoname"
416 #define XATTR_NAME_SOCKPROTONAME (XATTR_SYSTEM_PREFIX XATTR_SOCKPROTONAME_SUFFIX)
417 #define XATTR_NAME_SOCKPROTONAME_LEN (sizeof(XATTR_NAME_SOCKPROTONAME)-1)
418 
419 static const struct xattr_handler sockfs_xattr_handler = {
420 	.name = XATTR_NAME_SOCKPROTONAME,
421 	.get = sockfs_xattr_get,
422 };
423 
424 static int sockfs_security_xattr_set(const struct xattr_handler *handler,
425 				     struct mnt_idmap *idmap,
426 				     struct dentry *dentry, struct inode *inode,
427 				     const char *suffix, const void *value,
428 				     size_t size, int flags)
429 {
430 	/* Handled by LSM. */
431 	return -EAGAIN;
432 }
433 
434 static const struct xattr_handler sockfs_security_xattr_handler = {
435 	.prefix = XATTR_SECURITY_PREFIX,
436 	.set = sockfs_security_xattr_set,
437 };
438 
439 static int sockfs_user_xattr_get(const struct xattr_handler *handler,
440 				 struct dentry *dentry, struct inode *inode,
441 				 const char *suffix, void *value, size_t size)
442 {
443 	const char *name = xattr_full_name(handler, suffix);
444 	struct sockfs_inode *si = SOCKFS_I(inode);
445 
446 	return simple_xattr_get(&sockfs_xa_cache, &si->xattrs, name, value, size);
447 }
448 
449 static int sockfs_user_xattr_set(const struct xattr_handler *handler,
450 				 struct mnt_idmap *idmap,
451 				 struct dentry *dentry, struct inode *inode,
452 				 const char *suffix, const void *value,
453 				 size_t size, int flags)
454 {
455 	const char *name = xattr_full_name(handler, suffix);
456 	struct sockfs_inode *si = SOCKFS_I(inode);
457 
458 	return simple_xattr_set_limited(&sockfs_xa_cache, &si->xattrs, &si->xattr_limits,
459 					name, value, size, flags);
460 }
461 
462 static const struct xattr_handler sockfs_user_xattr_handler = {
463 	.prefix = XATTR_USER_PREFIX,
464 	.get = sockfs_user_xattr_get,
465 	.set = sockfs_user_xattr_set,
466 };
467 
468 static const struct xattr_handler * const sockfs_xattr_handlers[] = {
469 	&sockfs_xattr_handler,
470 	&sockfs_security_xattr_handler,
471 	&sockfs_user_xattr_handler,
472 	NULL
473 };
474 
475 static int sockfs_init_fs_context(struct fs_context *fc)
476 {
477 	struct pseudo_fs_context *ctx = init_pseudo(fc, SOCKFS_MAGIC);
478 	if (!ctx)
479 		return -ENOMEM;
480 	ctx->ops = &sockfs_ops;
481 	ctx->dops = &sockfs_dentry_operations;
482 	ctx->xattr = sockfs_xattr_handlers;
483 	return 0;
484 }
485 
486 static struct vfsmount *sock_mnt __read_mostly;
487 
488 static struct file_system_type sock_fs_type = {
489 	.name =		"sockfs",
490 	.init_fs_context = sockfs_init_fs_context,
491 	.kill_sb =	kill_anon_super,
492 };
493 
494 /*
495  *	Obtains the first available file descriptor and sets it up for use.
496  *
497  *	These functions create file structures and maps them to fd space
498  *	of the current process. On success it returns file descriptor
499  *	and file struct implicitly stored in sock->file.
500  *	Note that another thread may close file descriptor before we return
501  *	from this function. We use the fact that now we do not refer
502  *	to socket after mapping. If one day we will need it, this
503  *	function will increment ref. count on file by 1.
504  *
505  *	In any case returned fd MAY BE not valid!
506  *	This race condition is unavoidable
507  *	with shared fd spaces, we cannot solve it inside kernel,
508  *	but we take care of internal coherence yet.
509  */
510 
511 /**
512  *	sock_alloc_file - Bind a &socket to a &file
513  *	@sock: socket
514  *	@flags: file status flags
515  *	@dname: protocol name
516  *
517  *	Returns the &file bound with @sock, implicitly storing it
518  *	in sock->file. If dname is %NULL, sets to "".
519  *
520  *	On failure @sock is released, and an ERR pointer is returned.
521  *
522  *	This function uses GFP_KERNEL internally.
523  */
524 
525 struct file *sock_alloc_file(struct socket *sock, int flags, const char *dname)
526 {
527 	struct file *file;
528 
529 	if (!dname)
530 		dname = sock->sk ? sock->sk->sk_prot_creator->name : "";
531 
532 	file = alloc_file_pseudo(SOCK_INODE(sock), sock_mnt, dname,
533 				O_RDWR | (flags & O_NONBLOCK),
534 				&socket_file_ops);
535 	if (IS_ERR(file)) {
536 		sock_release(sock);
537 		return file;
538 	}
539 
540 	file->f_mode |= FMODE_NOWAIT;
541 	sock->file = file;
542 	file->private_data = sock;
543 	stream_open(SOCK_INODE(sock), file);
544 	/*
545 	 * Disable permission and pre-content events, but enable legacy
546 	 * inotify events for legacy users.
547 	 */
548 	file_set_fsnotify_mode(file, FMODE_NONOTIFY_PERM);
549 	return file;
550 }
551 EXPORT_SYMBOL(sock_alloc_file);
552 
553 static int sock_map_fd(struct socket *sock, int flags)
554 {
555 	struct file *newfile;
556 	int fd = get_unused_fd_flags(flags);
557 	if (unlikely(fd < 0)) {
558 		sock_release(sock);
559 		return fd;
560 	}
561 
562 	newfile = sock_alloc_file(sock, flags, NULL);
563 	if (!IS_ERR(newfile)) {
564 		fd_install(fd, newfile);
565 		return fd;
566 	}
567 
568 	put_unused_fd(fd);
569 	return PTR_ERR(newfile);
570 }
571 
572 /**
573  *	sock_from_file - Return the &socket bounded to @file.
574  *	@file: file
575  *
576  *	On failure returns %NULL.
577  */
578 
579 struct socket *sock_from_file(struct file *file)
580 {
581 	if (likely(file->f_op == &socket_file_ops))
582 		return file->private_data;	/* set in sock_alloc_file */
583 
584 	return NULL;
585 }
586 EXPORT_SYMBOL(sock_from_file);
587 
588 /**
589  *	sockfd_lookup - Go from a file number to its socket slot
590  *	@fd: file handle
591  *	@err: pointer to an error code return
592  *
593  *	The file handle passed in is locked and the socket it is bound
594  *	to is returned. If an error occurs the err pointer is overwritten
595  *	with a negative errno code and NULL is returned. The function checks
596  *	for both invalid handles and passing a handle which is not a socket.
597  *
598  *	On a success the socket object pointer is returned.
599  */
600 
601 struct socket *sockfd_lookup(int fd, int *err)
602 {
603 	struct file *file;
604 	struct socket *sock;
605 
606 	file = fget(fd);
607 	if (!file) {
608 		*err = -EBADF;
609 		return NULL;
610 	}
611 
612 	sock = sock_from_file(file);
613 	if (!sock) {
614 		*err = -ENOTSOCK;
615 		fput(file);
616 	}
617 	return sock;
618 }
619 EXPORT_SYMBOL(sockfd_lookup);
620 
621 static ssize_t sockfs_listxattr(struct dentry *dentry, char *buffer,
622 				size_t size)
623 {
624 	struct sockfs_inode *si = SOCKFS_I(d_inode(dentry));
625 	ssize_t len, used;
626 
627 	len = simple_xattr_list(d_inode(dentry), &si->xattrs, buffer, size);
628 	if (len < 0)
629 		return len;
630 
631 	used = len;
632 	if (buffer) {
633 		buffer += len;
634 		size -= len;
635 	}
636 
637 	len = XATTR_NAME_SOCKPROTONAME_LEN + 1;
638 	used += len;
639 	if (buffer) {
640 		if (size < len)
641 			return -ERANGE;
642 		memcpy(buffer, XATTR_NAME_SOCKPROTONAME, len);
643 	}
644 
645 	return used;
646 }
647 
648 static int sockfs_setattr(struct mnt_idmap *idmap,
649 			  struct dentry *dentry, struct iattr *iattr)
650 {
651 	int err = simple_setattr(&nop_mnt_idmap, dentry, iattr);
652 
653 	if (!err && (iattr->ia_valid & ATTR_UID)) {
654 		struct socket *sock = SOCKET_I(d_inode(dentry));
655 
656 		if (sock->sk) {
657 			/* Paired with READ_ONCE() in sk_uid() */
658 			WRITE_ONCE(sock->sk->sk_uid, iattr->ia_uid);
659 		} else {
660 			err = -ENOENT;
661 		}
662 	}
663 
664 	return err;
665 }
666 
667 static const struct inode_operations sockfs_inode_ops = {
668 	.listxattr = sockfs_listxattr,
669 	.setattr = sockfs_setattr,
670 };
671 
672 /**
673  *	sock_alloc - allocate a socket
674  *
675  *	Allocate a new inode and socket object. The two are bound together
676  *	and initialised. The socket is then returned. If we are out of inodes
677  *	NULL is returned. This functions uses GFP_KERNEL internally.
678  */
679 
680 struct socket *sock_alloc(void)
681 {
682 	struct inode *inode;
683 	struct socket *sock;
684 
685 	inode = new_inode_pseudo(sock_mnt->mnt_sb);
686 	if (!inode)
687 		return NULL;
688 
689 	sock = SOCKET_I(inode);
690 
691 	inode->i_ino = get_next_ino();
692 	inode->i_mode = S_IFSOCK | S_IRWXUGO;
693 	inode->i_uid = current_fsuid();
694 	inode->i_gid = current_fsgid();
695 	inode->i_op = &sockfs_inode_ops;
696 
697 	return sock;
698 }
699 EXPORT_SYMBOL(sock_alloc);
700 
701 static void __sock_release(struct socket *sock, struct inode *inode)
702 {
703 	const struct proto_ops *ops = READ_ONCE(sock->ops);
704 
705 	if (ops) {
706 		struct module *owner = ops->owner;
707 
708 		if (inode)
709 			inode_lock(inode);
710 		ops->release(sock);
711 		sock->sk = NULL;
712 		if (inode)
713 			inode_unlock(inode);
714 		sock->ops = NULL;
715 		module_put(owner);
716 	}
717 
718 	if (sock->wq.fasync_list)
719 		pr_err("%s: fasync list not empty!\n", __func__);
720 
721 	if (!sock->file) {
722 		iput(SOCK_INODE(sock));
723 		return;
724 	}
725 	WRITE_ONCE(sock->file, NULL);
726 }
727 
728 /**
729  *	sock_release - close a socket
730  *	@sock: socket to close
731  *
732  *	The socket is released from the protocol stack if it has a release
733  *	callback, and the inode is then released if the socket is bound to
734  *	an inode not a file.
735  */
736 void sock_release(struct socket *sock)
737 {
738 	__sock_release(sock, NULL);
739 }
740 EXPORT_SYMBOL(sock_release);
741 
742 void __sock_tx_timestamp(__u32 tsflags, __u8 *tx_flags)
743 {
744 	u8 flags = *tx_flags;
745 
746 	if (tsflags & SOF_TIMESTAMPING_TX_HARDWARE)
747 		flags |= SKBTX_HW_TSTAMP_NOBPF;
748 
749 	if (tsflags & SOF_TIMESTAMPING_TX_SOFTWARE)
750 		flags |= SKBTX_SW_TSTAMP;
751 
752 	if (tsflags & SOF_TIMESTAMPING_TX_SCHED)
753 		flags |= SKBTX_SCHED_TSTAMP;
754 
755 	if (tsflags & SOF_TIMESTAMPING_TX_COMPLETION)
756 		flags |= SKBTX_COMPLETION_TSTAMP;
757 
758 	*tx_flags = flags;
759 }
760 EXPORT_SYMBOL(__sock_tx_timestamp);
761 
762 INDIRECT_CALLABLE_DECLARE(int inet_sendmsg(struct socket *, struct msghdr *,
763 					   size_t));
764 INDIRECT_CALLABLE_DECLARE(int inet6_sendmsg(struct socket *, struct msghdr *,
765 					    size_t));
766 
767 static noinline void call_trace_sock_send_length(struct sock *sk, int ret,
768 						 int flags)
769 {
770 	trace_sock_send_length(sk, ret, 0);
771 }
772 
773 static inline int sock_sendmsg_nosec(struct socket *sock, struct msghdr *msg)
774 {
775 	int ret = INDIRECT_CALL_INET(READ_ONCE(sock->ops)->sendmsg, inet6_sendmsg,
776 				     inet_sendmsg, sock, msg,
777 				     msg_data_left(msg));
778 	BUG_ON(ret == -EIOCBQUEUED);
779 
780 	if (trace_sock_send_length_enabled())
781 		call_trace_sock_send_length(sock->sk, ret, 0);
782 	return ret;
783 }
784 
785 static int __sock_sendmsg(struct socket *sock, struct msghdr *msg)
786 {
787 	int err = security_socket_sendmsg(sock, msg,
788 					  msg_data_left(msg));
789 
790 	return err ?: sock_sendmsg_nosec(sock, msg);
791 }
792 
793 /**
794  *	sock_sendmsg - send a message through @sock
795  *	@sock: socket
796  *	@msg: message to send
797  *
798  *	Sends @msg through @sock, passing through LSM.
799  *	Returns the number of bytes sent, or an error code.
800  */
801 int sock_sendmsg(struct socket *sock, struct msghdr *msg)
802 {
803 	struct sockaddr_storage *save_addr = (struct sockaddr_storage *)msg->msg_name;
804 	struct sockaddr_storage address;
805 	int save_len = msg->msg_namelen;
806 	int ret;
807 
808 	if (msg->msg_name) {
809 		memcpy(&address, msg->msg_name, msg->msg_namelen);
810 		msg->msg_name = &address;
811 	}
812 
813 	ret = __sock_sendmsg(sock, msg);
814 	msg->msg_name = save_addr;
815 	msg->msg_namelen = save_len;
816 
817 	return ret;
818 }
819 EXPORT_SYMBOL(sock_sendmsg);
820 
821 /**
822  *	kernel_sendmsg - send a message through @sock (kernel-space)
823  *	@sock: socket
824  *	@msg: message header
825  *	@vec: kernel vec
826  *	@num: vec array length
827  *	@size: total message data size
828  *
829  *	Builds the message data with @vec and sends it through @sock.
830  *	Returns the number of bytes sent, or an error code.
831  */
832 
833 int kernel_sendmsg(struct socket *sock, struct msghdr *msg,
834 		   struct kvec *vec, size_t num, size_t size)
835 {
836 	iov_iter_kvec(&msg->msg_iter, ITER_SOURCE, vec, num, size);
837 	return sock_sendmsg(sock, msg);
838 }
839 EXPORT_SYMBOL(kernel_sendmsg);
840 
841 static bool skb_is_err_queue(const struct sk_buff *skb)
842 {
843 	/* Error-queue skbs are marked as PACKET_OUTGOING in
844 	 * skb_set_err_queue() and use the destructor installed by
845 	 * sock_queue_err_skb(). PACKET_OUTGOING alone is not unique:
846 	 * AF_PACKET outgoing taps use the same pkt_type.
847 	 */
848 	return skb->pkt_type == PACKET_OUTGOING &&
849 	       skb->destructor == sock_rmem_free;
850 }
851 
852 /* On transmit, software and hardware timestamps are returned independently.
853  * As the two skb clones share the hardware timestamp, which may be updated
854  * before the software timestamp is received, a hardware TX timestamp may be
855  * returned only if there is no software TX timestamp. Ignore false software
856  * timestamps, which may be made in the __sock_recv_timestamp() call when the
857  * option SO_TIMESTAMP_OLD(NS) is enabled on the socket, even when the skb has a
858  * hardware timestamp.
859  */
860 static bool skb_is_swtx_tstamp(const struct sk_buff *skb, int false_tstamp)
861 {
862 	return skb->tstamp && !false_tstamp && skb_is_err_queue(skb);
863 }
864 
865 static ktime_t get_timestamp(struct sock *sk, struct sk_buff *skb, int *if_index)
866 {
867 	bool cycles = READ_ONCE(sk->sk_tsflags) & SOF_TIMESTAMPING_BIND_PHC;
868 	struct skb_shared_hwtstamps *shhwtstamps = skb_hwtstamps(skb);
869 	struct net_device *orig_dev;
870 	ktime_t hwtstamp;
871 
872 	rcu_read_lock();
873 	orig_dev = dev_get_by_napi_id(skb_napi_id(skb));
874 	if (orig_dev) {
875 		*if_index = orig_dev->ifindex;
876 		hwtstamp = netdev_get_tstamp(orig_dev, shhwtstamps, cycles);
877 	} else {
878 		hwtstamp = shhwtstamps->hwtstamp;
879 	}
880 	rcu_read_unlock();
881 
882 	return hwtstamp;
883 }
884 
885 static void put_ts_pktinfo(struct msghdr *msg, struct sk_buff *skb,
886 			   int if_index)
887 {
888 	struct scm_ts_pktinfo ts_pktinfo;
889 	struct net_device *orig_dev;
890 
891 	if (!skb_mac_header_was_set(skb))
892 		return;
893 
894 	memset(&ts_pktinfo, 0, sizeof(ts_pktinfo));
895 
896 	if (!if_index) {
897 		rcu_read_lock();
898 		orig_dev = dev_get_by_napi_id(skb_napi_id(skb));
899 		if (orig_dev)
900 			if_index = orig_dev->ifindex;
901 		rcu_read_unlock();
902 	}
903 	ts_pktinfo.if_index = if_index;
904 
905 	ts_pktinfo.pkt_length = skb->len - skb_mac_offset(skb);
906 	put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_PKTINFO,
907 		 sizeof(ts_pktinfo), &ts_pktinfo);
908 }
909 
910 bool skb_has_tx_timestamp(struct sk_buff *skb, const struct sock *sk)
911 {
912 	const struct sock_exterr_skb *serr = SKB_EXT_ERR(skb);
913 	u32 tsflags = READ_ONCE(sk->sk_tsflags);
914 
915 	if (serr->ee.ee_errno != ENOMSG ||
916 	   serr->ee.ee_origin != SO_EE_ORIGIN_TIMESTAMPING)
917 		return false;
918 
919 	/* software time stamp available and wanted */
920 	if ((tsflags & SOF_TIMESTAMPING_SOFTWARE) && skb->tstamp)
921 		return true;
922 	/* hardware time stamps available and wanted */
923 	return (tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) &&
924 		skb_hwtstamps(skb)->hwtstamp;
925 }
926 
927 int skb_get_tx_timestamp(struct sk_buff *skb, struct sock *sk,
928 			  struct timespec64 *ts)
929 {
930 	u32 tsflags = READ_ONCE(sk->sk_tsflags);
931 	ktime_t hwtstamp;
932 	int if_index = 0;
933 
934 	if ((tsflags & SOF_TIMESTAMPING_SOFTWARE) &&
935 	    ktime_to_timespec64_cond(skb->tstamp, ts))
936 		return SOF_TIMESTAMPING_TX_SOFTWARE;
937 
938 	if (!(tsflags & SOF_TIMESTAMPING_RAW_HARDWARE) ||
939 	    skb_is_swtx_tstamp(skb, false))
940 		return -ENOENT;
941 
942 	if (skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP_NETDEV)
943 		hwtstamp = get_timestamp(sk, skb, &if_index);
944 	else
945 		hwtstamp = skb_hwtstamps(skb)->hwtstamp;
946 
947 	if (tsflags & SOF_TIMESTAMPING_BIND_PHC)
948 		hwtstamp = ptp_convert_timestamp(&hwtstamp,
949 						READ_ONCE(sk->sk_bind_phc));
950 	if (!ktime_to_timespec64_cond(hwtstamp, ts))
951 		return -ENOENT;
952 
953 	return SOF_TIMESTAMPING_TX_HARDWARE;
954 }
955 
956 /*
957  * called from sock_recv_timestamp() if sock_flag(sk, SOCK_RCVTSTAMP)
958  */
959 void __sock_recv_timestamp(struct msghdr *msg, struct sock *sk,
960 	struct sk_buff *skb)
961 {
962 	int need_software_tstamp = sock_flag(sk, SOCK_RCVTSTAMP);
963 	int new_tstamp = sock_flag(sk, SOCK_TSTAMP_NEW);
964 	struct skb_shared_hwtstamps *shhwtstamps =
965 		skb_hwtstamps(skb);
966 	struct scm_timestamping_internal tss;
967 	int if_index, false_tstamp = 0;
968 	ktime_t hwtstamp;
969 	u32 tsflags;
970 
971 	/* Race occurred between timestamp enabling and packet
972 	   receiving.  Fill in the current time for now. */
973 	if (need_software_tstamp && skb->tstamp == 0) {
974 		__net_timestamp(skb);
975 		false_tstamp = 1;
976 	}
977 
978 	if (need_software_tstamp) {
979 		if (!sock_flag(sk, SOCK_RCVTSTAMPNS)) {
980 			if (new_tstamp) {
981 				struct __kernel_sock_timeval tv;
982 
983 				skb_get_new_timestamp(skb, &tv);
984 				put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_NEW,
985 					 sizeof(tv), &tv);
986 			} else {
987 				struct __kernel_old_timeval tv;
988 
989 				skb_get_timestamp(skb, &tv);
990 				put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMP_OLD,
991 					 sizeof(tv), &tv);
992 			}
993 		} else {
994 			if (new_tstamp) {
995 				struct __kernel_timespec ts;
996 
997 				skb_get_new_timestampns(skb, &ts);
998 				put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_NEW,
999 					 sizeof(ts), &ts);
1000 			} else {
1001 				struct __kernel_old_timespec ts;
1002 
1003 				skb_get_timestampns(skb, &ts);
1004 				put_cmsg(msg, SOL_SOCKET, SO_TIMESTAMPNS_OLD,
1005 					 sizeof(ts), &ts);
1006 			}
1007 		}
1008 	}
1009 
1010 	memset(&tss, 0, sizeof(tss));
1011 	tsflags = READ_ONCE(sk->sk_tsflags);
1012 	if (tsflags & SOF_TIMESTAMPING_SOFTWARE &&
1013 	    (tsflags & SOF_TIMESTAMPING_RX_SOFTWARE ||
1014 	    skb_is_err_queue(skb) ||
1015 	    !(tsflags & SOF_TIMESTAMPING_OPT_RX_FILTER)))
1016 		tss.ts[0] = skb->tstamp;
1017 
1018 	if (shhwtstamps &&
1019 	    (tsflags & SOF_TIMESTAMPING_RAW_HARDWARE &&
1020 	     (tsflags & SOF_TIMESTAMPING_RX_HARDWARE ||
1021 	      skb_is_err_queue(skb) ||
1022 	      !(tsflags & SOF_TIMESTAMPING_OPT_RX_FILTER))) &&
1023 	    !skb_is_swtx_tstamp(skb, false_tstamp)) {
1024 		if_index = 0;
1025 		if (skb_shinfo(skb)->tx_flags & SKBTX_HW_TSTAMP_NETDEV)
1026 			hwtstamp = get_timestamp(sk, skb, &if_index);
1027 		else
1028 			hwtstamp = shhwtstamps->hwtstamp;
1029 
1030 		if (tsflags & SOF_TIMESTAMPING_BIND_PHC)
1031 			hwtstamp = ptp_convert_timestamp(&hwtstamp,
1032 							 READ_ONCE(sk->sk_bind_phc));
1033 
1034 		if (hwtstamp) {
1035 			tss.ts[2] = hwtstamp;
1036 
1037 			if ((tsflags & SOF_TIMESTAMPING_OPT_PKTINFO) &&
1038 			    !skb_is_err_queue(skb))
1039 				put_ts_pktinfo(msg, skb, if_index);
1040 		}
1041 	}
1042 	if (tss.ts[0] | tss.ts[2]) {
1043 		if (sock_flag(sk, SOCK_TSTAMP_NEW))
1044 			put_cmsg_scm_timestamping64(msg, &tss);
1045 		else
1046 			put_cmsg_scm_timestamping(msg, &tss);
1047 
1048 		if (skb_is_err_queue(skb) && skb->len &&
1049 		    SKB_EXT_ERR(skb)->opt_stats)
1050 			put_cmsg(msg, SOL_SOCKET, SCM_TIMESTAMPING_OPT_STATS,
1051 				 skb->len, skb->data);
1052 	}
1053 }
1054 EXPORT_SYMBOL_GPL(__sock_recv_timestamp);
1055 
1056 #ifdef CONFIG_WIRELESS
1057 void __sock_recv_wifi_status(struct msghdr *msg, struct sock *sk,
1058 	struct sk_buff *skb)
1059 {
1060 	int ack;
1061 
1062 	if (!sock_flag(sk, SOCK_WIFI_STATUS))
1063 		return;
1064 	if (!skb->wifi_acked_valid)
1065 		return;
1066 
1067 	ack = skb->wifi_acked;
1068 
1069 	put_cmsg(msg, SOL_SOCKET, SCM_WIFI_STATUS, sizeof(ack), &ack);
1070 }
1071 EXPORT_SYMBOL_GPL(__sock_recv_wifi_status);
1072 #endif
1073 
1074 static inline void sock_recv_drops(struct msghdr *msg, struct sock *sk,
1075 				   struct sk_buff *skb)
1076 {
1077 	if (sock_flag(sk, SOCK_RXQ_OVFL) && skb && SOCK_SKB_CB(skb)->dropcount)
1078 		put_cmsg(msg, SOL_SOCKET, SO_RXQ_OVFL,
1079 			sizeof(__u32), &SOCK_SKB_CB(skb)->dropcount);
1080 }
1081 
1082 static void sock_recv_mark(struct msghdr *msg, struct sock *sk,
1083 			   struct sk_buff *skb)
1084 {
1085 	if (sock_flag(sk, SOCK_RCVMARK) && skb) {
1086 		/* We must use a bounce buffer for CONFIG_HARDENED_USERCOPY=y */
1087 		__u32 mark = skb->mark;
1088 
1089 		put_cmsg(msg, SOL_SOCKET, SO_MARK, sizeof(__u32), &mark);
1090 	}
1091 }
1092 
1093 static void sock_recv_priority(struct msghdr *msg, struct sock *sk,
1094 			       struct sk_buff *skb)
1095 {
1096 	if (sock_flag(sk, SOCK_RCVPRIORITY) && skb) {
1097 		__u32 priority = skb->priority;
1098 
1099 		put_cmsg(msg, SOL_SOCKET, SO_PRIORITY, sizeof(__u32), &priority);
1100 	}
1101 }
1102 
1103 void __sock_recv_cmsgs(struct msghdr *msg, struct sock *sk,
1104 		       struct sk_buff *skb)
1105 {
1106 	sock_recv_timestamp(msg, sk, skb);
1107 	sock_recv_drops(msg, sk, skb);
1108 	sock_recv_mark(msg, sk, skb);
1109 	sock_recv_priority(msg, sk, skb);
1110 }
1111 EXPORT_SYMBOL_GPL(__sock_recv_cmsgs);
1112 
1113 INDIRECT_CALLABLE_DECLARE(int inet_recvmsg(struct socket *, struct msghdr *,
1114 					   size_t, int));
1115 INDIRECT_CALLABLE_DECLARE(int inet6_recvmsg(struct socket *, struct msghdr *,
1116 					    size_t, int));
1117 
1118 static noinline void call_trace_sock_recv_length(struct sock *sk, int ret, int flags)
1119 {
1120 	trace_sock_recv_length(sk, ret, flags);
1121 }
1122 
1123 static inline int sock_recvmsg_nosec(struct socket *sock, struct msghdr *msg,
1124 				     int flags)
1125 {
1126 	int ret = INDIRECT_CALL_INET(READ_ONCE(sock->ops)->recvmsg,
1127 				     inet6_recvmsg,
1128 				     inet_recvmsg, sock, msg,
1129 				     msg_data_left(msg), flags);
1130 	if (trace_sock_recv_length_enabled())
1131 		call_trace_sock_recv_length(sock->sk, ret, flags);
1132 	return ret;
1133 }
1134 
1135 /**
1136  *	sock_recvmsg - receive a message from @sock
1137  *	@sock: socket
1138  *	@msg: message to receive
1139  *	@flags: message flags
1140  *
1141  *	Receives @msg from @sock, passing through LSM. Returns the total number
1142  *	of bytes received, or an error.
1143  */
1144 int sock_recvmsg(struct socket *sock, struct msghdr *msg, int flags)
1145 {
1146 	int err = security_socket_recvmsg(sock, msg, msg_data_left(msg), flags);
1147 
1148 	return err ?: sock_recvmsg_nosec(sock, msg, flags);
1149 }
1150 EXPORT_SYMBOL(sock_recvmsg);
1151 
1152 /**
1153  *	kernel_recvmsg - Receive a message from a socket (kernel space)
1154  *	@sock: The socket to receive the message from
1155  *	@msg: Received message
1156  *	@vec: Input s/g array for message data
1157  *	@num: Size of input s/g array
1158  *	@size: Number of bytes to read
1159  *	@flags: Message flags (MSG_DONTWAIT, etc...)
1160  *
1161  *	On return the msg structure contains the scatter/gather array passed in the
1162  *	vec argument. The array is modified so that it consists of the unfilled
1163  *	portion of the original array.
1164  *
1165  *	The returned value is the total number of bytes received, or an error.
1166  */
1167 
1168 int kernel_recvmsg(struct socket *sock, struct msghdr *msg,
1169 		   struct kvec *vec, size_t num, size_t size, int flags)
1170 {
1171 	msg->msg_control_is_user = false;
1172 	iov_iter_kvec(&msg->msg_iter, ITER_DEST, vec, num, size);
1173 	return sock_recvmsg(sock, msg, flags);
1174 }
1175 EXPORT_SYMBOL(kernel_recvmsg);
1176 
1177 static ssize_t sock_splice_read(struct file *file, loff_t *ppos,
1178 				struct pipe_inode_info *pipe, size_t len,
1179 				unsigned int flags)
1180 {
1181 	struct socket *sock = file->private_data;
1182 	const struct proto_ops *ops;
1183 
1184 	ops = READ_ONCE(sock->ops);
1185 	if (unlikely(!ops->splice_read))
1186 		return copy_splice_read(file, ppos, pipe, len, flags);
1187 
1188 	return ops->splice_read(sock, ppos, pipe, len, flags);
1189 }
1190 
1191 static void sock_splice_eof(struct file *file)
1192 {
1193 	struct socket *sock = file->private_data;
1194 	const struct proto_ops *ops;
1195 
1196 	ops = READ_ONCE(sock->ops);
1197 	if (ops->splice_eof)
1198 		ops->splice_eof(sock);
1199 }
1200 
1201 static ssize_t sock_read_iter(struct kiocb *iocb, struct iov_iter *to)
1202 {
1203 	struct file *file = iocb->ki_filp;
1204 	struct socket *sock = file->private_data;
1205 	struct msghdr msg = {.msg_iter = *to,
1206 			     .msg_iocb = iocb};
1207 	ssize_t res;
1208 
1209 	if (file->f_flags & O_NONBLOCK || (iocb->ki_flags & IOCB_NOWAIT))
1210 		msg.msg_flags = MSG_DONTWAIT;
1211 
1212 	if (iocb->ki_pos != 0)
1213 		return -ESPIPE;
1214 
1215 	if (!iov_iter_count(to))	/* Match SYS5 behaviour */
1216 		return 0;
1217 
1218 	res = sock_recvmsg(sock, &msg, msg.msg_flags);
1219 	*to = msg.msg_iter;
1220 	return res;
1221 }
1222 
1223 static ssize_t sock_write_iter(struct kiocb *iocb, struct iov_iter *from)
1224 {
1225 	struct file *file = iocb->ki_filp;
1226 	struct socket *sock = file->private_data;
1227 	struct msghdr msg = {.msg_iter = *from,
1228 			     .msg_iocb = iocb};
1229 	ssize_t res;
1230 
1231 	if (iocb->ki_pos != 0)
1232 		return -ESPIPE;
1233 
1234 	if (file->f_flags & O_NONBLOCK || (iocb->ki_flags & IOCB_NOWAIT))
1235 		msg.msg_flags = MSG_DONTWAIT;
1236 
1237 	if (sock->type == SOCK_SEQPACKET)
1238 		msg.msg_flags |= MSG_EOR;
1239 
1240 	if (iocb->ki_flags & IOCB_NOSIGNAL)
1241 		msg.msg_flags |= MSG_NOSIGNAL;
1242 
1243 	res = __sock_sendmsg(sock, &msg);
1244 	*from = msg.msg_iter;
1245 	return res;
1246 }
1247 
1248 /*
1249  * Atomic setting of ioctl hooks to avoid race
1250  * with module unload.
1251  */
1252 
1253 static DEFINE_MUTEX(br_ioctl_mutex);
1254 static int (*br_ioctl_hook)(struct net *net, unsigned int cmd,
1255 			    void __user *uarg);
1256 
1257 void brioctl_set(int (*hook)(struct net *net, unsigned int cmd,
1258 			     void __user *uarg))
1259 {
1260 	mutex_lock(&br_ioctl_mutex);
1261 	br_ioctl_hook = hook;
1262 	mutex_unlock(&br_ioctl_mutex);
1263 }
1264 EXPORT_SYMBOL(brioctl_set);
1265 
1266 int br_ioctl_call(struct net *net, unsigned int cmd, void __user *uarg)
1267 {
1268 	int err = -ENOPKG;
1269 
1270 	if (!br_ioctl_hook)
1271 		request_module("bridge");
1272 
1273 	mutex_lock(&br_ioctl_mutex);
1274 	if (br_ioctl_hook)
1275 		err = br_ioctl_hook(net, cmd, uarg);
1276 	mutex_unlock(&br_ioctl_mutex);
1277 
1278 	return err;
1279 }
1280 
1281 static DEFINE_MUTEX(vlan_ioctl_mutex);
1282 static int (*vlan_ioctl_hook) (struct net *, void __user *arg);
1283 
1284 void vlan_ioctl_set(int (*hook) (struct net *, void __user *))
1285 {
1286 	mutex_lock(&vlan_ioctl_mutex);
1287 	vlan_ioctl_hook = hook;
1288 	mutex_unlock(&vlan_ioctl_mutex);
1289 }
1290 EXPORT_SYMBOL(vlan_ioctl_set);
1291 
1292 static long sock_do_ioctl(struct net *net, struct socket *sock,
1293 			  unsigned int cmd, unsigned long arg)
1294 {
1295 	const struct proto_ops *ops = READ_ONCE(sock->ops);
1296 	struct ifreq ifr;
1297 	bool need_copyout;
1298 	int err;
1299 	void __user *argp = (void __user *)arg;
1300 	void __user *data;
1301 
1302 	err = ops->ioctl(sock, cmd, arg);
1303 
1304 	/*
1305 	 * If this ioctl is unknown try to hand it down
1306 	 * to the NIC driver.
1307 	 */
1308 	if (err != -ENOIOCTLCMD)
1309 		return err;
1310 
1311 	if (!is_socket_ioctl_cmd(cmd))
1312 		return -ENOTTY;
1313 
1314 	if (get_user_ifreq(&ifr, &data, argp))
1315 		return -EFAULT;
1316 	err = dev_ioctl(net, cmd, &ifr, data, &need_copyout);
1317 	if (!err && need_copyout)
1318 		if (put_user_ifreq(&ifr, argp))
1319 			return -EFAULT;
1320 
1321 	return err;
1322 }
1323 
1324 /*
1325  *	With an ioctl, arg may well be a user mode pointer, but we don't know
1326  *	what to do with it - that's up to the protocol still.
1327  */
1328 
1329 static long sock_ioctl(struct file *file, unsigned cmd, unsigned long arg)
1330 {
1331 	const struct proto_ops  *ops;
1332 	struct socket *sock;
1333 	struct sock *sk;
1334 	void __user *argp = (void __user *)arg;
1335 	int pid, err;
1336 	struct net *net;
1337 
1338 	sock = file->private_data;
1339 	ops = READ_ONCE(sock->ops);
1340 	sk = sock->sk;
1341 	net = sock_net(sk);
1342 	if (unlikely(cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15))) {
1343 		struct ifreq ifr;
1344 		void __user *data;
1345 		bool need_copyout;
1346 		if (get_user_ifreq(&ifr, &data, argp))
1347 			return -EFAULT;
1348 		err = dev_ioctl(net, cmd, &ifr, data, &need_copyout);
1349 		if (!err && need_copyout)
1350 			if (put_user_ifreq(&ifr, argp))
1351 				return -EFAULT;
1352 	} else
1353 #ifdef CONFIG_WEXT_CORE
1354 	if (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST) {
1355 		err = wext_handle_ioctl(net, cmd, argp);
1356 	} else
1357 #endif
1358 		switch (cmd) {
1359 		case FIOSETOWN:
1360 		case SIOCSPGRP:
1361 			err = -EFAULT;
1362 			if (get_user(pid, (int __user *)argp))
1363 				break;
1364 			err = f_setown(sock->file, pid, 1);
1365 			break;
1366 		case FIOGETOWN:
1367 		case SIOCGPGRP:
1368 			err = put_user(f_getown(sock->file),
1369 				       (int __user *)argp);
1370 			break;
1371 		case SIOCGIFBR:
1372 		case SIOCSIFBR:
1373 		case SIOCBRADDBR:
1374 		case SIOCBRDELBR:
1375 		case SIOCBRADDIF:
1376 		case SIOCBRDELIF:
1377 			err = br_ioctl_call(net, cmd, argp);
1378 			break;
1379 		case SIOCGIFVLAN:
1380 		case SIOCSIFVLAN:
1381 			err = -ENOPKG;
1382 			if (!vlan_ioctl_hook)
1383 				request_module("8021q");
1384 
1385 			mutex_lock(&vlan_ioctl_mutex);
1386 			if (vlan_ioctl_hook)
1387 				err = vlan_ioctl_hook(net, argp);
1388 			mutex_unlock(&vlan_ioctl_mutex);
1389 			break;
1390 		case SIOCGSKNS:
1391 			err = -EPERM;
1392 			if (!ns_capable(net->user_ns, CAP_NET_ADMIN))
1393 				break;
1394 
1395 			err = open_related_ns(&net->ns, get_net_ns);
1396 			break;
1397 		case SIOCGSTAMP_OLD:
1398 		case SIOCGSTAMPNS_OLD:
1399 			if (!ops->gettstamp) {
1400 				err = -ENOIOCTLCMD;
1401 				break;
1402 			}
1403 			err = ops->gettstamp(sock, argp,
1404 					     cmd == SIOCGSTAMP_OLD,
1405 					     !IS_ENABLED(CONFIG_64BIT));
1406 			break;
1407 		case SIOCGSTAMP_NEW:
1408 		case SIOCGSTAMPNS_NEW:
1409 			if (!ops->gettstamp) {
1410 				err = -ENOIOCTLCMD;
1411 				break;
1412 			}
1413 			err = ops->gettstamp(sock, argp,
1414 					     cmd == SIOCGSTAMP_NEW,
1415 					     false);
1416 			break;
1417 
1418 		case SIOCGIFCONF:
1419 			err = dev_ifconf(net, argp);
1420 			break;
1421 
1422 		default:
1423 			err = sock_do_ioctl(net, sock, cmd, arg);
1424 			break;
1425 		}
1426 	return err;
1427 }
1428 
1429 /**
1430  *	sock_create_lite - creates a socket
1431  *	@family: protocol family (AF_INET, ...)
1432  *	@type: communication type (SOCK_STREAM, ...)
1433  *	@protocol: protocol (0, ...)
1434  *	@res: new socket
1435  *
1436  *	Creates a new socket and assigns it to @res, passing through LSM.
1437  *	The new socket initialization is not complete, see kernel_accept().
1438  *	Returns 0 or an error. On failure @res is set to %NULL.
1439  *	This function internally uses GFP_KERNEL.
1440  */
1441 
1442 int sock_create_lite(int family, int type, int protocol, struct socket **res)
1443 {
1444 	int err;
1445 	struct socket *sock = NULL;
1446 
1447 	err = security_socket_create(family, type, protocol, 1);
1448 	if (err)
1449 		goto out;
1450 
1451 	sock = sock_alloc();
1452 	if (!sock) {
1453 		err = -ENOMEM;
1454 		goto out;
1455 	}
1456 
1457 	sock->type = type;
1458 	err = security_socket_post_create(sock, family, type, protocol, 1);
1459 	if (err)
1460 		goto out_release;
1461 
1462 out:
1463 	*res = sock;
1464 	return err;
1465 out_release:
1466 	sock_release(sock);
1467 	sock = NULL;
1468 	goto out;
1469 }
1470 EXPORT_SYMBOL(sock_create_lite);
1471 
1472 /* No kernel lock held - perfect */
1473 static __poll_t sock_poll(struct file *file, poll_table *wait)
1474 {
1475 	struct socket *sock = file->private_data;
1476 	const struct proto_ops *ops = READ_ONCE(sock->ops);
1477 	__poll_t events = poll_requested_events(wait), flag = 0;
1478 
1479 	if (!ops->poll)
1480 		return 0;
1481 
1482 	if (sk_can_busy_loop(sock->sk)) {
1483 		/* poll once if requested by the syscall */
1484 		if (events & POLL_BUSY_LOOP)
1485 			sk_busy_loop(sock->sk, 1);
1486 
1487 		/* if this socket can poll_ll, tell the system call */
1488 		flag = POLL_BUSY_LOOP;
1489 	}
1490 
1491 	return ops->poll(file, sock, wait) | flag;
1492 }
1493 
1494 static int sock_mmap(struct file *file, struct vm_area_struct *vma)
1495 {
1496 	struct socket *sock = file->private_data;
1497 
1498 	return READ_ONCE(sock->ops)->mmap(file, sock, vma);
1499 }
1500 
1501 static int sock_close(struct inode *inode, struct file *filp)
1502 {
1503 	__sock_release(SOCKET_I(inode), inode);
1504 	return 0;
1505 }
1506 
1507 /*
1508  *	Update the socket async list
1509  *
1510  *	Fasync_list locking strategy.
1511  *
1512  *	1. fasync_list is modified only under process context socket lock
1513  *	   i.e. under semaphore.
1514  *	2. fasync_list is used under read_lock(&sk->sk_callback_lock)
1515  *	   or under socket lock
1516  */
1517 
1518 static int sock_fasync(int fd, struct file *filp, int on)
1519 {
1520 	struct socket *sock = filp->private_data;
1521 	struct sock *sk = sock->sk;
1522 	struct socket_wq *wq = &sock->wq;
1523 
1524 	if (sk == NULL)
1525 		return -EINVAL;
1526 
1527 	lock_sock(sk);
1528 	fasync_helper(fd, filp, on, &wq->fasync_list);
1529 
1530 	if (!wq->fasync_list)
1531 		sock_reset_flag(sk, SOCK_FASYNC);
1532 	else
1533 		sock_set_flag(sk, SOCK_FASYNC);
1534 
1535 	release_sock(sk);
1536 	return 0;
1537 }
1538 
1539 /* This function may be called only under rcu_lock */
1540 
1541 int sock_wake_async(struct socket_wq *wq, int how, int band)
1542 {
1543 	if (!wq || !wq->fasync_list)
1544 		return -1;
1545 
1546 	switch (how) {
1547 	case SOCK_WAKE_WAITD:
1548 		if (test_bit(SOCKWQ_ASYNC_WAITDATA, &wq->flags))
1549 			break;
1550 		goto call_kill;
1551 	case SOCK_WAKE_SPACE:
1552 		if (!test_and_clear_bit(SOCKWQ_ASYNC_NOSPACE, &wq->flags))
1553 			break;
1554 		fallthrough;
1555 	case SOCK_WAKE_IO:
1556 call_kill:
1557 		kill_fasync(&wq->fasync_list, SIGIO, band);
1558 		break;
1559 	case SOCK_WAKE_URG:
1560 		kill_fasync(&wq->fasync_list, SIGURG, band);
1561 	}
1562 
1563 	return 0;
1564 }
1565 EXPORT_SYMBOL(sock_wake_async);
1566 
1567 /**
1568  *	__sock_create - creates a socket
1569  *	@net: net namespace
1570  *	@family: protocol family (AF_INET, ...)
1571  *	@type: communication type (SOCK_STREAM, ...)
1572  *	@protocol: protocol (0, ...)
1573  *	@res: new socket
1574  *	@kern: boolean for kernel space sockets
1575  *
1576  *	Creates a new socket and assigns it to @res, passing through LSM.
1577  *	Returns 0 or an error. On failure @res is set to %NULL. @kern must
1578  *	be set to true if the socket resides in kernel space.
1579  *	This function internally uses GFP_KERNEL.
1580  */
1581 
1582 int __sock_create(struct net *net, int family, int type, int protocol,
1583 			 struct socket **res, int kern)
1584 {
1585 	int err;
1586 	struct socket *sock;
1587 	const struct net_proto_family *pf;
1588 
1589 	/*
1590 	 *      Check protocol is in range
1591 	 */
1592 	if (family < 0 || family >= NPROTO)
1593 		return -EAFNOSUPPORT;
1594 	if (type < 0 || type >= SOCK_MAX)
1595 		return -EINVAL;
1596 
1597 	/* Compatibility.
1598 
1599 	   This uglymoron is moved from INET layer to here to avoid
1600 	   deadlock in module load.
1601 	 */
1602 	if (family == PF_INET && type == SOCK_PACKET) {
1603 		pr_info_once("%s uses obsolete (PF_INET,SOCK_PACKET)\n",
1604 			     current->comm);
1605 		family = PF_PACKET;
1606 	}
1607 
1608 	err = security_socket_create(family, type, protocol, kern);
1609 	if (err)
1610 		return err;
1611 
1612 	/*
1613 	 *	Allocate the socket and allow the family to set things up. if
1614 	 *	the protocol is 0, the family is instructed to select an appropriate
1615 	 *	default.
1616 	 */
1617 	sock = sock_alloc();
1618 	if (!sock) {
1619 		net_warn_ratelimited("socket: no more sockets\n");
1620 		return -ENFILE;	/* Not exactly a match, but its the
1621 				   closest posix thing */
1622 	}
1623 
1624 	sock->type = type;
1625 
1626 #ifdef CONFIG_MODULES
1627 	/* Attempt to load a protocol module if the find failed.
1628 	 *
1629 	 * 12/09/1996 Marcin: But! this makes REALLY only sense, if the user
1630 	 * requested real, full-featured networking support upon configuration.
1631 	 * Otherwise module support will break!
1632 	 */
1633 	if (rcu_access_pointer(net_families[family]) == NULL)
1634 		request_module("net-pf-%d", family);
1635 #endif
1636 
1637 	rcu_read_lock();
1638 	pf = rcu_dereference(net_families[family]);
1639 	err = -EAFNOSUPPORT;
1640 	if (!pf)
1641 		goto out_release;
1642 
1643 	/*
1644 	 * We will call the ->create function, that possibly is in a loadable
1645 	 * module, so we have to bump that loadable module refcnt first.
1646 	 */
1647 	if (!try_module_get(pf->owner))
1648 		goto out_release;
1649 
1650 	/* Now protected by module ref count */
1651 	rcu_read_unlock();
1652 
1653 	err = pf->create(net, sock, protocol, kern);
1654 	if (err < 0) {
1655 		/* ->create should release the allocated sock->sk object on error
1656 		 * and make sure sock->sk is set to NULL to avoid use-after-free
1657 		 */
1658 		DEBUG_NET_WARN_ONCE(sock->sk,
1659 				    "%ps must clear sock->sk on failure, family: %d, type: %d, protocol: %d\n",
1660 				    pf->create, family, type, protocol);
1661 		goto out_module_put;
1662 	}
1663 
1664 	/*
1665 	 * Now to bump the refcnt of the [loadable] module that owns this
1666 	 * socket at sock_release time we decrement its refcnt.
1667 	 */
1668 	if (!try_module_get(sock->ops->owner))
1669 		goto out_module_busy;
1670 
1671 	/*
1672 	 * Now that we're done with the ->create function, the [loadable]
1673 	 * module can have its refcnt decremented
1674 	 */
1675 	module_put(pf->owner);
1676 	err = security_socket_post_create(sock, family, type, protocol, kern);
1677 	if (err)
1678 		goto out_sock_release;
1679 	*res = sock;
1680 
1681 	return 0;
1682 
1683 out_module_busy:
1684 	err = -EAFNOSUPPORT;
1685 out_module_put:
1686 	sock->ops = NULL;
1687 	module_put(pf->owner);
1688 out_sock_release:
1689 	sock_release(sock);
1690 	return err;
1691 
1692 out_release:
1693 	rcu_read_unlock();
1694 	goto out_sock_release;
1695 }
1696 EXPORT_SYMBOL(__sock_create);
1697 
1698 /**
1699  *	sock_create - creates a socket
1700  *	@family: protocol family (AF_INET, ...)
1701  *	@type: communication type (SOCK_STREAM, ...)
1702  *	@protocol: protocol (0, ...)
1703  *	@res: new socket
1704  *
1705  *	A wrapper around __sock_create().
1706  *	Returns 0 or an error. This function internally uses GFP_KERNEL.
1707  */
1708 
1709 int sock_create(int family, int type, int protocol, struct socket **res)
1710 {
1711 	return __sock_create(current->nsproxy->net_ns, family, type, protocol, res, 0);
1712 }
1713 EXPORT_SYMBOL(sock_create);
1714 
1715 /**
1716  *	sock_create_kern - creates a socket (kernel space)
1717  *	@net: net namespace
1718  *	@family: protocol family (AF_INET, ...)
1719  *	@type: communication type (SOCK_STREAM, ...)
1720  *	@protocol: protocol (0, ...)
1721  *	@res: new socket
1722  *
1723  *	A wrapper around __sock_create().
1724  *	Returns 0 or an error. This function internally uses GFP_KERNEL.
1725  */
1726 
1727 int sock_create_kern(struct net *net, int family, int type, int protocol, struct socket **res)
1728 {
1729 	return __sock_create(net, family, type, protocol, res, 1);
1730 }
1731 EXPORT_SYMBOL(sock_create_kern);
1732 
1733 static struct socket *__sys_socket_create(int family, int type, int protocol)
1734 {
1735 	struct socket *sock;
1736 	int retval;
1737 
1738 	/* Check the SOCK_* constants for consistency.  */
1739 	BUILD_BUG_ON(SOCK_CLOEXEC != O_CLOEXEC);
1740 	BUILD_BUG_ON((SOCK_MAX | SOCK_TYPE_MASK) != SOCK_TYPE_MASK);
1741 	BUILD_BUG_ON(SOCK_CLOEXEC & SOCK_TYPE_MASK);
1742 	BUILD_BUG_ON(SOCK_NONBLOCK & SOCK_TYPE_MASK);
1743 
1744 	if ((type & ~SOCK_TYPE_MASK) & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
1745 		return ERR_PTR(-EINVAL);
1746 	type &= SOCK_TYPE_MASK;
1747 
1748 	retval = sock_create(family, type, protocol, &sock);
1749 	if (retval < 0)
1750 		return ERR_PTR(retval);
1751 
1752 	return sock;
1753 }
1754 
1755 struct file *__sys_socket_file(int family, int type, int protocol)
1756 {
1757 	struct socket *sock;
1758 	int flags;
1759 
1760 	sock = __sys_socket_create(family, type, protocol);
1761 	if (IS_ERR(sock))
1762 		return ERR_CAST(sock);
1763 
1764 	flags = type & ~SOCK_TYPE_MASK;
1765 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
1766 		flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
1767 
1768 	return sock_alloc_file(sock, flags, NULL);
1769 }
1770 
1771 /*	A hook for bpf progs to attach to and update socket protocol.
1772  *
1773  *	A static noinline declaration here could cause the compiler to
1774  *	optimize away the function. A global noinline declaration will
1775  *	keep the definition, but may optimize away the callsite.
1776  *	Therefore, __weak is needed to ensure that the call is still
1777  *	emitted, by telling the compiler that we don't know what the
1778  *	function might eventually be.
1779  */
1780 
1781 __bpf_hook_start();
1782 
1783 __weak noinline int update_socket_protocol(int family, int type, int protocol)
1784 {
1785 	return protocol;
1786 }
1787 
1788 __bpf_hook_end();
1789 
1790 int __sys_socket(int family, int type, int protocol)
1791 {
1792 	struct socket *sock;
1793 	int flags;
1794 
1795 	sock = __sys_socket_create(family, type,
1796 				   update_socket_protocol(family, type, protocol));
1797 	if (IS_ERR(sock))
1798 		return PTR_ERR(sock);
1799 
1800 	flags = type & ~SOCK_TYPE_MASK;
1801 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
1802 		flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
1803 
1804 	return sock_map_fd(sock, flags & (O_CLOEXEC | O_NONBLOCK));
1805 }
1806 
1807 SYSCALL_DEFINE3(socket, int, family, int, type, int, protocol)
1808 {
1809 	return __sys_socket(family, type, protocol);
1810 }
1811 
1812 /*
1813  *	Create a pair of connected sockets.
1814  */
1815 
1816 int __sys_socketpair(int family, int type, int protocol, int __user *usockvec)
1817 {
1818 	struct socket *sock1, *sock2;
1819 	int fd1, fd2, err;
1820 	struct file *newfile1, *newfile2;
1821 	int flags;
1822 
1823 	flags = type & ~SOCK_TYPE_MASK;
1824 	if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
1825 		return -EINVAL;
1826 	type &= SOCK_TYPE_MASK;
1827 
1828 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
1829 		flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
1830 
1831 	/*
1832 	 * reserve descriptors and make sure we won't fail
1833 	 * to return them to userland.
1834 	 */
1835 	fd1 = get_unused_fd_flags(flags);
1836 	if (unlikely(fd1 < 0))
1837 		return fd1;
1838 
1839 	fd2 = get_unused_fd_flags(flags);
1840 	if (unlikely(fd2 < 0)) {
1841 		put_unused_fd(fd1);
1842 		return fd2;
1843 	}
1844 
1845 	err = put_user(fd1, &usockvec[0]);
1846 	if (err)
1847 		goto out;
1848 
1849 	err = put_user(fd2, &usockvec[1]);
1850 	if (err)
1851 		goto out;
1852 
1853 	/*
1854 	 * Obtain the first socket and check if the underlying protocol
1855 	 * supports the socketpair call.
1856 	 */
1857 
1858 	err = sock_create(family, type, protocol, &sock1);
1859 	if (unlikely(err < 0))
1860 		goto out;
1861 
1862 	err = sock_create(family, type, protocol, &sock2);
1863 	if (unlikely(err < 0)) {
1864 		sock_release(sock1);
1865 		goto out;
1866 	}
1867 
1868 	err = security_socket_socketpair(sock1, sock2);
1869 	if (unlikely(err)) {
1870 		sock_release(sock2);
1871 		sock_release(sock1);
1872 		goto out;
1873 	}
1874 
1875 	err = READ_ONCE(sock1->ops)->socketpair(sock1, sock2);
1876 	if (unlikely(err < 0)) {
1877 		sock_release(sock2);
1878 		sock_release(sock1);
1879 		goto out;
1880 	}
1881 
1882 	newfile1 = sock_alloc_file(sock1, flags, NULL);
1883 	if (IS_ERR(newfile1)) {
1884 		err = PTR_ERR(newfile1);
1885 		sock_release(sock2);
1886 		goto out;
1887 	}
1888 
1889 	newfile2 = sock_alloc_file(sock2, flags, NULL);
1890 	if (IS_ERR(newfile2)) {
1891 		err = PTR_ERR(newfile2);
1892 		fput(newfile1);
1893 		goto out;
1894 	}
1895 
1896 	audit_fd_pair(fd1, fd2);
1897 
1898 	fd_install(fd1, newfile1);
1899 	fd_install(fd2, newfile2);
1900 	return 0;
1901 
1902 out:
1903 	put_unused_fd(fd2);
1904 	put_unused_fd(fd1);
1905 	return err;
1906 }
1907 
1908 SYSCALL_DEFINE4(socketpair, int, family, int, type, int, protocol,
1909 		int __user *, usockvec)
1910 {
1911 	return __sys_socketpair(family, type, protocol, usockvec);
1912 }
1913 
1914 int __sys_bind_socket(struct socket *sock, struct sockaddr_storage *address,
1915 		      int addrlen)
1916 {
1917 	int err;
1918 
1919 	err = security_socket_bind(sock, (struct sockaddr *)address,
1920 				   addrlen);
1921 	if (!err)
1922 		err = READ_ONCE(sock->ops)->bind(sock,
1923 						 (struct sockaddr_unsized *)address,
1924 						 addrlen);
1925 	return err;
1926 }
1927 
1928 /*
1929  *	Bind a name to a socket. Nothing much to do here since it's
1930  *	the protocol's responsibility to handle the local address.
1931  *
1932  *	We move the socket address to kernel space before we call
1933  *	the protocol layer (having also checked the address is ok).
1934  */
1935 
1936 int __sys_bind(int fd, struct sockaddr __user *umyaddr, int addrlen)
1937 {
1938 	struct socket *sock;
1939 	struct sockaddr_storage address;
1940 	CLASS(fd, f)(fd);
1941 	int err;
1942 
1943 	if (fd_empty(f))
1944 		return -EBADF;
1945 	sock = sock_from_file(fd_file(f));
1946 	if (unlikely(!sock))
1947 		return -ENOTSOCK;
1948 
1949 	err = move_addr_to_kernel(umyaddr, addrlen, &address);
1950 	if (unlikely(err))
1951 		return err;
1952 
1953 	return __sys_bind_socket(sock, &address, addrlen);
1954 }
1955 
1956 SYSCALL_DEFINE3(bind, int, fd, struct sockaddr __user *, umyaddr, int, addrlen)
1957 {
1958 	return __sys_bind(fd, umyaddr, addrlen);
1959 }
1960 
1961 /*
1962  *	Perform a listen. Basically, we allow the protocol to do anything
1963  *	necessary for a listen, and if that works, we mark the socket as
1964  *	ready for listening.
1965  */
1966 int __sys_listen_socket(struct socket *sock, int backlog)
1967 {
1968 	int somaxconn, err;
1969 
1970 	somaxconn = READ_ONCE(sock_net(sock->sk)->core.sysctl_somaxconn);
1971 	if ((unsigned int)backlog > somaxconn)
1972 		backlog = somaxconn;
1973 
1974 	err = security_socket_listen(sock, backlog);
1975 	if (!err)
1976 		err = READ_ONCE(sock->ops)->listen(sock, backlog);
1977 	return err;
1978 }
1979 
1980 int __sys_listen(int fd, int backlog)
1981 {
1982 	CLASS(fd, f)(fd);
1983 	struct socket *sock;
1984 
1985 	if (fd_empty(f))
1986 		return -EBADF;
1987 	sock = sock_from_file(fd_file(f));
1988 	if (unlikely(!sock))
1989 		return -ENOTSOCK;
1990 
1991 	return __sys_listen_socket(sock, backlog);
1992 }
1993 
1994 SYSCALL_DEFINE2(listen, int, fd, int, backlog)
1995 {
1996 	return __sys_listen(fd, backlog);
1997 }
1998 
1999 struct file *do_accept(struct file *file, struct proto_accept_arg *arg,
2000 		       struct sockaddr __user *upeer_sockaddr,
2001 		       int __user *upeer_addrlen, int flags)
2002 {
2003 	struct socket *sock, *newsock;
2004 	struct file *newfile;
2005 	int err, len;
2006 	struct sockaddr_storage address;
2007 	const struct proto_ops *ops;
2008 
2009 	sock = sock_from_file(file);
2010 	if (!sock)
2011 		return ERR_PTR(-ENOTSOCK);
2012 
2013 	newsock = sock_alloc();
2014 	if (!newsock)
2015 		return ERR_PTR(-ENFILE);
2016 	ops = READ_ONCE(sock->ops);
2017 
2018 	newsock->type = sock->type;
2019 	newsock->ops = ops;
2020 
2021 	/*
2022 	 * We don't need try_module_get here, as the listening socket (sock)
2023 	 * has the protocol module (sock->ops->owner) held.
2024 	 */
2025 	__module_get(ops->owner);
2026 
2027 	newfile = sock_alloc_file(newsock, flags, sock->sk->sk_prot_creator->name);
2028 	if (IS_ERR(newfile))
2029 		return newfile;
2030 
2031 	err = security_socket_accept(sock, newsock);
2032 	if (err)
2033 		goto out_fd;
2034 
2035 	arg->flags |= sock->file->f_flags;
2036 	err = ops->accept(sock, newsock, arg);
2037 	if (err < 0)
2038 		goto out_fd;
2039 
2040 	if (upeer_sockaddr) {
2041 		len = ops->getname(newsock, (struct sockaddr *)&address, 2);
2042 		if (len < 0) {
2043 			err = -ECONNABORTED;
2044 			goto out_fd;
2045 		}
2046 		err = move_addr_to_user(&address,
2047 					len, upeer_sockaddr, upeer_addrlen);
2048 		if (err < 0)
2049 			goto out_fd;
2050 	}
2051 
2052 	/* File flags are not inherited via accept() unlike another OSes. */
2053 	return newfile;
2054 out_fd:
2055 	fput(newfile);
2056 	return ERR_PTR(err);
2057 }
2058 
2059 static int __sys_accept4_file(struct file *file, struct sockaddr __user *upeer_sockaddr,
2060 			      int __user *upeer_addrlen, int flags)
2061 {
2062 	struct proto_accept_arg arg = { };
2063 
2064 	if (flags & ~(SOCK_CLOEXEC | SOCK_NONBLOCK))
2065 		return -EINVAL;
2066 
2067 	if (SOCK_NONBLOCK != O_NONBLOCK && (flags & SOCK_NONBLOCK))
2068 		flags = (flags & ~SOCK_NONBLOCK) | O_NONBLOCK;
2069 
2070 	return FD_ADD(flags, do_accept(file, &arg, upeer_sockaddr, upeer_addrlen, flags));
2071 }
2072 
2073 /*
2074  *	For accept, we attempt to create a new socket, set up the link
2075  *	with the client, wake up the client, then return the new
2076  *	connected fd. We collect the address of the connector in kernel
2077  *	space and move it to user at the very end. This is unclean because
2078  *	we open the socket then return an error.
2079  *
2080  *	1003.1g adds the ability to recvmsg() to query connection pending
2081  *	status to recvmsg. We need to add that support in a way thats
2082  *	clean when we restructure accept also.
2083  */
2084 
2085 int __sys_accept4(int fd, struct sockaddr __user *upeer_sockaddr,
2086 		  int __user *upeer_addrlen, int flags)
2087 {
2088 	CLASS(fd, f)(fd);
2089 
2090 	if (fd_empty(f))
2091 		return -EBADF;
2092 	return __sys_accept4_file(fd_file(f), upeer_sockaddr,
2093 					 upeer_addrlen, flags);
2094 }
2095 
2096 SYSCALL_DEFINE4(accept4, int, fd, struct sockaddr __user *, upeer_sockaddr,
2097 		int __user *, upeer_addrlen, int, flags)
2098 {
2099 	return __sys_accept4(fd, upeer_sockaddr, upeer_addrlen, flags);
2100 }
2101 
2102 SYSCALL_DEFINE3(accept, int, fd, struct sockaddr __user *, upeer_sockaddr,
2103 		int __user *, upeer_addrlen)
2104 {
2105 	return __sys_accept4(fd, upeer_sockaddr, upeer_addrlen, 0);
2106 }
2107 
2108 /*
2109  *	Attempt to connect to a socket with the server address.  The address
2110  *	is in user space so we verify it is OK and move it to kernel space.
2111  *
2112  *	For 1003.1g we need to add clean support for a bind to AF_UNSPEC to
2113  *	break bindings
2114  *
2115  *	NOTE: 1003.1g draft 6.3 is broken with respect to AX.25/NetROM and
2116  *	other SEQPACKET protocols that take time to connect() as it doesn't
2117  *	include the -EINPROGRESS status for such sockets.
2118  */
2119 
2120 int __sys_connect_file(struct file *file, struct sockaddr_storage *address,
2121 		       int addrlen, int file_flags)
2122 {
2123 	struct socket *sock;
2124 	int err;
2125 
2126 	sock = sock_from_file(file);
2127 	if (!sock) {
2128 		err = -ENOTSOCK;
2129 		goto out;
2130 	}
2131 
2132 	err =
2133 	    security_socket_connect(sock, (struct sockaddr *)address, addrlen);
2134 	if (err)
2135 		goto out;
2136 
2137 	err = READ_ONCE(sock->ops)->connect(sock, (struct sockaddr_unsized *)address,
2138 					    addrlen, sock->file->f_flags | file_flags);
2139 out:
2140 	return err;
2141 }
2142 
2143 int __sys_connect(int fd, struct sockaddr __user *uservaddr, int addrlen)
2144 {
2145 	struct sockaddr_storage address;
2146 	CLASS(fd, f)(fd);
2147 	int ret;
2148 
2149 	if (fd_empty(f))
2150 		return -EBADF;
2151 
2152 	ret = move_addr_to_kernel(uservaddr, addrlen, &address);
2153 	if (ret)
2154 		return ret;
2155 
2156 	return __sys_connect_file(fd_file(f), &address, addrlen, 0);
2157 }
2158 
2159 SYSCALL_DEFINE3(connect, int, fd, struct sockaddr __user *, uservaddr,
2160 		int, addrlen)
2161 {
2162 	return __sys_connect(fd, uservaddr, addrlen);
2163 }
2164 
2165 int do_getsockname(struct socket *sock, int peer,
2166 		   struct sockaddr __user *usockaddr, int __user *usockaddr_len)
2167 {
2168 	struct sockaddr_storage address;
2169 	int err;
2170 
2171 	if (peer)
2172 		err = security_socket_getpeername(sock);
2173 	else
2174 		err = security_socket_getsockname(sock);
2175 	if (err)
2176 		return err;
2177 	err = READ_ONCE(sock->ops)->getname(sock, (struct sockaddr *)&address, peer);
2178 	if (err < 0)
2179 		return err;
2180 	/* "err" is actually length in this case */
2181 	return move_addr_to_user(&address, err, usockaddr, usockaddr_len);
2182 }
2183 
2184 /*
2185  *	Get the remote or local address ('name') of a socket object. Move the
2186  *	obtained name to user space.
2187  */
2188 int __sys_getsockname(int fd, struct sockaddr __user *usockaddr,
2189 		      int __user *usockaddr_len, int peer)
2190 {
2191 	struct socket *sock;
2192 	CLASS(fd, f)(fd);
2193 
2194 	if (fd_empty(f))
2195 		return -EBADF;
2196 	sock = sock_from_file(fd_file(f));
2197 	if (unlikely(!sock))
2198 		return -ENOTSOCK;
2199 	return do_getsockname(sock, peer, usockaddr, usockaddr_len);
2200 }
2201 
2202 SYSCALL_DEFINE3(getsockname, int, fd, struct sockaddr __user *, usockaddr,
2203 		int __user *, usockaddr_len)
2204 {
2205 	return __sys_getsockname(fd, usockaddr, usockaddr_len, 0);
2206 }
2207 
2208 SYSCALL_DEFINE3(getpeername, int, fd, struct sockaddr __user *, usockaddr,
2209 		int __user *, usockaddr_len)
2210 {
2211 	return __sys_getsockname(fd, usockaddr, usockaddr_len, 1);
2212 }
2213 
2214 /*
2215  *	Send a datagram to a given address. We move the address into kernel
2216  *	space and check the user space data area is readable before invoking
2217  *	the protocol.
2218  */
2219 int __sys_sendto(int fd, void __user *buff, size_t len, unsigned int flags,
2220 		 struct sockaddr __user *addr,  int addr_len)
2221 {
2222 	struct socket *sock;
2223 	struct sockaddr_storage address;
2224 	int err;
2225 	struct msghdr msg;
2226 
2227 	err = import_ubuf(ITER_SOURCE, buff, len, &msg.msg_iter);
2228 	if (unlikely(err))
2229 		return err;
2230 
2231 	CLASS(fd, f)(fd);
2232 	if (fd_empty(f))
2233 		return -EBADF;
2234 	sock = sock_from_file(fd_file(f));
2235 	if (unlikely(!sock))
2236 		return -ENOTSOCK;
2237 
2238 	msg.msg_name = NULL;
2239 	msg.msg_control = NULL;
2240 	msg.msg_controllen = 0;
2241 	msg.msg_namelen = 0;
2242 	msg.msg_ubuf = NULL;
2243 	if (addr) {
2244 		err = move_addr_to_kernel(addr, addr_len, &address);
2245 		if (err < 0)
2246 			return err;
2247 		msg.msg_name = (struct sockaddr *)&address;
2248 		msg.msg_namelen = addr_len;
2249 	}
2250 	flags &= ~MSG_INTERNAL_SENDMSG_FLAGS;
2251 	if (sock->file->f_flags & O_NONBLOCK)
2252 		flags |= MSG_DONTWAIT;
2253 	msg.msg_flags = flags;
2254 	return __sock_sendmsg(sock, &msg);
2255 }
2256 
2257 SYSCALL_DEFINE6(sendto, int, fd, void __user *, buff, size_t, len,
2258 		unsigned int, flags, struct sockaddr __user *, addr,
2259 		int, addr_len)
2260 {
2261 	return __sys_sendto(fd, buff, len, flags, addr, addr_len);
2262 }
2263 
2264 /*
2265  *	Send a datagram down a socket.
2266  */
2267 
2268 SYSCALL_DEFINE4(send, int, fd, void __user *, buff, size_t, len,
2269 		unsigned int, flags)
2270 {
2271 	return __sys_sendto(fd, buff, len, flags, NULL, 0);
2272 }
2273 
2274 /*
2275  *	Receive a frame from the socket and optionally record the address of the
2276  *	sender. We verify the buffers are writable and if needed move the
2277  *	sender address from kernel to user space.
2278  */
2279 int __sys_recvfrom(int fd, void __user *ubuf, size_t size, unsigned int flags,
2280 		   struct sockaddr __user *addr, int __user *addr_len)
2281 {
2282 	struct sockaddr_storage address;
2283 	struct msghdr msg = {
2284 		/* Save some cycles and don't copy the address if not needed */
2285 		.msg_name = addr ? (struct sockaddr *)&address : NULL,
2286 	};
2287 	struct socket *sock;
2288 	int err, err2;
2289 
2290 	err = import_ubuf(ITER_DEST, ubuf, size, &msg.msg_iter);
2291 	if (unlikely(err))
2292 		return err;
2293 
2294 	CLASS(fd, f)(fd);
2295 
2296 	if (fd_empty(f))
2297 		return -EBADF;
2298 	sock = sock_from_file(fd_file(f));
2299 	if (unlikely(!sock))
2300 		return -ENOTSOCK;
2301 
2302 	if (sock->file->f_flags & O_NONBLOCK)
2303 		flags |= MSG_DONTWAIT;
2304 	err = sock_recvmsg(sock, &msg, flags);
2305 
2306 	if (err >= 0 && addr != NULL) {
2307 		err2 = move_addr_to_user(&address,
2308 					 msg.msg_namelen, addr, addr_len);
2309 		if (err2 < 0)
2310 			err = err2;
2311 	}
2312 	return err;
2313 }
2314 
2315 SYSCALL_DEFINE6(recvfrom, int, fd, void __user *, ubuf, size_t, size,
2316 		unsigned int, flags, struct sockaddr __user *, addr,
2317 		int __user *, addr_len)
2318 {
2319 	return __sys_recvfrom(fd, ubuf, size, flags, addr, addr_len);
2320 }
2321 
2322 /*
2323  *	Receive a datagram from a socket.
2324  */
2325 
2326 SYSCALL_DEFINE4(recv, int, fd, void __user *, ubuf, size_t, size,
2327 		unsigned int, flags)
2328 {
2329 	return __sys_recvfrom(fd, ubuf, size, flags, NULL, NULL);
2330 }
2331 
2332 static bool sock_use_custom_sol_socket(const struct socket *sock)
2333 {
2334 	return test_bit(SOCK_CUSTOM_SOCKOPT, &sock->flags);
2335 }
2336 
2337 int do_sock_setsockopt(struct socket *sock, bool compat, int level,
2338 		       int optname, sockptr_t optval, int optlen)
2339 {
2340 	const struct proto_ops *ops;
2341 	char *kernel_optval = NULL;
2342 	int err;
2343 
2344 	if (optlen < 0)
2345 		return -EINVAL;
2346 
2347 	err = security_socket_setsockopt(sock, level, optname);
2348 	if (err)
2349 		goto out_put;
2350 
2351 	if (!compat)
2352 		err = BPF_CGROUP_RUN_PROG_SETSOCKOPT(sock->sk, &level, &optname,
2353 						     optval, &optlen,
2354 						     &kernel_optval);
2355 	if (err < 0)
2356 		goto out_put;
2357 	if (err > 0) {
2358 		err = 0;
2359 		goto out_put;
2360 	}
2361 
2362 	if (kernel_optval)
2363 		optval = KERNEL_SOCKPTR(kernel_optval);
2364 	ops = READ_ONCE(sock->ops);
2365 	if (level == SOL_SOCKET && !sock_use_custom_sol_socket(sock))
2366 		err = sock_setsockopt(sock, level, optname, optval, optlen);
2367 	else if (unlikely(!ops->setsockopt))
2368 		err = -EOPNOTSUPP;
2369 	else
2370 		err = ops->setsockopt(sock, level, optname, optval,
2371 					    optlen);
2372 	kfree(kernel_optval);
2373 out_put:
2374 	return err;
2375 }
2376 EXPORT_SYMBOL(do_sock_setsockopt);
2377 
2378 /* Set a socket option. Because we don't know the option lengths we have
2379  * to pass the user mode parameter for the protocols to sort out.
2380  */
2381 int __sys_setsockopt(int fd, int level, int optname, char __user *user_optval,
2382 		     int optlen)
2383 {
2384 	sockptr_t optval = USER_SOCKPTR(user_optval);
2385 	bool compat = in_compat_syscall();
2386 	struct socket *sock;
2387 	CLASS(fd, f)(fd);
2388 
2389 	if (fd_empty(f))
2390 		return -EBADF;
2391 	sock = sock_from_file(fd_file(f));
2392 	if (unlikely(!sock))
2393 		return -ENOTSOCK;
2394 
2395 	return do_sock_setsockopt(sock, compat, level, optname, optval, optlen);
2396 }
2397 
2398 SYSCALL_DEFINE5(setsockopt, int, fd, int, level, int, optname,
2399 		char __user *, optval, int, optlen)
2400 {
2401 	return __sys_setsockopt(fd, level, optname, optval, optlen);
2402 }
2403 
2404 INDIRECT_CALLABLE_DECLARE(bool tcp_bpf_bypass_getsockopt(int level,
2405 							 int optname));
2406 
2407 /*
2408  * Initialize a sockopt_t from sockptr optval/optlen, setting up iov_iter
2409  * for both input and output directions.
2410  * It is important to remember that both iov points to the same data, but,
2411  * .iter_in is read-only and .iter_out is write-only by the protocol callbacks
2412  */
2413 static int sockptr_to_sockopt(sockopt_t *opt, sockptr_t optval,
2414 			      sockptr_t optlen, struct kvec *kvec)
2415 {
2416 	int koptlen;
2417 
2418 	if (copy_from_sockptr(&koptlen, optlen, sizeof(int)))
2419 		return -EFAULT;
2420 
2421 	if (koptlen < 0)
2422 		return -EINVAL;
2423 
2424 	if (optval.is_kernel) {
2425 		kvec->iov_base = optval.kernel;
2426 		kvec->iov_len = koptlen;
2427 		iov_iter_kvec(&opt->iter_out, ITER_DEST, kvec, 1, koptlen);
2428 		iov_iter_kvec(&opt->iter_in, ITER_SOURCE, kvec, 1, koptlen);
2429 	} else {
2430 		iov_iter_ubuf(&opt->iter_out, ITER_DEST, optval.user, koptlen);
2431 		iov_iter_ubuf(&opt->iter_in, ITER_SOURCE, optval.user,
2432 			      koptlen);
2433 	}
2434 	opt->optlen = koptlen;
2435 
2436 	return 0;
2437 }
2438 
2439 int do_sock_getsockopt(struct socket *sock, bool compat, int level,
2440 		       int optname, sockptr_t optval, sockptr_t optlen)
2441 {
2442 	int max_optlen __maybe_unused = 0;
2443 	const struct proto_ops *ops;
2444 	struct kvec kvec;
2445 	sockopt_t opt;
2446 	int err;
2447 
2448 	err = security_socket_getsockopt(sock, level, optname);
2449 	if (err)
2450 		return err;
2451 
2452 	if (!compat)
2453 		copy_from_sockptr(&max_optlen, optlen, sizeof(int));
2454 
2455 	ops = READ_ONCE(sock->ops);
2456 	if (level == SOL_SOCKET) {
2457 		err = sk_getsockopt(sock->sk, level, optname, optval, optlen);
2458 	} else if (ops->getsockopt_iter) {
2459 		err = sockptr_to_sockopt(&opt, optval, optlen, &kvec);
2460 		if (err)
2461 			return err;
2462 
2463 		err = ops->getsockopt_iter(sock, level, optname, &opt);
2464 
2465 		/* Always write back optlen, even on failure. Some protocols
2466 		 * (e.g. CAN raw) return -ERANGE and set optlen to the
2467 		 * required buffer size so userspace can discover it.
2468 		 */
2469 		if (copy_to_sockptr(optlen, &opt.optlen, sizeof(int)))
2470 			return -EFAULT;
2471 	} else if (ops->getsockopt) {
2472 		if (WARN_ONCE(optval.is_kernel || optlen.is_kernel,
2473 			      "Invalid argument type"))
2474 			return -EOPNOTSUPP;
2475 
2476 		err = ops->getsockopt(sock, level, optname, optval.user,
2477 				      optlen.user);
2478 	} else {
2479 		err = -EOPNOTSUPP;
2480 	}
2481 
2482 	if (!compat)
2483 		err = BPF_CGROUP_RUN_PROG_GETSOCKOPT(sock->sk, level, optname,
2484 						     optval, optlen, max_optlen,
2485 						     err);
2486 
2487 	return err;
2488 }
2489 EXPORT_SYMBOL(do_sock_getsockopt);
2490 
2491 /*
2492  *	Get a socket option. Because we don't know the option lengths we have
2493  *	to pass a user mode parameter for the protocols to sort out.
2494  */
2495 int __sys_getsockopt(int fd, int level, int optname, char __user *optval,
2496 		int __user *optlen)
2497 {
2498 	struct socket *sock;
2499 	CLASS(fd, f)(fd);
2500 
2501 	if (fd_empty(f))
2502 		return -EBADF;
2503 	sock = sock_from_file(fd_file(f));
2504 	if (unlikely(!sock))
2505 		return -ENOTSOCK;
2506 
2507 	return do_sock_getsockopt(sock, in_compat_syscall(), level, optname,
2508 				 USER_SOCKPTR(optval), USER_SOCKPTR(optlen));
2509 }
2510 
2511 SYSCALL_DEFINE5(getsockopt, int, fd, int, level, int, optname,
2512 		char __user *, optval, int __user *, optlen)
2513 {
2514 	return __sys_getsockopt(fd, level, optname, optval, optlen);
2515 }
2516 
2517 /*
2518  *	Shutdown a socket.
2519  */
2520 
2521 int __sys_shutdown_sock(struct socket *sock, int how)
2522 {
2523 	int err;
2524 
2525 	err = security_socket_shutdown(sock, how);
2526 	if (!err)
2527 		err = READ_ONCE(sock->ops)->shutdown(sock, how);
2528 
2529 	return err;
2530 }
2531 
2532 int __sys_shutdown(int fd, int how)
2533 {
2534 	struct socket *sock;
2535 	CLASS(fd, f)(fd);
2536 
2537 	if (fd_empty(f))
2538 		return -EBADF;
2539 	sock = sock_from_file(fd_file(f));
2540 	if (unlikely(!sock))
2541 		return -ENOTSOCK;
2542 
2543 	return __sys_shutdown_sock(sock, how);
2544 }
2545 
2546 SYSCALL_DEFINE2(shutdown, int, fd, int, how)
2547 {
2548 	return __sys_shutdown(fd, how);
2549 }
2550 
2551 /* A couple of helpful macros for getting the address of the 32/64 bit
2552  * fields which are the same type (int / unsigned) on our platforms.
2553  */
2554 #define COMPAT_MSG(msg, member)	((MSG_CMSG_COMPAT & flags) ? &msg##_compat->member : &msg->member)
2555 #define COMPAT_NAMELEN(msg)	COMPAT_MSG(msg, msg_namelen)
2556 #define COMPAT_FLAGS(msg)	COMPAT_MSG(msg, msg_flags)
2557 
2558 struct used_address {
2559 	struct sockaddr_storage name;
2560 	unsigned int name_len;
2561 };
2562 
2563 int __copy_msghdr(struct msghdr *kmsg,
2564 		  struct user_msghdr *msg,
2565 		  struct sockaddr __user **save_addr)
2566 {
2567 	ssize_t err;
2568 
2569 	kmsg->msg_control_is_user = true;
2570 	kmsg->msg_get_inq = 0;
2571 	kmsg->msg_control_user = msg->msg_control;
2572 	kmsg->msg_controllen = msg->msg_controllen;
2573 	kmsg->msg_flags = msg->msg_flags;
2574 
2575 	kmsg->msg_namelen = msg->msg_namelen;
2576 	if (!msg->msg_name)
2577 		kmsg->msg_namelen = 0;
2578 
2579 	if (kmsg->msg_namelen < 0)
2580 		return -EINVAL;
2581 
2582 	if (kmsg->msg_namelen > sizeof(struct sockaddr_storage))
2583 		kmsg->msg_namelen = sizeof(struct sockaddr_storage);
2584 
2585 	if (save_addr)
2586 		*save_addr = msg->msg_name;
2587 
2588 	if (msg->msg_name && kmsg->msg_namelen) {
2589 		if (!save_addr) {
2590 			err = move_addr_to_kernel(msg->msg_name,
2591 						  kmsg->msg_namelen,
2592 						  kmsg->msg_name);
2593 			if (err < 0)
2594 				return err;
2595 		}
2596 	} else {
2597 		kmsg->msg_name = NULL;
2598 		kmsg->msg_namelen = 0;
2599 	}
2600 
2601 	if (msg->msg_iovlen > UIO_MAXIOV)
2602 		return -EMSGSIZE;
2603 
2604 	kmsg->msg_iocb = NULL;
2605 	kmsg->msg_ubuf = NULL;
2606 	return 0;
2607 }
2608 
2609 static int copy_msghdr_from_user(struct msghdr *kmsg,
2610 				 struct user_msghdr __user *umsg,
2611 				 struct sockaddr __user **save_addr,
2612 				 struct iovec **iov)
2613 {
2614 	struct user_msghdr msg;
2615 	ssize_t err;
2616 
2617 	if (copy_from_user(&msg, umsg, sizeof(*umsg)))
2618 		return -EFAULT;
2619 
2620 	err = __copy_msghdr(kmsg, &msg, save_addr);
2621 	if (err)
2622 		return err;
2623 
2624 	err = import_iovec(save_addr ? ITER_DEST : ITER_SOURCE,
2625 			    msg.msg_iov, msg.msg_iovlen,
2626 			    UIO_FASTIOV, iov, &kmsg->msg_iter);
2627 	return err < 0 ? err : 0;
2628 }
2629 
2630 static int ____sys_sendmsg(struct socket *sock, struct msghdr *msg_sys,
2631 			   unsigned int flags, struct used_address *used_address,
2632 			   unsigned int allowed_msghdr_flags)
2633 {
2634 	unsigned char ctl[sizeof(struct cmsghdr) + 20]
2635 				__aligned(sizeof(__kernel_size_t));
2636 	/* 20 is size of ipv6_pktinfo */
2637 	unsigned char *ctl_buf = ctl;
2638 	int ctl_len;
2639 	ssize_t err;
2640 
2641 	err = -ENOBUFS;
2642 
2643 	if (msg_sys->msg_controllen > INT_MAX)
2644 		goto out;
2645 	flags |= (msg_sys->msg_flags & allowed_msghdr_flags);
2646 	ctl_len = msg_sys->msg_controllen;
2647 	if ((MSG_CMSG_COMPAT & flags) && ctl_len) {
2648 		err =
2649 		    cmsghdr_from_user_compat_to_kern(msg_sys, sock->sk, ctl,
2650 						     sizeof(ctl));
2651 		if (err)
2652 			goto out;
2653 		ctl_buf = msg_sys->msg_control;
2654 		ctl_len = msg_sys->msg_controllen;
2655 	} else if (ctl_len) {
2656 		BUILD_BUG_ON(sizeof(struct cmsghdr) !=
2657 			     CMSG_ALIGN(sizeof(struct cmsghdr)));
2658 		if (ctl_len > sizeof(ctl)) {
2659 			ctl_buf = sock_kmalloc(sock->sk, ctl_len, GFP_KERNEL);
2660 			if (ctl_buf == NULL)
2661 				goto out;
2662 		}
2663 		err = -EFAULT;
2664 		if (copy_from_user(ctl_buf, msg_sys->msg_control_user, ctl_len))
2665 			goto out_freectl;
2666 		msg_sys->msg_control = ctl_buf;
2667 		msg_sys->msg_control_is_user = false;
2668 	}
2669 	flags &= ~MSG_INTERNAL_SENDMSG_FLAGS;
2670 	msg_sys->msg_flags = flags;
2671 
2672 	if (sock->file->f_flags & O_NONBLOCK)
2673 		msg_sys->msg_flags |= MSG_DONTWAIT;
2674 	/*
2675 	 * If this is sendmmsg() and current destination address is same as
2676 	 * previously succeeded address, omit asking LSM's decision.
2677 	 * used_address->name_len is initialized to UINT_MAX so that the first
2678 	 * destination address never matches.
2679 	 */
2680 	if (used_address && msg_sys->msg_name &&
2681 	    used_address->name_len == msg_sys->msg_namelen &&
2682 	    !memcmp(&used_address->name, msg_sys->msg_name,
2683 		    used_address->name_len)) {
2684 		err = sock_sendmsg_nosec(sock, msg_sys);
2685 		goto out_freectl;
2686 	}
2687 	err = __sock_sendmsg(sock, msg_sys);
2688 	/*
2689 	 * If this is sendmmsg() and sending to current destination address was
2690 	 * successful, remember it.
2691 	 */
2692 	if (used_address && err >= 0) {
2693 		used_address->name_len = msg_sys->msg_namelen;
2694 		if (msg_sys->msg_name)
2695 			memcpy(&used_address->name, msg_sys->msg_name,
2696 			       used_address->name_len);
2697 	}
2698 
2699 out_freectl:
2700 	if (ctl_buf != ctl)
2701 		sock_kfree_s(sock->sk, ctl_buf, ctl_len);
2702 out:
2703 	return err;
2704 }
2705 
2706 static int sendmsg_copy_msghdr(struct msghdr *msg,
2707 			       struct user_msghdr __user *umsg, unsigned flags,
2708 			       struct iovec **iov)
2709 {
2710 	int err;
2711 
2712 	if (flags & MSG_CMSG_COMPAT) {
2713 		struct compat_msghdr __user *msg_compat;
2714 
2715 		msg_compat = (struct compat_msghdr __user *) umsg;
2716 		err = get_compat_msghdr(msg, msg_compat, NULL, iov);
2717 	} else {
2718 		err = copy_msghdr_from_user(msg, umsg, NULL, iov);
2719 	}
2720 	if (err < 0)
2721 		return err;
2722 
2723 	return 0;
2724 }
2725 
2726 static int ___sys_sendmsg(struct socket *sock, struct user_msghdr __user *msg,
2727 			 struct msghdr *msg_sys, unsigned int flags,
2728 			 struct used_address *used_address,
2729 			 unsigned int allowed_msghdr_flags)
2730 {
2731 	struct sockaddr_storage address;
2732 	struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
2733 	ssize_t err;
2734 
2735 	msg_sys->msg_name = &address;
2736 
2737 	err = sendmsg_copy_msghdr(msg_sys, msg, flags, &iov);
2738 	if (err < 0)
2739 		return err;
2740 
2741 	err = ____sys_sendmsg(sock, msg_sys, flags, used_address,
2742 				allowed_msghdr_flags);
2743 	kfree(iov);
2744 	return err;
2745 }
2746 
2747 /*
2748  *	BSD sendmsg interface
2749  */
2750 long __sys_sendmsg_sock(struct socket *sock, struct msghdr *msg,
2751 			unsigned int flags)
2752 {
2753 	return ____sys_sendmsg(sock, msg, flags, NULL, 0);
2754 }
2755 
2756 long __sys_sendmsg(int fd, struct user_msghdr __user *msg, unsigned int flags,
2757 		   bool forbid_cmsg_compat)
2758 {
2759 	struct msghdr msg_sys;
2760 	struct socket *sock;
2761 
2762 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2763 		return -EINVAL;
2764 
2765 	CLASS(fd, f)(fd);
2766 
2767 	if (fd_empty(f))
2768 		return -EBADF;
2769 	sock = sock_from_file(fd_file(f));
2770 	if (unlikely(!sock))
2771 		return -ENOTSOCK;
2772 
2773 	return ___sys_sendmsg(sock, msg, &msg_sys, flags, NULL, 0);
2774 }
2775 
2776 SYSCALL_DEFINE3(sendmsg, int, fd, struct user_msghdr __user *, msg, unsigned int, flags)
2777 {
2778 	return __sys_sendmsg(fd, msg, flags, true);
2779 }
2780 
2781 /*
2782  *	Linux sendmmsg interface
2783  */
2784 
2785 int __sys_sendmmsg(int fd, struct mmsghdr __user *mmsg, unsigned int vlen,
2786 		   unsigned int flags, bool forbid_cmsg_compat)
2787 {
2788 	int err, datagrams;
2789 	struct socket *sock;
2790 	struct mmsghdr __user *entry;
2791 	struct compat_mmsghdr __user *compat_entry;
2792 	struct msghdr msg_sys;
2793 	struct used_address used_address;
2794 	unsigned int oflags = flags;
2795 
2796 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2797 		return -EINVAL;
2798 
2799 	if (vlen > UIO_MAXIOV)
2800 		vlen = UIO_MAXIOV;
2801 
2802 	datagrams = 0;
2803 
2804 	CLASS(fd, f)(fd);
2805 
2806 	if (fd_empty(f))
2807 		return -EBADF;
2808 	sock = sock_from_file(fd_file(f));
2809 	if (unlikely(!sock))
2810 		return -ENOTSOCK;
2811 
2812 	used_address.name_len = UINT_MAX;
2813 	entry = mmsg;
2814 	compat_entry = (struct compat_mmsghdr __user *)mmsg;
2815 	err = 0;
2816 	flags |= MSG_BATCH;
2817 
2818 	while (datagrams < vlen) {
2819 		if (datagrams == vlen - 1)
2820 			flags = oflags;
2821 
2822 		if (MSG_CMSG_COMPAT & flags) {
2823 			err = ___sys_sendmsg(sock, (struct user_msghdr __user *)compat_entry,
2824 					     &msg_sys, flags, &used_address, MSG_EOR);
2825 			if (err < 0)
2826 				break;
2827 			err = __put_user(err, &compat_entry->msg_len);
2828 			++compat_entry;
2829 		} else {
2830 			err = ___sys_sendmsg(sock,
2831 					     (struct user_msghdr __user *)entry,
2832 					     &msg_sys, flags, &used_address, MSG_EOR);
2833 			if (err < 0)
2834 				break;
2835 			err = put_user(err, &entry->msg_len);
2836 			++entry;
2837 		}
2838 
2839 		if (err)
2840 			break;
2841 		++datagrams;
2842 		if (msg_data_left(&msg_sys))
2843 			break;
2844 		cond_resched();
2845 	}
2846 
2847 	/* We only return an error if no datagrams were able to be sent */
2848 	if (datagrams != 0)
2849 		return datagrams;
2850 
2851 	return err;
2852 }
2853 
2854 SYSCALL_DEFINE4(sendmmsg, int, fd, struct mmsghdr __user *, mmsg,
2855 		unsigned int, vlen, unsigned int, flags)
2856 {
2857 	return __sys_sendmmsg(fd, mmsg, vlen, flags, true);
2858 }
2859 
2860 static int recvmsg_copy_msghdr(struct msghdr *msg,
2861 			       struct user_msghdr __user *umsg, unsigned flags,
2862 			       struct sockaddr __user **uaddr,
2863 			       struct iovec **iov)
2864 {
2865 	ssize_t err;
2866 
2867 	if (MSG_CMSG_COMPAT & flags) {
2868 		struct compat_msghdr __user *msg_compat;
2869 
2870 		msg_compat = (struct compat_msghdr __user *) umsg;
2871 		err = get_compat_msghdr(msg, msg_compat, uaddr, iov);
2872 	} else {
2873 		err = copy_msghdr_from_user(msg, umsg, uaddr, iov);
2874 	}
2875 	if (err < 0)
2876 		return err;
2877 
2878 	return 0;
2879 }
2880 
2881 static int ____sys_recvmsg(struct socket *sock, struct msghdr *msg_sys,
2882 			   struct user_msghdr __user *msg,
2883 			   struct sockaddr __user *uaddr,
2884 			   unsigned int flags, int nosec)
2885 {
2886 	struct compat_msghdr __user *msg_compat =
2887 					(struct compat_msghdr __user *) msg;
2888 	int __user *uaddr_len = COMPAT_NAMELEN(msg);
2889 	struct sockaddr_storage addr;
2890 	unsigned long cmsg_ptr;
2891 	int len;
2892 	ssize_t err;
2893 
2894 	msg_sys->msg_name = &addr;
2895 	cmsg_ptr = (unsigned long)msg_sys->msg_control;
2896 	msg_sys->msg_flags = flags & (MSG_CMSG_CLOEXEC|MSG_CMSG_COMPAT);
2897 
2898 	/* We assume all kernel code knows the size of sockaddr_storage */
2899 	msg_sys->msg_namelen = 0;
2900 
2901 	if (sock->file->f_flags & O_NONBLOCK)
2902 		flags |= MSG_DONTWAIT;
2903 
2904 	if (unlikely(nosec))
2905 		err = sock_recvmsg_nosec(sock, msg_sys, flags);
2906 	else
2907 		err = sock_recvmsg(sock, msg_sys, flags);
2908 
2909 	if (err < 0)
2910 		goto out;
2911 	len = err;
2912 
2913 	if (uaddr != NULL) {
2914 		err = move_addr_to_user(&addr,
2915 					msg_sys->msg_namelen, uaddr,
2916 					uaddr_len);
2917 		if (err < 0)
2918 			goto out;
2919 	}
2920 	err = __put_user((msg_sys->msg_flags & ~MSG_CMSG_COMPAT),
2921 			 COMPAT_FLAGS(msg));
2922 	if (err)
2923 		goto out;
2924 	if (MSG_CMSG_COMPAT & flags)
2925 		err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
2926 				 &msg_compat->msg_controllen);
2927 	else
2928 		err = __put_user((unsigned long)msg_sys->msg_control - cmsg_ptr,
2929 				 &msg->msg_controllen);
2930 	if (err)
2931 		goto out;
2932 	err = len;
2933 out:
2934 	return err;
2935 }
2936 
2937 static int ___sys_recvmsg(struct socket *sock, struct user_msghdr __user *msg,
2938 			 struct msghdr *msg_sys, unsigned int flags, int nosec)
2939 {
2940 	struct iovec iovstack[UIO_FASTIOV], *iov = iovstack;
2941 	/* user mode address pointers */
2942 	struct sockaddr __user *uaddr;
2943 	ssize_t err;
2944 
2945 	err = recvmsg_copy_msghdr(msg_sys, msg, flags, &uaddr, &iov);
2946 	if (err < 0)
2947 		return err;
2948 
2949 	err = ____sys_recvmsg(sock, msg_sys, msg, uaddr, flags, nosec);
2950 	kfree(iov);
2951 	return err;
2952 }
2953 
2954 /*
2955  *	BSD recvmsg interface
2956  */
2957 
2958 long __sys_recvmsg_sock(struct socket *sock, struct msghdr *msg,
2959 			struct user_msghdr __user *umsg,
2960 			struct sockaddr __user *uaddr, unsigned int flags)
2961 {
2962 	return ____sys_recvmsg(sock, msg, umsg, uaddr, flags, 0);
2963 }
2964 
2965 long __sys_recvmsg(int fd, struct user_msghdr __user *msg, unsigned int flags,
2966 		   bool forbid_cmsg_compat)
2967 {
2968 	struct msghdr msg_sys;
2969 	struct socket *sock;
2970 
2971 	if (forbid_cmsg_compat && (flags & MSG_CMSG_COMPAT))
2972 		return -EINVAL;
2973 
2974 	CLASS(fd, f)(fd);
2975 
2976 	if (fd_empty(f))
2977 		return -EBADF;
2978 	sock = sock_from_file(fd_file(f));
2979 	if (unlikely(!sock))
2980 		return -ENOTSOCK;
2981 
2982 	return ___sys_recvmsg(sock, msg, &msg_sys, flags, 0);
2983 }
2984 
2985 SYSCALL_DEFINE3(recvmsg, int, fd, struct user_msghdr __user *, msg,
2986 		unsigned int, flags)
2987 {
2988 	return __sys_recvmsg(fd, msg, flags, true);
2989 }
2990 
2991 /*
2992  *     Linux recvmmsg interface
2993  */
2994 
2995 static int do_recvmmsg(int fd, struct mmsghdr __user *mmsg,
2996 			  unsigned int vlen, unsigned int flags,
2997 			  struct timespec64 *timeout)
2998 {
2999 	int err = 0, datagrams;
3000 	struct socket *sock;
3001 	struct mmsghdr __user *entry;
3002 	struct compat_mmsghdr __user *compat_entry;
3003 	struct msghdr msg_sys;
3004 	struct timespec64 end_time;
3005 	struct timespec64 timeout64;
3006 
3007 	if (timeout &&
3008 	    poll_select_set_timeout(&end_time, timeout->tv_sec,
3009 				    timeout->tv_nsec))
3010 		return -EINVAL;
3011 
3012 	datagrams = 0;
3013 
3014 	CLASS(fd, f)(fd);
3015 
3016 	if (fd_empty(f))
3017 		return -EBADF;
3018 	sock = sock_from_file(fd_file(f));
3019 	if (unlikely(!sock))
3020 		return -ENOTSOCK;
3021 
3022 	if (likely(!(flags & MSG_ERRQUEUE))) {
3023 		err = sock_error(sock->sk);
3024 		if (err)
3025 			return err;
3026 	}
3027 
3028 	entry = mmsg;
3029 	compat_entry = (struct compat_mmsghdr __user *)mmsg;
3030 
3031 	while (datagrams < vlen) {
3032 		/*
3033 		 * No need to ask LSM for more than the first datagram.
3034 		 */
3035 		if (MSG_CMSG_COMPAT & flags) {
3036 			err = ___sys_recvmsg(sock, (struct user_msghdr __user *)compat_entry,
3037 					     &msg_sys, flags & ~MSG_WAITFORONE,
3038 					     datagrams);
3039 			if (err < 0)
3040 				break;
3041 			err = __put_user(err, &compat_entry->msg_len);
3042 			++compat_entry;
3043 		} else {
3044 			err = ___sys_recvmsg(sock,
3045 					     (struct user_msghdr __user *)entry,
3046 					     &msg_sys, flags & ~MSG_WAITFORONE,
3047 					     datagrams);
3048 			if (err < 0)
3049 				break;
3050 			err = put_user(err, &entry->msg_len);
3051 			++entry;
3052 		}
3053 
3054 		if (err)
3055 			break;
3056 		++datagrams;
3057 
3058 		/* MSG_WAITFORONE turns on MSG_DONTWAIT after one packet */
3059 		if (flags & MSG_WAITFORONE)
3060 			flags |= MSG_DONTWAIT;
3061 
3062 		if (timeout) {
3063 			ktime_get_ts64(&timeout64);
3064 			*timeout = timespec64_sub(end_time, timeout64);
3065 			if (timeout->tv_sec < 0) {
3066 				timeout->tv_sec = timeout->tv_nsec = 0;
3067 				break;
3068 			}
3069 
3070 			/* Timeout, return less than vlen datagrams */
3071 			if (timeout->tv_nsec == 0 && timeout->tv_sec == 0)
3072 				break;
3073 		}
3074 
3075 		/* Out of band data, return right away */
3076 		if (msg_sys.msg_flags & MSG_OOB)
3077 			break;
3078 		cond_resched();
3079 	}
3080 
3081 	if (err == 0)
3082 		return datagrams;
3083 
3084 	if (datagrams == 0)
3085 		return err;
3086 
3087 	/*
3088 	 * We may return less entries than requested (vlen) if the
3089 	 * sock is non block and there aren't enough datagrams...
3090 	 */
3091 	if (err != -EAGAIN) {
3092 		/*
3093 		 * ... or  if recvmsg returns an error after we
3094 		 * received some datagrams, where we record the
3095 		 * error to return on the next call or if the
3096 		 * app asks about it using getsockopt(SO_ERROR).
3097 		 */
3098 		WRITE_ONCE(sock->sk->sk_err, -err);
3099 	}
3100 	return datagrams;
3101 }
3102 
3103 int __sys_recvmmsg(int fd, struct mmsghdr __user *mmsg,
3104 		   unsigned int vlen, unsigned int flags,
3105 		   struct __kernel_timespec __user *timeout,
3106 		   struct old_timespec32 __user *timeout32)
3107 {
3108 	int datagrams;
3109 	struct timespec64 timeout_sys;
3110 
3111 	if (timeout && get_timespec64(&timeout_sys, timeout))
3112 		return -EFAULT;
3113 
3114 	if (timeout32 && get_old_timespec32(&timeout_sys, timeout32))
3115 		return -EFAULT;
3116 
3117 	if (!timeout && !timeout32)
3118 		return do_recvmmsg(fd, mmsg, vlen, flags, NULL);
3119 
3120 	datagrams = do_recvmmsg(fd, mmsg, vlen, flags, &timeout_sys);
3121 
3122 	if (datagrams <= 0)
3123 		return datagrams;
3124 
3125 	if (timeout && put_timespec64(&timeout_sys, timeout))
3126 		datagrams = -EFAULT;
3127 
3128 	if (timeout32 && put_old_timespec32(&timeout_sys, timeout32))
3129 		datagrams = -EFAULT;
3130 
3131 	return datagrams;
3132 }
3133 
3134 SYSCALL_DEFINE5(recvmmsg, int, fd, struct mmsghdr __user *, mmsg,
3135 		unsigned int, vlen, unsigned int, flags,
3136 		struct __kernel_timespec __user *, timeout)
3137 {
3138 	if (flags & MSG_CMSG_COMPAT)
3139 		return -EINVAL;
3140 
3141 	return __sys_recvmmsg(fd, mmsg, vlen, flags, timeout, NULL);
3142 }
3143 
3144 #ifdef CONFIG_COMPAT_32BIT_TIME
3145 SYSCALL_DEFINE5(recvmmsg_time32, int, fd, struct mmsghdr __user *, mmsg,
3146 		unsigned int, vlen, unsigned int, flags,
3147 		struct old_timespec32 __user *, timeout)
3148 {
3149 	if (flags & MSG_CMSG_COMPAT)
3150 		return -EINVAL;
3151 
3152 	return __sys_recvmmsg(fd, mmsg, vlen, flags, NULL, timeout);
3153 }
3154 #endif
3155 
3156 #ifdef __ARCH_WANT_SYS_SOCKETCALL
3157 /* Argument list sizes for sys_socketcall */
3158 #define AL(x) ((x) * sizeof(unsigned long))
3159 static const unsigned char nargs[21] = {
3160 	AL(0), AL(3), AL(3), AL(3), AL(2), AL(3),
3161 	AL(3), AL(3), AL(4), AL(4), AL(4), AL(6),
3162 	AL(6), AL(2), AL(5), AL(5), AL(3), AL(3),
3163 	AL(4), AL(5), AL(4)
3164 };
3165 
3166 #undef AL
3167 
3168 /*
3169  *	System call vectors.
3170  *
3171  *	Argument checking cleaned up. Saved 20% in size.
3172  *  This function doesn't need to set the kernel lock because
3173  *  it is set by the callees.
3174  */
3175 
3176 SYSCALL_DEFINE2(socketcall, int, call, unsigned long __user *, args)
3177 {
3178 	unsigned long a[AUDITSC_ARGS];
3179 	unsigned long a0, a1;
3180 	int err;
3181 	unsigned int len;
3182 
3183 	if (call < 1 || call > SYS_SENDMMSG)
3184 		return -EINVAL;
3185 	call = array_index_nospec(call, SYS_SENDMMSG + 1);
3186 
3187 	len = nargs[call];
3188 	if (len > sizeof(a))
3189 		return -EINVAL;
3190 
3191 	/* copy_from_user should be SMP safe. */
3192 	if (copy_from_user(a, args, len))
3193 		return -EFAULT;
3194 
3195 	err = audit_socketcall(nargs[call] / sizeof(unsigned long), a);
3196 	if (err)
3197 		return err;
3198 
3199 	a0 = a[0];
3200 	a1 = a[1];
3201 
3202 	switch (call) {
3203 	case SYS_SOCKET:
3204 		err = __sys_socket(a0, a1, a[2]);
3205 		break;
3206 	case SYS_BIND:
3207 		err = __sys_bind(a0, (struct sockaddr __user *)a1, a[2]);
3208 		break;
3209 	case SYS_CONNECT:
3210 		err = __sys_connect(a0, (struct sockaddr __user *)a1, a[2]);
3211 		break;
3212 	case SYS_LISTEN:
3213 		err = __sys_listen(a0, a1);
3214 		break;
3215 	case SYS_ACCEPT:
3216 		err = __sys_accept4(a0, (struct sockaddr __user *)a1,
3217 				    (int __user *)a[2], 0);
3218 		break;
3219 	case SYS_GETSOCKNAME:
3220 		err =
3221 		    __sys_getsockname(a0, (struct sockaddr __user *)a1,
3222 				      (int __user *)a[2], 0);
3223 		break;
3224 	case SYS_GETPEERNAME:
3225 		err =
3226 		    __sys_getsockname(a0, (struct sockaddr __user *)a1,
3227 				      (int __user *)a[2], 1);
3228 		break;
3229 	case SYS_SOCKETPAIR:
3230 		err = __sys_socketpair(a0, a1, a[2], (int __user *)a[3]);
3231 		break;
3232 	case SYS_SEND:
3233 		err = __sys_sendto(a0, (void __user *)a1, a[2], a[3],
3234 				   NULL, 0);
3235 		break;
3236 	case SYS_SENDTO:
3237 		err = __sys_sendto(a0, (void __user *)a1, a[2], a[3],
3238 				   (struct sockaddr __user *)a[4], a[5]);
3239 		break;
3240 	case SYS_RECV:
3241 		err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3],
3242 				     NULL, NULL);
3243 		break;
3244 	case SYS_RECVFROM:
3245 		err = __sys_recvfrom(a0, (void __user *)a1, a[2], a[3],
3246 				     (struct sockaddr __user *)a[4],
3247 				     (int __user *)a[5]);
3248 		break;
3249 	case SYS_SHUTDOWN:
3250 		err = __sys_shutdown(a0, a1);
3251 		break;
3252 	case SYS_SETSOCKOPT:
3253 		err = __sys_setsockopt(a0, a1, a[2], (char __user *)a[3],
3254 				       a[4]);
3255 		break;
3256 	case SYS_GETSOCKOPT:
3257 		err =
3258 		    __sys_getsockopt(a0, a1, a[2], (char __user *)a[3],
3259 				     (int __user *)a[4]);
3260 		break;
3261 	case SYS_SENDMSG:
3262 		err = __sys_sendmsg(a0, (struct user_msghdr __user *)a1,
3263 				    a[2], true);
3264 		break;
3265 	case SYS_SENDMMSG:
3266 		err = __sys_sendmmsg(a0, (struct mmsghdr __user *)a1, a[2],
3267 				     a[3], true);
3268 		break;
3269 	case SYS_RECVMSG:
3270 		err = __sys_recvmsg(a0, (struct user_msghdr __user *)a1,
3271 				    a[2], true);
3272 		break;
3273 	case SYS_RECVMMSG:
3274 		if (IS_ENABLED(CONFIG_64BIT))
3275 			err = __sys_recvmmsg(a0, (struct mmsghdr __user *)a1,
3276 					     a[2], a[3],
3277 					     (struct __kernel_timespec __user *)a[4],
3278 					     NULL);
3279 		else
3280 			err = __sys_recvmmsg(a0, (struct mmsghdr __user *)a1,
3281 					     a[2], a[3], NULL,
3282 					     (struct old_timespec32 __user *)a[4]);
3283 		break;
3284 	case SYS_ACCEPT4:
3285 		err = __sys_accept4(a0, (struct sockaddr __user *)a1,
3286 				    (int __user *)a[2], a[3]);
3287 		break;
3288 	default:
3289 		err = -EINVAL;
3290 		break;
3291 	}
3292 	return err;
3293 }
3294 
3295 #endif				/* __ARCH_WANT_SYS_SOCKETCALL */
3296 
3297 /**
3298  *	sock_register - add a socket protocol handler
3299  *	@ops: description of protocol
3300  *
3301  *	This function is called by a protocol handler that wants to
3302  *	advertise its address family, and have it linked into the
3303  *	socket interface. The value ops->family corresponds to the
3304  *	socket system call protocol family.
3305  */
3306 int sock_register(const struct net_proto_family *ops)
3307 {
3308 	int err;
3309 
3310 	if (ops->family >= NPROTO) {
3311 		pr_crit("protocol %d >= NPROTO(%d)\n", ops->family, NPROTO);
3312 		return -ENOBUFS;
3313 	}
3314 
3315 	spin_lock(&net_family_lock);
3316 	if (rcu_dereference_protected(net_families[ops->family],
3317 				      lockdep_is_held(&net_family_lock)))
3318 		err = -EEXIST;
3319 	else {
3320 		rcu_assign_pointer(net_families[ops->family], ops);
3321 		err = 0;
3322 	}
3323 	spin_unlock(&net_family_lock);
3324 
3325 	pr_info("NET: Registered %s protocol family\n", pf_family_names[ops->family]);
3326 	return err;
3327 }
3328 EXPORT_SYMBOL(sock_register);
3329 
3330 /**
3331  *	sock_unregister - remove a protocol handler
3332  *	@family: protocol family to remove
3333  *
3334  *	This function is called by a protocol handler that wants to
3335  *	remove its address family, and have it unlinked from the
3336  *	new socket creation.
3337  *
3338  *	If protocol handler is a module, then it can use module reference
3339  *	counts to protect against new references. If protocol handler is not
3340  *	a module then it needs to provide its own protection in
3341  *	the ops->create routine.
3342  */
3343 void sock_unregister(int family)
3344 {
3345 	BUG_ON(family < 0 || family >= NPROTO);
3346 
3347 	spin_lock(&net_family_lock);
3348 	RCU_INIT_POINTER(net_families[family], NULL);
3349 	spin_unlock(&net_family_lock);
3350 
3351 	synchronize_rcu();
3352 
3353 	pr_info("NET: Unregistered %s protocol family\n", pf_family_names[family]);
3354 }
3355 EXPORT_SYMBOL(sock_unregister);
3356 
3357 bool sock_is_registered(int family)
3358 {
3359 	return family < NPROTO && rcu_access_pointer(net_families[family]);
3360 }
3361 
3362 static int __init sock_init(void)
3363 {
3364 	int err;
3365 	/*
3366 	 *      Initialize the network sysctl infrastructure.
3367 	 */
3368 	err = net_sysctl_init();
3369 	if (err)
3370 		goto out;
3371 
3372 	/*
3373 	 *      Initialize skbuff SLAB cache
3374 	 */
3375 	skb_init();
3376 
3377 	/*
3378 	 *      Initialize the protocols module.
3379 	 */
3380 
3381 	init_inodecache();
3382 
3383 	err = register_filesystem(&sock_fs_type);
3384 	if (err)
3385 		goto out;
3386 	sock_mnt = kern_mount(&sock_fs_type);
3387 	if (IS_ERR(sock_mnt)) {
3388 		err = PTR_ERR(sock_mnt);
3389 		goto out_mount;
3390 	}
3391 
3392 	/* The real protocol initialization is performed in later initcalls.
3393 	 */
3394 
3395 #ifdef CONFIG_NETFILTER
3396 	err = netfilter_init();
3397 	if (err)
3398 		goto out;
3399 #endif
3400 
3401 	ptp_classifier_init();
3402 
3403 out:
3404 	return err;
3405 
3406 out_mount:
3407 	unregister_filesystem(&sock_fs_type);
3408 	goto out;
3409 }
3410 
3411 core_initcall(sock_init);	/* early initcall */
3412 
3413 #ifdef CONFIG_PROC_FS
3414 void socket_seq_show(struct seq_file *seq)
3415 {
3416 	seq_printf(seq, "sockets: used %d\n",
3417 		   sock_inuse_get(seq->private));
3418 }
3419 #endif				/* CONFIG_PROC_FS */
3420 
3421 /* Handle the fact that while struct ifreq has the same *layout* on
3422  * 32/64 for everything but ifreq::ifru_ifmap and ifreq::ifru_data,
3423  * which are handled elsewhere, it still has different *size* due to
3424  * ifreq::ifru_ifmap (which is 16 bytes on 32 bit, 24 bytes on 64-bit,
3425  * resulting in struct ifreq being 32 and 40 bytes respectively).
3426  * As a result, if the struct happens to be at the end of a page and
3427  * the next page isn't readable/writable, we get a fault. To prevent
3428  * that, copy back and forth to the full size.
3429  */
3430 int get_user_ifreq(struct ifreq *ifr, void __user **ifrdata, void __user *arg)
3431 {
3432 	if (in_compat_syscall()) {
3433 		struct compat_ifreq *ifr32 = (struct compat_ifreq *)ifr;
3434 
3435 		memset(ifr, 0, sizeof(*ifr));
3436 		if (copy_from_user(ifr32, arg, sizeof(*ifr32)))
3437 			return -EFAULT;
3438 
3439 		if (ifrdata)
3440 			*ifrdata = compat_ptr(ifr32->ifr_data);
3441 
3442 		return 0;
3443 	}
3444 
3445 	if (copy_from_user(ifr, arg, sizeof(*ifr)))
3446 		return -EFAULT;
3447 
3448 	if (ifrdata)
3449 		*ifrdata = ifr->ifr_data;
3450 
3451 	return 0;
3452 }
3453 EXPORT_SYMBOL(get_user_ifreq);
3454 
3455 int put_user_ifreq(struct ifreq *ifr, void __user *arg)
3456 {
3457 	size_t size = sizeof(*ifr);
3458 
3459 	if (in_compat_syscall())
3460 		size = sizeof(struct compat_ifreq);
3461 
3462 	if (copy_to_user(arg, ifr, size))
3463 		return -EFAULT;
3464 
3465 	return 0;
3466 }
3467 EXPORT_SYMBOL(put_user_ifreq);
3468 
3469 #ifdef CONFIG_COMPAT
3470 static int compat_siocwandev(struct net *net, struct compat_ifreq __user *uifr32)
3471 {
3472 	compat_uptr_t uptr32;
3473 	struct ifreq ifr;
3474 	void __user *saved;
3475 	int err;
3476 
3477 	if (get_user_ifreq(&ifr, NULL, uifr32))
3478 		return -EFAULT;
3479 
3480 	if (get_user(uptr32, &uifr32->ifr_settings.ifs_ifsu))
3481 		return -EFAULT;
3482 
3483 	saved = ifr.ifr_settings.ifs_ifsu.raw_hdlc;
3484 	ifr.ifr_settings.ifs_ifsu.raw_hdlc = compat_ptr(uptr32);
3485 
3486 	err = dev_ioctl(net, SIOCWANDEV, &ifr, NULL, NULL);
3487 	if (!err) {
3488 		ifr.ifr_settings.ifs_ifsu.raw_hdlc = saved;
3489 		if (put_user_ifreq(&ifr, uifr32))
3490 			err = -EFAULT;
3491 	}
3492 	return err;
3493 }
3494 
3495 /* Handle ioctls that use ifreq::ifr_data and just need struct ifreq converted */
3496 static int compat_ifr_data_ioctl(struct net *net, unsigned int cmd,
3497 				 struct compat_ifreq __user *u_ifreq32)
3498 {
3499 	struct ifreq ifreq;
3500 	void __user *data;
3501 
3502 	if (!is_socket_ioctl_cmd(cmd))
3503 		return -ENOTTY;
3504 	if (get_user_ifreq(&ifreq, &data, u_ifreq32))
3505 		return -EFAULT;
3506 	ifreq.ifr_data = data;
3507 
3508 	return dev_ioctl(net, cmd, &ifreq, data, NULL);
3509 }
3510 
3511 static int compat_sock_ioctl_trans(struct file *file, struct socket *sock,
3512 			 unsigned int cmd, unsigned long arg)
3513 {
3514 	void __user *argp = compat_ptr(arg);
3515 	struct sock *sk = sock->sk;
3516 	struct net *net = sock_net(sk);
3517 	const struct proto_ops *ops;
3518 
3519 	if (cmd >= SIOCDEVPRIVATE && cmd <= (SIOCDEVPRIVATE + 15))
3520 		return sock_ioctl(file, cmd, (unsigned long)argp);
3521 
3522 	switch (cmd) {
3523 	case SIOCWANDEV:
3524 		return compat_siocwandev(net, argp);
3525 	case SIOCGSTAMP_OLD:
3526 	case SIOCGSTAMPNS_OLD:
3527 		ops = READ_ONCE(sock->ops);
3528 		if (!ops->gettstamp)
3529 			return -ENOIOCTLCMD;
3530 		return ops->gettstamp(sock, argp, cmd == SIOCGSTAMP_OLD,
3531 				      !COMPAT_USE_64BIT_TIME);
3532 
3533 	case SIOCETHTOOL:
3534 	case SIOCBONDSLAVEINFOQUERY:
3535 	case SIOCBONDINFOQUERY:
3536 	case SIOCSHWTSTAMP:
3537 	case SIOCGHWTSTAMP:
3538 		return compat_ifr_data_ioctl(net, cmd, argp);
3539 
3540 	case FIOSETOWN:
3541 	case SIOCSPGRP:
3542 	case FIOGETOWN:
3543 	case SIOCGPGRP:
3544 	case SIOCBRADDBR:
3545 	case SIOCBRDELBR:
3546 	case SIOCBRADDIF:
3547 	case SIOCBRDELIF:
3548 	case SIOCGIFVLAN:
3549 	case SIOCSIFVLAN:
3550 	case SIOCGSKNS:
3551 	case SIOCGSTAMP_NEW:
3552 	case SIOCGSTAMPNS_NEW:
3553 	case SIOCGIFCONF:
3554 	case SIOCSIFBR:
3555 	case SIOCGIFBR:
3556 		return sock_ioctl(file, cmd, arg);
3557 
3558 	case SIOCGIFFLAGS:
3559 	case SIOCSIFFLAGS:
3560 	case SIOCGIFMAP:
3561 	case SIOCSIFMAP:
3562 	case SIOCGIFMETRIC:
3563 	case SIOCSIFMETRIC:
3564 	case SIOCGIFMTU:
3565 	case SIOCSIFMTU:
3566 	case SIOCGIFMEM:
3567 	case SIOCSIFMEM:
3568 	case SIOCGIFHWADDR:
3569 	case SIOCSIFHWADDR:
3570 	case SIOCADDMULTI:
3571 	case SIOCDELMULTI:
3572 	case SIOCGIFINDEX:
3573 	case SIOCGIFADDR:
3574 	case SIOCSIFADDR:
3575 	case SIOCSIFHWBROADCAST:
3576 	case SIOCDIFADDR:
3577 	case SIOCGIFBRDADDR:
3578 	case SIOCSIFBRDADDR:
3579 	case SIOCGIFDSTADDR:
3580 	case SIOCSIFDSTADDR:
3581 	case SIOCGIFNETMASK:
3582 	case SIOCSIFNETMASK:
3583 	case SIOCSIFPFLAGS:
3584 	case SIOCGIFPFLAGS:
3585 	case SIOCGIFTXQLEN:
3586 	case SIOCSIFTXQLEN:
3587 	case SIOCGIFNAME:
3588 	case SIOCSIFNAME:
3589 	case SIOCGMIIPHY:
3590 	case SIOCGMIIREG:
3591 	case SIOCSMIIREG:
3592 	case SIOCBONDENSLAVE:
3593 	case SIOCBONDRELEASE:
3594 	case SIOCBONDSETHWADDR:
3595 	case SIOCBONDCHANGEACTIVE:
3596 	case SIOCSARP:
3597 	case SIOCGARP:
3598 	case SIOCDARP:
3599 	case SIOCOUTQ:
3600 	case SIOCOUTQNSD:
3601 	case SIOCATMARK:
3602 		return sock_do_ioctl(net, sock, cmd, arg);
3603 	}
3604 
3605 	return -ENOIOCTLCMD;
3606 }
3607 
3608 static long compat_sock_ioctl(struct file *file, unsigned int cmd,
3609 			      unsigned long arg)
3610 {
3611 	struct socket *sock = file->private_data;
3612 	const struct proto_ops *ops = READ_ONCE(sock->ops);
3613 	int ret = -ENOIOCTLCMD;
3614 	struct sock *sk;
3615 	struct net *net;
3616 
3617 	sk = sock->sk;
3618 	net = sock_net(sk);
3619 
3620 	if (ops->compat_ioctl)
3621 		ret = ops->compat_ioctl(sock, cmd, arg);
3622 
3623 	if (ret == -ENOIOCTLCMD &&
3624 	    (cmd >= SIOCIWFIRST && cmd <= SIOCIWLAST))
3625 		ret = compat_wext_handle_ioctl(net, cmd, arg);
3626 
3627 	if (ret == -ENOIOCTLCMD)
3628 		ret = compat_sock_ioctl_trans(file, sock, cmd, arg);
3629 
3630 	return ret;
3631 }
3632 #endif
3633 
3634 /**
3635  *	kernel_bind - bind an address to a socket (kernel space)
3636  *	@sock: socket
3637  *	@addr: address
3638  *	@addrlen: length of address
3639  *
3640  *	Returns 0 or an error.
3641  */
3642 
3643 int kernel_bind(struct socket *sock, struct sockaddr_unsized *addr, int addrlen)
3644 {
3645 	struct sockaddr_storage address;
3646 
3647 	memcpy(&address, addr, addrlen);
3648 
3649 	return READ_ONCE(sock->ops)->bind(sock, (struct sockaddr_unsized *)&address,
3650 					  addrlen);
3651 }
3652 EXPORT_SYMBOL(kernel_bind);
3653 
3654 /**
3655  *	kernel_listen - move socket to listening state (kernel space)
3656  *	@sock: socket
3657  *	@backlog: pending connections queue size
3658  *
3659  *	Returns 0 or an error.
3660  */
3661 
3662 int kernel_listen(struct socket *sock, int backlog)
3663 {
3664 	return READ_ONCE(sock->ops)->listen(sock, backlog);
3665 }
3666 EXPORT_SYMBOL(kernel_listen);
3667 
3668 /**
3669  *	kernel_accept - accept a connection (kernel space)
3670  *	@sock: listening socket
3671  *	@newsock: new connected socket
3672  *	@flags: flags
3673  *
3674  *	@flags must be SOCK_CLOEXEC, SOCK_NONBLOCK or 0.
3675  *	If it fails, @newsock is guaranteed to be %NULL.
3676  *	Returns 0 or an error.
3677  */
3678 
3679 int kernel_accept(struct socket *sock, struct socket **newsock, int flags)
3680 {
3681 	struct sock *sk = sock->sk;
3682 	const struct proto_ops *ops = READ_ONCE(sock->ops);
3683 	struct proto_accept_arg arg = {
3684 		.flags = flags,
3685 		.kern = true,
3686 	};
3687 	int err;
3688 
3689 	err = sock_create_lite(sk->sk_family, sk->sk_type, sk->sk_protocol,
3690 			       newsock);
3691 	if (err < 0)
3692 		goto done;
3693 
3694 	err = ops->accept(sock, *newsock, &arg);
3695 	if (err < 0) {
3696 		sock_release(*newsock);
3697 		*newsock = NULL;
3698 		goto done;
3699 	}
3700 
3701 	(*newsock)->ops = ops;
3702 	__module_get(ops->owner);
3703 
3704 done:
3705 	return err;
3706 }
3707 EXPORT_SYMBOL(kernel_accept);
3708 
3709 /**
3710  *	kernel_connect - connect a socket (kernel space)
3711  *	@sock: socket
3712  *	@addr: address
3713  *	@addrlen: address length
3714  *	@flags: flags (O_NONBLOCK, ...)
3715  *
3716  *	For datagram sockets, @addr is the address to which datagrams are sent
3717  *	by default, and the only address from which datagrams are received.
3718  *	For stream sockets, attempts to connect to @addr.
3719  *	Returns 0 or an error code.
3720  */
3721 
3722 int kernel_connect(struct socket *sock, struct sockaddr_unsized *addr, int addrlen,
3723 		   int flags)
3724 {
3725 	struct sockaddr_storage address;
3726 
3727 	memcpy(&address, addr, addrlen);
3728 
3729 	return READ_ONCE(sock->ops)->connect(sock, (struct sockaddr_unsized *)&address,
3730 					     addrlen, flags);
3731 }
3732 EXPORT_SYMBOL(kernel_connect);
3733 
3734 /**
3735  *	kernel_getsockname - get the address which the socket is bound (kernel space)
3736  *	@sock: socket
3737  *	@addr: address holder
3738  *
3739  * 	Fills the @addr pointer with the address which the socket is bound.
3740  *	Returns the length of the address in bytes or an error code.
3741  */
3742 
3743 int kernel_getsockname(struct socket *sock, struct sockaddr *addr)
3744 {
3745 	return READ_ONCE(sock->ops)->getname(sock, addr, 0);
3746 }
3747 EXPORT_SYMBOL(kernel_getsockname);
3748 
3749 /**
3750  *	kernel_getpeername - get the address which the socket is connected (kernel space)
3751  *	@sock: socket
3752  *	@addr: address holder
3753  *
3754  * 	Fills the @addr pointer with the address which the socket is connected.
3755  *	Returns the length of the address in bytes or an error code.
3756  */
3757 
3758 int kernel_getpeername(struct socket *sock, struct sockaddr *addr)
3759 {
3760 	return READ_ONCE(sock->ops)->getname(sock, addr, 1);
3761 }
3762 EXPORT_SYMBOL(kernel_getpeername);
3763 
3764 /**
3765  *	kernel_sock_shutdown - shut down part of a full-duplex connection (kernel space)
3766  *	@sock: socket
3767  *	@how: connection part
3768  *
3769  *	Returns 0 or an error.
3770  */
3771 
3772 int kernel_sock_shutdown(struct socket *sock, enum sock_shutdown_cmd how)
3773 {
3774 	return READ_ONCE(sock->ops)->shutdown(sock, how);
3775 }
3776 EXPORT_SYMBOL(kernel_sock_shutdown);
3777 
3778 /**
3779  *	kernel_sock_ip_overhead - returns the IP overhead imposed by a socket
3780  *	@sk: socket
3781  *
3782  *	This routine returns the IP overhead imposed by a socket i.e.
3783  *	the length of the underlying IP header, depending on whether
3784  *	this is an IPv4 or IPv6 socket and the length from IP options turned
3785  *	on at the socket. Assumes that the caller has a lock on the socket.
3786  */
3787 
3788 u32 kernel_sock_ip_overhead(struct sock *sk)
3789 {
3790 	struct inet_sock *inet;
3791 	struct ip_options_rcu *opt;
3792 	u32 overhead = 0;
3793 #if IS_ENABLED(CONFIG_IPV6)
3794 	struct ipv6_pinfo *np;
3795 	struct ipv6_txoptions *optv6 = NULL;
3796 #endif /* IS_ENABLED(CONFIG_IPV6) */
3797 
3798 	if (!sk)
3799 		return overhead;
3800 
3801 	switch (sk->sk_family) {
3802 	case AF_INET:
3803 		inet = inet_sk(sk);
3804 		overhead += sizeof(struct iphdr);
3805 		opt = rcu_dereference_protected(inet->inet_opt,
3806 						sock_owned_by_user(sk));
3807 		if (opt)
3808 			overhead += opt->opt.optlen;
3809 		return overhead;
3810 #if IS_ENABLED(CONFIG_IPV6)
3811 	case AF_INET6:
3812 		np = inet6_sk(sk);
3813 		overhead += sizeof(struct ipv6hdr);
3814 		if (np)
3815 			optv6 = rcu_dereference_protected(np->opt,
3816 							  sock_owned_by_user(sk));
3817 		if (optv6)
3818 			overhead += (optv6->opt_flen + optv6->opt_nflen);
3819 		return overhead;
3820 #endif /* IS_ENABLED(CONFIG_IPV6) */
3821 	default: /* Returns 0 overhead if the socket is not ipv4 or ipv6 */
3822 		return overhead;
3823 	}
3824 }
3825 EXPORT_SYMBOL(kernel_sock_ip_overhead);
3826