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