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