1 // SPDX-License-Identifier: GPL-2.0-or-later
3 * NET4: Implementation of BSD Unix domain sockets.
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
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
25 * Kirk Petersen : Made this a module
26 * Christoph Rohland : Elegant non-blocking accept/connect algorithm.
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
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+)
48 * Known differences from reference BSD that was tested:
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).
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)
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.
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
78 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
80 #include <linux/module.h>
81 #include <linux/kernel.h>
82 #include <linux/signal.h>
83 #include <linux/sched/signal.h>
84 #include <linux/errno.h>
85 #include <linux/string.h>
86 #include <linux/stat.h>
87 #include <linux/dcache.h>
88 #include <linux/namei.h>
89 #include <linux/socket.h>
91 #include <linux/fcntl.h>
92 #include <linux/termios.h>
93 #include <linux/sockios.h>
94 #include <linux/net.h>
97 #include <linux/slab.h>
98 #include <linux/uaccess.h>
99 #include <linux/skbuff.h>
100 #include <linux/netdevice.h>
101 #include <net/net_namespace.h>
102 #include <net/sock.h>
103 #include <net/tcp_states.h>
104 #include <net/af_unix.h>
105 #include <linux/proc_fs.h>
106 #include <linux/seq_file.h>
108 #include <linux/init.h>
109 #include <linux/poll.h>
110 #include <linux/rtnetlink.h>
111 #include <linux/mount.h>
112 #include <net/checksum.h>
113 #include <linux/security.h>
114 #include <linux/freezer.h>
115 #include <linux/file.h>
119 struct hlist_head unix_socket_table[2 * UNIX_HASH_SIZE];
120 EXPORT_SYMBOL_GPL(unix_socket_table);
121 DEFINE_SPINLOCK(unix_table_lock);
122 EXPORT_SYMBOL_GPL(unix_table_lock);
123 static atomic_long_t unix_nr_socks;
126 static struct hlist_head *unix_sockets_unbound(void *addr)
128 unsigned long hash = (unsigned long)addr;
132 hash %= UNIX_HASH_SIZE;
133 return &unix_socket_table[UNIX_HASH_SIZE + hash];
136 #define UNIX_ABSTRACT(sk) (unix_sk(sk)->addr->hash < UNIX_HASH_SIZE)
138 #ifdef CONFIG_SECURITY_NETWORK
139 static void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
141 UNIXCB(skb).secid = scm->secid;
144 static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
146 scm->secid = UNIXCB(skb).secid;
149 static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
151 return (scm->secid == UNIXCB(skb).secid);
154 static inline void unix_get_secdata(struct scm_cookie *scm, struct sk_buff *skb)
157 static inline void unix_set_secdata(struct scm_cookie *scm, struct sk_buff *skb)
160 static inline bool unix_secdata_eq(struct scm_cookie *scm, struct sk_buff *skb)
164 #endif /* CONFIG_SECURITY_NETWORK */
167 * SMP locking strategy:
168 * hash table is protected with spinlock unix_table_lock
169 * each socket state is protected by separate spin lock.
172 static inline unsigned int unix_hash_fold(__wsum n)
174 unsigned int hash = (__force unsigned int)csum_fold(n);
177 return hash&(UNIX_HASH_SIZE-1);
180 #define unix_peer(sk) (unix_sk(sk)->peer)
182 static inline int unix_our_peer(struct sock *sk, struct sock *osk)
184 return unix_peer(osk) == sk;
187 static inline int unix_may_send(struct sock *sk, struct sock *osk)
189 return unix_peer(osk) == NULL || unix_our_peer(sk, osk);
192 static inline int unix_recvq_full(const struct sock *sk)
194 return skb_queue_len(&sk->sk_receive_queue) > sk->sk_max_ack_backlog;
197 static inline int unix_recvq_full_lockless(const struct sock *sk)
199 return skb_queue_len_lockless(&sk->sk_receive_queue) >
200 READ_ONCE(sk->sk_max_ack_backlog);
203 struct sock *unix_peer_get(struct sock *s)
211 unix_state_unlock(s);
214 EXPORT_SYMBOL_GPL(unix_peer_get);
216 static inline void unix_release_addr(struct unix_address *addr)
218 if (refcount_dec_and_test(&addr->refcnt))
223 * Check unix socket name:
224 * - should be not zero length.
225 * - if started by not zero, should be NULL terminated (FS object)
226 * - if started by zero, it is abstract name.
229 static int unix_mkname(struct sockaddr_un *sunaddr, int len, unsigned int *hashp)
233 if (len <= sizeof(short) || len > sizeof(*sunaddr))
235 if (!sunaddr || sunaddr->sun_family != AF_UNIX)
237 if (sunaddr->sun_path[0]) {
239 * This may look like an off by one error but it is a bit more
240 * subtle. 108 is the longest valid AF_UNIX path for a binding.
241 * sun_path[108] doesn't as such exist. However in kernel space
242 * we are guaranteed that it is a valid memory location in our
243 * kernel address buffer.
245 ((char *)sunaddr)[len] = 0;
246 len = strlen(sunaddr->sun_path)+1+sizeof(short);
250 *hashp = unix_hash_fold(csum_partial(sunaddr, len, 0));
254 static void __unix_remove_socket(struct sock *sk)
256 sk_del_node_init(sk);
259 static void __unix_insert_socket(struct hlist_head *list, struct sock *sk)
261 WARN_ON(!sk_unhashed(sk));
262 sk_add_node(sk, list);
265 static void __unix_set_addr(struct sock *sk, struct unix_address *addr,
268 __unix_remove_socket(sk);
269 smp_store_release(&unix_sk(sk)->addr, addr);
270 __unix_insert_socket(&unix_socket_table[hash], sk);
273 static inline void unix_remove_socket(struct sock *sk)
275 spin_lock(&unix_table_lock);
276 __unix_remove_socket(sk);
277 spin_unlock(&unix_table_lock);
280 static inline void unix_insert_socket(struct hlist_head *list, struct sock *sk)
282 spin_lock(&unix_table_lock);
283 __unix_insert_socket(list, sk);
284 spin_unlock(&unix_table_lock);
287 static struct sock *__unix_find_socket_byname(struct net *net,
288 struct sockaddr_un *sunname,
289 int len, unsigned int hash)
293 sk_for_each(s, &unix_socket_table[hash]) {
294 struct unix_sock *u = unix_sk(s);
296 if (!net_eq(sock_net(s), net))
299 if (u->addr->len == len &&
300 !memcmp(u->addr->name, sunname, len))
306 static inline struct sock *unix_find_socket_byname(struct net *net,
307 struct sockaddr_un *sunname,
308 int len, unsigned int hash)
312 spin_lock(&unix_table_lock);
313 s = __unix_find_socket_byname(net, sunname, len, hash);
316 spin_unlock(&unix_table_lock);
320 static struct sock *unix_find_socket_byinode(struct inode *i)
324 spin_lock(&unix_table_lock);
326 &unix_socket_table[i->i_ino & (UNIX_HASH_SIZE - 1)]) {
327 struct dentry *dentry = unix_sk(s)->path.dentry;
329 if (dentry && d_backing_inode(dentry) == i) {
336 spin_unlock(&unix_table_lock);
340 /* Support code for asymmetrically connected dgram sockets
342 * If a datagram socket is connected to a socket not itself connected
343 * to the first socket (eg, /dev/log), clients may only enqueue more
344 * messages if the present receive queue of the server socket is not
345 * "too large". This means there's a second writeability condition
346 * poll and sendmsg need to test. The dgram recv code will do a wake
347 * up on the peer_wait wait queue of a socket upon reception of a
348 * datagram which needs to be propagated to sleeping would-be writers
349 * since these might not have sent anything so far. This can't be
350 * accomplished via poll_wait because the lifetime of the server
351 * socket might be less than that of its clients if these break their
352 * association with it or if the server socket is closed while clients
353 * are still connected to it and there's no way to inform "a polling
354 * implementation" that it should let go of a certain wait queue
356 * In order to propagate a wake up, a wait_queue_entry_t of the client
357 * socket is enqueued on the peer_wait queue of the server socket
358 * whose wake function does a wake_up on the ordinary client socket
359 * wait queue. This connection is established whenever a write (or
360 * poll for write) hit the flow control condition and broken when the
361 * association to the server socket is dissolved or after a wake up
365 static int unix_dgram_peer_wake_relay(wait_queue_entry_t *q, unsigned mode, int flags,
369 wait_queue_head_t *u_sleep;
371 u = container_of(q, struct unix_sock, peer_wake);
373 __remove_wait_queue(&unix_sk(u->peer_wake.private)->peer_wait,
375 u->peer_wake.private = NULL;
377 /* relaying can only happen while the wq still exists */
378 u_sleep = sk_sleep(&u->sk);
380 wake_up_interruptible_poll(u_sleep, key_to_poll(key));
385 static int unix_dgram_peer_wake_connect(struct sock *sk, struct sock *other)
387 struct unix_sock *u, *u_other;
391 u_other = unix_sk(other);
393 spin_lock(&u_other->peer_wait.lock);
395 if (!u->peer_wake.private) {
396 u->peer_wake.private = other;
397 __add_wait_queue(&u_other->peer_wait, &u->peer_wake);
402 spin_unlock(&u_other->peer_wait.lock);
406 static void unix_dgram_peer_wake_disconnect(struct sock *sk,
409 struct unix_sock *u, *u_other;
412 u_other = unix_sk(other);
413 spin_lock(&u_other->peer_wait.lock);
415 if (u->peer_wake.private == other) {
416 __remove_wait_queue(&u_other->peer_wait, &u->peer_wake);
417 u->peer_wake.private = NULL;
420 spin_unlock(&u_other->peer_wait.lock);
423 static void unix_dgram_peer_wake_disconnect_wakeup(struct sock *sk,
426 unix_dgram_peer_wake_disconnect(sk, other);
427 wake_up_interruptible_poll(sk_sleep(sk),
434 * - unix_peer(sk) == other
435 * - association is stable
437 static int unix_dgram_peer_wake_me(struct sock *sk, struct sock *other)
441 connected = unix_dgram_peer_wake_connect(sk, other);
443 /* If other is SOCK_DEAD, we want to make sure we signal
444 * POLLOUT, such that a subsequent write() can get a
445 * -ECONNREFUSED. Otherwise, if we haven't queued any skbs
446 * to other and its full, we will hang waiting for POLLOUT.
448 if (unix_recvq_full(other) && !sock_flag(other, SOCK_DEAD))
452 unix_dgram_peer_wake_disconnect(sk, other);
457 static int unix_writable(const struct sock *sk)
459 return sk->sk_state != TCP_LISTEN &&
460 (refcount_read(&sk->sk_wmem_alloc) << 2) <= sk->sk_sndbuf;
463 static void unix_write_space(struct sock *sk)
465 struct socket_wq *wq;
468 if (unix_writable(sk)) {
469 wq = rcu_dereference(sk->sk_wq);
470 if (skwq_has_sleeper(wq))
471 wake_up_interruptible_sync_poll(&wq->wait,
472 EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND);
473 sk_wake_async(sk, SOCK_WAKE_SPACE, POLL_OUT);
478 /* When dgram socket disconnects (or changes its peer), we clear its receive
479 * queue of packets arrived from previous peer. First, it allows to do
480 * flow control based only on wmem_alloc; second, sk connected to peer
481 * may receive messages only from that peer. */
482 static void unix_dgram_disconnected(struct sock *sk, struct sock *other)
484 if (!skb_queue_empty(&sk->sk_receive_queue)) {
485 skb_queue_purge(&sk->sk_receive_queue);
486 wake_up_interruptible_all(&unix_sk(sk)->peer_wait);
488 /* If one link of bidirectional dgram pipe is disconnected,
489 * we signal error. Messages are lost. Do not make this,
490 * when peer was not connected to us.
492 if (!sock_flag(other, SOCK_DEAD) && unix_peer(other) == sk) {
493 other->sk_err = ECONNRESET;
494 sk_error_report(other);
497 sk->sk_state = other->sk_state = TCP_CLOSE;
500 static void unix_sock_destructor(struct sock *sk)
502 struct unix_sock *u = unix_sk(sk);
504 skb_queue_purge(&sk->sk_receive_queue);
506 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
508 kfree_skb(u->oob_skb);
512 WARN_ON(refcount_read(&sk->sk_wmem_alloc));
513 WARN_ON(!sk_unhashed(sk));
514 WARN_ON(sk->sk_socket);
515 if (!sock_flag(sk, SOCK_DEAD)) {
516 pr_info("Attempt to release alive unix socket: %p\n", sk);
521 unix_release_addr(u->addr);
523 atomic_long_dec(&unix_nr_socks);
525 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
527 #ifdef UNIX_REFCNT_DEBUG
528 pr_debug("UNIX %p is destroyed, %ld are still alive.\n", sk,
529 atomic_long_read(&unix_nr_socks));
533 static void unix_release_sock(struct sock *sk, int embrion)
535 struct unix_sock *u = unix_sk(sk);
541 unix_remove_socket(sk);
546 sk->sk_shutdown = SHUTDOWN_MASK;
548 u->path.dentry = NULL;
550 state = sk->sk_state;
551 sk->sk_state = TCP_CLOSE;
553 skpair = unix_peer(sk);
554 unix_peer(sk) = NULL;
556 unix_state_unlock(sk);
558 wake_up_interruptible_all(&u->peer_wait);
560 if (skpair != NULL) {
561 if (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) {
562 unix_state_lock(skpair);
564 skpair->sk_shutdown = SHUTDOWN_MASK;
565 if (!skb_queue_empty(&sk->sk_receive_queue) || embrion)
566 skpair->sk_err = ECONNRESET;
567 unix_state_unlock(skpair);
568 skpair->sk_state_change(skpair);
569 sk_wake_async(skpair, SOCK_WAKE_WAITD, POLL_HUP);
572 unix_dgram_peer_wake_disconnect(sk, skpair);
573 sock_put(skpair); /* It may now die */
576 /* Try to flush out this socket. Throw out buffers at least */
578 while ((skb = skb_dequeue(&sk->sk_receive_queue)) != NULL) {
579 if (state == TCP_LISTEN)
580 unix_release_sock(skb->sk, 1);
581 /* passed fds are erased in the kfree_skb hook */
582 UNIXCB(skb).consumed = skb->len;
591 /* ---- Socket is dead now and most probably destroyed ---- */
594 * Fixme: BSD difference: In BSD all sockets connected to us get
595 * ECONNRESET and we die on the spot. In Linux we behave
596 * like files and pipes do and wait for the last
599 * Can't we simply set sock->err?
601 * What the above comment does talk about? --ANK(980817)
604 if (unix_tot_inflight)
605 unix_gc(); /* Garbage collect fds */
608 static void init_peercred(struct sock *sk)
610 put_pid(sk->sk_peer_pid);
611 if (sk->sk_peer_cred)
612 put_cred(sk->sk_peer_cred);
613 sk->sk_peer_pid = get_pid(task_tgid(current));
614 sk->sk_peer_cred = get_current_cred();
617 static void copy_peercred(struct sock *sk, struct sock *peersk)
619 put_pid(sk->sk_peer_pid);
620 if (sk->sk_peer_cred)
621 put_cred(sk->sk_peer_cred);
622 sk->sk_peer_pid = get_pid(peersk->sk_peer_pid);
623 sk->sk_peer_cred = get_cred(peersk->sk_peer_cred);
626 static int unix_listen(struct socket *sock, int backlog)
629 struct sock *sk = sock->sk;
630 struct unix_sock *u = unix_sk(sk);
633 if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
634 goto out; /* Only stream/seqpacket sockets accept */
637 goto out; /* No listens on an unbound socket */
639 if (sk->sk_state != TCP_CLOSE && sk->sk_state != TCP_LISTEN)
641 if (backlog > sk->sk_max_ack_backlog)
642 wake_up_interruptible_all(&u->peer_wait);
643 sk->sk_max_ack_backlog = backlog;
644 sk->sk_state = TCP_LISTEN;
645 /* set credentials so connect can copy them */
650 unix_state_unlock(sk);
655 static int unix_release(struct socket *);
656 static int unix_bind(struct socket *, struct sockaddr *, int);
657 static int unix_stream_connect(struct socket *, struct sockaddr *,
658 int addr_len, int flags);
659 static int unix_socketpair(struct socket *, struct socket *);
660 static int unix_accept(struct socket *, struct socket *, int, bool);
661 static int unix_getname(struct socket *, struct sockaddr *, int);
662 static __poll_t unix_poll(struct file *, struct socket *, poll_table *);
663 static __poll_t unix_dgram_poll(struct file *, struct socket *,
665 static int unix_ioctl(struct socket *, unsigned int, unsigned long);
667 static int unix_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg);
669 static int unix_shutdown(struct socket *, int);
670 static int unix_stream_sendmsg(struct socket *, struct msghdr *, size_t);
671 static int unix_stream_recvmsg(struct socket *, struct msghdr *, size_t, int);
672 static ssize_t unix_stream_sendpage(struct socket *, struct page *, int offset,
673 size_t size, int flags);
674 static ssize_t unix_stream_splice_read(struct socket *, loff_t *ppos,
675 struct pipe_inode_info *, size_t size,
677 static int unix_dgram_sendmsg(struct socket *, struct msghdr *, size_t);
678 static int unix_dgram_recvmsg(struct socket *, struct msghdr *, size_t, int);
679 static int unix_read_sock(struct sock *sk, read_descriptor_t *desc,
680 sk_read_actor_t recv_actor);
681 static int unix_dgram_connect(struct socket *, struct sockaddr *,
683 static int unix_seqpacket_sendmsg(struct socket *, struct msghdr *, size_t);
684 static int unix_seqpacket_recvmsg(struct socket *, struct msghdr *, size_t,
687 static int unix_set_peek_off(struct sock *sk, int val)
689 struct unix_sock *u = unix_sk(sk);
691 if (mutex_lock_interruptible(&u->iolock))
694 sk->sk_peek_off = val;
695 mutex_unlock(&u->iolock);
700 #ifdef CONFIG_PROC_FS
701 static void unix_show_fdinfo(struct seq_file *m, struct socket *sock)
703 struct sock *sk = sock->sk;
707 u = unix_sk(sock->sk);
708 seq_printf(m, "scm_fds: %u\n",
709 atomic_read(&u->scm_stat.nr_fds));
713 #define unix_show_fdinfo NULL
716 static const struct proto_ops unix_stream_ops = {
718 .owner = THIS_MODULE,
719 .release = unix_release,
721 .connect = unix_stream_connect,
722 .socketpair = unix_socketpair,
723 .accept = unix_accept,
724 .getname = unix_getname,
728 .compat_ioctl = unix_compat_ioctl,
730 .listen = unix_listen,
731 .shutdown = unix_shutdown,
732 .sendmsg = unix_stream_sendmsg,
733 .recvmsg = unix_stream_recvmsg,
734 .mmap = sock_no_mmap,
735 .sendpage = unix_stream_sendpage,
736 .splice_read = unix_stream_splice_read,
737 .set_peek_off = unix_set_peek_off,
738 .show_fdinfo = unix_show_fdinfo,
741 static const struct proto_ops unix_dgram_ops = {
743 .owner = THIS_MODULE,
744 .release = unix_release,
746 .connect = unix_dgram_connect,
747 .socketpair = unix_socketpair,
748 .accept = sock_no_accept,
749 .getname = unix_getname,
750 .poll = unix_dgram_poll,
753 .compat_ioctl = unix_compat_ioctl,
755 .listen = sock_no_listen,
756 .shutdown = unix_shutdown,
757 .sendmsg = unix_dgram_sendmsg,
758 .read_sock = unix_read_sock,
759 .recvmsg = unix_dgram_recvmsg,
760 .mmap = sock_no_mmap,
761 .sendpage = sock_no_sendpage,
762 .set_peek_off = unix_set_peek_off,
763 .show_fdinfo = unix_show_fdinfo,
766 static const struct proto_ops unix_seqpacket_ops = {
768 .owner = THIS_MODULE,
769 .release = unix_release,
771 .connect = unix_stream_connect,
772 .socketpair = unix_socketpair,
773 .accept = unix_accept,
774 .getname = unix_getname,
775 .poll = unix_dgram_poll,
778 .compat_ioctl = unix_compat_ioctl,
780 .listen = unix_listen,
781 .shutdown = unix_shutdown,
782 .sendmsg = unix_seqpacket_sendmsg,
783 .recvmsg = unix_seqpacket_recvmsg,
784 .mmap = sock_no_mmap,
785 .sendpage = sock_no_sendpage,
786 .set_peek_off = unix_set_peek_off,
787 .show_fdinfo = unix_show_fdinfo,
790 static void unix_close(struct sock *sk, long timeout)
792 /* Nothing to do here, unix socket does not need a ->close().
793 * This is merely for sockmap.
797 struct proto unix_proto = {
799 .owner = THIS_MODULE,
800 .obj_size = sizeof(struct unix_sock),
802 #ifdef CONFIG_BPF_SYSCALL
803 .psock_update_sk_prot = unix_bpf_update_proto,
807 static struct sock *unix_create1(struct net *net, struct socket *sock, int kern)
809 struct sock *sk = NULL;
812 atomic_long_inc(&unix_nr_socks);
813 if (atomic_long_read(&unix_nr_socks) > 2 * get_max_files())
816 sk = sk_alloc(net, PF_UNIX, GFP_KERNEL, &unix_proto, kern);
820 sock_init_data(sock, sk);
822 sk->sk_allocation = GFP_KERNEL_ACCOUNT;
823 sk->sk_write_space = unix_write_space;
824 sk->sk_max_ack_backlog = net->unx.sysctl_max_dgram_qlen;
825 sk->sk_destruct = unix_sock_destructor;
827 u->path.dentry = NULL;
829 spin_lock_init(&u->lock);
830 atomic_long_set(&u->inflight, 0);
831 INIT_LIST_HEAD(&u->link);
832 mutex_init(&u->iolock); /* single task reading lock */
833 mutex_init(&u->bindlock); /* single task binding lock */
834 init_waitqueue_head(&u->peer_wait);
835 init_waitqueue_func_entry(&u->peer_wake, unix_dgram_peer_wake_relay);
836 memset(&u->scm_stat, 0, sizeof(struct scm_stat));
837 unix_insert_socket(unix_sockets_unbound(sk), sk);
840 atomic_long_dec(&unix_nr_socks);
843 sock_prot_inuse_add(sock_net(sk), sk->sk_prot, 1);
849 static int unix_create(struct net *net, struct socket *sock, int protocol,
852 if (protocol && protocol != PF_UNIX)
853 return -EPROTONOSUPPORT;
855 sock->state = SS_UNCONNECTED;
857 switch (sock->type) {
859 sock->ops = &unix_stream_ops;
862 * Believe it or not BSD has AF_UNIX, SOCK_RAW though
866 sock->type = SOCK_DGRAM;
869 sock->ops = &unix_dgram_ops;
872 sock->ops = &unix_seqpacket_ops;
875 return -ESOCKTNOSUPPORT;
878 return unix_create1(net, sock, kern) ? 0 : -ENOMEM;
881 static int unix_release(struct socket *sock)
883 struct sock *sk = sock->sk;
888 sk->sk_prot->close(sk, 0);
889 unix_release_sock(sk, 0);
895 static int unix_autobind(struct socket *sock)
897 struct sock *sk = sock->sk;
898 struct net *net = sock_net(sk);
899 struct unix_sock *u = unix_sk(sk);
900 static u32 ordernum = 1;
901 struct unix_address *addr;
903 unsigned int retries = 0;
905 err = mutex_lock_interruptible(&u->bindlock);
913 addr = kzalloc(sizeof(*addr) + sizeof(short) + 16, GFP_KERNEL);
917 addr->name->sun_family = AF_UNIX;
918 refcount_set(&addr->refcnt, 1);
921 addr->len = sprintf(addr->name->sun_path+1, "%05x", ordernum) + 1 + sizeof(short);
922 addr->hash = unix_hash_fold(csum_partial(addr->name, addr->len, 0));
923 addr->hash ^= sk->sk_type;
925 spin_lock(&unix_table_lock);
926 ordernum = (ordernum+1)&0xFFFFF;
928 if (__unix_find_socket_byname(net, addr->name, addr->len, addr->hash)) {
929 spin_unlock(&unix_table_lock);
931 * __unix_find_socket_byname() may take long time if many names
932 * are already in use.
935 /* Give up if all names seems to be in use. */
936 if (retries++ == 0xFFFFF) {
944 __unix_set_addr(sk, addr, addr->hash);
945 spin_unlock(&unix_table_lock);
948 out: mutex_unlock(&u->bindlock);
952 static struct sock *unix_find_other(struct net *net,
953 struct sockaddr_un *sunname, int len,
954 int type, unsigned int hash, int *error)
960 if (sunname->sun_path[0]) {
962 err = kern_path(sunname->sun_path, LOOKUP_FOLLOW, &path);
965 inode = d_backing_inode(path.dentry);
966 err = path_permission(&path, MAY_WRITE);
971 if (!S_ISSOCK(inode->i_mode))
973 u = unix_find_socket_byinode(inode);
977 if (u->sk_type == type)
983 if (u->sk_type != type) {
989 u = unix_find_socket_byname(net, sunname, len, type ^ hash);
991 struct dentry *dentry;
992 dentry = unix_sk(u)->path.dentry;
994 touch_atime(&unix_sk(u)->path);
1007 static int unix_bind_bsd(struct sock *sk, struct unix_address *addr)
1009 struct unix_sock *u = unix_sk(sk);
1010 umode_t mode = S_IFSOCK |
1011 (SOCK_INODE(sk->sk_socket)->i_mode & ~current_umask());
1012 struct user_namespace *ns; // barf...
1014 struct dentry *dentry;
1019 * Get the parent directory, calculate the hash for last
1022 dentry = kern_path_create(AT_FDCWD, addr->name->sun_path, &parent, 0);
1024 return PTR_ERR(dentry);
1025 ns = mnt_user_ns(parent.mnt);
1028 * All right, let's create it.
1030 err = security_path_mknod(&parent, dentry, mode, 0);
1032 err = vfs_mknod(ns, d_inode(parent.dentry), dentry, mode, 0);
1035 err = mutex_lock_interruptible(&u->bindlock);
1041 addr->hash = UNIX_HASH_SIZE;
1042 hash = d_backing_inode(dentry)->i_ino & (UNIX_HASH_SIZE - 1);
1043 spin_lock(&unix_table_lock);
1044 u->path.mnt = mntget(parent.mnt);
1045 u->path.dentry = dget(dentry);
1046 __unix_set_addr(sk, addr, hash);
1047 spin_unlock(&unix_table_lock);
1048 mutex_unlock(&u->bindlock);
1049 done_path_create(&parent, dentry);
1053 mutex_unlock(&u->bindlock);
1056 /* failed after successful mknod? unlink what we'd created... */
1057 vfs_unlink(ns, d_inode(parent.dentry), dentry, NULL);
1059 done_path_create(&parent, dentry);
1063 static int unix_bind_abstract(struct sock *sk, struct unix_address *addr)
1065 struct unix_sock *u = unix_sk(sk);
1068 err = mutex_lock_interruptible(&u->bindlock);
1073 mutex_unlock(&u->bindlock);
1077 spin_lock(&unix_table_lock);
1078 if (__unix_find_socket_byname(sock_net(sk), addr->name, addr->len,
1080 spin_unlock(&unix_table_lock);
1081 mutex_unlock(&u->bindlock);
1084 __unix_set_addr(sk, addr, addr->hash);
1085 spin_unlock(&unix_table_lock);
1086 mutex_unlock(&u->bindlock);
1090 static int unix_bind(struct socket *sock, struct sockaddr *uaddr, int addr_len)
1092 struct sock *sk = sock->sk;
1093 struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
1094 char *sun_path = sunaddr->sun_path;
1097 struct unix_address *addr;
1099 if (addr_len < offsetofend(struct sockaddr_un, sun_family) ||
1100 sunaddr->sun_family != AF_UNIX)
1103 if (addr_len == sizeof(short))
1104 return unix_autobind(sock);
1106 err = unix_mkname(sunaddr, addr_len, &hash);
1110 addr = kmalloc(sizeof(*addr)+addr_len, GFP_KERNEL);
1114 memcpy(addr->name, sunaddr, addr_len);
1115 addr->len = addr_len;
1116 addr->hash = hash ^ sk->sk_type;
1117 refcount_set(&addr->refcnt, 1);
1120 err = unix_bind_bsd(sk, addr);
1122 err = unix_bind_abstract(sk, addr);
1124 unix_release_addr(addr);
1125 return err == -EEXIST ? -EADDRINUSE : err;
1128 static void unix_state_double_lock(struct sock *sk1, struct sock *sk2)
1130 if (unlikely(sk1 == sk2) || !sk2) {
1131 unix_state_lock(sk1);
1135 unix_state_lock(sk1);
1136 unix_state_lock_nested(sk2);
1138 unix_state_lock(sk2);
1139 unix_state_lock_nested(sk1);
1143 static void unix_state_double_unlock(struct sock *sk1, struct sock *sk2)
1145 if (unlikely(sk1 == sk2) || !sk2) {
1146 unix_state_unlock(sk1);
1149 unix_state_unlock(sk1);
1150 unix_state_unlock(sk2);
1153 static int unix_dgram_connect(struct socket *sock, struct sockaddr *addr,
1154 int alen, int flags)
1156 struct sock *sk = sock->sk;
1157 struct net *net = sock_net(sk);
1158 struct sockaddr_un *sunaddr = (struct sockaddr_un *)addr;
1164 if (alen < offsetofend(struct sockaddr, sa_family))
1167 if (addr->sa_family != AF_UNSPEC) {
1168 err = unix_mkname(sunaddr, alen, &hash);
1173 if (test_bit(SOCK_PASSCRED, &sock->flags) &&
1174 !unix_sk(sk)->addr && (err = unix_autobind(sock)) != 0)
1178 other = unix_find_other(net, sunaddr, alen, sock->type, hash, &err);
1182 unix_state_double_lock(sk, other);
1184 /* Apparently VFS overslept socket death. Retry. */
1185 if (sock_flag(other, SOCK_DEAD)) {
1186 unix_state_double_unlock(sk, other);
1192 if (!unix_may_send(sk, other))
1195 err = security_unix_may_send(sk->sk_socket, other->sk_socket);
1201 * 1003.1g breaking connected state with AF_UNSPEC
1204 unix_state_double_lock(sk, other);
1208 * If it was connected, reconnect.
1210 if (unix_peer(sk)) {
1211 struct sock *old_peer = unix_peer(sk);
1212 unix_peer(sk) = other;
1213 unix_dgram_peer_wake_disconnect_wakeup(sk, old_peer);
1215 unix_state_double_unlock(sk, other);
1217 if (other != old_peer)
1218 unix_dgram_disconnected(sk, old_peer);
1221 unix_peer(sk) = other;
1222 unix_state_double_unlock(sk, other);
1226 sk->sk_state = other->sk_state = TCP_ESTABLISHED;
1230 unix_state_double_unlock(sk, other);
1236 static long unix_wait_for_peer(struct sock *other, long timeo)
1237 __releases(&unix_sk(other)->lock)
1239 struct unix_sock *u = unix_sk(other);
1243 prepare_to_wait_exclusive(&u->peer_wait, &wait, TASK_INTERRUPTIBLE);
1245 sched = !sock_flag(other, SOCK_DEAD) &&
1246 !(other->sk_shutdown & RCV_SHUTDOWN) &&
1247 unix_recvq_full(other);
1249 unix_state_unlock(other);
1252 timeo = schedule_timeout(timeo);
1254 finish_wait(&u->peer_wait, &wait);
1258 static int unix_stream_connect(struct socket *sock, struct sockaddr *uaddr,
1259 int addr_len, int flags)
1261 struct sockaddr_un *sunaddr = (struct sockaddr_un *)uaddr;
1262 struct sock *sk = sock->sk;
1263 struct net *net = sock_net(sk);
1264 struct unix_sock *u = unix_sk(sk), *newu, *otheru;
1265 struct sock *newsk = NULL;
1266 struct sock *other = NULL;
1267 struct sk_buff *skb = NULL;
1273 err = unix_mkname(sunaddr, addr_len, &hash);
1278 if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr &&
1279 (err = unix_autobind(sock)) != 0)
1282 timeo = sock_sndtimeo(sk, flags & O_NONBLOCK);
1284 /* First of all allocate resources.
1285 If we will make it after state is locked,
1286 we will have to recheck all again in any case.
1291 /* create new sock for complete connection */
1292 newsk = unix_create1(sock_net(sk), NULL, 0);
1296 /* Allocate skb for sending to listening sock */
1297 skb = sock_wmalloc(newsk, 1, 0, GFP_KERNEL);
1302 /* Find listening sock. */
1303 other = unix_find_other(net, sunaddr, addr_len, sk->sk_type, hash, &err);
1307 /* Latch state of peer */
1308 unix_state_lock(other);
1310 /* Apparently VFS overslept socket death. Retry. */
1311 if (sock_flag(other, SOCK_DEAD)) {
1312 unix_state_unlock(other);
1317 err = -ECONNREFUSED;
1318 if (other->sk_state != TCP_LISTEN)
1320 if (other->sk_shutdown & RCV_SHUTDOWN)
1323 if (unix_recvq_full(other)) {
1328 timeo = unix_wait_for_peer(other, timeo);
1330 err = sock_intr_errno(timeo);
1331 if (signal_pending(current))
1339 It is tricky place. We need to grab our state lock and cannot
1340 drop lock on peer. It is dangerous because deadlock is
1341 possible. Connect to self case and simultaneous
1342 attempt to connect are eliminated by checking socket
1343 state. other is TCP_LISTEN, if sk is TCP_LISTEN we
1344 check this before attempt to grab lock.
1346 Well, and we have to recheck the state after socket locked.
1352 /* This is ok... continue with connect */
1354 case TCP_ESTABLISHED:
1355 /* Socket is already connected */
1363 unix_state_lock_nested(sk);
1365 if (sk->sk_state != st) {
1366 unix_state_unlock(sk);
1367 unix_state_unlock(other);
1372 err = security_unix_stream_connect(sk, other, newsk);
1374 unix_state_unlock(sk);
1378 /* The way is open! Fastly set all the necessary fields... */
1381 unix_peer(newsk) = sk;
1382 newsk->sk_state = TCP_ESTABLISHED;
1383 newsk->sk_type = sk->sk_type;
1384 init_peercred(newsk);
1385 newu = unix_sk(newsk);
1386 RCU_INIT_POINTER(newsk->sk_wq, &newu->peer_wq);
1387 otheru = unix_sk(other);
1389 /* copy address information from listening to new sock
1391 * The contents of *(otheru->addr) and otheru->path
1392 * are seen fully set up here, since we have found
1393 * otheru in hash under unix_table_lock. Insertion
1394 * into the hash chain we'd found it in had been done
1395 * in an earlier critical area protected by unix_table_lock,
1396 * the same one where we'd set *(otheru->addr) contents,
1397 * as well as otheru->path and otheru->addr itself.
1399 * Using smp_store_release() here to set newu->addr
1400 * is enough to make those stores, as well as stores
1401 * to newu->path visible to anyone who gets newu->addr
1402 * by smp_load_acquire(). IOW, the same warranties
1403 * as for unix_sock instances bound in unix_bind() or
1404 * in unix_autobind().
1406 if (otheru->path.dentry) {
1407 path_get(&otheru->path);
1408 newu->path = otheru->path;
1410 refcount_inc(&otheru->addr->refcnt);
1411 smp_store_release(&newu->addr, otheru->addr);
1413 /* Set credentials */
1414 copy_peercred(sk, other);
1416 sock->state = SS_CONNECTED;
1417 sk->sk_state = TCP_ESTABLISHED;
1420 smp_mb__after_atomic(); /* sock_hold() does an atomic_inc() */
1421 unix_peer(sk) = newsk;
1423 unix_state_unlock(sk);
1425 /* take ten and send info to listening sock */
1426 spin_lock(&other->sk_receive_queue.lock);
1427 __skb_queue_tail(&other->sk_receive_queue, skb);
1428 spin_unlock(&other->sk_receive_queue.lock);
1429 unix_state_unlock(other);
1430 other->sk_data_ready(other);
1436 unix_state_unlock(other);
1441 unix_release_sock(newsk, 0);
1447 static int unix_socketpair(struct socket *socka, struct socket *sockb)
1449 struct sock *ska = socka->sk, *skb = sockb->sk;
1451 /* Join our sockets back to back */
1454 unix_peer(ska) = skb;
1455 unix_peer(skb) = ska;
1459 ska->sk_state = TCP_ESTABLISHED;
1460 skb->sk_state = TCP_ESTABLISHED;
1461 socka->state = SS_CONNECTED;
1462 sockb->state = SS_CONNECTED;
1466 static void unix_sock_inherit_flags(const struct socket *old,
1469 if (test_bit(SOCK_PASSCRED, &old->flags))
1470 set_bit(SOCK_PASSCRED, &new->flags);
1471 if (test_bit(SOCK_PASSSEC, &old->flags))
1472 set_bit(SOCK_PASSSEC, &new->flags);
1475 static int unix_accept(struct socket *sock, struct socket *newsock, int flags,
1478 struct sock *sk = sock->sk;
1480 struct sk_buff *skb;
1484 if (sock->type != SOCK_STREAM && sock->type != SOCK_SEQPACKET)
1488 if (sk->sk_state != TCP_LISTEN)
1491 /* If socket state is TCP_LISTEN it cannot change (for now...),
1492 * so that no locks are necessary.
1495 skb = skb_recv_datagram(sk, 0, flags&O_NONBLOCK, &err);
1497 /* This means receive shutdown. */
1504 skb_free_datagram(sk, skb);
1505 wake_up_interruptible(&unix_sk(sk)->peer_wait);
1507 /* attach accepted sock to socket */
1508 unix_state_lock(tsk);
1509 newsock->state = SS_CONNECTED;
1510 unix_sock_inherit_flags(sock, newsock);
1511 sock_graft(tsk, newsock);
1512 unix_state_unlock(tsk);
1520 static int unix_getname(struct socket *sock, struct sockaddr *uaddr, int peer)
1522 struct sock *sk = sock->sk;
1523 struct unix_address *addr;
1524 DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, uaddr);
1528 sk = unix_peer_get(sk);
1538 addr = smp_load_acquire(&unix_sk(sk)->addr);
1540 sunaddr->sun_family = AF_UNIX;
1541 sunaddr->sun_path[0] = 0;
1542 err = sizeof(short);
1545 memcpy(sunaddr, addr->name, addr->len);
1552 static void unix_peek_fds(struct scm_cookie *scm, struct sk_buff *skb)
1554 scm->fp = scm_fp_dup(UNIXCB(skb).fp);
1557 * Garbage collection of unix sockets starts by selecting a set of
1558 * candidate sockets which have reference only from being in flight
1559 * (total_refs == inflight_refs). This condition is checked once during
1560 * the candidate collection phase, and candidates are marked as such, so
1561 * that non-candidates can later be ignored. While inflight_refs is
1562 * protected by unix_gc_lock, total_refs (file count) is not, hence this
1563 * is an instantaneous decision.
1565 * Once a candidate, however, the socket must not be reinstalled into a
1566 * file descriptor while the garbage collection is in progress.
1568 * If the above conditions are met, then the directed graph of
1569 * candidates (*) does not change while unix_gc_lock is held.
1571 * Any operations that changes the file count through file descriptors
1572 * (dup, close, sendmsg) does not change the graph since candidates are
1573 * not installed in fds.
1575 * Dequeing a candidate via recvmsg would install it into an fd, but
1576 * that takes unix_gc_lock to decrement the inflight count, so it's
1577 * serialized with garbage collection.
1579 * MSG_PEEK is special in that it does not change the inflight count,
1580 * yet does install the socket into an fd. The following lock/unlock
1581 * pair is to ensure serialization with garbage collection. It must be
1582 * done between incrementing the file count and installing the file into
1585 * If garbage collection starts after the barrier provided by the
1586 * lock/unlock, then it will see the elevated refcount and not mark this
1587 * as a candidate. If a garbage collection is already in progress
1588 * before the file count was incremented, then the lock/unlock pair will
1589 * ensure that garbage collection is finished before progressing to
1590 * installing the fd.
1592 * (*) A -> B where B is on the queue of A or B is on the queue of C
1593 * which is on the queue of listening socket A.
1595 spin_lock(&unix_gc_lock);
1596 spin_unlock(&unix_gc_lock);
1599 static int unix_scm_to_skb(struct scm_cookie *scm, struct sk_buff *skb, bool send_fds)
1603 UNIXCB(skb).pid = get_pid(scm->pid);
1604 UNIXCB(skb).uid = scm->creds.uid;
1605 UNIXCB(skb).gid = scm->creds.gid;
1606 UNIXCB(skb).fp = NULL;
1607 unix_get_secdata(scm, skb);
1608 if (scm->fp && send_fds)
1609 err = unix_attach_fds(scm, skb);
1611 skb->destructor = unix_destruct_scm;
1615 static bool unix_passcred_enabled(const struct socket *sock,
1616 const struct sock *other)
1618 return test_bit(SOCK_PASSCRED, &sock->flags) ||
1619 !other->sk_socket ||
1620 test_bit(SOCK_PASSCRED, &other->sk_socket->flags);
1624 * Some apps rely on write() giving SCM_CREDENTIALS
1625 * We include credentials if source or destination socket
1626 * asserted SOCK_PASSCRED.
1628 static void maybe_add_creds(struct sk_buff *skb, const struct socket *sock,
1629 const struct sock *other)
1631 if (UNIXCB(skb).pid)
1633 if (unix_passcred_enabled(sock, other)) {
1634 UNIXCB(skb).pid = get_pid(task_tgid(current));
1635 current_uid_gid(&UNIXCB(skb).uid, &UNIXCB(skb).gid);
1639 static int maybe_init_creds(struct scm_cookie *scm,
1640 struct socket *socket,
1641 const struct sock *other)
1644 struct msghdr msg = { .msg_controllen = 0 };
1646 err = scm_send(socket, &msg, scm, false);
1650 if (unix_passcred_enabled(socket, other)) {
1651 scm->pid = get_pid(task_tgid(current));
1652 current_uid_gid(&scm->creds.uid, &scm->creds.gid);
1657 static bool unix_skb_scm_eq(struct sk_buff *skb,
1658 struct scm_cookie *scm)
1660 const struct unix_skb_parms *u = &UNIXCB(skb);
1662 return u->pid == scm->pid &&
1663 uid_eq(u->uid, scm->creds.uid) &&
1664 gid_eq(u->gid, scm->creds.gid) &&
1665 unix_secdata_eq(scm, skb);
1668 static void scm_stat_add(struct sock *sk, struct sk_buff *skb)
1670 struct scm_fp_list *fp = UNIXCB(skb).fp;
1671 struct unix_sock *u = unix_sk(sk);
1673 if (unlikely(fp && fp->count))
1674 atomic_add(fp->count, &u->scm_stat.nr_fds);
1677 static void scm_stat_del(struct sock *sk, struct sk_buff *skb)
1679 struct scm_fp_list *fp = UNIXCB(skb).fp;
1680 struct unix_sock *u = unix_sk(sk);
1682 if (unlikely(fp && fp->count))
1683 atomic_sub(fp->count, &u->scm_stat.nr_fds);
1687 * Send AF_UNIX data.
1690 static int unix_dgram_sendmsg(struct socket *sock, struct msghdr *msg,
1693 struct sock *sk = sock->sk;
1694 struct net *net = sock_net(sk);
1695 struct unix_sock *u = unix_sk(sk);
1696 DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr, msg->msg_name);
1697 struct sock *other = NULL;
1698 int namelen = 0; /* fake GCC */
1701 struct sk_buff *skb;
1703 struct scm_cookie scm;
1708 err = scm_send(sock, msg, &scm, false);
1713 if (msg->msg_flags&MSG_OOB)
1716 if (msg->msg_namelen) {
1717 err = unix_mkname(sunaddr, msg->msg_namelen, &hash);
1724 other = unix_peer_get(sk);
1729 if (test_bit(SOCK_PASSCRED, &sock->flags) && !u->addr
1730 && (err = unix_autobind(sock)) != 0)
1734 if (len > sk->sk_sndbuf - 32)
1737 if (len > SKB_MAX_ALLOC) {
1738 data_len = min_t(size_t,
1739 len - SKB_MAX_ALLOC,
1740 MAX_SKB_FRAGS * PAGE_SIZE);
1741 data_len = PAGE_ALIGN(data_len);
1743 BUILD_BUG_ON(SKB_MAX_ALLOC < PAGE_SIZE);
1746 skb = sock_alloc_send_pskb(sk, len - data_len, data_len,
1747 msg->msg_flags & MSG_DONTWAIT, &err,
1748 PAGE_ALLOC_COSTLY_ORDER);
1752 err = unix_scm_to_skb(&scm, skb, true);
1756 skb_put(skb, len - data_len);
1757 skb->data_len = data_len;
1759 err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, len);
1763 timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1768 if (sunaddr == NULL)
1771 other = unix_find_other(net, sunaddr, namelen, sk->sk_type,
1777 if (sk_filter(other, skb) < 0) {
1778 /* Toss the packet but do not return any error to the sender */
1784 unix_state_lock(other);
1787 if (!unix_may_send(sk, other))
1790 if (unlikely(sock_flag(other, SOCK_DEAD))) {
1792 * Check with 1003.1g - what should
1795 unix_state_unlock(other);
1799 unix_state_lock(sk);
1802 if (unix_peer(sk) == other) {
1803 unix_peer(sk) = NULL;
1804 unix_dgram_peer_wake_disconnect_wakeup(sk, other);
1806 unix_state_unlock(sk);
1808 unix_dgram_disconnected(sk, other);
1810 err = -ECONNREFUSED;
1812 unix_state_unlock(sk);
1822 if (other->sk_shutdown & RCV_SHUTDOWN)
1825 if (sk->sk_type != SOCK_SEQPACKET) {
1826 err = security_unix_may_send(sk->sk_socket, other->sk_socket);
1831 /* other == sk && unix_peer(other) != sk if
1832 * - unix_peer(sk) == NULL, destination address bound to sk
1833 * - unix_peer(sk) == sk by time of get but disconnected before lock
1836 unlikely(unix_peer(other) != sk &&
1837 unix_recvq_full_lockless(other))) {
1839 timeo = unix_wait_for_peer(other, timeo);
1841 err = sock_intr_errno(timeo);
1842 if (signal_pending(current))
1849 unix_state_unlock(other);
1850 unix_state_double_lock(sk, other);
1853 if (unix_peer(sk) != other ||
1854 unix_dgram_peer_wake_me(sk, other)) {
1862 goto restart_locked;
1866 if (unlikely(sk_locked))
1867 unix_state_unlock(sk);
1869 if (sock_flag(other, SOCK_RCVTSTAMP))
1870 __net_timestamp(skb);
1871 maybe_add_creds(skb, sock, other);
1872 scm_stat_add(other, skb);
1873 skb_queue_tail(&other->sk_receive_queue, skb);
1874 unix_state_unlock(other);
1875 other->sk_data_ready(other);
1882 unix_state_unlock(sk);
1883 unix_state_unlock(other);
1893 /* We use paged skbs for stream sockets, and limit occupancy to 32768
1894 * bytes, and a minimum of a full page.
1896 #define UNIX_SKB_FRAGS_SZ (PAGE_SIZE << get_order(32768))
1898 #if (IS_ENABLED(CONFIG_AF_UNIX_OOB))
1899 static int queue_oob(struct socket *sock, struct msghdr *msg, struct sock *other)
1901 struct unix_sock *ousk = unix_sk(other);
1902 struct sk_buff *skb;
1905 skb = sock_alloc_send_skb(sock->sk, 1, msg->msg_flags & MSG_DONTWAIT, &err);
1912 err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, 1);
1919 unix_state_lock(other);
1920 maybe_add_creds(skb, sock, other);
1924 kfree_skb(ousk->oob_skb);
1926 ousk->oob_skb = skb;
1928 scm_stat_add(other, skb);
1929 skb_queue_tail(&other->sk_receive_queue, skb);
1930 sk_send_sigurg(other);
1931 unix_state_unlock(other);
1932 other->sk_data_ready(other);
1938 static int unix_stream_sendmsg(struct socket *sock, struct msghdr *msg,
1941 struct sock *sk = sock->sk;
1942 struct sock *other = NULL;
1944 struct sk_buff *skb;
1946 struct scm_cookie scm;
1947 bool fds_sent = false;
1951 err = scm_send(sock, msg, &scm, false);
1956 if (msg->msg_flags & MSG_OOB) {
1957 #if (IS_ENABLED(CONFIG_AF_UNIX_OOB))
1965 if (msg->msg_namelen) {
1966 err = sk->sk_state == TCP_ESTABLISHED ? -EISCONN : -EOPNOTSUPP;
1970 other = unix_peer(sk);
1975 if (sk->sk_shutdown & SEND_SHUTDOWN)
1978 while (sent < len) {
1981 /* Keep two messages in the pipe so it schedules better */
1982 size = min_t(int, size, (sk->sk_sndbuf >> 1) - 64);
1984 /* allow fallback to order-0 allocations */
1985 size = min_t(int, size, SKB_MAX_HEAD(0) + UNIX_SKB_FRAGS_SZ);
1987 data_len = max_t(int, 0, size - SKB_MAX_HEAD(0));
1989 data_len = min_t(size_t, size, PAGE_ALIGN(data_len));
1991 skb = sock_alloc_send_pskb(sk, size - data_len, data_len,
1992 msg->msg_flags & MSG_DONTWAIT, &err,
1993 get_order(UNIX_SKB_FRAGS_SZ));
1997 /* Only send the fds in the first buffer */
1998 err = unix_scm_to_skb(&scm, skb, !fds_sent);
2005 skb_put(skb, size - data_len);
2006 skb->data_len = data_len;
2008 err = skb_copy_datagram_from_iter(skb, 0, &msg->msg_iter, size);
2014 unix_state_lock(other);
2016 if (sock_flag(other, SOCK_DEAD) ||
2017 (other->sk_shutdown & RCV_SHUTDOWN))
2020 maybe_add_creds(skb, sock, other);
2021 scm_stat_add(other, skb);
2022 skb_queue_tail(&other->sk_receive_queue, skb);
2023 unix_state_unlock(other);
2024 other->sk_data_ready(other);
2028 #if (IS_ENABLED(CONFIG_AF_UNIX_OOB))
2029 if (msg->msg_flags & MSG_OOB) {
2030 err = queue_oob(sock, msg, other);
2042 unix_state_unlock(other);
2045 if (sent == 0 && !(msg->msg_flags&MSG_NOSIGNAL))
2046 send_sig(SIGPIPE, current, 0);
2050 return sent ? : err;
2053 static ssize_t unix_stream_sendpage(struct socket *socket, struct page *page,
2054 int offset, size_t size, int flags)
2057 bool send_sigpipe = false;
2058 bool init_scm = true;
2059 struct scm_cookie scm;
2060 struct sock *other, *sk = socket->sk;
2061 struct sk_buff *skb, *newskb = NULL, *tail = NULL;
2063 if (flags & MSG_OOB)
2066 other = unix_peer(sk);
2067 if (!other || sk->sk_state != TCP_ESTABLISHED)
2072 unix_state_unlock(other);
2073 mutex_unlock(&unix_sk(other)->iolock);
2074 newskb = sock_alloc_send_pskb(sk, 0, 0, flags & MSG_DONTWAIT,
2080 /* we must acquire iolock as we modify already present
2081 * skbs in the sk_receive_queue and mess with skb->len
2083 err = mutex_lock_interruptible(&unix_sk(other)->iolock);
2085 err = flags & MSG_DONTWAIT ? -EAGAIN : -ERESTARTSYS;
2089 if (sk->sk_shutdown & SEND_SHUTDOWN) {
2091 send_sigpipe = true;
2095 unix_state_lock(other);
2097 if (sock_flag(other, SOCK_DEAD) ||
2098 other->sk_shutdown & RCV_SHUTDOWN) {
2100 send_sigpipe = true;
2101 goto err_state_unlock;
2105 err = maybe_init_creds(&scm, socket, other);
2107 goto err_state_unlock;
2111 skb = skb_peek_tail(&other->sk_receive_queue);
2112 if (tail && tail == skb) {
2114 } else if (!skb || !unix_skb_scm_eq(skb, &scm)) {
2121 } else if (newskb) {
2122 /* this is fast path, we don't necessarily need to
2123 * call to kfree_skb even though with newskb == NULL
2124 * this - does no harm
2126 consume_skb(newskb);
2130 if (skb_append_pagefrags(skb, page, offset, size)) {
2136 skb->data_len += size;
2137 skb->truesize += size;
2138 refcount_add(size, &sk->sk_wmem_alloc);
2141 err = unix_scm_to_skb(&scm, skb, false);
2143 goto err_state_unlock;
2144 spin_lock(&other->sk_receive_queue.lock);
2145 __skb_queue_tail(&other->sk_receive_queue, newskb);
2146 spin_unlock(&other->sk_receive_queue.lock);
2149 unix_state_unlock(other);
2150 mutex_unlock(&unix_sk(other)->iolock);
2152 other->sk_data_ready(other);
2157 unix_state_unlock(other);
2159 mutex_unlock(&unix_sk(other)->iolock);
2162 if (send_sigpipe && !(flags & MSG_NOSIGNAL))
2163 send_sig(SIGPIPE, current, 0);
2169 static int unix_seqpacket_sendmsg(struct socket *sock, struct msghdr *msg,
2173 struct sock *sk = sock->sk;
2175 err = sock_error(sk);
2179 if (sk->sk_state != TCP_ESTABLISHED)
2182 if (msg->msg_namelen)
2183 msg->msg_namelen = 0;
2185 return unix_dgram_sendmsg(sock, msg, len);
2188 static int unix_seqpacket_recvmsg(struct socket *sock, struct msghdr *msg,
2189 size_t size, int flags)
2191 struct sock *sk = sock->sk;
2193 if (sk->sk_state != TCP_ESTABLISHED)
2196 return unix_dgram_recvmsg(sock, msg, size, flags);
2199 static void unix_copy_addr(struct msghdr *msg, struct sock *sk)
2201 struct unix_address *addr = smp_load_acquire(&unix_sk(sk)->addr);
2204 msg->msg_namelen = addr->len;
2205 memcpy(msg->msg_name, addr->name, addr->len);
2209 int __unix_dgram_recvmsg(struct sock *sk, struct msghdr *msg, size_t size,
2212 struct scm_cookie scm;
2213 struct socket *sock = sk->sk_socket;
2214 struct unix_sock *u = unix_sk(sk);
2215 struct sk_buff *skb, *last;
2224 timeo = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
2227 mutex_lock(&u->iolock);
2229 skip = sk_peek_offset(sk, flags);
2230 skb = __skb_try_recv_datagram(sk, &sk->sk_receive_queue, flags,
2231 &skip, &err, &last);
2233 if (!(flags & MSG_PEEK))
2234 scm_stat_del(sk, skb);
2238 mutex_unlock(&u->iolock);
2243 !__skb_wait_for_more_packets(sk, &sk->sk_receive_queue,
2244 &err, &timeo, last));
2246 if (!skb) { /* implies iolock unlocked */
2247 unix_state_lock(sk);
2248 /* Signal EOF on disconnected non-blocking SEQPACKET socket. */
2249 if (sk->sk_type == SOCK_SEQPACKET && err == -EAGAIN &&
2250 (sk->sk_shutdown & RCV_SHUTDOWN))
2252 unix_state_unlock(sk);
2256 if (wq_has_sleeper(&u->peer_wait))
2257 wake_up_interruptible_sync_poll(&u->peer_wait,
2258 EPOLLOUT | EPOLLWRNORM |
2262 unix_copy_addr(msg, skb->sk);
2264 if (size > skb->len - skip)
2265 size = skb->len - skip;
2266 else if (size < skb->len - skip)
2267 msg->msg_flags |= MSG_TRUNC;
2269 err = skb_copy_datagram_msg(skb, skip, msg, size);
2273 if (sock_flag(sk, SOCK_RCVTSTAMP))
2274 __sock_recv_timestamp(msg, sk, skb);
2276 memset(&scm, 0, sizeof(scm));
2278 scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
2279 unix_set_secdata(&scm, skb);
2281 if (!(flags & MSG_PEEK)) {
2283 unix_detach_fds(&scm, skb);
2285 sk_peek_offset_bwd(sk, skb->len);
2287 /* It is questionable: on PEEK we could:
2288 - do not return fds - good, but too simple 8)
2289 - return fds, and do not return them on read (old strategy,
2291 - clone fds (I chose it for now, it is the most universal
2294 POSIX 1003.1g does not actually define this clearly
2295 at all. POSIX 1003.1g doesn't define a lot of things
2300 sk_peek_offset_fwd(sk, size);
2303 unix_peek_fds(&scm, skb);
2305 err = (flags & MSG_TRUNC) ? skb->len - skip : size;
2307 scm_recv(sock, msg, &scm, flags);
2310 skb_free_datagram(sk, skb);
2311 mutex_unlock(&u->iolock);
2316 static int unix_dgram_recvmsg(struct socket *sock, struct msghdr *msg, size_t size,
2319 struct sock *sk = sock->sk;
2321 #ifdef CONFIG_BPF_SYSCALL
2322 if (sk->sk_prot != &unix_proto)
2323 return sk->sk_prot->recvmsg(sk, msg, size, flags & MSG_DONTWAIT,
2324 flags & ~MSG_DONTWAIT, NULL);
2326 return __unix_dgram_recvmsg(sk, msg, size, flags);
2329 static int unix_read_sock(struct sock *sk, read_descriptor_t *desc,
2330 sk_read_actor_t recv_actor)
2335 struct unix_sock *u = unix_sk(sk);
2336 struct sk_buff *skb;
2339 mutex_lock(&u->iolock);
2340 skb = skb_recv_datagram(sk, 0, 1, &err);
2341 mutex_unlock(&u->iolock);
2345 used = recv_actor(desc, skb, 0, skb->len);
2351 } else if (used <= skb->len) {
2364 * Sleep until more data has arrived. But check for races..
2366 static long unix_stream_data_wait(struct sock *sk, long timeo,
2367 struct sk_buff *last, unsigned int last_len,
2370 struct sk_buff *tail;
2373 unix_state_lock(sk);
2376 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
2378 tail = skb_peek_tail(&sk->sk_receive_queue);
2380 (tail && tail->len != last_len) ||
2382 (sk->sk_shutdown & RCV_SHUTDOWN) ||
2383 signal_pending(current) ||
2387 sk_set_bit(SOCKWQ_ASYNC_WAITDATA, sk);
2388 unix_state_unlock(sk);
2390 timeo = freezable_schedule_timeout(timeo);
2392 timeo = schedule_timeout(timeo);
2393 unix_state_lock(sk);
2395 if (sock_flag(sk, SOCK_DEAD))
2398 sk_clear_bit(SOCKWQ_ASYNC_WAITDATA, sk);
2401 finish_wait(sk_sleep(sk), &wait);
2402 unix_state_unlock(sk);
2406 static unsigned int unix_skb_len(const struct sk_buff *skb)
2408 return skb->len - UNIXCB(skb).consumed;
2411 struct unix_stream_read_state {
2412 int (*recv_actor)(struct sk_buff *, int, int,
2413 struct unix_stream_read_state *);
2414 struct socket *socket;
2416 struct pipe_inode_info *pipe;
2419 unsigned int splice_flags;
2422 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2423 static int unix_stream_recv_urg(struct unix_stream_read_state *state)
2425 struct socket *sock = state->socket;
2426 struct sock *sk = sock->sk;
2427 struct unix_sock *u = unix_sk(sk);
2430 if (sock_flag(sk, SOCK_URGINLINE) || !u->oob_skb)
2433 chunk = state->recv_actor(u->oob_skb, 0, chunk, state);
2437 if (!(state->flags & MSG_PEEK)) {
2438 UNIXCB(u->oob_skb).consumed += 1;
2439 kfree_skb(u->oob_skb);
2442 state->msg->msg_flags |= MSG_OOB;
2446 static struct sk_buff *manage_oob(struct sk_buff *skb, struct sock *sk,
2447 int flags, int copied)
2449 struct unix_sock *u = unix_sk(sk);
2451 if (!unix_skb_len(skb) && !(flags & MSG_PEEK)) {
2452 skb_unlink(skb, &sk->sk_receive_queue);
2456 if (skb == u->oob_skb) {
2459 } else if (sock_flag(sk, SOCK_URGINLINE)) {
2460 if (!(flags & MSG_PEEK)) {
2464 } else if (!(flags & MSG_PEEK)) {
2465 skb_unlink(skb, &sk->sk_receive_queue);
2467 skb = skb_peek(&sk->sk_receive_queue);
2475 static int unix_stream_read_generic(struct unix_stream_read_state *state,
2478 struct scm_cookie scm;
2479 struct socket *sock = state->socket;
2480 struct sock *sk = sock->sk;
2481 struct unix_sock *u = unix_sk(sk);
2483 int flags = state->flags;
2484 int noblock = flags & MSG_DONTWAIT;
2485 bool check_creds = false;
2490 size_t size = state->size;
2491 unsigned int last_len;
2493 if (unlikely(sk->sk_state != TCP_ESTABLISHED)) {
2498 if (unlikely(flags & MSG_OOB)) {
2500 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2501 mutex_lock(&u->iolock);
2502 unix_state_lock(sk);
2504 err = unix_stream_recv_urg(state);
2506 unix_state_unlock(sk);
2507 mutex_unlock(&u->iolock);
2512 target = sock_rcvlowat(sk, flags & MSG_WAITALL, size);
2513 timeo = sock_rcvtimeo(sk, noblock);
2515 memset(&scm, 0, sizeof(scm));
2517 /* Lock the socket to prevent queue disordering
2518 * while sleeps in memcpy_tomsg
2520 mutex_lock(&u->iolock);
2522 skip = max(sk_peek_offset(sk, flags), 0);
2527 struct sk_buff *skb, *last;
2530 unix_state_lock(sk);
2531 if (sock_flag(sk, SOCK_DEAD)) {
2535 last = skb = skb_peek(&sk->sk_receive_queue);
2536 last_len = last ? last->len : 0;
2538 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2540 skb = manage_oob(skb, sk, flags, copied);
2542 unix_state_unlock(sk);
2551 if (copied >= target)
2555 * POSIX 1003.1g mandates this order.
2558 err = sock_error(sk);
2561 if (sk->sk_shutdown & RCV_SHUTDOWN)
2564 unix_state_unlock(sk);
2570 mutex_unlock(&u->iolock);
2572 timeo = unix_stream_data_wait(sk, timeo, last,
2573 last_len, freezable);
2575 if (signal_pending(current)) {
2576 err = sock_intr_errno(timeo);
2581 mutex_lock(&u->iolock);
2584 unix_state_unlock(sk);
2588 while (skip >= unix_skb_len(skb)) {
2589 skip -= unix_skb_len(skb);
2591 last_len = skb->len;
2592 skb = skb_peek_next(skb, &sk->sk_receive_queue);
2597 unix_state_unlock(sk);
2600 /* Never glue messages from different writers */
2601 if (!unix_skb_scm_eq(skb, &scm))
2603 } else if (test_bit(SOCK_PASSCRED, &sock->flags)) {
2604 /* Copy credentials */
2605 scm_set_cred(&scm, UNIXCB(skb).pid, UNIXCB(skb).uid, UNIXCB(skb).gid);
2606 unix_set_secdata(&scm, skb);
2610 /* Copy address just once */
2611 if (state->msg && state->msg->msg_name) {
2612 DECLARE_SOCKADDR(struct sockaddr_un *, sunaddr,
2613 state->msg->msg_name);
2614 unix_copy_addr(state->msg, skb->sk);
2618 chunk = min_t(unsigned int, unix_skb_len(skb) - skip, size);
2620 chunk = state->recv_actor(skb, skip, chunk, state);
2621 drop_skb = !unix_skb_len(skb);
2622 /* skb is only safe to use if !drop_skb */
2633 /* the skb was touched by a concurrent reader;
2634 * we should not expect anything from this skb
2635 * anymore and assume it invalid - we can be
2636 * sure it was dropped from the socket queue
2638 * let's report a short read
2644 /* Mark read part of skb as used */
2645 if (!(flags & MSG_PEEK)) {
2646 UNIXCB(skb).consumed += chunk;
2648 sk_peek_offset_bwd(sk, chunk);
2650 if (UNIXCB(skb).fp) {
2651 scm_stat_del(sk, skb);
2652 unix_detach_fds(&scm, skb);
2655 if (unix_skb_len(skb))
2658 skb_unlink(skb, &sk->sk_receive_queue);
2664 /* It is questionable, see note in unix_dgram_recvmsg.
2667 unix_peek_fds(&scm, skb);
2669 sk_peek_offset_fwd(sk, chunk);
2676 last_len = skb->len;
2677 unix_state_lock(sk);
2678 skb = skb_peek_next(skb, &sk->sk_receive_queue);
2681 unix_state_unlock(sk);
2686 mutex_unlock(&u->iolock);
2688 scm_recv(sock, state->msg, &scm, flags);
2692 return copied ? : err;
2695 static int unix_stream_read_actor(struct sk_buff *skb,
2696 int skip, int chunk,
2697 struct unix_stream_read_state *state)
2701 ret = skb_copy_datagram_msg(skb, UNIXCB(skb).consumed + skip,
2703 return ret ?: chunk;
2706 static int unix_stream_recvmsg(struct socket *sock, struct msghdr *msg,
2707 size_t size, int flags)
2709 struct unix_stream_read_state state = {
2710 .recv_actor = unix_stream_read_actor,
2717 return unix_stream_read_generic(&state, true);
2720 static int unix_stream_splice_actor(struct sk_buff *skb,
2721 int skip, int chunk,
2722 struct unix_stream_read_state *state)
2724 return skb_splice_bits(skb, state->socket->sk,
2725 UNIXCB(skb).consumed + skip,
2726 state->pipe, chunk, state->splice_flags);
2729 static ssize_t unix_stream_splice_read(struct socket *sock, loff_t *ppos,
2730 struct pipe_inode_info *pipe,
2731 size_t size, unsigned int flags)
2733 struct unix_stream_read_state state = {
2734 .recv_actor = unix_stream_splice_actor,
2738 .splice_flags = flags,
2741 if (unlikely(*ppos))
2744 if (sock->file->f_flags & O_NONBLOCK ||
2745 flags & SPLICE_F_NONBLOCK)
2746 state.flags = MSG_DONTWAIT;
2748 return unix_stream_read_generic(&state, false);
2751 static int unix_shutdown(struct socket *sock, int mode)
2753 struct sock *sk = sock->sk;
2756 if (mode < SHUT_RD || mode > SHUT_RDWR)
2759 * SHUT_RD (0) -> RCV_SHUTDOWN (1)
2760 * SHUT_WR (1) -> SEND_SHUTDOWN (2)
2761 * SHUT_RDWR (2) -> SHUTDOWN_MASK (3)
2765 unix_state_lock(sk);
2766 sk->sk_shutdown |= mode;
2767 other = unix_peer(sk);
2770 unix_state_unlock(sk);
2771 sk->sk_state_change(sk);
2774 (sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET)) {
2778 if (mode&RCV_SHUTDOWN)
2779 peer_mode |= SEND_SHUTDOWN;
2780 if (mode&SEND_SHUTDOWN)
2781 peer_mode |= RCV_SHUTDOWN;
2782 unix_state_lock(other);
2783 other->sk_shutdown |= peer_mode;
2784 unix_state_unlock(other);
2785 other->sk_state_change(other);
2786 if (peer_mode == SHUTDOWN_MASK)
2787 sk_wake_async(other, SOCK_WAKE_WAITD, POLL_HUP);
2788 else if (peer_mode & RCV_SHUTDOWN)
2789 sk_wake_async(other, SOCK_WAKE_WAITD, POLL_IN);
2797 long unix_inq_len(struct sock *sk)
2799 struct sk_buff *skb;
2802 if (sk->sk_state == TCP_LISTEN)
2805 spin_lock(&sk->sk_receive_queue.lock);
2806 if (sk->sk_type == SOCK_STREAM ||
2807 sk->sk_type == SOCK_SEQPACKET) {
2808 skb_queue_walk(&sk->sk_receive_queue, skb)
2809 amount += unix_skb_len(skb);
2811 skb = skb_peek(&sk->sk_receive_queue);
2815 spin_unlock(&sk->sk_receive_queue.lock);
2819 EXPORT_SYMBOL_GPL(unix_inq_len);
2821 long unix_outq_len(struct sock *sk)
2823 return sk_wmem_alloc_get(sk);
2825 EXPORT_SYMBOL_GPL(unix_outq_len);
2827 static int unix_open_file(struct sock *sk)
2833 if (!ns_capable(sock_net(sk)->user_ns, CAP_NET_ADMIN))
2836 if (!smp_load_acquire(&unix_sk(sk)->addr))
2839 path = unix_sk(sk)->path;
2845 fd = get_unused_fd_flags(O_CLOEXEC);
2849 f = dentry_open(&path, O_PATH, current_cred());
2863 static int unix_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
2865 struct sock *sk = sock->sk;
2871 amount = unix_outq_len(sk);
2872 err = put_user(amount, (int __user *)arg);
2875 amount = unix_inq_len(sk);
2879 err = put_user(amount, (int __user *)arg);
2882 err = unix_open_file(sk);
2884 #if IS_ENABLED(CONFIG_AF_UNIX_OOB)
2887 struct sk_buff *skb;
2888 struct unix_sock *u = unix_sk(sk);
2891 skb = skb_peek(&sk->sk_receive_queue);
2892 if (skb && skb == u->oob_skb)
2894 err = put_user(answ, (int __user *)arg);
2905 #ifdef CONFIG_COMPAT
2906 static int unix_compat_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
2908 return unix_ioctl(sock, cmd, (unsigned long)compat_ptr(arg));
2912 static __poll_t unix_poll(struct file *file, struct socket *sock, poll_table *wait)
2914 struct sock *sk = sock->sk;
2917 sock_poll_wait(file, sock, wait);
2920 /* exceptional events? */
2923 if (sk->sk_shutdown == SHUTDOWN_MASK)
2925 if (sk->sk_shutdown & RCV_SHUTDOWN)
2926 mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
2929 if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
2930 mask |= EPOLLIN | EPOLLRDNORM;
2932 /* Connection-based need to check for termination and startup */
2933 if ((sk->sk_type == SOCK_STREAM || sk->sk_type == SOCK_SEQPACKET) &&
2934 sk->sk_state == TCP_CLOSE)
2938 * we set writable also when the other side has shut down the
2939 * connection. This prevents stuck sockets.
2941 if (unix_writable(sk))
2942 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
2947 static __poll_t unix_dgram_poll(struct file *file, struct socket *sock,
2950 struct sock *sk = sock->sk, *other;
2951 unsigned int writable;
2954 sock_poll_wait(file, sock, wait);
2957 /* exceptional events? */
2958 if (sk->sk_err || !skb_queue_empty_lockless(&sk->sk_error_queue))
2960 (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? EPOLLPRI : 0);
2962 if (sk->sk_shutdown & RCV_SHUTDOWN)
2963 mask |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
2964 if (sk->sk_shutdown == SHUTDOWN_MASK)
2968 if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
2969 mask |= EPOLLIN | EPOLLRDNORM;
2971 /* Connection-based need to check for termination and startup */
2972 if (sk->sk_type == SOCK_SEQPACKET) {
2973 if (sk->sk_state == TCP_CLOSE)
2975 /* connection hasn't started yet? */
2976 if (sk->sk_state == TCP_SYN_SENT)
2980 /* No write status requested, avoid expensive OUT tests. */
2981 if (!(poll_requested_events(wait) & (EPOLLWRBAND|EPOLLWRNORM|EPOLLOUT)))
2984 writable = unix_writable(sk);
2986 unix_state_lock(sk);
2988 other = unix_peer(sk);
2989 if (other && unix_peer(other) != sk &&
2990 unix_recvq_full(other) &&
2991 unix_dgram_peer_wake_me(sk, other))
2994 unix_state_unlock(sk);
2998 mask |= EPOLLOUT | EPOLLWRNORM | EPOLLWRBAND;
3000 sk_set_bit(SOCKWQ_ASYNC_NOSPACE, sk);
3005 #ifdef CONFIG_PROC_FS
3007 #define BUCKET_SPACE (BITS_PER_LONG - (UNIX_HASH_BITS + 1) - 1)
3009 #define get_bucket(x) ((x) >> BUCKET_SPACE)
3010 #define get_offset(x) ((x) & ((1L << BUCKET_SPACE) - 1))
3011 #define set_bucket_offset(b, o) ((b) << BUCKET_SPACE | (o))
3013 static struct sock *unix_from_bucket(struct seq_file *seq, loff_t *pos)
3015 unsigned long offset = get_offset(*pos);
3016 unsigned long bucket = get_bucket(*pos);
3018 unsigned long count = 0;
3020 for (sk = sk_head(&unix_socket_table[bucket]); sk; sk = sk_next(sk)) {
3021 if (sock_net(sk) != seq_file_net(seq))
3023 if (++count == offset)
3030 static struct sock *unix_next_socket(struct seq_file *seq,
3034 unsigned long bucket;
3036 while (sk > (struct sock *)SEQ_START_TOKEN) {
3040 if (sock_net(sk) == seq_file_net(seq))
3045 sk = unix_from_bucket(seq, pos);
3050 bucket = get_bucket(*pos) + 1;
3051 *pos = set_bucket_offset(bucket, 1);
3052 } while (bucket < ARRAY_SIZE(unix_socket_table));
3057 static void *unix_seq_start(struct seq_file *seq, loff_t *pos)
3058 __acquires(unix_table_lock)
3060 spin_lock(&unix_table_lock);
3063 return SEQ_START_TOKEN;
3065 if (get_bucket(*pos) >= ARRAY_SIZE(unix_socket_table))
3068 return unix_next_socket(seq, NULL, pos);
3071 static void *unix_seq_next(struct seq_file *seq, void *v, loff_t *pos)
3074 return unix_next_socket(seq, v, pos);
3077 static void unix_seq_stop(struct seq_file *seq, void *v)
3078 __releases(unix_table_lock)
3080 spin_unlock(&unix_table_lock);
3083 static int unix_seq_show(struct seq_file *seq, void *v)
3086 if (v == SEQ_START_TOKEN)
3087 seq_puts(seq, "Num RefCount Protocol Flags Type St "
3091 struct unix_sock *u = unix_sk(s);
3094 seq_printf(seq, "%pK: %08X %08X %08X %04X %02X %5lu",
3096 refcount_read(&s->sk_refcnt),
3098 s->sk_state == TCP_LISTEN ? __SO_ACCEPTCON : 0,
3101 (s->sk_state == TCP_ESTABLISHED ? SS_CONNECTED : SS_UNCONNECTED) :
3102 (s->sk_state == TCP_ESTABLISHED ? SS_CONNECTING : SS_DISCONNECTING),
3105 if (u->addr) { // under unix_table_lock here
3110 len = u->addr->len - sizeof(short);
3111 if (!UNIX_ABSTRACT(s))
3117 for ( ; i < len; i++)
3118 seq_putc(seq, u->addr->name->sun_path[i] ?:
3121 unix_state_unlock(s);
3122 seq_putc(seq, '\n');
3128 static const struct seq_operations unix_seq_ops = {
3129 .start = unix_seq_start,
3130 .next = unix_seq_next,
3131 .stop = unix_seq_stop,
3132 .show = unix_seq_show,
3136 static const struct net_proto_family unix_family_ops = {
3138 .create = unix_create,
3139 .owner = THIS_MODULE,
3143 static int __net_init unix_net_init(struct net *net)
3145 int error = -ENOMEM;
3147 net->unx.sysctl_max_dgram_qlen = 10;
3148 if (unix_sysctl_register(net))
3151 #ifdef CONFIG_PROC_FS
3152 if (!proc_create_net("unix", 0, net->proc_net, &unix_seq_ops,
3153 sizeof(struct seq_net_private))) {
3154 unix_sysctl_unregister(net);
3163 static void __net_exit unix_net_exit(struct net *net)
3165 unix_sysctl_unregister(net);
3166 remove_proc_entry("unix", net->proc_net);
3169 static struct pernet_operations unix_net_ops = {
3170 .init = unix_net_init,
3171 .exit = unix_net_exit,
3174 static int __init af_unix_init(void)
3178 BUILD_BUG_ON(sizeof(struct unix_skb_parms) > sizeof_field(struct sk_buff, cb));
3180 rc = proto_register(&unix_proto, 1);
3182 pr_crit("%s: Cannot create unix_sock SLAB cache!\n", __func__);
3186 sock_register(&unix_family_ops);
3187 register_pernet_subsys(&unix_net_ops);
3188 unix_bpf_build_proto();
3193 static void __exit af_unix_exit(void)
3195 sock_unregister(PF_UNIX);
3196 proto_unregister(&unix_proto);
3197 unregister_pernet_subsys(&unix_net_ops);
3200 /* Earlier than device_initcall() so that other drivers invoking
3201 request_module() don't end up in a loop when modprobe tries
3202 to use a UNIX socket. But later than subsys_initcall() because
3203 we depend on stuff initialised there */
3204 fs_initcall(af_unix_init);
3205 module_exit(af_unix_exit);
3207 MODULE_LICENSE("GPL");
3208 MODULE_ALIAS_NETPROTO(PF_UNIX);