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