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