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