af_unix: Pass struct sock to unix_autobind().
[linux-block.git] / net / unix / af_unix.c
1 // SPDX-License-Identifier: GPL-2.0-or-later
2 /*
3  * NET4:        Implementation of BSD Unix domain sockets.
4  *
5  * Authors:     Alan Cox, <alan@lxorguk.ukuu.org.uk>
6  *
7  * Fixes:
8  *              Linus Torvalds  :       Assorted bug cures.
9  *              Niibe Yutaka    :       async I/O support.
10  *              Carsten Paeth   :       PF_UNIX check, address fixes.
11  *              Alan Cox        :       Limit size of allocated blocks.
12  *              Alan Cox        :       Fixed the stupid socketpair bug.
13  *              Alan Cox        :       BSD compatibility fine tuning.
14  *              Alan Cox        :       Fixed a bug in connect when interrupted.
15  *              Alan Cox        :       Sorted out a proper draft version of
16  *                                      file descriptor passing hacked up from
17  *                                      Mike Shaver's work.
18  *              Marty Leisner   :       Fixes to fd passing
19  *              Nick Nevin      :       recvmsg bugfix.
20  *              Alan Cox        :       Started proper garbage collector
21  *              Heiko EiBfeldt  :       Missing verify_area check
22  *              Alan Cox        :       Started POSIXisms
23  *              Andreas Schwab  :       Replace inode by dentry for proper
24  *                                      reference counting
25  *              Kirk Petersen   :       Made this a module
26  *          Christoph Rohland   :       Elegant non-blocking accept/connect algorithm.
27  *                                      Lots of bug fixes.
28  *           Alexey Kuznetosv   :       Repaired (I hope) bugs introduces
29  *                                      by above two patches.
30  *           Andrea Arcangeli   :       If possible we block in connect(2)
31  *                                      if the max backlog of the listen socket
32  *                                      is been reached. This won't break
33  *                                      old apps and it will avoid huge amount
34  *                                      of socks hashed (this for unix_gc()
35  *                                      performances reasons).
36  *                                      Security fix that limits the max
37  *                                      number of socks to 2*max_files and
38  *                                      the number of skb queueable in the
39  *                                      dgram receiver.
40  *              Artur Skawina   :       Hash function optimizations
41  *           Alexey Kuznetsov   :       Full scale SMP. Lot of bugs are introduced 8)
42  *            Malcolm Beattie   :       Set peercred for socketpair
43  *           Michal Ostrowski   :       Module initialization cleanup.
44  *           Arnaldo C. Melo    :       Remove MOD_{INC,DEC}_USE_COUNT,
45  *                                      the core infrastructure is doing that
46  *                                      for all net proto families now (2.5.69+)
47  *
48  * Known differences from reference BSD that was tested:
49  *
50  *      [TO FIX]
51  *      ECONNREFUSED is not returned from one end of a connected() socket to the
52  *              other the moment one end closes.
53  *      fstat() doesn't return st_dev=0, and give the blksize as high water mark
54  *              and a fake inode identifier (nor the BSD first socket fstat twice bug).
55  *      [NOT TO FIX]
56  *      accept() returns a path name even if the connecting socket has closed
57  *              in the meantime (BSD loses the path and gives up).
58  *      accept() returns 0 length path for an unbound connector. BSD returns 16
59  *              and a null first byte in the path (but not for gethost/peername - BSD bug ??)
60  *      socketpair(...SOCK_RAW..) doesn't panic the kernel.
61  *      BSD af_unix apparently has connect forgetting to block properly.
62  *              (need to check this with the POSIX spec in detail)
63  *
64  * Differences from 2.0.0-11-... (ANK)
65  *      Bug fixes and improvements.
66  *              - client shutdown killed server socket.
67  *              - removed all useless cli/sti pairs.
68  *
69  *      Semantic changes/extensions.
70  *              - generic control message passing.
71  *              - SCM_CREDENTIALS control message.
72  *              - "Abstract" (not FS based) socket bindings.
73  *                Abstract names are sequences of bytes (not zero terminated)
74  *                started by 0, so that this name space does not intersect
75  *                with BSD names.
76  */
77
78 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
79
80 #include <linux/module.h>
81 #include <linux/kernel.h>
82 #include <linux/signal.h>
83 #include <linux/sched/signal.h>
84 #include <linux/errno.h>
85 #include <linux/string.h>
86 #include <linux/stat.h>
87 #include <linux/dcache.h>
88 #include <linux/namei.h>
89 #include <linux/socket.h>
90 #include <linux/un.h>
91 #include <linux/fcntl.h>
92 #include <linux/termios.h>
93 #include <linux/sockios.h>
94 #include <linux/net.h>
95 #include <linux/in.h>
96 #include <linux/fs.h>
97 #include <linux/slab.h>
98 #include <linux/uaccess.h>
99 #include <linux/skbuff.h>
100 #include <linux/netdevice.h>
101 #include <net/net_namespace.h>
102 #include <net/sock.h>
103 #include <net/tcp_states.h>
104 #include <net/af_unix.h>
105 #include <linux/proc_fs.h>
106 #include <linux/seq_file.h>
107 #include <net/scm.h>
108 #include <linux/init.h>
109 #include <linux/poll.h>
110 #include <linux/rtnetlink.h>
111 #include <linux/mount.h>
112 #include <net/checksum.h>
113 #include <linux/security.h>
114 #include <linux/freezer.h>
115 #include <linux/file.h>
116 #include <linux/btf_ids.h>
117
118 #include "scm.h"
119
120 struct hlist_head unix_socket_table[2 * UNIX_HASH_SIZE];
121 EXPORT_SYMBOL_GPL(unix_socket_table);
122 DEFINE_SPINLOCK(unix_table_lock);
123 EXPORT_SYMBOL_GPL(unix_table_lock);
124 static atomic_long_t unix_nr_socks;
125
126
127 static struct hlist_head *unix_sockets_unbound(void *addr)
128 {
129         unsigned long hash = (unsigned long)addr;
130
131         hash ^= hash >> 16;
132         hash ^= hash >> 8;
133         hash %= UNIX_HASH_SIZE;
134         return &unix_socket_table[UNIX_HASH_SIZE + hash];
135 }
136
137 #define UNIX_ABSTRACT(sk)       (unix_sk(sk)->addr->hash < UNIX_HASH_SIZE)
138
139 #ifdef CONFIG_SECURITY_NETWORK
140 static void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
141 {
142         UNIXCB(skb).secid = scm->secid;
143 }
144
145 static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
146 {
147         scm->secid = UNIXCB(skb).secid;
148 }
149
150 static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
151 {
152         return (scm->secid == UNIXCB(skb).secid);
153 }
154 #else
155 static inline void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
156 { }
157
158 static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
159 { }
160
161 static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
162 {
163         return true;
164 }
165 #endif /* CONFIG_SECURITY_NETWORK */
166
167 /*
168  *  SMP locking strategy:
169  *    hash table is protected with spinlock unix_table_lock
170  *    each socket state is protected by separate spin lock.
171  */
172
173 static inline unsigned int unix_hash_fold(__wsum n)
174 {
175         unsigned int hash = (__force unsigned int)csum_fold(n);
176
177         hash ^= hash>>8;
178         return hash&(UNIX_HASH_SIZE-1);
179 }
180
181 #define unix_peer(sk) (unix_sk(sk)->peer)
182
183 static inline int unix_our_peer(struct sock *sk, struct sock *osk)
184 {
185         return unix_peer(osk) == sk;
186 }
187
188 static inline int unix_may_send(struct sock *sk, struct sock *osk)
189 {
190         return unix_peer(osk) == NULL || unix_our_peer(sk, osk);
191 }
192
193 static inline int unix_recvq_full(const struct sock *sk)
194 {
195         return skb_queue_len(&sk->sk_receive_queue) > sk->sk_max_ack_backlog;
196 }
197
198 static inline int unix_recvq_full_lockless(const struct sock *sk)
199 {
200         return skb_queue_len_lockless(&sk->sk_receive_queue) >
201                 READ_ONCE(sk->sk_max_ack_backlog);
202 }
203
204 struct sock *unix_peer_get(struct sock *s)
205 {
206         struct sock *peer;
207
208         unix_state_lock(s);
209         peer = unix_peer(s);
210         if (peer)
211                 sock_hold(peer);
212         unix_state_unlock(s);
213         return peer;
214 }
215 EXPORT_SYMBOL_GPL(unix_peer_get);
216
217 static inline void unix_release_addr(struct unix_address *addr)
218 {
219         if (refcount_dec_and_test(&addr->refcnt))
220                 kfree(addr);
221 }
222
223 /*
224  *      Check unix socket name:
225  *              - should be not zero length.
226  *              - if started by not zero, should be NULL terminated (FS object)
227  *              - if started by zero, it is abstract name.
228  */
229
230 static int unix_mkname(struct sockaddr_un *sunaddr, int len, unsigned int *hashp)
231 {
232         *hashp = 0;
233
234         if (len <= offsetof(struct sockaddr_un, sun_path) ||
235             len > sizeof(*sunaddr))
236                 return -EINVAL;
237         if (!sunaddr || sunaddr->sun_family != AF_UNIX)
238                 return -EINVAL;
239         if (sunaddr->sun_path[0]) {
240                 /*
241                  * This may look like an off by one error but it is a bit more
242                  * subtle. 108 is the longest valid AF_UNIX path for a binding.
243                  * sun_path[108] doesn't as such exist.  However in kernel space
244                  * we are guaranteed that it is a valid memory location in our
245                  * kernel address buffer.
246                  */
247                 ((char *)sunaddr)[len] = 0;
248                 len = strlen(sunaddr->sun_path) +
249                         offsetof(struct sockaddr_un, sun_path) + 1;
250                 return len;
251         }
252
253         *hashp = unix_hash_fold(csum_partial(sunaddr, len, 0));
254         return len;
255 }
256
257 static void __unix_remove_socket(struct sock *sk)
258 {
259         sk_del_node_init(sk);
260 }
261
262 static void __unix_insert_socket(struct hlist_head *list, struct sock *sk)
263 {
264         WARN_ON(!sk_unhashed(sk));
265         sk_add_node(sk, list);
266 }
267
268 static void __unix_set_addr(struct sock *sk, struct unix_address *addr,
269                             unsigned hash)
270 {
271         __unix_remove_socket(sk);
272         smp_store_release(&unix_sk(sk)->addr, addr);
273         __unix_insert_socket(&unix_socket_table[hash], sk);
274 }
275
276 static inline void unix_remove_socket(struct sock *sk)
277 {
278         spin_lock(&unix_table_lock);
279         __unix_remove_socket(sk);
280         spin_unlock(&unix_table_lock);
281 }
282
283 static inline void unix_insert_socket(struct hlist_head *list, struct sock *sk)
284 {
285         spin_lock(&unix_table_lock);
286         __unix_insert_socket(list, sk);
287         spin_unlock(&unix_table_lock);
288 }
289
290 static struct sock *__unix_find_socket_byname(struct net *net,
291                                               struct sockaddr_un *sunname,
292                                               int len, unsigned int hash)
293 {
294         struct sock *s;
295
296         sk_for_each(s, &unix_socket_table[hash]) {
297                 struct unix_sock *u = unix_sk(s);
298
299                 if (!net_eq(sock_net(s), net))
300                         continue;
301
302                 if (u->addr->len == len &&
303                     !memcmp(u->addr->name, sunname, len))
304                         return s;
305         }
306         return NULL;
307 }
308
309 static inline struct sock *unix_find_socket_byname(struct net *net,
310                                                    struct sockaddr_un *sunname,
311                                                    int len, unsigned int hash)
312 {
313         struct sock *s;
314
315         spin_lock(&unix_table_lock);
316         s = __unix_find_socket_byname(net, sunname, len, hash);
317         if (s)
318                 sock_hold(s);
319         spin_unlock(&unix_table_lock);
320         return s;
321 }
322
323 static struct sock *unix_find_socket_byinode(struct inode *i)
324 {
325         struct sock *s;
326
327         spin_lock(&unix_table_lock);
328         sk_for_each(s,
329                     &unix_socket_table[i->i_ino & (UNIX_HASH_SIZE - 1)]) {
330                 struct dentry *dentry = unix_sk(s)->path.dentry;
331
332                 if (dentry && d_backing_inode(dentry) == i) {
333                         sock_hold(s);
334                         goto found;
335                 }
336         }
337         s = NULL;
338 found:
339         spin_unlock(&unix_table_lock);
340         return s;
341 }
342
343 /* Support code for asymmetrically connected dgram sockets
344  *
345  * If a datagram socket is connected to a socket not itself connected
346  * to the first socket (eg, /dev/log), clients may only enqueue more
347  * messages if the present receive queue of the server socket is not
348  * "too large". This means there's a second writeability condition
349  * poll and sendmsg need to test. The dgram recv code will do a wake
350  * up on the peer_wait wait queue of a socket upon reception of a
351  * datagram which needs to be propagated to sleeping would-be writers
352  * since these might not have sent anything so far. This can't be
353  * accomplished via poll_wait because the lifetime of the server
354  * socket might be less than that of its clients if these break their
355  * association with it or if the server socket is closed while clients
356  * are still connected to it and there's no way to inform "a polling
357  * implementation" that it should let go of a certain wait queue
358  *
359  * In order to propagate a wake up, a wait_queue_entry_t of the client
360  * socket is enqueued on the peer_wait queue of the server socket
361  * whose wake function does a wake_up on the ordinary client socket
362  * wait queue. This connection is established whenever a write (or
363  * poll for write) hit the flow control condition and broken when the
364  * association to the server socket is dissolved or after a wake up
365  * was relayed.
366  */
367
368 static int unix_dgram_peer_wake_relay(wait_queue_entry_t *q, unsigned mode, int flags,
369                                       void *key)
370 {
371         struct unix_sock *u;
372         wait_queue_head_t *u_sleep;
373
374         u = container_of(q, struct unix_sock, peer_wake);
375
376         __remove_wait_queue(&unix_sk(u->peer_wake.private)->peer_wait,
377                             q);
378         u->peer_wake.private = NULL;
379
380         /* relaying can only happen while the wq still exists */
381         u_sleep = sk_sleep(&u->sk);
382         if (u_sleep)
383                 wake_up_interruptible_poll(u_sleep, key_to_poll(key));
384
385         return 0;
386 }
387
388 static int unix_dgram_peer_wake_connect(struct sock *sk, struct sock *other)
389 {
390         struct unix_sock *u, *u_other;
391         int rc;
392
393         u = unix_sk(sk);
394         u_other = unix_sk(other);
395         rc = 0;
396         spin_lock(&u_other->peer_wait.lock);
397
398         if (!u->peer_wake.private) {
399                 u->peer_wake.private = other;
400                 __add_wait_queue(&u_other->peer_wait, &u->peer_wake);
401
402                 rc = 1;
403         }
404
405         spin_unlock(&u_other->peer_wait.lock);
406         return rc;
407 }
408
409 static void unix_dgram_peer_wake_disconnect(struct sock *sk,
410                                             struct sock *other)
411 {
412         struct unix_sock *u, *u_other;
413
414         u = unix_sk(sk);
415         u_other = unix_sk(other);
416         spin_lock(&u_other->peer_wait.lock);
417
418         if (u->peer_wake.private == other) {
419                 __remove_wait_queue(&u_other->peer_wait, &u->peer_wake);
420                 u->peer_wake.private = NULL;
421         }
422
423         spin_unlock(&u_other->peer_wait.lock);
424 }
425
426 static void unix_dgram_peer_wake_disconnect_wakeup(struct sock *sk,
427                                                    struct sock *other)
428 {
429         unix_dgram_peer_wake_disconnect(sk, other);
430         wake_up_interruptible_poll(sk_sleep(sk),
431                                    EPOLLOUT |
432                                    EPOLLWRNORM |
433                                    EPOLLWRBAND);
434 }
435
436 /* preconditions:
437  *      - unix_peer(sk) == other
438  *      - association is stable
439  */
440 static int unix_dgram_peer_wake_me(struct sock *sk, struct sock *other)
441 {
442         int connected;
443
444         connected = unix_dgram_peer_wake_connect(sk, other);
445
446         /* If other is SOCK_DEAD, we want to make sure we signal
447          * POLLOUT, such that a subsequent write() can get a
448          * -ECONNREFUSED. Otherwise, if we haven't queued any skbs
449          * to other and its full, we will hang waiting for POLLOUT.
450          */
451         if (unix_recvq_full(other) && !sock_flag(other, SOCK_DEAD))
452                 return 1;
453
454         if (connected)
455                 unix_dgram_peer_wake_disconnect(sk, other);
456
457         return 0;
458 }
459
460 static int unix_writable(const struct sock *sk)
461 {
462         return sk->sk_state != TCP_LISTEN &&
463                (refcount_read(&sk->sk_wmem_alloc) << 2) <= sk->sk_sndbuf;
464 }
465
466 static void unix_write_space(struct sock *sk)
467 {
468         struct socket_wq *wq;
469
470         rcu_read_lock();
471         if (unix_writable(sk)) {
472                 wq = rcu_dereference(sk->sk_wq);
473                 if (skwq_has_sleeper(wq))
474                         wake_up_interruptible_sync_poll(&wq->wait,
475                                 EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND);
476                 sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
477         }
478         rcu_read_unlock();
479 }
480
481 /* When dgram socket disconnects (or changes its peer), we clear its receive
482  * queue of packets arrived from previous peer. First, it allows to do
483  * flow control based only on wmem_alloc; second, sk connected to peer
484  * may receive messages only from that peer. */
485 static void unix_dgram_disconnected(struct sock *sk, struct sock *other)
486 {
487         if (!skb_queue_empty(&sk->sk_receive_queue)) {
488                 skb_queue_purge(&sk->sk_receive_queue);
489                 wake_up_interruptible_all(&unix_sk(sk)->peer_wait);
490
491                 /* If one link of bidirectional dgram pipe is disconnected,
492                  * we signal error. Messages are lost. Do not make this,
493                  * when peer was not connected to us.
494                  */
495                 if (!sock_flag(other, SOCK_DEAD) && unix_peer(other) == sk) {
496                         other->sk_err = ECONNRESET;
497                         sk_error_report(other);
498                 }
499         }
500         other->sk_state = TCP_CLOSE;
501 }
502
503 static void unix_sock_destructor(struct sock *sk)
504 {
505         struct unix_sock *u = unix_sk(sk);
506
507         skb_queue_purge(&sk->sk_receive_queue);
508
509 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
510         if (u->oob_skb) {
511                 kfree_skb(u->oob_skb);
512                 u->oob_skb = NULL;
513         }
514 #endif
515         WARN_ON(refcount_read(&sk->sk_wmem_alloc));
516         WARN_ON(!sk_unhashed(sk));
517         WARN_ON(sk->sk_socket);
518         if (!sock_flag(sk, SOCK_DEAD)) {
519                 pr_info("Attempt to release alive unix socket: %p\n", sk);
520                 return;
521         }
522
523         if (u->addr)
524                 unix_release_addr(u->addr);
525
526         atomic_long_dec(&unix_nr_socks);
527         sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
528 #ifdef UNIX_REFCNT_DEBUG
529         pr_debug("UNIX %p is destroyed, %ld are still alive.\n", sk,
530                 atomic_long_read(&unix_nr_socks));
531 #endif
532 }
533
534 static void unix_release_sock(struct sock *sk, int embrion)
535 {
536         struct unix_sock *u = unix_sk(sk);
537         struct path path;
538         struct sock *skpair;
539         struct sk_buff *skb;
540         int state;
541
542         unix_remove_socket(sk);
543
544         /* Clear state */
545         unix_state_lock(sk);
546         sock_orphan(sk);
547         sk->sk_shutdown = SHUTDOWN_MASK;
548         path         = u->path;
549         u->path.dentry = NULL;
550         u->path.mnt = NULL;
551         state = sk->sk_state;
552         sk->sk_state = TCP_CLOSE;
553
554         skpair = unix_peer(sk);
555         unix_peer(sk) = NULL;
556
557         unix_state_unlock(sk);
558
559         wake_up_interruptible_all(&u->peer_wait);
560
561         if (skpair != NULL) {
562                 if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) {
563                         unix_state_lock(skpair);
564                         /* No more writes */
565                         skpair->sk_shutdown = SHUTDOWN_MASK;
566                         if (!skb_queue_empty(&sk->sk_receive_queue) || embrion)
567                                 skpair->sk_err = ECONNRESET;
568                         unix_state_unlock(skpair);
569                         skpair->sk_state_change(skpair);
570                         sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP);
571                 }
572
573                 unix_dgram_peer_wake_disconnect(sk, skpair);
574                 sock_put(skpair); /* It may now die */
575         }
576
577         /* Try to flush out this socket. Throw out buffers at least */
578
579         while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
580                 if (state == TCP_LISTEN)
581                         unix_release_sock(skb->sk, 1);
582                 /* passed fds are erased in the kfree_skb hook        */
583                 UNIXCB(skb).consumed = skb->len;
584                 kfree_skb(skb);
585         }
586
587         if (path.dentry)
588                 path_put(&path);
589
590         sock_put(sk);
591
592         /* ---- Socket is dead now and most probably destroyed ---- */
593
594         /*
595          * Fixme: BSD difference: In BSD all sockets connected to us get
596          *        ECONNRESET and we die on the spot. In Linux we behave
597          *        like files and pipes do and wait for the last
598          *        dereference.
599          *
600          * Can't we simply set sock->err?
601          *
602          *        What the above comment does talk about? --ANK(980817)
603          */
604
605         if (unix_tot_inflight)
606                 unix_gc();              /* Garbage collect fds */
607 }
608
609 static void init_peercred(struct sock *sk)
610 {
611         const struct cred *old_cred;
612         struct pid *old_pid;
613
614         spin_lock(&sk->sk_peer_lock);
615         old_pid = sk->sk_peer_pid;
616         old_cred = sk->sk_peer_cred;
617         sk->sk_peer_pid  = get_pid(task_tgid(current));
618         sk->sk_peer_cred = get_current_cred();
619         spin_unlock(&sk->sk_peer_lock);
620
621         put_pid(old_pid);
622         put_cred(old_cred);
623 }
624
625 static void copy_peercred(struct sock *sk, struct sock *peersk)
626 {
627         const struct cred *old_cred;
628         struct pid *old_pid;
629
630         if (sk < peersk) {
631                 spin_lock(&sk->sk_peer_lock);
632                 spin_lock_nested(&peersk->sk_peer_lock, SINGLE_DEPTH_NESTING);
633         } else {
634                 spin_lock(&peersk->sk_peer_lock);
635                 spin_lock_nested(&sk->sk_peer_lock, SINGLE_DEPTH_NESTING);
636         }
637         old_pid = sk->sk_peer_pid;
638         old_cred = sk->sk_peer_cred;
639         sk->sk_peer_pid  = get_pid(peersk->sk_peer_pid);
640         sk->sk_peer_cred = get_cred(peersk->sk_peer_cred);
641
642         spin_unlock(&sk->sk_peer_lock);
643         spin_unlock(&peersk->sk_peer_lock);
644
645         put_pid(old_pid);
646         put_cred(old_cred);
647 }
648
649 static int unix_listen(struct socket *sock, int backlog)
650 {
651         int err;
652         struct sock *sk = sock->sk;
653         struct unix_sock *u = unix_sk(sk);
654
655         err = -EOPNOTSUPP;
656         if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
657                 goto out;       /* Only stream/seqpacket sockets accept */
658         err = -EINVAL;
659         if (!u->addr)
660                 goto out;       /* No listens on an unbound socket */
661         unix_state_lock(sk);
662         if (sk->sk_state != TCP_CLOSE && sk->sk_state != TCP_LISTEN)
663                 goto out_unlock;
664         if (backlog > sk->sk_max_ack_backlog)
665                 wake_up_interruptible_all(&u->peer_wait);
666         sk->sk_max_ack_backlog  = backlog;
667         sk->sk_state            = TCP_LISTEN;
668         /* set credentials so connect can copy them */
669         init_peercred(sk);
670         err = 0;
671
672 out_unlock:
673         unix_state_unlock(sk);
674 out:
675         return err;
676 }
677
678 static int unix_release(struct socket *);
679 static int unix_bind(struct socket *, struct sockaddr *, int);
680 static int unix_stream_connect(struct socket *, struct sockaddr *,
681                                int addr_len, int flags);
682 static int unix_socketpair(struct socket *, struct socket *);
683 static int unix_accept(struct socket *, struct socket *, int, bool);
684 static int unix_getname(struct socket *, struct sockaddr *, int);
685 static __poll_t unix_poll(struct file *, struct socket *, poll_table *);
686 static __poll_t unix_dgram_poll(struct file *, struct socket *,
687                                     poll_table *);
688 static int unix_ioctl(struct socket *, unsigned int, unsigned long);
689 #ifdef CONFIG_COMPAT
690 static int unix_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg);
691 #endif
692 static int unix_shutdown(struct socket *, int);
693 static int unix_stream_sendmsg(struct socket *, struct msghdr *, size_t);
694 static int unix_stream_recvmsg(struct socket *, struct msghdr *, size_t, int);
695 static ssize_t unix_stream_sendpage(struct socket *, struct page *, int offset,
696                                     size_t size, int flags);
697 static ssize_t unix_stream_splice_read(struct socket *,  loff_t *ppos,
698                                        struct pipe_inode_info *, size_t size,
699                                        unsigned int flags);
700 static int unix_dgram_sendmsg(struct socket *, struct msghdr *, size_t);
701 static int unix_dgram_recvmsg(struct socket *, struct msghdr *, size_t, int);
702 static int unix_read_sock(struct sock *sk, read_descriptor_t *desc,
703                           sk_read_actor_t recv_actor);
704 static int unix_stream_read_sock(struct sock *sk, read_descriptor_t *desc,
705                                  sk_read_actor_t recv_actor);
706 static int unix_dgram_connect(struct socket *, struct sockaddr *,
707                               int, int);
708 static int unix_seqpacket_sendmsg(struct socket *, struct msghdr *, size_t);
709 static int unix_seqpacket_recvmsg(struct socket *, struct msghdr *, size_t,
710                                   int);
711
712 static int unix_set_peek_off(struct sock *sk, int val)
713 {
714         struct unix_sock *u = unix_sk(sk);
715
716         if (mutex_lock_interruptible(&u->iolock))
717                 return -EINTR;
718
719         sk->sk_peek_off = val;
720         mutex_unlock(&u->iolock);
721
722         return 0;
723 }
724
725 #ifdef CONFIG_PROC_FS
726 static void unix_show_fdinfo(struct seq_file *m, struct socket *sock)
727 {
728         struct sock *sk = sock->sk;
729         struct unix_sock *u;
730
731         if (sk) {
732                 u = unix_sk(sock->sk);
733                 seq_printf(m, "scm_fds: %u\n",
734                            atomic_read(&u->scm_stat.nr_fds));
735         }
736 }
737 #else
738 #define unix_show_fdinfo NULL
739 #endif
740
741 static const struct proto_ops unix_stream_ops = {
742         .family =       PF_UNIX,
743         .owner =        THIS_MODULE,
744         .release =      unix_release,
745         .bind =         unix_bind,
746         .connect =      unix_stream_connect,
747         .socketpair =   unix_socketpair,
748         .accept =       unix_accept,
749         .getname =      unix_getname,
750         .poll =         unix_poll,
751         .ioctl =        unix_ioctl,
752 #ifdef CONFIG_COMPAT
753         .compat_ioctl = unix_compat_ioctl,
754 #endif
755         .listen =       unix_listen,
756         .shutdown =     unix_shutdown,
757         .sendmsg =      unix_stream_sendmsg,
758         .recvmsg =      unix_stream_recvmsg,
759         .read_sock =    unix_stream_read_sock,
760         .mmap =         sock_no_mmap,
761         .sendpage =     unix_stream_sendpage,
762         .splice_read =  unix_stream_splice_read,
763         .set_peek_off = unix_set_peek_off,
764         .show_fdinfo =  unix_show_fdinfo,
765 };
766
767 static const struct proto_ops unix_dgram_ops = {
768         .family =       PF_UNIX,
769         .owner =        THIS_MODULE,
770         .release =      unix_release,
771         .bind =         unix_bind,
772         .connect =      unix_dgram_connect,
773         .socketpair =   unix_socketpair,
774         .accept =       sock_no_accept,
775         .getname =      unix_getname,
776         .poll =         unix_dgram_poll,
777         .ioctl =        unix_ioctl,
778 #ifdef CONFIG_COMPAT
779         .compat_ioctl = unix_compat_ioctl,
780 #endif
781         .listen =       sock_no_listen,
782         .shutdown =     unix_shutdown,
783         .sendmsg =      unix_dgram_sendmsg,
784         .read_sock =    unix_read_sock,
785         .recvmsg =      unix_dgram_recvmsg,
786         .mmap =         sock_no_mmap,
787         .sendpage =     sock_no_sendpage,
788         .set_peek_off = unix_set_peek_off,
789         .show_fdinfo =  unix_show_fdinfo,
790 };
791
792 static const struct proto_ops unix_seqpacket_ops = {
793         .family =       PF_UNIX,
794         .owner =        THIS_MODULE,
795         .release =      unix_release,
796         .bind =         unix_bind,
797         .connect =      unix_stream_connect,
798         .socketpair =   unix_socketpair,
799         .accept =       unix_accept,
800         .getname =      unix_getname,
801         .poll =         unix_dgram_poll,
802         .ioctl =        unix_ioctl,
803 #ifdef CONFIG_COMPAT
804         .compat_ioctl = unix_compat_ioctl,
805 #endif
806         .listen =       unix_listen,
807         .shutdown =     unix_shutdown,
808         .sendmsg =      unix_seqpacket_sendmsg,
809         .recvmsg =      unix_seqpacket_recvmsg,
810         .mmap =         sock_no_mmap,
811         .sendpage =     sock_no_sendpage,
812         .set_peek_off = unix_set_peek_off,
813         .show_fdinfo =  unix_show_fdinfo,
814 };
815
816 static void unix_close(struct sock *sk, long timeout)
817 {
818         /* Nothing to do here, unix socket does not need a ->close().
819          * This is merely for sockmap.
820          */
821 }
822
823 static void unix_unhash(struct sock *sk)
824 {
825         /* Nothing to do here, unix socket does not need a ->unhash().
826          * This is merely for sockmap.
827          */
828 }
829
830 struct proto unix_dgram_proto = {
831         .name                   = "UNIX",
832         .owner                  = THIS_MODULE,
833         .obj_size               = sizeof(struct unix_sock),
834         .close                  = unix_close,
835 #ifdef CONFIG_BPF_SYSCALL
836         .psock_update_sk_prot   = unix_dgram_bpf_update_proto,
837 #endif
838 };
839
840 struct proto unix_stream_proto = {
841         .name                   = "UNIX-STREAM",
842         .owner                  = THIS_MODULE,
843         .obj_size               = sizeof(struct unix_sock),
844         .close                  = unix_close,
845         .unhash                 = unix_unhash,
846 #ifdef CONFIG_BPF_SYSCALL
847         .psock_update_sk_prot   = unix_stream_bpf_update_proto,
848 #endif
849 };
850
851 static struct sock *unix_create1(struct net *net, struct socket *sock, int kern, int type)
852 {
853         struct unix_sock *u;
854         struct sock *sk;
855         int err;
856
857         atomic_long_inc(&unix_nr_socks);
858         if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files()) {
859                 err = -ENFILE;
860                 goto err;
861         }
862
863         if (type == SOCK_STREAM)
864                 sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_stream_proto, kern);
865         else /*dgram and  seqpacket */
866                 sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_dgram_proto, kern);
867
868         if (!sk) {
869                 err = -ENOMEM;
870                 goto err;
871         }
872
873         sock_init_data(sock, sk);
874
875         sk->sk_allocation       = GFP_KERNEL_ACCOUNT;
876         sk->sk_write_space      = unix_write_space;
877         sk->sk_max_ack_backlog  = net->unx.sysctl_max_dgram_qlen;
878         sk->sk_destruct         = unix_sock_destructor;
879         u         = unix_sk(sk);
880         u->path.dentry = NULL;
881         u->path.mnt = NULL;
882         spin_lock_init(&u->lock);
883         atomic_long_set(&u->inflight, 0);
884         INIT_LIST_HEAD(&u->link);
885         mutex_init(&u->iolock); /* single task reading lock */
886         mutex_init(&u->bindlock); /* single task binding lock */
887         init_waitqueue_head(&u->peer_wait);
888         init_waitqueue_func_entry(&u->peer_wake, unix_dgram_peer_wake_relay);
889         memset(&u->scm_stat, 0, sizeof(struct scm_stat));
890         unix_insert_socket(unix_sockets_unbound(sk), sk);
891
892         sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
893
894         return sk;
895
896 err:
897         atomic_long_dec(&unix_nr_socks);
898         return ERR_PTR(err);
899 }
900
901 static int unix_create(struct net *net, struct socket *sock, int protocol,
902                        int kern)
903 {
904         struct sock *sk;
905
906         if (protocol && protocol != PF_UNIX)
907                 return -EPROTONOSUPPORT;
908
909         sock->state = SS_UNCONNECTED;
910
911         switch (sock->type) {
912         case SOCK_STREAM:
913                 sock->ops = &unix_stream_ops;
914                 break;
915                 /*
916                  *      Believe it or not BSD has AF_UNIX, SOCK_RAW though
917                  *      nothing uses it.
918                  */
919         case SOCK_RAW:
920                 sock->type = SOCK_DGRAM;
921                 fallthrough;
922         case SOCK_DGRAM:
923                 sock->ops = &unix_dgram_ops;
924                 break;
925         case SOCK_SEQPACKET:
926                 sock->ops = &unix_seqpacket_ops;
927                 break;
928         default:
929                 return -ESOCKTNOSUPPORT;
930         }
931
932         sk = unix_create1(net, sock, kern, sock->type);
933         if (IS_ERR(sk))
934                 return PTR_ERR(sk);
935
936         return 0;
937 }
938
939 static int unix_release(struct socket *sock)
940 {
941         struct sock *sk = sock->sk;
942
943         if (!sk)
944                 return 0;
945
946         sk->sk_prot->close(sk, 0);
947         unix_release_sock(sk, 0);
948         sock->sk = NULL;
949
950         return 0;
951 }
952
953 static int unix_autobind(struct sock *sk)
954 {
955         struct unix_sock *u = unix_sk(sk);
956         struct unix_address *addr;
957         unsigned int retries = 0;
958         static u32 ordernum = 1;
959         int err;
960
961         err = mutex_lock_interruptible(&u->bindlock);
962         if (err)
963                 return err;
964
965         if (u->addr)
966                 goto out;
967
968         err = -ENOMEM;
969         addr = kzalloc(sizeof(*addr) +
970                        offsetof(struct sockaddr_un, sun_path) + 16, GFP_KERNEL);
971         if (!addr)
972                 goto out;
973
974         addr->name->sun_family = AF_UNIX;
975         refcount_set(&addr->refcnt, 1);
976
977 retry:
978         addr->len = sprintf(addr->name->sun_path + 1, "%05x", ordernum) +
979                 offsetof(struct sockaddr_un, sun_path) + 1;
980         addr->hash = unix_hash_fold(csum_partial(addr->name, addr->len, 0));
981         addr->hash ^= sk->sk_type;
982
983         spin_lock(&unix_table_lock);
984         ordernum = (ordernum+1)&0xFFFFF;
985
986         if (__unix_find_socket_byname(sock_net(sk), addr->name, addr->len,
987                                       addr->hash)) {
988                 spin_unlock(&unix_table_lock);
989                 /*
990                  * __unix_find_socket_byname() may take long time if many names
991                  * are already in use.
992                  */
993                 cond_resched();
994                 /* Give up if all names seems to be in use. */
995                 if (retries++ == 0xFFFFF) {
996                         err = -ENOSPC;
997                         kfree(addr);
998                         goto out;
999                 }
1000                 goto retry;
1001         }
1002
1003         __unix_set_addr(sk, addr, addr->hash);
1004         spin_unlock(&unix_table_lock);
1005         err = 0;
1006
1007 out:    mutex_unlock(&u->bindlock);
1008         return err;
1009 }
1010
1011 static struct sock *unix_find_other(struct net *net,
1012                                     struct sockaddr_un *sunname, int len,
1013                                     int type, unsigned int hash, int *error)
1014 {
1015         struct sock *u;
1016         struct path path;
1017         int err = 0;
1018
1019         if (sunname->sun_path[0]) {
1020                 struct inode *inode;
1021                 err = kern_path(sunname->sun_path, LOOKUP_FOLLOW, &path);
1022                 if (err)
1023                         goto fail;
1024                 inode = d_backing_inode(path.dentry);
1025                 err = path_permission(&path, MAY_WRITE);
1026                 if (err)
1027                         goto put_fail;
1028
1029                 err = -ECONNREFUSED;
1030                 if (!S_ISSOCK(inode->i_mode))
1031                         goto put_fail;
1032                 u = unix_find_socket_byinode(inode);
1033                 if (!u)
1034                         goto put_fail;
1035
1036                 if (u->sk_type == type)
1037                         touch_atime(&path);
1038
1039                 path_put(&path);
1040
1041                 err = -EPROTOTYPE;
1042                 if (u->sk_type != type) {
1043                         sock_put(u);
1044                         goto fail;
1045                 }
1046         } else {
1047                 err = -ECONNREFUSED;
1048                 u = unix_find_socket_byname(net, sunname, len, type ^ hash);
1049                 if (u) {
1050                         struct dentry *dentry;
1051                         dentry = unix_sk(u)->path.dentry;
1052                         if (dentry)
1053                                 touch_atime(&unix_sk(u)->path);
1054                 } else
1055                         goto fail;
1056         }
1057         return u;
1058
1059 put_fail:
1060         path_put(&path);
1061 fail:
1062         *error = err;
1063         return NULL;
1064 }
1065
1066 static int unix_bind_bsd(struct sock *sk, struct unix_address *addr)
1067 {
1068         struct unix_sock *u = unix_sk(sk);
1069         umode_t mode = S_IFSOCK |
1070                (SOCK_INODE(sk->sk_socket)->i_mode & ~current_umask());
1071         struct user_namespace *ns; // barf...
1072         struct path parent;
1073         struct dentry *dentry;
1074         unsigned int hash;
1075         int err;
1076
1077         /*
1078          * Get the parent directory, calculate the hash for last
1079          * component.
1080          */
1081         dentry = kern_path_create(AT_FDCWD, addr->name->sun_path, &parent, 0);
1082         if (IS_ERR(dentry))
1083                 return PTR_ERR(dentry);
1084         ns = mnt_user_ns(parent.mnt);
1085
1086         /*
1087          * All right, let's create it.
1088          */
1089         err = security_path_mknod(&parent, dentry, mode, 0);
1090         if (!err)
1091                 err = vfs_mknod(ns, d_inode(parent.dentry), dentry, mode, 0);
1092         if (err)
1093                 goto out;
1094         err = mutex_lock_interruptible(&u->bindlock);
1095         if (err)
1096                 goto out_unlink;
1097         if (u->addr)
1098                 goto out_unlock;
1099
1100         addr->hash = UNIX_HASH_SIZE;
1101         hash = d_backing_inode(dentry)->i_ino & (UNIX_HASH_SIZE - 1);
1102         spin_lock(&unix_table_lock);
1103         u->path.mnt = mntget(parent.mnt);
1104         u->path.dentry = dget(dentry);
1105         __unix_set_addr(sk, addr, hash);
1106         spin_unlock(&unix_table_lock);
1107         mutex_unlock(&u->bindlock);
1108         done_path_create(&parent, dentry);
1109         return 0;
1110
1111 out_unlock:
1112         mutex_unlock(&u->bindlock);
1113         err = -EINVAL;
1114 out_unlink:
1115         /* failed after successful mknod?  unlink what we'd created... */
1116         vfs_unlink(ns, d_inode(parent.dentry), dentry, NULL);
1117 out:
1118         done_path_create(&parent, dentry);
1119         return err;
1120 }
1121
1122 static int unix_bind_abstract(struct sock *sk, struct unix_address *addr)
1123 {
1124         struct unix_sock *u = unix_sk(sk);
1125         int err;
1126
1127         err = mutex_lock_interruptible(&u->bindlock);
1128         if (err)
1129                 return err;
1130
1131         if (u->addr) {
1132                 mutex_unlock(&u->bindlock);
1133                 return -EINVAL;
1134         }
1135
1136         spin_lock(&unix_table_lock);
1137         if (__unix_find_socket_byname(sock_net(sk), addr->name, addr->len,
1138                                       addr->hash)) {
1139                 spin_unlock(&unix_table_lock);
1140                 mutex_unlock(&u->bindlock);
1141                 return -EADDRINUSE;
1142         }
1143         __unix_set_addr(sk, addr, addr->hash);
1144         spin_unlock(&unix_table_lock);
1145         mutex_unlock(&u->bindlock);
1146         return 0;
1147 }
1148
1149 static int unix_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
1150 {
1151         struct sock *sk = sock->sk;
1152         struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
1153         char *sun_path = sunaddr->sun_path;
1154         int err;
1155         unsigned int hash;
1156         struct unix_address *addr;
1157
1158         if (addr_len < offsetofend(struct sockaddr_un, sun_family) ||
1159             sunaddr->sun_family != AF_UNIX)
1160                 return -EINVAL;
1161
1162         if (addr_len == offsetof(struct sockaddr_un, sun_path))
1163                 return unix_autobind(sk);
1164
1165         err = unix_mkname(sunaddr, addr_len, &hash);
1166         if (err < 0)
1167                 return err;
1168         addr_len = err;
1169         addr = kmalloc(sizeof(*addr)+addr_len, GFP_KERNEL);
1170         if (!addr)
1171                 return -ENOMEM;
1172
1173         memcpy(addr->name, sunaddr, addr_len);
1174         addr->len = addr_len;
1175         addr->hash = hash ^ sk->sk_type;
1176         refcount_set(&addr->refcnt, 1);
1177
1178         if (sun_path[0])
1179                 err = unix_bind_bsd(sk, addr);
1180         else
1181                 err = unix_bind_abstract(sk, addr);
1182         if (err)
1183                 unix_release_addr(addr);
1184         return err == -EEXIST ? -EADDRINUSE : err;
1185 }
1186
1187 static void unix_state_double_lock(struct sock *sk1, struct sock *sk2)
1188 {
1189         if (unlikely(sk1 == sk2) || !sk2) {
1190                 unix_state_lock(sk1);
1191                 return;
1192         }
1193         if (sk1 < sk2) {
1194                 unix_state_lock(sk1);
1195                 unix_state_lock_nested(sk2);
1196         } else {
1197                 unix_state_lock(sk2);
1198                 unix_state_lock_nested(sk1);
1199         }
1200 }
1201
1202 static void unix_state_double_unlock(struct sock *sk1, struct sock *sk2)
1203 {
1204         if (unlikely(sk1 == sk2) || !sk2) {
1205                 unix_state_unlock(sk1);
1206                 return;
1207         }
1208         unix_state_unlock(sk1);
1209         unix_state_unlock(sk2);
1210 }
1211
1212 static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
1213                               int alen, int flags)
1214 {
1215         struct sock *sk = sock->sk;
1216         struct net *net = sock_net(sk);
1217         struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
1218         struct sock *other;
1219         unsigned int hash;
1220         int err;
1221
1222         err = -EINVAL;
1223         if (alen < offsetofend(struct sockaddr, sa_family))
1224                 goto out;
1225
1226         if (addr->sa_family != AF_UNSPEC) {
1227                 err = unix_mkname(sunaddr, alen, &hash);
1228                 if (err < 0)
1229                         goto out;
1230                 alen = err;
1231
1232                 if (test_bit(SOCK_PASSCRED, &sock->flags) &&
1233                     !unix_sk(sk)->addr) {
1234                         err = unix_autobind(sk);
1235                         if (err)
1236                                 goto out;
1237                 }
1238
1239 restart:
1240                 other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
1241                 if (!other)
1242                         goto out;
1243
1244                 unix_state_double_lock(sk, other);
1245
1246                 /* Apparently VFS overslept socket death. Retry. */
1247                 if (sock_flag(other, SOCK_DEAD)) {
1248                         unix_state_double_unlock(sk, other);
1249                         sock_put(other);
1250                         goto restart;
1251                 }
1252
1253                 err = -EPERM;
1254                 if (!unix_may_send(sk, other))
1255                         goto out_unlock;
1256
1257                 err = security_unix_may_send(sk->sk_socket, other->sk_socket);
1258                 if (err)
1259                         goto out_unlock;
1260
1261                 sk->sk_state = other->sk_state = TCP_ESTABLISHED;
1262         } else {
1263                 /*
1264                  *      1003.1g breaking connected state with AF_UNSPEC
1265                  */
1266                 other = NULL;
1267                 unix_state_double_lock(sk, other);
1268         }
1269
1270         /*
1271          * If it was connected, reconnect.
1272          */
1273         if (unix_peer(sk)) {
1274                 struct sock *old_peer = unix_peer(sk);
1275
1276                 unix_peer(sk) = other;
1277                 if (!other)
1278                         sk->sk_state = TCP_CLOSE;
1279                 unix_dgram_peer_wake_disconnect_wakeup(sk, old_peer);
1280
1281                 unix_state_double_unlock(sk, other);
1282
1283                 if (other != old_peer)
1284                         unix_dgram_disconnected(sk, old_peer);
1285                 sock_put(old_peer);
1286         } else {
1287                 unix_peer(sk) = other;
1288                 unix_state_double_unlock(sk, other);
1289         }
1290
1291         return 0;
1292
1293 out_unlock:
1294         unix_state_double_unlock(sk, other);
1295         sock_put(other);
1296 out:
1297         return err;
1298 }
1299
1300 static long unix_wait_for_peer(struct sock *other, long timeo)
1301         __releases(&unix_sk(other)->lock)
1302 {
1303         struct unix_sock *u = unix_sk(other);
1304         int sched;
1305         DEFINE_WAIT(wait);
1306
1307         prepare_to_wait_exclusive(&u->peer_wait, &wait, TASK_INTERRUPTIBLE);
1308
1309         sched = !sock_flag(other, SOCK_DEAD) &&
1310                 !(other->sk_shutdown & RCV_SHUTDOWN) &&
1311                 unix_recvq_full(other);
1312
1313         unix_state_unlock(other);
1314
1315         if (sched)
1316                 timeo = schedule_timeout(timeo);
1317
1318         finish_wait(&u->peer_wait, &wait);
1319         return timeo;
1320 }
1321
1322 static int unix_stream_connect(struct socket *sock, struct sockaddr *uaddr,
1323                                int addr_len, int flags)
1324 {
1325         struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
1326         struct sock *sk = sock->sk;
1327         struct net *net = sock_net(sk);
1328         struct unix_sock *u = unix_sk(sk), *newu, *otheru;
1329         struct sock *newsk = NULL;
1330         struct sock *other = NULL;
1331         struct sk_buff *skb = NULL;
1332         unsigned int hash;
1333         int st;
1334         int err;
1335         long timeo;
1336
1337         err = unix_mkname(sunaddr, addr_len, &hash);
1338         if (err < 0)
1339                 goto out;
1340         addr_len = err;
1341
1342         if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr) {
1343                 err = unix_autobind(sk);
1344                 if (err)
1345                         goto out;
1346         }
1347
1348         timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
1349
1350         /* First of all allocate resources.
1351            If we will make it after state is locked,
1352            we will have to recheck all again in any case.
1353          */
1354
1355         /* create new sock for complete connection */
1356         newsk = unix_create1(sock_net(sk), NULL, 0, sock->type);
1357         if (IS_ERR(newsk)) {
1358                 err = PTR_ERR(newsk);
1359                 newsk = NULL;
1360                 goto out;
1361         }
1362
1363         err = -ENOMEM;
1364
1365         /* Allocate skb for sending to listening sock */
1366         skb = sock_wmalloc(newsk, 1, 0, GFP_KERNEL);
1367         if (skb == NULL)
1368                 goto out;
1369
1370 restart:
1371         /*  Find listening sock. */
1372         other = unix_find_other(net, sunaddr, addr_len, sk->sk_type, hash, &err);
1373         if (!other)
1374                 goto out;
1375
1376         /* Latch state of peer */
1377         unix_state_lock(other);
1378
1379         /* Apparently VFS overslept socket death. Retry. */
1380         if (sock_flag(other, SOCK_DEAD)) {
1381                 unix_state_unlock(other);
1382                 sock_put(other);
1383                 goto restart;
1384         }
1385
1386         err = -ECONNREFUSED;
1387         if (other->sk_state != TCP_LISTEN)
1388                 goto out_unlock;
1389         if (other->sk_shutdown & RCV_SHUTDOWN)
1390                 goto out_unlock;
1391
1392         if (unix_recvq_full(other)) {
1393                 err = -EAGAIN;
1394                 if (!timeo)
1395                         goto out_unlock;
1396
1397                 timeo = unix_wait_for_peer(other, timeo);
1398
1399                 err = sock_intr_errno(timeo);
1400                 if (signal_pending(current))
1401                         goto out;
1402                 sock_put(other);
1403                 goto restart;
1404         }
1405
1406         /* Latch our state.
1407
1408            It is tricky place. We need to grab our state lock and cannot
1409            drop lock on peer. It is dangerous because deadlock is
1410            possible. Connect to self case and simultaneous
1411            attempt to connect are eliminated by checking socket
1412            state. other is TCP_LISTEN, if sk is TCP_LISTEN we
1413            check this before attempt to grab lock.
1414
1415            Well, and we have to recheck the state after socket locked.
1416          */
1417         st = sk->sk_state;
1418
1419         switch (st) {
1420         case TCP_CLOSE:
1421                 /* This is ok... continue with connect */
1422                 break;
1423         case TCP_ESTABLISHED:
1424                 /* Socket is already connected */
1425                 err = -EISCONN;
1426                 goto out_unlock;
1427         default:
1428                 err = -EINVAL;
1429                 goto out_unlock;
1430         }
1431
1432         unix_state_lock_nested(sk);
1433
1434         if (sk->sk_state != st) {
1435                 unix_state_unlock(sk);
1436                 unix_state_unlock(other);
1437                 sock_put(other);
1438                 goto restart;
1439         }
1440
1441         err = security_unix_stream_connect(sk, other, newsk);
1442         if (err) {
1443                 unix_state_unlock(sk);
1444                 goto out_unlock;
1445         }
1446
1447         /* The way is open! Fastly set all the necessary fields... */
1448
1449         sock_hold(sk);
1450         unix_peer(newsk)        = sk;
1451         newsk->sk_state         = TCP_ESTABLISHED;
1452         newsk->sk_type          = sk->sk_type;
1453         init_peercred(newsk);
1454         newu = unix_sk(newsk);
1455         RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq);
1456         otheru = unix_sk(other);
1457
1458         /* copy address information from listening to new sock
1459          *
1460          * The contents of *(otheru->addr) and otheru->path
1461          * are seen fully set up here, since we have found
1462          * otheru in hash under unix_table_lock.  Insertion
1463          * into the hash chain we'd found it in had been done
1464          * in an earlier critical area protected by unix_table_lock,
1465          * the same one where we'd set *(otheru->addr) contents,
1466          * as well as otheru->path and otheru->addr itself.
1467          *
1468          * Using smp_store_release() here to set newu->addr
1469          * is enough to make those stores, as well as stores
1470          * to newu->path visible to anyone who gets newu->addr
1471          * by smp_load_acquire().  IOW, the same warranties
1472          * as for unix_sock instances bound in unix_bind() or
1473          * in unix_autobind().
1474          */
1475         if (otheru->path.dentry) {
1476                 path_get(&otheru->path);
1477                 newu->path = otheru->path;
1478         }
1479         refcount_inc(&otheru->addr->refcnt);
1480         smp_store_release(&newu->addr, otheru->addr);
1481
1482         /* Set credentials */
1483         copy_peercred(sk, other);
1484
1485         sock->state     = SS_CONNECTED;
1486         sk->sk_state    = TCP_ESTABLISHED;
1487         sock_hold(newsk);
1488
1489         smp_mb__after_atomic(); /* sock_hold() does an atomic_inc() */
1490         unix_peer(sk)   = newsk;
1491
1492         unix_state_unlock(sk);
1493
1494         /* take ten and send info to listening sock */
1495         spin_lock(&other->sk_receive_queue.lock);
1496         __skb_queue_tail(&other->sk_receive_queue, skb);
1497         spin_unlock(&other->sk_receive_queue.lock);
1498         unix_state_unlock(other);
1499         other->sk_data_ready(other);
1500         sock_put(other);
1501         return 0;
1502
1503 out_unlock:
1504         if (other)
1505                 unix_state_unlock(other);
1506
1507 out:
1508         kfree_skb(skb);
1509         if (newsk)
1510                 unix_release_sock(newsk, 0);
1511         if (other)
1512                 sock_put(other);
1513         return err;
1514 }
1515
1516 static int unix_socketpair(struct socket *socka, struct socket *sockb)
1517 {
1518         struct sock *ska = socka->sk, *skb = sockb->sk;
1519
1520         /* Join our sockets back to back */
1521         sock_hold(ska);
1522         sock_hold(skb);
1523         unix_peer(ska) = skb;
1524         unix_peer(skb) = ska;
1525         init_peercred(ska);
1526         init_peercred(skb);
1527
1528         ska->sk_state = TCP_ESTABLISHED;
1529         skb->sk_state = TCP_ESTABLISHED;
1530         socka->state  = SS_CONNECTED;
1531         sockb->state  = SS_CONNECTED;
1532         return 0;
1533 }
1534
1535 static void unix_sock_inherit_flags(const struct socket *old,
1536                                     struct socket *new)
1537 {
1538         if (test_bit(SOCK_PASSCRED, &old->flags))
1539                 set_bit(SOCK_PASSCRED, &new->flags);
1540         if (test_bit(SOCK_PASSSEC, &old->flags))
1541                 set_bit(SOCK_PASSSEC, &new->flags);
1542 }
1543
1544 static int unix_accept(struct socket *sock, struct socket *newsock, int flags,
1545                        bool kern)
1546 {
1547         struct sock *sk = sock->sk;
1548         struct sock *tsk;
1549         struct sk_buff *skb;
1550         int err;
1551
1552         err = -EOPNOTSUPP;
1553         if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
1554                 goto out;
1555
1556         err = -EINVAL;
1557         if (sk->sk_state != TCP_LISTEN)
1558                 goto out;
1559
1560         /* If socket state is TCP_LISTEN it cannot change (for now...),
1561          * so that no locks are necessary.
1562          */
1563
1564         skb = skb_recv_datagram(sk, 0, flags&O_NONBLOCK, &err);
1565         if (!skb) {
1566                 /* This means receive shutdown. */
1567                 if (err == 0)
1568                         err = -EINVAL;
1569                 goto out;
1570         }
1571
1572         tsk = skb->sk;
1573         skb_free_datagram(sk, skb);
1574         wake_up_interruptible(&unix_sk(sk)->peer_wait);
1575
1576         /* attach accepted sock to socket */
1577         unix_state_lock(tsk);
1578         newsock->state = SS_CONNECTED;
1579         unix_sock_inherit_flags(sock, newsock);
1580         sock_graft(tsk, newsock);
1581         unix_state_unlock(tsk);
1582         return 0;
1583
1584 out:
1585         return err;
1586 }
1587
1588
1589 static int unix_getname(struct socket *sock, struct sockaddr *uaddr, int peer)
1590 {
1591         struct sock *sk = sock->sk;
1592         struct unix_address *addr;
1593         DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, uaddr);
1594         int err = 0;
1595
1596         if (peer) {
1597                 sk = unix_peer_get(sk);
1598
1599                 err = -ENOTCONN;
1600                 if (!sk)
1601                         goto out;
1602                 err = 0;
1603         } else {
1604                 sock_hold(sk);
1605         }
1606
1607         addr = smp_load_acquire(&unix_sk(sk)->addr);
1608         if (!addr) {
1609                 sunaddr->sun_family = AF_UNIX;
1610                 sunaddr->sun_path[0] = 0;
1611                 err = offsetof(struct sockaddr_un, sun_path);
1612         } else {
1613                 err = addr->len;
1614                 memcpy(sunaddr, addr->name, addr->len);
1615         }
1616         sock_put(sk);
1617 out:
1618         return err;
1619 }
1620
1621 static void unix_peek_fds(struct scm_cookie *scm, struct sk_buff *skb)
1622 {
1623         scm->fp = scm_fp_dup(UNIXCB(skb).fp);
1624
1625         /*
1626          * Garbage collection of unix sockets starts by selecting a set of
1627          * candidate sockets which have reference only from being in flight
1628          * (total_refs == inflight_refs).  This condition is checked once during
1629          * the candidate collection phase, and candidates are marked as such, so
1630          * that non-candidates can later be ignored.  While inflight_refs is
1631          * protected by unix_gc_lock, total_refs (file count) is not, hence this
1632          * is an instantaneous decision.
1633          *
1634          * Once a candidate, however, the socket must not be reinstalled into a
1635          * file descriptor while the garbage collection is in progress.
1636          *
1637          * If the above conditions are met, then the directed graph of
1638          * candidates (*) does not change while unix_gc_lock is held.
1639          *
1640          * Any operations that changes the file count through file descriptors
1641          * (dup, close, sendmsg) does not change the graph since candidates are
1642          * not installed in fds.
1643          *
1644          * Dequeing a candidate via recvmsg would install it into an fd, but
1645          * that takes unix_gc_lock to decrement the inflight count, so it's
1646          * serialized with garbage collection.
1647          *
1648          * MSG_PEEK is special in that it does not change the inflight count,
1649          * yet does install the socket into an fd.  The following lock/unlock
1650          * pair is to ensure serialization with garbage collection.  It must be
1651          * done between incrementing the file count and installing the file into
1652          * an fd.
1653          *
1654          * If garbage collection starts after the barrier provided by the
1655          * lock/unlock, then it will see the elevated refcount and not mark this
1656          * as a candidate.  If a garbage collection is already in progress
1657          * before the file count was incremented, then the lock/unlock pair will
1658          * ensure that garbage collection is finished before progressing to
1659          * installing the fd.
1660          *
1661          * (*) A -> B where B is on the queue of A or B is on the queue of C
1662          * which is on the queue of listening socket A.
1663          */
1664         spin_lock(&unix_gc_lock);
1665         spin_unlock(&unix_gc_lock);
1666 }
1667
1668 static int unix_scm_to_skb(struct scm_cookie *scm, struct sk_buff *skb, bool send_fds)
1669 {
1670         int err = 0;
1671
1672         UNIXCB(skb).pid  = get_pid(scm->pid);
1673         UNIXCB(skb).uid = scm->creds.uid;
1674         UNIXCB(skb).gid = scm->creds.gid;
1675         UNIXCB(skb).fp = NULL;
1676         unix_get_secdata(scm, skb);
1677         if (scm->fp && send_fds)
1678                 err = unix_attach_fds(scm, skb);
1679
1680         skb->destructor = unix_destruct_scm;
1681         return err;
1682 }
1683
1684 static bool unix_passcred_enabled(const struct socket *sock,
1685                                   const struct sock *other)
1686 {
1687         return test_bit(SOCK_PASSCRED, &sock->flags) ||
1688                !other->sk_socket ||
1689                test_bit(SOCK_PASSCRED, &other->sk_socket->flags);
1690 }
1691
1692 /*
1693  * Some apps rely on write() giving SCM_CREDENTIALS
1694  * We include credentials if source or destination socket
1695  * asserted SOCK_PASSCRED.
1696  */
1697 static void maybe_add_creds(struct sk_buff *skb, const struct socket *sock,
1698                             const struct sock *other)
1699 {
1700         if (UNIXCB(skb).pid)
1701                 return;
1702         if (unix_passcred_enabled(sock, other)) {
1703                 UNIXCB(skb).pid  = get_pid(task_tgid(current));
1704                 current_uid_gid(&UNIXCB(skb).uid, &UNIXCB(skb).gid);
1705         }
1706 }
1707
1708 static int maybe_init_creds(struct scm_cookie *scm,
1709                             struct socket *socket,
1710                             const struct sock *other)
1711 {
1712         int err;
1713         struct msghdr msg = { .msg_controllen = 0 };
1714
1715         err = scm_send(socket, &msg, scm, false);
1716         if (err)
1717                 return err;
1718
1719         if (unix_passcred_enabled(socket, other)) {
1720                 scm->pid = get_pid(task_tgid(current));
1721                 current_uid_gid(&scm->creds.uid, &scm->creds.gid);
1722         }
1723         return err;
1724 }
1725
1726 static bool unix_skb_scm_eq(struct sk_buff *skb,
1727                             struct scm_cookie *scm)
1728 {
1729         const struct unix_skb_parms *u = &UNIXCB(skb);
1730
1731         return u->pid == scm->pid &&
1732                uid_eq(u->uid, scm->creds.uid) &&
1733                gid_eq(u->gid, scm->creds.gid) &&
1734                unix_secdata_eq(scm, skb);
1735 }
1736
1737 static void scm_stat_add(struct sock *sk, struct sk_buff *skb)
1738 {
1739         struct scm_fp_list *fp = UNIXCB(skb).fp;
1740         struct unix_sock *u = unix_sk(sk);
1741
1742         if (unlikely(fp && fp->count))
1743                 atomic_add(fp->count, &u->scm_stat.nr_fds);
1744 }
1745
1746 static void scm_stat_del(struct sock *sk, struct sk_buff *skb)
1747 {
1748         struct scm_fp_list *fp = UNIXCB(skb).fp;
1749         struct unix_sock *u = unix_sk(sk);
1750
1751         if (unlikely(fp && fp->count))
1752                 atomic_sub(fp->count, &u->scm_stat.nr_fds);
1753 }
1754
1755 /*
1756  *      Send AF_UNIX data.
1757  */
1758
1759 static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
1760                               size_t len)
1761 {
1762         struct sock *sk = sock->sk;
1763         struct net *net = sock_net(sk);
1764         struct unix_sock *u = unix_sk(sk);
1765         DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name);
1766         struct sock *other = NULL;
1767         int namelen = 0; /* fake GCC */
1768         int err;
1769         unsigned int hash;
1770         struct sk_buff *skb;
1771         long timeo;
1772         struct scm_cookie scm;
1773         int data_len = 0;
1774         int sk_locked;
1775
1776         wait_for_unix_gc();
1777         err = scm_send(sock, msg, &scm, false);
1778         if (err < 0)
1779                 return err;
1780
1781         err = -EOPNOTSUPP;
1782         if (msg->msg_flags&MSG_OOB)
1783                 goto out;
1784
1785         if (msg->msg_namelen) {
1786                 err = unix_mkname(sunaddr, msg->msg_namelen, &hash);
1787                 if (err < 0)
1788                         goto out;
1789                 namelen = err;
1790         } else {
1791                 sunaddr = NULL;
1792                 err = -ENOTCONN;
1793                 other = unix_peer_get(sk);
1794                 if (!other)
1795                         goto out;
1796         }
1797
1798         if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr) {
1799                 err = unix_autobind(sk);
1800                 if (err)
1801                         goto out;
1802         }
1803
1804         err = -EMSGSIZE;
1805         if (len > sk->sk_sndbuf - 32)
1806                 goto out;
1807
1808         if (len > SKB_MAX_ALLOC) {
1809                 data_len = min_t(size_t,
1810                                  len - SKB_MAX_ALLOC,
1811                                  MAX_SKB_FRAGS * PAGE_SIZE);
1812                 data_len = PAGE_ALIGN(data_len);
1813
1814                 BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
1815         }
1816
1817         skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
1818                                    msg->msg_flags & MSG_DONTWAIT, &err,
1819                                    PAGE_ALLOC_COSTLY_ORDER);
1820         if (skb == NULL)
1821                 goto out;
1822
1823         err = unix_scm_to_skb(&scm, skb, true);
1824         if (err < 0)
1825                 goto out_free;
1826
1827         skb_put(skb, len - data_len);
1828         skb->data_len = data_len;
1829         skb->len = len;
1830         err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len);
1831         if (err)
1832                 goto out_free;
1833
1834         timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1835
1836 restart:
1837         if (!other) {
1838                 err = -ECONNRESET;
1839                 if (sunaddr == NULL)
1840                         goto out_free;
1841
1842                 other = unix_find_other(net, sunaddr, namelen, sk->sk_type,
1843                                         hash, &err);
1844                 if (other == NULL)
1845                         goto out_free;
1846         }
1847
1848         if (sk_filter(other, skb) < 0) {
1849                 /* Toss the packet but do not return any error to the sender */
1850                 err = len;
1851                 goto out_free;
1852         }
1853
1854         sk_locked = 0;
1855         unix_state_lock(other);
1856 restart_locked:
1857         err = -EPERM;
1858         if (!unix_may_send(sk, other))
1859                 goto out_unlock;
1860
1861         if (unlikely(sock_flag(other, SOCK_DEAD))) {
1862                 /*
1863                  *      Check with 1003.1g - what should
1864                  *      datagram error
1865                  */
1866                 unix_state_unlock(other);
1867                 sock_put(other);
1868
1869                 if (!sk_locked)
1870                         unix_state_lock(sk);
1871
1872                 err = 0;
1873                 if (unix_peer(sk) == other) {
1874                         unix_peer(sk) = NULL;
1875                         unix_dgram_peer_wake_disconnect_wakeup(sk, other);
1876
1877                         unix_state_unlock(sk);
1878
1879                         sk->sk_state = TCP_CLOSE;
1880                         unix_dgram_disconnected(sk, other);
1881                         sock_put(other);
1882                         err = -ECONNREFUSED;
1883                 } else {
1884                         unix_state_unlock(sk);
1885                 }
1886
1887                 other = NULL;
1888                 if (err)
1889                         goto out_free;
1890                 goto restart;
1891         }
1892
1893         err = -EPIPE;
1894         if (other->sk_shutdown & RCV_SHUTDOWN)
1895                 goto out_unlock;
1896
1897         if (sk->sk_type != SOCK_SEQPACKET) {
1898                 err = security_unix_may_send(sk->sk_socket, other->sk_socket);
1899                 if (err)
1900                         goto out_unlock;
1901         }
1902
1903         /* other == sk && unix_peer(other) != sk if
1904          * - unix_peer(sk) == NULL, destination address bound to sk
1905          * - unix_peer(sk) == sk by time of get but disconnected before lock
1906          */
1907         if (other != sk &&
1908             unlikely(unix_peer(other) != sk &&
1909             unix_recvq_full_lockless(other))) {
1910                 if (timeo) {
1911                         timeo = unix_wait_for_peer(other, timeo);
1912
1913                         err = sock_intr_errno(timeo);
1914                         if (signal_pending(current))
1915                                 goto out_free;
1916
1917                         goto restart;
1918                 }
1919
1920                 if (!sk_locked) {
1921                         unix_state_unlock(other);
1922                         unix_state_double_lock(sk, other);
1923                 }
1924
1925                 if (unix_peer(sk) != other ||
1926                     unix_dgram_peer_wake_me(sk, other)) {
1927                         err = -EAGAIN;
1928                         sk_locked = 1;
1929                         goto out_unlock;
1930                 }
1931
1932                 if (!sk_locked) {
1933                         sk_locked = 1;
1934                         goto restart_locked;
1935                 }
1936         }
1937
1938         if (unlikely(sk_locked))
1939                 unix_state_unlock(sk);
1940
1941         if (sock_flag(other, SOCK_RCVTSTAMP))
1942                 __net_timestamp(skb);
1943         maybe_add_creds(skb, sock, other);
1944         scm_stat_add(other, skb);
1945         skb_queue_tail(&other->sk_receive_queue, skb);
1946         unix_state_unlock(other);
1947         other->sk_data_ready(other);
1948         sock_put(other);
1949         scm_destroy(&scm);
1950         return len;
1951
1952 out_unlock:
1953         if (sk_locked)
1954                 unix_state_unlock(sk);
1955         unix_state_unlock(other);
1956 out_free:
1957         kfree_skb(skb);
1958 out:
1959         if (other)
1960                 sock_put(other);
1961         scm_destroy(&scm);
1962         return err;
1963 }
1964
1965 /* We use paged skbs for stream sockets, and limit occupancy to 32768
1966  * bytes, and a minimum of a full page.
1967  */
1968 #define UNIX_SKB_FRAGS_SZ (PAGE_SIZE << get_order(32768))
1969
1970 #if (IS_ENABLED(CONFIG_AF_UNIX_OOB))
1971 static int queue_oob(struct socket *sock, struct msghdr *msg, struct sock *other)
1972 {
1973         struct unix_sock *ousk = unix_sk(other);
1974         struct sk_buff *skb;
1975         int err = 0;
1976
1977         skb = sock_alloc_send_skb(sock->sk, 1, msg->msg_flags & MSG_DONTWAIT, &err);
1978
1979         if (!skb)
1980                 return err;
1981
1982         skb_put(skb, 1);
1983         err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, 1);
1984
1985         if (err) {
1986                 kfree_skb(skb);
1987                 return err;
1988         }
1989
1990         unix_state_lock(other);
1991
1992         if (sock_flag(other, SOCK_DEAD) ||
1993             (other->sk_shutdown & RCV_SHUTDOWN)) {
1994                 unix_state_unlock(other);
1995                 kfree_skb(skb);
1996                 return -EPIPE;
1997         }
1998
1999         maybe_add_creds(skb, sock, other);
2000         skb_get(skb);
2001
2002         if (ousk->oob_skb)
2003                 consume_skb(ousk->oob_skb);
2004
2005         ousk->oob_skb = skb;
2006
2007         scm_stat_add(other, skb);
2008         skb_queue_tail(&other->sk_receive_queue, skb);
2009         sk_send_sigurg(other);
2010         unix_state_unlock(other);
2011         other->sk_data_ready(other);
2012
2013         return err;
2014 }
2015 #endif
2016
2017 static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
2018                                size_t len)
2019 {
2020         struct sock *sk = sock->sk;
2021         struct sock *other = NULL;
2022         int err, size;
2023         struct sk_buff *skb;
2024         int sent = 0;
2025         struct scm_cookie scm;
2026         bool fds_sent = false;
2027         int data_len;
2028
2029         wait_for_unix_gc();
2030         err = scm_send(sock, msg, &scm, false);
2031         if (err < 0)
2032                 return err;
2033
2034         err = -EOPNOTSUPP;
2035         if (msg->msg_flags & MSG_OOB) {
2036 #if (IS_ENABLED(CONFIG_AF_UNIX_OOB))
2037                 if (len)
2038                         len--;
2039                 else
2040 #endif
2041                         goto out_err;
2042         }
2043
2044         if (msg->msg_namelen) {
2045                 err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
2046                 goto out_err;
2047         } else {
2048                 err = -ENOTCONN;
2049                 other = unix_peer(sk);
2050                 if (!other)
2051                         goto out_err;
2052         }
2053
2054         if (sk->sk_shutdown & SEND_SHUTDOWN)
2055                 goto pipe_err;
2056
2057         while (sent < len) {
2058                 size = len - sent;
2059
2060                 /* Keep two messages in the pipe so it schedules better */
2061                 size = min_t(int, size, (sk->sk_sndbuf >> 1) - 64);
2062
2063                 /* allow fallback to order-0 allocations */
2064                 size = min_t(int, size, SKB_MAX_HEAD(0) + UNIX_SKB_FRAGS_SZ);
2065
2066                 data_len = max_t(int, 0, size - SKB_MAX_HEAD(0));
2067
2068                 data_len = min_t(size_t, size, PAGE_ALIGN(data_len));
2069
2070                 skb = sock_alloc_send_pskb(sk, size - data_len, data_len,
2071                                            msg->msg_flags & MSG_DONTWAIT, &err,
2072                                            get_order(UNIX_SKB_FRAGS_SZ));
2073                 if (!skb)
2074                         goto out_err;
2075
2076                 /* Only send the fds in the first buffer */
2077                 err = unix_scm_to_skb(&scm, skb, !fds_sent);
2078                 if (err < 0) {
2079                         kfree_skb(skb);
2080                         goto out_err;
2081                 }
2082                 fds_sent = true;
2083
2084                 skb_put(skb, size - data_len);
2085                 skb->data_len = data_len;
2086                 skb->len = size;
2087                 err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
2088                 if (err) {
2089                         kfree_skb(skb);
2090                         goto out_err;
2091                 }
2092
2093                 unix_state_lock(other);
2094
2095                 if (sock_flag(other, SOCK_DEAD) ||
2096                     (other->sk_shutdown & RCV_SHUTDOWN))
2097                         goto pipe_err_free;
2098
2099                 maybe_add_creds(skb, sock, other);
2100                 scm_stat_add(other, skb);
2101                 skb_queue_tail(&other->sk_receive_queue, skb);
2102                 unix_state_unlock(other);
2103                 other->sk_data_ready(other);
2104                 sent += size;
2105         }
2106
2107 #if (IS_ENABLED(CONFIG_AF_UNIX_OOB))
2108         if (msg->msg_flags & MSG_OOB) {
2109                 err = queue_oob(sock, msg, other);
2110                 if (err)
2111                         goto out_err;
2112                 sent++;
2113         }
2114 #endif
2115
2116         scm_destroy(&scm);
2117
2118         return sent;
2119
2120 pipe_err_free:
2121         unix_state_unlock(other);
2122         kfree_skb(skb);
2123 pipe_err:
2124         if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
2125                 send_sig(SIGPIPE, current, 0);
2126         err = -EPIPE;
2127 out_err:
2128         scm_destroy(&scm);
2129         return sent ? : err;
2130 }
2131
2132 static ssize_t unix_stream_sendpage(struct socket *socket, struct page *page,
2133                                     int offset, size_t size, int flags)
2134 {
2135         int err;
2136         bool send_sigpipe = false;
2137         bool init_scm = true;
2138         struct scm_cookie scm;
2139         struct sock *other, *sk = socket->sk;
2140         struct sk_buff *skb, *newskb = NULL, *tail = NULL;
2141
2142         if (flags & MSG_OOB)
2143                 return -EOPNOTSUPP;
2144
2145         other = unix_peer(sk);
2146         if (!other || sk->sk_state != TCP_ESTABLISHED)
2147                 return -ENOTCONN;
2148
2149         if (false) {
2150 alloc_skb:
2151                 unix_state_unlock(other);
2152                 mutex_unlock(&unix_sk(other)->iolock);
2153                 newskb = sock_alloc_send_pskb(sk, 0, 0, flags & MSG_DONTWAIT,
2154                                               &err, 0);
2155                 if (!newskb)
2156                         goto err;
2157         }
2158
2159         /* we must acquire iolock as we modify already present
2160          * skbs in the sk_receive_queue and mess with skb->len
2161          */
2162         err = mutex_lock_interruptible(&unix_sk(other)->iolock);
2163         if (err) {
2164                 err = flags & MSG_DONTWAIT ? -EAGAIN : -ERESTARTSYS;
2165                 goto err;
2166         }
2167
2168         if (sk->sk_shutdown & SEND_SHUTDOWN) {
2169                 err = -EPIPE;
2170                 send_sigpipe = true;
2171                 goto err_unlock;
2172         }
2173
2174         unix_state_lock(other);
2175
2176         if (sock_flag(other, SOCK_DEAD) ||
2177             other->sk_shutdown & RCV_SHUTDOWN) {
2178                 err = -EPIPE;
2179                 send_sigpipe = true;
2180                 goto err_state_unlock;
2181         }
2182
2183         if (init_scm) {
2184                 err = maybe_init_creds(&scm, socket, other);
2185                 if (err)
2186                         goto err_state_unlock;
2187                 init_scm = false;
2188         }
2189
2190         skb = skb_peek_tail(&other->sk_receive_queue);
2191         if (tail && tail == skb) {
2192                 skb = newskb;
2193         } else if (!skb || !unix_skb_scm_eq(skb, &scm)) {
2194                 if (newskb) {
2195                         skb = newskb;
2196                 } else {
2197                         tail = skb;
2198                         goto alloc_skb;
2199                 }
2200         } else if (newskb) {
2201                 /* this is fast path, we don't necessarily need to
2202                  * call to kfree_skb even though with newskb == NULL
2203                  * this - does no harm
2204                  */
2205                 consume_skb(newskb);
2206                 newskb = NULL;
2207         }
2208
2209         if (skb_append_pagefrags(skb, page, offset, size)) {
2210                 tail = skb;
2211                 goto alloc_skb;
2212         }
2213
2214         skb->len += size;
2215         skb->data_len += size;
2216         skb->truesize += size;
2217         refcount_add(size, &sk->sk_wmem_alloc);
2218
2219         if (newskb) {
2220                 err = unix_scm_to_skb(&scm, skb, false);
2221                 if (err)
2222                         goto err_state_unlock;
2223                 spin_lock(&other->sk_receive_queue.lock);
2224                 __skb_queue_tail(&other->sk_receive_queue, newskb);
2225                 spin_unlock(&other->sk_receive_queue.lock);
2226         }
2227
2228         unix_state_unlock(other);
2229         mutex_unlock(&unix_sk(other)->iolock);
2230
2231         other->sk_data_ready(other);
2232         scm_destroy(&scm);
2233         return size;
2234
2235 err_state_unlock:
2236         unix_state_unlock(other);
2237 err_unlock:
2238         mutex_unlock(&unix_sk(other)->iolock);
2239 err:
2240         kfree_skb(newskb);
2241         if (send_sigpipe && !(flags & MSG_NOSIGNAL))
2242                 send_sig(SIGPIPE, current, 0);
2243         if (!init_scm)
2244                 scm_destroy(&scm);
2245         return err;
2246 }
2247
2248 static int unix_seqpacket_sendmsg(struct socket *sock, struct msghdr *msg,
2249                                   size_t len)
2250 {
2251         int err;
2252         struct sock *sk = sock->sk;
2253
2254         err = sock_error(sk);
2255         if (err)
2256                 return err;
2257
2258         if (sk->sk_state != TCP_ESTABLISHED)
2259                 return -ENOTCONN;
2260
2261         if (msg->msg_namelen)
2262                 msg->msg_namelen = 0;
2263
2264         return unix_dgram_sendmsg(sock, msg, len);
2265 }
2266
2267 static int unix_seqpacket_recvmsg(struct socket *sock, struct msghdr *msg,
2268                                   size_t size, int flags)
2269 {
2270         struct sock *sk = sock->sk;
2271
2272         if (sk->sk_state != TCP_ESTABLISHED)
2273                 return -ENOTCONN;
2274
2275         return unix_dgram_recvmsg(sock, msg, size, flags);
2276 }
2277
2278 static void unix_copy_addr(struct msghdr *msg, struct sock *sk)
2279 {
2280         struct unix_address *addr = smp_load_acquire(&unix_sk(sk)->addr);
2281
2282         if (addr) {
2283                 msg->msg_namelen = addr->len;
2284                 memcpy(msg->msg_name, addr->name, addr->len);
2285         }
2286 }
2287
2288 int __unix_dgram_recvmsg(struct sock *sk, struct msghdr *msg, size_t size,
2289                          int flags)
2290 {
2291         struct scm_cookie scm;
2292         struct socket *sock = sk->sk_socket;
2293         struct unix_sock *u = unix_sk(sk);
2294         struct sk_buff *skb, *last;
2295         long timeo;
2296         int skip;
2297         int err;
2298
2299         err = -EOPNOTSUPP;
2300         if (flags&MSG_OOB)
2301                 goto out;
2302
2303         timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2304
2305         do {
2306                 mutex_lock(&u->iolock);
2307
2308                 skip = sk_peek_offset(sk, flags);
2309                 skb = __skb_try_recv_datagram(sk, &sk->sk_receive_queue, flags,
2310                                               &skip, &err, &last);
2311                 if (skb) {
2312                         if (!(flags & MSG_PEEK))
2313                                 scm_stat_del(sk, skb);
2314                         break;
2315                 }
2316
2317                 mutex_unlock(&u->iolock);
2318
2319                 if (err != -EAGAIN)
2320                         break;
2321         } while (timeo &&
2322                  !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
2323                                               &err, &timeo, last));
2324
2325         if (!skb) { /* implies iolock unlocked */
2326                 unix_state_lock(sk);
2327                 /* Signal EOF on disconnected non-blocking SEQPACKET socket. */
2328                 if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&
2329                     (sk->sk_shutdown & RCV_SHUTDOWN))
2330                         err = 0;
2331                 unix_state_unlock(sk);
2332                 goto out;
2333         }
2334
2335         if (wq_has_sleeper(&u->peer_wait))
2336                 wake_up_interruptible_sync_poll(&u->peer_wait,
2337                                                 EPOLLOUT | EPOLLWRNORM |
2338                                                 EPOLLWRBAND);
2339
2340         if (msg->msg_name)
2341                 unix_copy_addr(msg, skb->sk);
2342
2343         if (size > skb->len - skip)
2344                 size = skb->len - skip;
2345         else if (size < skb->len - skip)
2346                 msg->msg_flags |= MSG_TRUNC;
2347
2348         err = skb_copy_datagram_msg(skb, skip, msg, size);
2349         if (err)
2350                 goto out_free;
2351
2352         if (sock_flag(sk, SOCK_RCVTSTAMP))
2353                 __sock_recv_timestamp(msg, sk, skb);
2354
2355         memset(&scm, 0, sizeof(scm));
2356
2357         scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
2358         unix_set_secdata(&scm, skb);
2359
2360         if (!(flags & MSG_PEEK)) {
2361                 if (UNIXCB(skb).fp)
2362                         unix_detach_fds(&scm, skb);
2363
2364                 sk_peek_offset_bwd(sk, skb->len);
2365         } else {
2366                 /* It is questionable: on PEEK we could:
2367                    - do not return fds - good, but too simple 8)
2368                    - return fds, and do not return them on read (old strategy,
2369                      apparently wrong)
2370                    - clone fds (I chose it for now, it is the most universal
2371                      solution)
2372
2373                    POSIX 1003.1g does not actually define this clearly
2374                    at all. POSIX 1003.1g doesn't define a lot of things
2375                    clearly however!
2376
2377                 */
2378
2379                 sk_peek_offset_fwd(sk, size);
2380
2381                 if (UNIXCB(skb).fp)
2382                         unix_peek_fds(&scm, skb);
2383         }
2384         err = (flags & MSG_TRUNC) ? skb->len - skip : size;
2385
2386         scm_recv(sock, msg, &scm, flags);
2387
2388 out_free:
2389         skb_free_datagram(sk, skb);
2390         mutex_unlock(&u->iolock);
2391 out:
2392         return err;
2393 }
2394
2395 static int unix_dgram_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
2396                               int flags)
2397 {
2398         struct sock *sk = sock->sk;
2399
2400 #ifdef CONFIG_BPF_SYSCALL
2401         const struct proto *prot = READ_ONCE(sk->sk_prot);
2402
2403         if (prot != &unix_dgram_proto)
2404                 return prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
2405                                             flags & ~MSG_DONTWAIT, NULL);
2406 #endif
2407         return __unix_dgram_recvmsg(sk, msg, size, flags);
2408 }
2409
2410 static int unix_read_sock(struct sock *sk, read_descriptor_t *desc,
2411                           sk_read_actor_t recv_actor)
2412 {
2413         int copied = 0;
2414
2415         while (1) {
2416                 struct unix_sock *u = unix_sk(sk);
2417                 struct sk_buff *skb;
2418                 int used, err;
2419
2420                 mutex_lock(&u->iolock);
2421                 skb = skb_recv_datagram(sk, 0, 1, &err);
2422                 mutex_unlock(&u->iolock);
2423                 if (!skb)
2424                         return err;
2425
2426                 used = recv_actor(desc, skb, 0, skb->len);
2427                 if (used <= 0) {
2428                         if (!copied)
2429                                 copied = used;
2430                         kfree_skb(skb);
2431                         break;
2432                 } else if (used <= skb->len) {
2433                         copied += used;
2434                 }
2435
2436                 kfree_skb(skb);
2437                 if (!desc->count)
2438                         break;
2439         }
2440
2441         return copied;
2442 }
2443
2444 /*
2445  *      Sleep until more data has arrived. But check for races..
2446  */
2447 static long unix_stream_data_wait(struct sock *sk, long timeo,
2448                                   struct sk_buff *last, unsigned int last_len,
2449                                   bool freezable)
2450 {
2451         struct sk_buff *tail;
2452         DEFINE_WAIT(wait);
2453
2454         unix_state_lock(sk);
2455
2456         for (;;) {
2457                 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
2458
2459                 tail = skb_peek_tail(&sk->sk_receive_queue);
2460                 if (tail != last ||
2461                     (tail && tail->len != last_len) ||
2462                     sk->sk_err ||
2463                     (sk->sk_shutdown & RCV_SHUTDOWN) ||
2464                     signal_pending(current) ||
2465                     !timeo)
2466                         break;
2467
2468                 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
2469                 unix_state_unlock(sk);
2470                 if (freezable)
2471                         timeo = freezable_schedule_timeout(timeo);
2472                 else
2473                         timeo = schedule_timeout(timeo);
2474                 unix_state_lock(sk);
2475
2476                 if (sock_flag(sk, SOCK_DEAD))
2477                         break;
2478
2479                 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
2480         }
2481
2482         finish_wait(sk_sleep(sk), &wait);
2483         unix_state_unlock(sk);
2484         return timeo;
2485 }
2486
2487 static unsigned int unix_skb_len(const struct sk_buff *skb)
2488 {
2489         return skb->len - UNIXCB(skb).consumed;
2490 }
2491
2492 struct unix_stream_read_state {
2493         int (*recv_actor)(struct sk_buff *, int, int,
2494                           struct unix_stream_read_state *);
2495         struct socket *socket;
2496         struct msghdr *msg;
2497         struct pipe_inode_info *pipe;
2498         size_t size;
2499         int flags;
2500         unsigned int splice_flags;
2501 };
2502
2503 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2504 static int unix_stream_recv_urg(struct unix_stream_read_state *state)
2505 {
2506         struct socket *sock = state->socket;
2507         struct sock *sk = sock->sk;
2508         struct unix_sock *u = unix_sk(sk);
2509         int chunk = 1;
2510         struct sk_buff *oob_skb;
2511
2512         mutex_lock(&u->iolock);
2513         unix_state_lock(sk);
2514
2515         if (sock_flag(sk, SOCK_URGINLINE) || !u->oob_skb) {
2516                 unix_state_unlock(sk);
2517                 mutex_unlock(&u->iolock);
2518                 return -EINVAL;
2519         }
2520
2521         oob_skb = u->oob_skb;
2522
2523         if (!(state->flags & MSG_PEEK)) {
2524                 u->oob_skb = NULL;
2525         }
2526
2527         unix_state_unlock(sk);
2528
2529         chunk = state->recv_actor(oob_skb, 0, chunk, state);
2530
2531         if (!(state->flags & MSG_PEEK)) {
2532                 UNIXCB(oob_skb).consumed += 1;
2533                 kfree_skb(oob_skb);
2534         }
2535
2536         mutex_unlock(&u->iolock);
2537
2538         if (chunk < 0)
2539                 return -EFAULT;
2540
2541         state->msg->msg_flags |= MSG_OOB;
2542         return 1;
2543 }
2544
2545 static struct sk_buff *manage_oob(struct sk_buff *skb, struct sock *sk,
2546                                   int flags, int copied)
2547 {
2548         struct unix_sock *u = unix_sk(sk);
2549
2550         if (!unix_skb_len(skb) && !(flags & MSG_PEEK)) {
2551                 skb_unlink(skb, &sk->sk_receive_queue);
2552                 consume_skb(skb);
2553                 skb = NULL;
2554         } else {
2555                 if (skb == u->oob_skb) {
2556                         if (copied) {
2557                                 skb = NULL;
2558                         } else if (sock_flag(sk, SOCK_URGINLINE)) {
2559                                 if (!(flags & MSG_PEEK)) {
2560                                         u->oob_skb = NULL;
2561                                         consume_skb(skb);
2562                                 }
2563                         } else if (!(flags & MSG_PEEK)) {
2564                                 skb_unlink(skb, &sk->sk_receive_queue);
2565                                 consume_skb(skb);
2566                                 skb = skb_peek(&sk->sk_receive_queue);
2567                         }
2568                 }
2569         }
2570         return skb;
2571 }
2572 #endif
2573
2574 static int unix_stream_read_sock(struct sock *sk, read_descriptor_t *desc,
2575                                  sk_read_actor_t recv_actor)
2576 {
2577         if (unlikely(sk->sk_state != TCP_ESTABLISHED))
2578                 return -ENOTCONN;
2579
2580         return unix_read_sock(sk, desc, recv_actor);
2581 }
2582
2583 static int unix_stream_read_generic(struct unix_stream_read_state *state,
2584                                     bool freezable)
2585 {
2586         struct scm_cookie scm;
2587         struct socket *sock = state->socket;
2588         struct sock *sk = sock->sk;
2589         struct unix_sock *u = unix_sk(sk);
2590         int copied = 0;
2591         int flags = state->flags;
2592         int noblock = flags & MSG_DONTWAIT;
2593         bool check_creds = false;
2594         int target;
2595         int err = 0;
2596         long timeo;
2597         int skip;
2598         size_t size = state->size;
2599         unsigned int last_len;
2600
2601         if (unlikely(sk->sk_state != TCP_ESTABLISHED)) {
2602                 err = -EINVAL;
2603                 goto out;
2604         }
2605
2606         if (unlikely(flags & MSG_OOB)) {
2607                 err = -EOPNOTSUPP;
2608 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2609                 err = unix_stream_recv_urg(state);
2610 #endif
2611                 goto out;
2612         }
2613
2614         target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
2615         timeo = sock_rcvtimeo(sk, noblock);
2616
2617         memset(&scm, 0, sizeof(scm));
2618
2619         /* Lock the socket to prevent queue disordering
2620          * while sleeps in memcpy_tomsg
2621          */
2622         mutex_lock(&u->iolock);
2623
2624         skip = max(sk_peek_offset(sk, flags), 0);
2625
2626         do {
2627                 int chunk;
2628                 bool drop_skb;
2629                 struct sk_buff *skb, *last;
2630
2631 redo:
2632                 unix_state_lock(sk);
2633                 if (sock_flag(sk, SOCK_DEAD)) {
2634                         err = -ECONNRESET;
2635                         goto unlock;
2636                 }
2637                 last = skb = skb_peek(&sk->sk_receive_queue);
2638                 last_len = last ? last->len : 0;
2639
2640 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2641                 if (skb) {
2642                         skb = manage_oob(skb, sk, flags, copied);
2643                         if (!skb) {
2644                                 unix_state_unlock(sk);
2645                                 if (copied)
2646                                         break;
2647                                 goto redo;
2648                         }
2649                 }
2650 #endif
2651 again:
2652                 if (skb == NULL) {
2653                         if (copied >= target)
2654                                 goto unlock;
2655
2656                         /*
2657                          *      POSIX 1003.1g mandates this order.
2658                          */
2659
2660                         err = sock_error(sk);
2661                         if (err)
2662                                 goto unlock;
2663                         if (sk->sk_shutdown & RCV_SHUTDOWN)
2664                                 goto unlock;
2665
2666                         unix_state_unlock(sk);
2667                         if (!timeo) {
2668                                 err = -EAGAIN;
2669                                 break;
2670                         }
2671
2672                         mutex_unlock(&u->iolock);
2673
2674                         timeo = unix_stream_data_wait(sk, timeo, last,
2675                                                       last_len, freezable);
2676
2677                         if (signal_pending(current)) {
2678                                 err = sock_intr_errno(timeo);
2679                                 scm_destroy(&scm);
2680                                 goto out;
2681                         }
2682
2683                         mutex_lock(&u->iolock);
2684                         goto redo;
2685 unlock:
2686                         unix_state_unlock(sk);
2687                         break;
2688                 }
2689
2690                 while (skip >= unix_skb_len(skb)) {
2691                         skip -= unix_skb_len(skb);
2692                         last = skb;
2693                         last_len = skb->len;
2694                         skb = skb_peek_next(skb, &sk->sk_receive_queue);
2695                         if (!skb)
2696                                 goto again;
2697                 }
2698
2699                 unix_state_unlock(sk);
2700
2701                 if (check_creds) {
2702                         /* Never glue messages from different writers */
2703                         if (!unix_skb_scm_eq(skb, &scm))
2704                                 break;
2705                 } else if (test_bit(SOCK_PASSCRED, &sock->flags)) {
2706                         /* Copy credentials */
2707                         scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
2708                         unix_set_secdata(&scm, skb);
2709                         check_creds = true;
2710                 }
2711
2712                 /* Copy address just once */
2713                 if (state->msg && state->msg->msg_name) {
2714                         DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr,
2715                                          state->msg->msg_name);
2716                         unix_copy_addr(state->msg, skb->sk);
2717                         sunaddr = NULL;
2718                 }
2719
2720                 chunk = min_t(unsigned int, unix_skb_len(skb) - skip, size);
2721                 skb_get(skb);
2722                 chunk = state->recv_actor(skb, skip, chunk, state);
2723                 drop_skb = !unix_skb_len(skb);
2724                 /* skb is only safe to use if !drop_skb */
2725                 consume_skb(skb);
2726                 if (chunk < 0) {
2727                         if (copied == 0)
2728                                 copied = -EFAULT;
2729                         break;
2730                 }
2731                 copied += chunk;
2732                 size -= chunk;
2733
2734                 if (drop_skb) {
2735                         /* the skb was touched by a concurrent reader;
2736                          * we should not expect anything from this skb
2737                          * anymore and assume it invalid - we can be
2738                          * sure it was dropped from the socket queue
2739                          *
2740                          * let's report a short read
2741                          */
2742                         err = 0;
2743                         break;
2744                 }
2745
2746                 /* Mark read part of skb as used */
2747                 if (!(flags & MSG_PEEK)) {
2748                         UNIXCB(skb).consumed += chunk;
2749
2750                         sk_peek_offset_bwd(sk, chunk);
2751
2752                         if (UNIXCB(skb).fp) {
2753                                 scm_stat_del(sk, skb);
2754                                 unix_detach_fds(&scm, skb);
2755                         }
2756
2757                         if (unix_skb_len(skb))
2758                                 break;
2759
2760                         skb_unlink(skb, &sk->sk_receive_queue);
2761                         consume_skb(skb);
2762
2763                         if (scm.fp)
2764                                 break;
2765                 } else {
2766                         /* It is questionable, see note in unix_dgram_recvmsg.
2767                          */
2768                         if (UNIXCB(skb).fp)
2769                                 unix_peek_fds(&scm, skb);
2770
2771                         sk_peek_offset_fwd(sk, chunk);
2772
2773                         if (UNIXCB(skb).fp)
2774                                 break;
2775
2776                         skip = 0;
2777                         last = skb;
2778                         last_len = skb->len;
2779                         unix_state_lock(sk);
2780                         skb = skb_peek_next(skb, &sk->sk_receive_queue);
2781                         if (skb)
2782                                 goto again;
2783                         unix_state_unlock(sk);
2784                         break;
2785                 }
2786         } while (size);
2787
2788         mutex_unlock(&u->iolock);
2789         if (state->msg)
2790                 scm_recv(sock, state->msg, &scm, flags);
2791         else
2792                 scm_destroy(&scm);
2793 out:
2794         return copied ? : err;
2795 }
2796
2797 static int unix_stream_read_actor(struct sk_buff *skb,
2798                                   int skip, int chunk,
2799                                   struct unix_stream_read_state *state)
2800 {
2801         int ret;
2802
2803         ret = skb_copy_datagram_msg(skb, UNIXCB(skb).consumed + skip,
2804                                     state->msg, chunk);
2805         return ret ?: chunk;
2806 }
2807
2808 int __unix_stream_recvmsg(struct sock *sk, struct msghdr *msg,
2809                           size_t size, int flags)
2810 {
2811         struct unix_stream_read_state state = {
2812                 .recv_actor = unix_stream_read_actor,
2813                 .socket = sk->sk_socket,
2814                 .msg = msg,
2815                 .size = size,
2816                 .flags = flags
2817         };
2818
2819         return unix_stream_read_generic(&state, true);
2820 }
2821
2822 static int unix_stream_recvmsg(struct socket *sock, struct msghdr *msg,
2823                                size_t size, int flags)
2824 {
2825         struct unix_stream_read_state state = {
2826                 .recv_actor = unix_stream_read_actor,
2827                 .socket = sock,
2828                 .msg = msg,
2829                 .size = size,
2830                 .flags = flags
2831         };
2832
2833 #ifdef CONFIG_BPF_SYSCALL
2834         struct sock *sk = sock->sk;
2835         const struct proto *prot = READ_ONCE(sk->sk_prot);
2836
2837         if (prot != &unix_stream_proto)
2838                 return prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
2839                                             flags & ~MSG_DONTWAIT, NULL);
2840 #endif
2841         return unix_stream_read_generic(&state, true);
2842 }
2843
2844 static int unix_stream_splice_actor(struct sk_buff *skb,
2845                                     int skip, int chunk,
2846                                     struct unix_stream_read_state *state)
2847 {
2848         return skb_splice_bits(skb, state->socket->sk,
2849                                UNIXCB(skb).consumed + skip,
2850                                state->pipe, chunk, state->splice_flags);
2851 }
2852
2853 static ssize_t unix_stream_splice_read(struct socket *sock,  loff_t *ppos,
2854                                        struct pipe_inode_info *pipe,
2855                                        size_t size, unsigned int flags)
2856 {
2857         struct unix_stream_read_state state = {
2858                 .recv_actor = unix_stream_splice_actor,
2859                 .socket = sock,
2860                 .pipe = pipe,
2861                 .size = size,
2862                 .splice_flags = flags,
2863         };
2864
2865         if (unlikely(*ppos))
2866                 return -ESPIPE;
2867
2868         if (sock->file->f_flags & O_NONBLOCK ||
2869             flags & SPLICE_F_NONBLOCK)
2870                 state.flags = MSG_DONTWAIT;
2871
2872         return unix_stream_read_generic(&state, false);
2873 }
2874
2875 static int unix_shutdown(struct socket *sock, int mode)
2876 {
2877         struct sock *sk = sock->sk;
2878         struct sock *other;
2879
2880         if (mode < SHUT_RD || mode > SHUT_RDWR)
2881                 return -EINVAL;
2882         /* This maps:
2883          * SHUT_RD   (0) -> RCV_SHUTDOWN  (1)
2884          * SHUT_WR   (1) -> SEND_SHUTDOWN (2)
2885          * SHUT_RDWR (2) -> SHUTDOWN_MASK (3)
2886          */
2887         ++mode;
2888
2889         unix_state_lock(sk);
2890         sk->sk_shutdown |= mode;
2891         other = unix_peer(sk);
2892         if (other)
2893                 sock_hold(other);
2894         unix_state_unlock(sk);
2895         sk->sk_state_change(sk);
2896
2897         if (other &&
2898                 (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET)) {
2899
2900                 int peer_mode = 0;
2901                 const struct proto *prot = READ_ONCE(other->sk_prot);
2902
2903                 if (prot->unhash)
2904                         prot->unhash(other);
2905                 if (mode&RCV_SHUTDOWN)
2906                         peer_mode |= SEND_SHUTDOWN;
2907                 if (mode&SEND_SHUTDOWN)
2908                         peer_mode |= RCV_SHUTDOWN;
2909                 unix_state_lock(other);
2910                 other->sk_shutdown |= peer_mode;
2911                 unix_state_unlock(other);
2912                 other->sk_state_change(other);
2913                 if (peer_mode == SHUTDOWN_MASK)
2914                         sk_wake_async(other, SOCK_WAKE_WAITD, POLL_HUP);
2915                 else if (peer_mode & RCV_SHUTDOWN)
2916                         sk_wake_async(other, SOCK_WAKE_WAITD, POLL_IN);
2917         }
2918         if (other)
2919                 sock_put(other);
2920
2921         return 0;
2922 }
2923
2924 long unix_inq_len(struct sock *sk)
2925 {
2926         struct sk_buff *skb;
2927         long amount = 0;
2928
2929         if (sk->sk_state == TCP_LISTEN)
2930                 return -EINVAL;
2931
2932         spin_lock(&sk->sk_receive_queue.lock);
2933         if (sk->sk_type == SOCK_STREAM ||
2934             sk->sk_type == SOCK_SEQPACKET) {
2935                 skb_queue_walk(&sk->sk_receive_queue, skb)
2936                         amount += unix_skb_len(skb);
2937         } else {
2938                 skb = skb_peek(&sk->sk_receive_queue);
2939                 if (skb)
2940                         amount = skb->len;
2941         }
2942         spin_unlock(&sk->sk_receive_queue.lock);
2943
2944         return amount;
2945 }
2946 EXPORT_SYMBOL_GPL(unix_inq_len);
2947
2948 long unix_outq_len(struct sock *sk)
2949 {
2950         return sk_wmem_alloc_get(sk);
2951 }
2952 EXPORT_SYMBOL_GPL(unix_outq_len);
2953
2954 static int unix_open_file(struct sock *sk)
2955 {
2956         struct path path;
2957         struct file *f;
2958         int fd;
2959
2960         if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2961                 return -EPERM;
2962
2963         if (!smp_load_acquire(&unix_sk(sk)->addr))
2964                 return -ENOENT;
2965
2966         path = unix_sk(sk)->path;
2967         if (!path.dentry)
2968                 return -ENOENT;
2969
2970         path_get(&path);
2971
2972         fd = get_unused_fd_flags(O_CLOEXEC);
2973         if (fd < 0)
2974                 goto out;
2975
2976         f = dentry_open(&path, O_PATH, current_cred());
2977         if (IS_ERR(f)) {
2978                 put_unused_fd(fd);
2979                 fd = PTR_ERR(f);
2980                 goto out;
2981         }
2982
2983         fd_install(fd, f);
2984 out:
2985         path_put(&path);
2986
2987         return fd;
2988 }
2989
2990 static int unix_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
2991 {
2992         struct sock *sk = sock->sk;
2993         long amount = 0;
2994         int err;
2995
2996         switch (cmd) {
2997         case SIOCOUTQ:
2998                 amount = unix_outq_len(sk);
2999                 err = put_user(amount, (int __user *)arg);
3000                 break;
3001         case SIOCINQ:
3002                 amount = unix_inq_len(sk);
3003                 if (amount < 0)
3004                         err = amount;
3005                 else
3006                         err = put_user(amount, (int __user *)arg);
3007                 break;
3008         case SIOCUNIXFILE:
3009                 err = unix_open_file(sk);
3010                 break;
3011 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
3012         case SIOCATMARK:
3013                 {
3014                         struct sk_buff *skb;
3015                         struct unix_sock *u = unix_sk(sk);
3016                         int answ = 0;
3017
3018                         skb = skb_peek(&sk->sk_receive_queue);
3019                         if (skb && skb == u->oob_skb)
3020                                 answ = 1;
3021                         err = put_user(answ, (int __user *)arg);
3022                 }
3023                 break;
3024 #endif
3025         default:
3026                 err = -ENOIOCTLCMD;
3027                 break;
3028         }
3029         return err;
3030 }
3031
3032 #ifdef CONFIG_COMPAT
3033 static int unix_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
3034 {
3035         return unix_ioctl(sock, cmd, (unsigned long)compat_ptr(arg));
3036 }
3037 #endif
3038
3039 static __poll_t unix_poll(struct file *file, struct socket *sock, poll_table *wait)
3040 {
3041         struct sock *sk = sock->sk;
3042         __poll_t mask;
3043
3044         sock_poll_wait(file, sock, wait);
3045         mask = 0;
3046
3047         /* exceptional events? */
3048         if (sk->sk_err)
3049                 mask |= EPOLLERR;
3050         if (sk->sk_shutdown == SHUTDOWN_MASK)
3051                 mask |= EPOLLHUP;
3052         if (sk->sk_shutdown & RCV_SHUTDOWN)
3053                 mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
3054
3055         /* readable? */
3056         if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
3057                 mask |= EPOLLIN | EPOLLRDNORM;
3058         if (sk_is_readable(sk))
3059                 mask |= EPOLLIN | EPOLLRDNORM;
3060
3061         /* Connection-based need to check for termination and startup */
3062         if ((sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) &&
3063             sk->sk_state == TCP_CLOSE)
3064                 mask |= EPOLLHUP;
3065
3066         /*
3067          * we set writable also when the other side has shut down the
3068          * connection. This prevents stuck sockets.
3069          */
3070         if (unix_writable(sk))
3071                 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
3072
3073         return mask;
3074 }
3075
3076 static __poll_t unix_dgram_poll(struct file *file, struct socket *sock,
3077                                     poll_table *wait)
3078 {
3079         struct sock *sk = sock->sk, *other;
3080         unsigned int writable;
3081         __poll_t mask;
3082
3083         sock_poll_wait(file, sock, wait);
3084         mask = 0;
3085
3086         /* exceptional events? */
3087         if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
3088                 mask |= EPOLLERR |
3089                         (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? EPOLLPRI : 0);
3090
3091         if (sk->sk_shutdown & RCV_SHUTDOWN)
3092                 mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
3093         if (sk->sk_shutdown == SHUTDOWN_MASK)
3094                 mask |= EPOLLHUP;
3095
3096         /* readable? */
3097         if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
3098                 mask |= EPOLLIN | EPOLLRDNORM;
3099         if (sk_is_readable(sk))
3100                 mask |= EPOLLIN | EPOLLRDNORM;
3101
3102         /* Connection-based need to check for termination and startup */
3103         if (sk->sk_type == SOCK_SEQPACKET) {
3104                 if (sk->sk_state == TCP_CLOSE)
3105                         mask |= EPOLLHUP;
3106                 /* connection hasn't started yet? */
3107                 if (sk->sk_state == TCP_SYN_SENT)
3108                         return mask;
3109         }
3110
3111         /* No write status requested, avoid expensive OUT tests. */
3112         if (!(poll_requested_events(wait) & (EPOLLWRBAND|EPOLLWRNORM|EPOLLOUT)))
3113                 return mask;
3114
3115         writable = unix_writable(sk);
3116         if (writable) {
3117                 unix_state_lock(sk);
3118
3119                 other = unix_peer(sk);
3120                 if (other && unix_peer(other) != sk &&
3121                     unix_recvq_full_lockless(other) &&
3122                     unix_dgram_peer_wake_me(sk, other))
3123                         writable = 0;
3124
3125                 unix_state_unlock(sk);
3126         }
3127
3128         if (writable)
3129                 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
3130         else
3131                 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
3132
3133         return mask;
3134 }
3135
3136 #ifdef CONFIG_PROC_FS
3137
3138 #define BUCKET_SPACE (BITS_PER_LONG - (UNIX_HASH_BITS + 1) - 1)
3139
3140 #define get_bucket(x) ((x) >> BUCKET_SPACE)
3141 #define get_offset(x) ((x) & ((1L << BUCKET_SPACE) - 1))
3142 #define set_bucket_offset(b, o) ((b) << BUCKET_SPACE | (o))
3143
3144 static struct sock *unix_from_bucket(struct seq_file *seq, loff_t *pos)
3145 {
3146         unsigned long offset = get_offset(*pos);
3147         unsigned long bucket = get_bucket(*pos);
3148         struct sock *sk;
3149         unsigned long count = 0;
3150
3151         for (sk = sk_head(&unix_socket_table[bucket]); sk; sk = sk_next(sk)) {
3152                 if (sock_net(sk) != seq_file_net(seq))
3153                         continue;
3154                 if (++count == offset)
3155                         break;
3156         }
3157
3158         return sk;
3159 }
3160
3161 static struct sock *unix_next_socket(struct seq_file *seq,
3162                                      struct sock *sk,
3163                                      loff_t *pos)
3164 {
3165         unsigned long bucket;
3166
3167         while (sk > (struct sock *)SEQ_START_TOKEN) {
3168                 sk = sk_next(sk);
3169                 if (!sk)
3170                         goto next_bucket;
3171                 if (sock_net(sk) == seq_file_net(seq))
3172                         return sk;
3173         }
3174
3175         do {
3176                 sk = unix_from_bucket(seq, pos);
3177                 if (sk)
3178                         return sk;
3179
3180 next_bucket:
3181                 bucket = get_bucket(*pos) + 1;
3182                 *pos = set_bucket_offset(bucket, 1);
3183         } while (bucket < ARRAY_SIZE(unix_socket_table));
3184
3185         return NULL;
3186 }
3187
3188 static void *unix_seq_start(struct seq_file *seq, loff_t *pos)
3189         __acquires(unix_table_lock)
3190 {
3191         spin_lock(&unix_table_lock);
3192
3193         if (!*pos)
3194                 return SEQ_START_TOKEN;
3195
3196         if (get_bucket(*pos) >= ARRAY_SIZE(unix_socket_table))
3197                 return NULL;
3198
3199         return unix_next_socket(seq, NULL, pos);
3200 }
3201
3202 static void *unix_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3203 {
3204         ++*pos;
3205         return unix_next_socket(seq, v, pos);
3206 }
3207
3208 static void unix_seq_stop(struct seq_file *seq, void *v)
3209         __releases(unix_table_lock)
3210 {
3211         spin_unlock(&unix_table_lock);
3212 }
3213
3214 static int unix_seq_show(struct seq_file *seq, void *v)
3215 {
3216
3217         if (v == SEQ_START_TOKEN)
3218                 seq_puts(seq, "Num       RefCount Protocol Flags    Type St "
3219                          "Inode Path\n");
3220         else {
3221                 struct sock *s = v;
3222                 struct unix_sock *u = unix_sk(s);
3223                 unix_state_lock(s);
3224
3225                 seq_printf(seq, "%pK: %08X %08X %08X %04X %02X %5lu",
3226                         s,
3227                         refcount_read(&s->sk_refcnt),
3228                         0,
3229                         s->sk_state == TCP_LISTEN ? __SO_ACCEPTCON : 0,
3230                         s->sk_type,
3231                         s->sk_socket ?
3232                         (s->sk_state == TCP_ESTABLISHED ? SS_CONNECTED : SS_UNCONNECTED) :
3233                         (s->sk_state == TCP_ESTABLISHED ? SS_CONNECTING : SS_DISCONNECTING),
3234                         sock_i_ino(s));
3235
3236                 if (u->addr) {  // under unix_table_lock here
3237                         int i, len;
3238                         seq_putc(seq, ' ');
3239
3240                         i = 0;
3241                         len = u->addr->len -
3242                                 offsetof(struct sockaddr_un, sun_path);
3243                         if (!UNIX_ABSTRACT(s))
3244                                 len--;
3245                         else {
3246                                 seq_putc(seq, '@');
3247                                 i++;
3248                         }
3249                         for ( ; i < len; i++)
3250                                 seq_putc(seq, u->addr->name->sun_path[i] ?:
3251                                          '@');
3252                 }
3253                 unix_state_unlock(s);
3254                 seq_putc(seq, '\n');
3255         }
3256
3257         return 0;
3258 }
3259
3260 static const struct seq_operations unix_seq_ops = {
3261         .start  = unix_seq_start,
3262         .next   = unix_seq_next,
3263         .stop   = unix_seq_stop,
3264         .show   = unix_seq_show,
3265 };
3266
3267 #if IS_BUILTIN(CONFIG_UNIX) && defined(CONFIG_BPF_SYSCALL)
3268 struct bpf_iter__unix {
3269         __bpf_md_ptr(struct bpf_iter_meta *, meta);
3270         __bpf_md_ptr(struct unix_sock *, unix_sk);
3271         uid_t uid __aligned(8);
3272 };
3273
3274 static int unix_prog_seq_show(struct bpf_prog *prog, struct bpf_iter_meta *meta,
3275                               struct unix_sock *unix_sk, uid_t uid)
3276 {
3277         struct bpf_iter__unix ctx;
3278
3279         meta->seq_num--;  /* skip SEQ_START_TOKEN */
3280         ctx.meta = meta;
3281         ctx.unix_sk = unix_sk;
3282         ctx.uid = uid;
3283         return bpf_iter_run_prog(prog, &ctx);
3284 }
3285
3286 static int bpf_iter_unix_seq_show(struct seq_file *seq, void *v)
3287 {
3288         struct bpf_iter_meta meta;
3289         struct bpf_prog *prog;
3290         struct sock *sk = v;
3291         uid_t uid;
3292
3293         if (v == SEQ_START_TOKEN)
3294                 return 0;
3295
3296         uid = from_kuid_munged(seq_user_ns(seq), sock_i_uid(sk));
3297         meta.seq = seq;
3298         prog = bpf_iter_get_info(&meta, false);
3299         return unix_prog_seq_show(prog, &meta, v, uid);
3300 }
3301
3302 static void bpf_iter_unix_seq_stop(struct seq_file *seq, void *v)
3303 {
3304         struct bpf_iter_meta meta;
3305         struct bpf_prog *prog;
3306
3307         if (!v) {
3308                 meta.seq = seq;
3309                 prog = bpf_iter_get_info(&meta, true);
3310                 if (prog)
3311                         (void)unix_prog_seq_show(prog, &meta, v, 0);
3312         }
3313
3314         unix_seq_stop(seq, v);
3315 }
3316
3317 static const struct seq_operations bpf_iter_unix_seq_ops = {
3318         .start  = unix_seq_start,
3319         .next   = unix_seq_next,
3320         .stop   = bpf_iter_unix_seq_stop,
3321         .show   = bpf_iter_unix_seq_show,
3322 };
3323 #endif
3324 #endif
3325
3326 static const struct net_proto_family unix_family_ops = {
3327         .family = PF_UNIX,
3328         .create = unix_create,
3329         .owner  = THIS_MODULE,
3330 };
3331
3332
3333 static int __net_init unix_net_init(struct net *net)
3334 {
3335         int error = -ENOMEM;
3336
3337         net->unx.sysctl_max_dgram_qlen = 10;
3338         if (unix_sysctl_register(net))
3339                 goto out;
3340
3341 #ifdef CONFIG_PROC_FS
3342         if (!proc_create_net("unix", 0, net->proc_net, &unix_seq_ops,
3343                         sizeof(struct seq_net_private))) {
3344                 unix_sysctl_unregister(net);
3345                 goto out;
3346         }
3347 #endif
3348         error = 0;
3349 out:
3350         return error;
3351 }
3352
3353 static void __net_exit unix_net_exit(struct net *net)
3354 {
3355         unix_sysctl_unregister(net);
3356         remove_proc_entry("unix", net->proc_net);
3357 }
3358
3359 static struct pernet_operations unix_net_ops = {
3360         .init = unix_net_init,
3361         .exit = unix_net_exit,
3362 };
3363
3364 #if IS_BUILTIN(CONFIG_UNIX) && defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3365 DEFINE_BPF_ITER_FUNC(unix, struct bpf_iter_meta *meta,
3366                      struct unix_sock *unix_sk, uid_t uid)
3367
3368 static const struct bpf_iter_seq_info unix_seq_info = {
3369         .seq_ops                = &bpf_iter_unix_seq_ops,
3370         .init_seq_private       = bpf_iter_init_seq_net,
3371         .fini_seq_private       = bpf_iter_fini_seq_net,
3372         .seq_priv_size          = sizeof(struct seq_net_private),
3373 };
3374
3375 static struct bpf_iter_reg unix_reg_info = {
3376         .target                 = "unix",
3377         .ctx_arg_info_size      = 1,
3378         .ctx_arg_info           = {
3379                 { offsetof(struct bpf_iter__unix, unix_sk),
3380                   PTR_TO_BTF_ID_OR_NULL },
3381         },
3382         .seq_info               = &unix_seq_info,
3383 };
3384
3385 static void __init bpf_iter_register(void)
3386 {
3387         unix_reg_info.ctx_arg_info[0].btf_id = btf_sock_ids[BTF_SOCK_TYPE_UNIX];
3388         if (bpf_iter_reg_target(&unix_reg_info))
3389                 pr_warn("Warning: could not register bpf iterator unix\n");
3390 }
3391 #endif
3392
3393 static int __init af_unix_init(void)
3394 {
3395         int rc = -1;
3396
3397         BUILD_BUG_ON(sizeof(struct unix_skb_parms) > sizeof_field(struct sk_buff, cb));
3398
3399         rc = proto_register(&unix_dgram_proto, 1);
3400         if (rc != 0) {
3401                 pr_crit("%s: Cannot create unix_sock SLAB cache!\n", __func__);
3402                 goto out;
3403         }
3404
3405         rc = proto_register(&unix_stream_proto, 1);
3406         if (rc != 0) {
3407                 pr_crit("%s: Cannot create unix_sock SLAB cache!\n", __func__);
3408                 goto out;
3409         }
3410
3411         sock_register(&unix_family_ops);
3412         register_pernet_subsys(&unix_net_ops);
3413         unix_bpf_build_proto();
3414
3415 #if IS_BUILTIN(CONFIG_UNIX) && defined(CONFIG_BPF_SYSCALL) && defined(CONFIG_PROC_FS)
3416         bpf_iter_register();
3417 #endif
3418
3419 out:
3420         return rc;
3421 }
3422
3423 static void __exit af_unix_exit(void)
3424 {
3425         sock_unregister(PF_UNIX);
3426         proto_unregister(&unix_dgram_proto);
3427         proto_unregister(&unix_stream_proto);
3428         unregister_pernet_subsys(&unix_net_ops);
3429 }
3430
3431 /* Earlier than device_initcall() so that other drivers invoking
3432    request_module() don't end up in a loop when modprobe tries
3433    to use a UNIX socket. But later than subsys_initcall() because
3434    we depend on stuff initialised there */
3435 fs_initcall(af_unix_init);
3436 module_exit(af_unix_exit);
3437
3438 MODULE_LICENSE("GPL");
3439 MODULE_ALIAS_NETPROTO(PF_UNIX);