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