bpf: Prevent memory disambiguation attack
[linux/fpc-iii.git] / net / tipc / socket.c
blobdf4f504b1fef4df9f31d30ddbf67760cd6164e8c
1 /*
2 * net/tipc/socket.c: TIPC socket API
4 * Copyright (c) 2001-2007, 2012-2017, Ericsson AB
5 * Copyright (c) 2004-2008, 2010-2013, Wind River Systems
6 * All rights reserved.
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the names of the copyright holders nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
20 * Alternatively, this software may be distributed under the terms of the
21 * GNU General Public License ("GPL") version 2 as published by the Free
22 * Software Foundation.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
37 #include <linux/rhashtable.h>
38 #include <linux/sched/signal.h>
40 #include "core.h"
41 #include "name_table.h"
42 #include "node.h"
43 #include "link.h"
44 #include "name_distr.h"
45 #include "socket.h"
46 #include "bcast.h"
47 #include "netlink.h"
48 #include "group.h"
50 #define CONN_TIMEOUT_DEFAULT 8000 /* default connect timeout = 8s */
51 #define CONN_PROBING_INTV msecs_to_jiffies(3600000) /* [ms] => 1 h */
52 #define TIPC_FWD_MSG 1
53 #define TIPC_MAX_PORT 0xffffffff
54 #define TIPC_MIN_PORT 1
55 #define TIPC_ACK_RATE 4 /* ACK at 1/4 of of rcv window size */
57 enum {
58 TIPC_LISTEN = TCP_LISTEN,
59 TIPC_ESTABLISHED = TCP_ESTABLISHED,
60 TIPC_OPEN = TCP_CLOSE,
61 TIPC_DISCONNECTING = TCP_CLOSE_WAIT,
62 TIPC_CONNECTING = TCP_SYN_SENT,
65 struct sockaddr_pair {
66 struct sockaddr_tipc sock;
67 struct sockaddr_tipc member;
70 /**
71 * struct tipc_sock - TIPC socket structure
72 * @sk: socket - interacts with 'port' and with user via the socket API
73 * @conn_type: TIPC type used when connection was established
74 * @conn_instance: TIPC instance used when connection was established
75 * @published: non-zero if port has one or more associated names
76 * @max_pkt: maximum packet size "hint" used when building messages sent by port
77 * @portid: unique port identity in TIPC socket hash table
78 * @phdr: preformatted message header used when sending messages
79 * #cong_links: list of congested links
80 * @publications: list of publications for port
81 * @blocking_link: address of the congested link we are currently sleeping on
82 * @pub_count: total # of publications port has made during its lifetime
83 * @probing_state:
84 * @conn_timeout: the time we can wait for an unresponded setup request
85 * @dupl_rcvcnt: number of bytes counted twice, in both backlog and rcv queue
86 * @cong_link_cnt: number of congested links
87 * @snt_unacked: # messages sent by socket, and not yet acked by peer
88 * @rcv_unacked: # messages read by user, but not yet acked back to peer
89 * @peer: 'connected' peer for dgram/rdm
90 * @node: hash table node
91 * @mc_method: cookie for use between socket and broadcast layer
92 * @rcu: rcu struct for tipc_sock
94 struct tipc_sock {
95 struct sock sk;
96 u32 conn_type;
97 u32 conn_instance;
98 int published;
99 u32 max_pkt;
100 u32 portid;
101 struct tipc_msg phdr;
102 struct list_head cong_links;
103 struct list_head publications;
104 u32 pub_count;
105 uint conn_timeout;
106 atomic_t dupl_rcvcnt;
107 bool probe_unacked;
108 u16 cong_link_cnt;
109 u16 snt_unacked;
110 u16 snd_win;
111 u16 peer_caps;
112 u16 rcv_unacked;
113 u16 rcv_win;
114 struct sockaddr_tipc peer;
115 struct rhash_head node;
116 struct tipc_mc_method mc_method;
117 struct rcu_head rcu;
118 struct tipc_group *group;
119 bool group_is_open;
122 static int tipc_sk_backlog_rcv(struct sock *sk, struct sk_buff *skb);
123 static void tipc_data_ready(struct sock *sk);
124 static void tipc_write_space(struct sock *sk);
125 static void tipc_sock_destruct(struct sock *sk);
126 static int tipc_release(struct socket *sock);
127 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
128 bool kern);
129 static void tipc_sk_timeout(struct timer_list *t);
130 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
131 struct tipc_name_seq const *seq);
132 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
133 struct tipc_name_seq const *seq);
134 static int tipc_sk_leave(struct tipc_sock *tsk);
135 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid);
136 static int tipc_sk_insert(struct tipc_sock *tsk);
137 static void tipc_sk_remove(struct tipc_sock *tsk);
138 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz);
139 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dsz);
141 static const struct proto_ops packet_ops;
142 static const struct proto_ops stream_ops;
143 static const struct proto_ops msg_ops;
144 static struct proto tipc_proto;
145 static const struct rhashtable_params tsk_rht_params;
147 static u32 tsk_own_node(struct tipc_sock *tsk)
149 return msg_prevnode(&tsk->phdr);
152 static u32 tsk_peer_node(struct tipc_sock *tsk)
154 return msg_destnode(&tsk->phdr);
157 static u32 tsk_peer_port(struct tipc_sock *tsk)
159 return msg_destport(&tsk->phdr);
162 static bool tsk_unreliable(struct tipc_sock *tsk)
164 return msg_src_droppable(&tsk->phdr) != 0;
167 static void tsk_set_unreliable(struct tipc_sock *tsk, bool unreliable)
169 msg_set_src_droppable(&tsk->phdr, unreliable ? 1 : 0);
172 static bool tsk_unreturnable(struct tipc_sock *tsk)
174 return msg_dest_droppable(&tsk->phdr) != 0;
177 static void tsk_set_unreturnable(struct tipc_sock *tsk, bool unreturnable)
179 msg_set_dest_droppable(&tsk->phdr, unreturnable ? 1 : 0);
182 static int tsk_importance(struct tipc_sock *tsk)
184 return msg_importance(&tsk->phdr);
187 static int tsk_set_importance(struct tipc_sock *tsk, int imp)
189 if (imp > TIPC_CRITICAL_IMPORTANCE)
190 return -EINVAL;
191 msg_set_importance(&tsk->phdr, (u32)imp);
192 return 0;
195 static struct tipc_sock *tipc_sk(const struct sock *sk)
197 return container_of(sk, struct tipc_sock, sk);
200 static bool tsk_conn_cong(struct tipc_sock *tsk)
202 return tsk->snt_unacked > tsk->snd_win;
205 static u16 tsk_blocks(int len)
207 return ((len / FLOWCTL_BLK_SZ) + 1);
210 /* tsk_blocks(): translate a buffer size in bytes to number of
211 * advertisable blocks, taking into account the ratio truesize(len)/len
212 * We can trust that this ratio is always < 4 for len >= FLOWCTL_BLK_SZ
214 static u16 tsk_adv_blocks(int len)
216 return len / FLOWCTL_BLK_SZ / 4;
219 /* tsk_inc(): increment counter for sent or received data
220 * - If block based flow control is not supported by peer we
221 * fall back to message based ditto, incrementing the counter
223 static u16 tsk_inc(struct tipc_sock *tsk, int msglen)
225 if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
226 return ((msglen / FLOWCTL_BLK_SZ) + 1);
227 return 1;
231 * tsk_advance_rx_queue - discard first buffer in socket receive queue
233 * Caller must hold socket lock
235 static void tsk_advance_rx_queue(struct sock *sk)
237 kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
240 /* tipc_sk_respond() : send response message back to sender
242 static void tipc_sk_respond(struct sock *sk, struct sk_buff *skb, int err)
244 u32 selector;
245 u32 dnode;
246 u32 onode = tipc_own_addr(sock_net(sk));
248 if (!tipc_msg_reverse(onode, &skb, err))
249 return;
251 dnode = msg_destnode(buf_msg(skb));
252 selector = msg_origport(buf_msg(skb));
253 tipc_node_xmit_skb(sock_net(sk), skb, dnode, selector);
257 * tsk_rej_rx_queue - reject all buffers in socket receive queue
259 * Caller must hold socket lock
261 static void tsk_rej_rx_queue(struct sock *sk)
263 struct sk_buff *skb;
265 while ((skb = __skb_dequeue(&sk->sk_receive_queue)))
266 tipc_sk_respond(sk, skb, TIPC_ERR_NO_PORT);
269 static bool tipc_sk_connected(struct sock *sk)
271 return sk->sk_state == TIPC_ESTABLISHED;
274 /* tipc_sk_type_connectionless - check if the socket is datagram socket
275 * @sk: socket
277 * Returns true if connection less, false otherwise
279 static bool tipc_sk_type_connectionless(struct sock *sk)
281 return sk->sk_type == SOCK_RDM || sk->sk_type == SOCK_DGRAM;
284 /* tsk_peer_msg - verify if message was sent by connected port's peer
286 * Handles cases where the node's network address has changed from
287 * the default of <0.0.0> to its configured setting.
289 static bool tsk_peer_msg(struct tipc_sock *tsk, struct tipc_msg *msg)
291 struct sock *sk = &tsk->sk;
292 struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
293 u32 peer_port = tsk_peer_port(tsk);
294 u32 orig_node;
295 u32 peer_node;
297 if (unlikely(!tipc_sk_connected(sk)))
298 return false;
300 if (unlikely(msg_origport(msg) != peer_port))
301 return false;
303 orig_node = msg_orignode(msg);
304 peer_node = tsk_peer_node(tsk);
306 if (likely(orig_node == peer_node))
307 return true;
309 if (!orig_node && (peer_node == tn->own_addr))
310 return true;
312 if (!peer_node && (orig_node == tn->own_addr))
313 return true;
315 return false;
318 /* tipc_set_sk_state - set the sk_state of the socket
319 * @sk: socket
321 * Caller must hold socket lock
323 * Returns 0 on success, errno otherwise
325 static int tipc_set_sk_state(struct sock *sk, int state)
327 int oldsk_state = sk->sk_state;
328 int res = -EINVAL;
330 switch (state) {
331 case TIPC_OPEN:
332 res = 0;
333 break;
334 case TIPC_LISTEN:
335 case TIPC_CONNECTING:
336 if (oldsk_state == TIPC_OPEN)
337 res = 0;
338 break;
339 case TIPC_ESTABLISHED:
340 if (oldsk_state == TIPC_CONNECTING ||
341 oldsk_state == TIPC_OPEN)
342 res = 0;
343 break;
344 case TIPC_DISCONNECTING:
345 if (oldsk_state == TIPC_CONNECTING ||
346 oldsk_state == TIPC_ESTABLISHED)
347 res = 0;
348 break;
351 if (!res)
352 sk->sk_state = state;
354 return res;
357 static int tipc_sk_sock_err(struct socket *sock, long *timeout)
359 struct sock *sk = sock->sk;
360 int err = sock_error(sk);
361 int typ = sock->type;
363 if (err)
364 return err;
365 if (typ == SOCK_STREAM || typ == SOCK_SEQPACKET) {
366 if (sk->sk_state == TIPC_DISCONNECTING)
367 return -EPIPE;
368 else if (!tipc_sk_connected(sk))
369 return -ENOTCONN;
371 if (!*timeout)
372 return -EAGAIN;
373 if (signal_pending(current))
374 return sock_intr_errno(*timeout);
376 return 0;
379 #define tipc_wait_for_cond(sock_, timeo_, condition_) \
380 ({ \
381 struct sock *sk_; \
382 int rc_; \
384 while ((rc_ = !(condition_))) { \
385 DEFINE_WAIT_FUNC(wait_, woken_wake_function); \
386 sk_ = (sock_)->sk; \
387 rc_ = tipc_sk_sock_err((sock_), timeo_); \
388 if (rc_) \
389 break; \
390 prepare_to_wait(sk_sleep(sk_), &wait_, TASK_INTERRUPTIBLE); \
391 release_sock(sk_); \
392 *(timeo_) = wait_woken(&wait_, TASK_INTERRUPTIBLE, *(timeo_)); \
393 sched_annotate_sleep(); \
394 lock_sock(sk_); \
395 remove_wait_queue(sk_sleep(sk_), &wait_); \
397 rc_; \
401 * tipc_sk_create - create a TIPC socket
402 * @net: network namespace (must be default network)
403 * @sock: pre-allocated socket structure
404 * @protocol: protocol indicator (must be 0)
405 * @kern: caused by kernel or by userspace?
407 * This routine creates additional data structures used by the TIPC socket,
408 * initializes them, and links them together.
410 * Returns 0 on success, errno otherwise
412 static int tipc_sk_create(struct net *net, struct socket *sock,
413 int protocol, int kern)
415 struct tipc_net *tn;
416 const struct proto_ops *ops;
417 struct sock *sk;
418 struct tipc_sock *tsk;
419 struct tipc_msg *msg;
421 /* Validate arguments */
422 if (unlikely(protocol != 0))
423 return -EPROTONOSUPPORT;
425 switch (sock->type) {
426 case SOCK_STREAM:
427 ops = &stream_ops;
428 break;
429 case SOCK_SEQPACKET:
430 ops = &packet_ops;
431 break;
432 case SOCK_DGRAM:
433 case SOCK_RDM:
434 ops = &msg_ops;
435 break;
436 default:
437 return -EPROTOTYPE;
440 /* Allocate socket's protocol area */
441 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto, kern);
442 if (sk == NULL)
443 return -ENOMEM;
445 tsk = tipc_sk(sk);
446 tsk->max_pkt = MAX_PKT_DEFAULT;
447 INIT_LIST_HEAD(&tsk->publications);
448 INIT_LIST_HEAD(&tsk->cong_links);
449 msg = &tsk->phdr;
450 tn = net_generic(sock_net(sk), tipc_net_id);
452 /* Finish initializing socket data structures */
453 sock->ops = ops;
454 sock_init_data(sock, sk);
455 tipc_set_sk_state(sk, TIPC_OPEN);
456 if (tipc_sk_insert(tsk)) {
457 pr_warn("Socket create failed; port number exhausted\n");
458 return -EINVAL;
461 /* Ensure tsk is visible before we read own_addr. */
462 smp_mb();
464 tipc_msg_init(tn->own_addr, msg, TIPC_LOW_IMPORTANCE, TIPC_NAMED_MSG,
465 NAMED_H_SIZE, 0);
467 msg_set_origport(msg, tsk->portid);
468 timer_setup(&sk->sk_timer, tipc_sk_timeout, 0);
469 sk->sk_shutdown = 0;
470 sk->sk_backlog_rcv = tipc_sk_backlog_rcv;
471 sk->sk_rcvbuf = sysctl_tipc_rmem[1];
472 sk->sk_data_ready = tipc_data_ready;
473 sk->sk_write_space = tipc_write_space;
474 sk->sk_destruct = tipc_sock_destruct;
475 tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
476 tsk->group_is_open = true;
477 atomic_set(&tsk->dupl_rcvcnt, 0);
479 /* Start out with safe limits until we receive an advertised window */
480 tsk->snd_win = tsk_adv_blocks(RCVBUF_MIN);
481 tsk->rcv_win = tsk->snd_win;
483 if (tipc_sk_type_connectionless(sk)) {
484 tsk_set_unreturnable(tsk, true);
485 if (sock->type == SOCK_DGRAM)
486 tsk_set_unreliable(tsk, true);
489 return 0;
492 static void tipc_sk_callback(struct rcu_head *head)
494 struct tipc_sock *tsk = container_of(head, struct tipc_sock, rcu);
496 sock_put(&tsk->sk);
499 /* Caller should hold socket lock for the socket. */
500 static void __tipc_shutdown(struct socket *sock, int error)
502 struct sock *sk = sock->sk;
503 struct tipc_sock *tsk = tipc_sk(sk);
504 struct net *net = sock_net(sk);
505 long timeout = CONN_TIMEOUT_DEFAULT;
506 u32 dnode = tsk_peer_node(tsk);
507 struct sk_buff *skb;
509 /* Avoid that hi-prio shutdown msgs bypass msgs in link wakeup queue */
510 tipc_wait_for_cond(sock, &timeout, (!tsk->cong_link_cnt &&
511 !tsk_conn_cong(tsk)));
513 /* Reject all unreceived messages, except on an active connection
514 * (which disconnects locally & sends a 'FIN+' to peer).
516 while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
517 if (TIPC_SKB_CB(skb)->bytes_read) {
518 kfree_skb(skb);
519 continue;
521 if (!tipc_sk_type_connectionless(sk) &&
522 sk->sk_state != TIPC_DISCONNECTING) {
523 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
524 tipc_node_remove_conn(net, dnode, tsk->portid);
526 tipc_sk_respond(sk, skb, error);
529 if (tipc_sk_type_connectionless(sk))
530 return;
532 if (sk->sk_state != TIPC_DISCONNECTING) {
533 skb = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
534 TIPC_CONN_MSG, SHORT_H_SIZE, 0, dnode,
535 tsk_own_node(tsk), tsk_peer_port(tsk),
536 tsk->portid, error);
537 if (skb)
538 tipc_node_xmit_skb(net, skb, dnode, tsk->portid);
539 tipc_node_remove_conn(net, dnode, tsk->portid);
540 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
545 * tipc_release - destroy a TIPC socket
546 * @sock: socket to destroy
548 * This routine cleans up any messages that are still queued on the socket.
549 * For DGRAM and RDM socket types, all queued messages are rejected.
550 * For SEQPACKET and STREAM socket types, the first message is rejected
551 * and any others are discarded. (If the first message on a STREAM socket
552 * is partially-read, it is discarded and the next one is rejected instead.)
554 * NOTE: Rejected messages are not necessarily returned to the sender! They
555 * are returned or discarded according to the "destination droppable" setting
556 * specified for the message by the sender.
558 * Returns 0 on success, errno otherwise
560 static int tipc_release(struct socket *sock)
562 struct sock *sk = sock->sk;
563 struct tipc_sock *tsk;
566 * Exit if socket isn't fully initialized (occurs when a failed accept()
567 * releases a pre-allocated child socket that was never used)
569 if (sk == NULL)
570 return 0;
572 tsk = tipc_sk(sk);
573 lock_sock(sk);
575 __tipc_shutdown(sock, TIPC_ERR_NO_PORT);
576 sk->sk_shutdown = SHUTDOWN_MASK;
577 tipc_sk_leave(tsk);
578 tipc_sk_withdraw(tsk, 0, NULL);
579 sk_stop_timer(sk, &sk->sk_timer);
580 tipc_sk_remove(tsk);
582 /* Reject any messages that accumulated in backlog queue */
583 release_sock(sk);
584 tipc_dest_list_purge(&tsk->cong_links);
585 tsk->cong_link_cnt = 0;
586 call_rcu(&tsk->rcu, tipc_sk_callback);
587 sock->sk = NULL;
589 return 0;
593 * tipc_bind - associate or disassocate TIPC name(s) with a socket
594 * @sock: socket structure
595 * @uaddr: socket address describing name(s) and desired operation
596 * @uaddr_len: size of socket address data structure
598 * Name and name sequence binding is indicated using a positive scope value;
599 * a negative scope value unbinds the specified name. Specifying no name
600 * (i.e. a socket address length of 0) unbinds all names from the socket.
602 * Returns 0 on success, errno otherwise
604 * NOTE: This routine doesn't need to take the socket lock since it doesn't
605 * access any non-constant socket information.
607 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
608 int uaddr_len)
610 struct sock *sk = sock->sk;
611 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
612 struct tipc_sock *tsk = tipc_sk(sk);
613 int res = -EINVAL;
615 lock_sock(sk);
616 if (unlikely(!uaddr_len)) {
617 res = tipc_sk_withdraw(tsk, 0, NULL);
618 goto exit;
620 if (tsk->group) {
621 res = -EACCES;
622 goto exit;
624 if (uaddr_len < sizeof(struct sockaddr_tipc)) {
625 res = -EINVAL;
626 goto exit;
628 if (addr->family != AF_TIPC) {
629 res = -EAFNOSUPPORT;
630 goto exit;
633 if (addr->addrtype == TIPC_ADDR_NAME)
634 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
635 else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
636 res = -EAFNOSUPPORT;
637 goto exit;
640 if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
641 (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
642 (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
643 res = -EACCES;
644 goto exit;
647 res = (addr->scope > 0) ?
648 tipc_sk_publish(tsk, addr->scope, &addr->addr.nameseq) :
649 tipc_sk_withdraw(tsk, -addr->scope, &addr->addr.nameseq);
650 exit:
651 release_sock(sk);
652 return res;
656 * tipc_getname - get port ID of socket or peer socket
657 * @sock: socket structure
658 * @uaddr: area for returned socket address
659 * @uaddr_len: area for returned length of socket address
660 * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
662 * Returns 0 on success, errno otherwise
664 * NOTE: This routine doesn't need to take the socket lock since it only
665 * accesses socket information that is unchanging (or which changes in
666 * a completely predictable manner).
668 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
669 int *uaddr_len, int peer)
671 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
672 struct sock *sk = sock->sk;
673 struct tipc_sock *tsk = tipc_sk(sk);
674 struct tipc_net *tn = net_generic(sock_net(sock->sk), tipc_net_id);
676 memset(addr, 0, sizeof(*addr));
677 if (peer) {
678 if ((!tipc_sk_connected(sk)) &&
679 ((peer != 2) || (sk->sk_state != TIPC_DISCONNECTING)))
680 return -ENOTCONN;
681 addr->addr.id.ref = tsk_peer_port(tsk);
682 addr->addr.id.node = tsk_peer_node(tsk);
683 } else {
684 addr->addr.id.ref = tsk->portid;
685 addr->addr.id.node = tn->own_addr;
688 *uaddr_len = sizeof(*addr);
689 addr->addrtype = TIPC_ADDR_ID;
690 addr->family = AF_TIPC;
691 addr->scope = 0;
692 addr->addr.name.domain = 0;
694 return 0;
698 * tipc_poll - read and possibly block on pollmask
699 * @file: file structure associated with the socket
700 * @sock: socket for which to calculate the poll bits
701 * @wait: ???
703 * Returns pollmask value
705 * COMMENTARY:
706 * It appears that the usual socket locking mechanisms are not useful here
707 * since the pollmask info is potentially out-of-date the moment this routine
708 * exits. TCP and other protocols seem to rely on higher level poll routines
709 * to handle any preventable race conditions, so TIPC will do the same ...
711 * IMPORTANT: The fact that a read or write operation is indicated does NOT
712 * imply that the operation will succeed, merely that it should be performed
713 * and will not block.
715 static __poll_t tipc_poll(struct file *file, struct socket *sock,
716 poll_table *wait)
718 struct sock *sk = sock->sk;
719 struct tipc_sock *tsk = tipc_sk(sk);
720 __poll_t revents = 0;
722 sock_poll_wait(file, sk_sleep(sk), wait);
724 if (sk->sk_shutdown & RCV_SHUTDOWN)
725 revents |= EPOLLRDHUP | EPOLLIN | EPOLLRDNORM;
726 if (sk->sk_shutdown == SHUTDOWN_MASK)
727 revents |= EPOLLHUP;
729 switch (sk->sk_state) {
730 case TIPC_ESTABLISHED:
731 case TIPC_CONNECTING:
732 if (!tsk->cong_link_cnt && !tsk_conn_cong(tsk))
733 revents |= EPOLLOUT;
734 /* fall thru' */
735 case TIPC_LISTEN:
736 if (!skb_queue_empty(&sk->sk_receive_queue))
737 revents |= EPOLLIN | EPOLLRDNORM;
738 break;
739 case TIPC_OPEN:
740 if (tsk->group_is_open && !tsk->cong_link_cnt)
741 revents |= EPOLLOUT;
742 if (!tipc_sk_type_connectionless(sk))
743 break;
744 if (skb_queue_empty(&sk->sk_receive_queue))
745 break;
746 revents |= EPOLLIN | EPOLLRDNORM;
747 break;
748 case TIPC_DISCONNECTING:
749 revents = EPOLLIN | EPOLLRDNORM | EPOLLHUP;
750 break;
752 return revents;
756 * tipc_sendmcast - send multicast message
757 * @sock: socket structure
758 * @seq: destination address
759 * @msg: message to send
760 * @dlen: length of data to send
761 * @timeout: timeout to wait for wakeup
763 * Called from function tipc_sendmsg(), which has done all sanity checks
764 * Returns the number of bytes sent on success, or errno
766 static int tipc_sendmcast(struct socket *sock, struct tipc_name_seq *seq,
767 struct msghdr *msg, size_t dlen, long timeout)
769 struct sock *sk = sock->sk;
770 struct tipc_sock *tsk = tipc_sk(sk);
771 struct tipc_msg *hdr = &tsk->phdr;
772 struct net *net = sock_net(sk);
773 int mtu = tipc_bcast_get_mtu(net);
774 struct tipc_mc_method *method = &tsk->mc_method;
775 struct sk_buff_head pkts;
776 struct tipc_nlist dsts;
777 int rc;
779 if (tsk->group)
780 return -EACCES;
782 /* Block or return if any destination link is congested */
783 rc = tipc_wait_for_cond(sock, &timeout, !tsk->cong_link_cnt);
784 if (unlikely(rc))
785 return rc;
787 /* Lookup destination nodes */
788 tipc_nlist_init(&dsts, tipc_own_addr(net));
789 tipc_nametbl_lookup_dst_nodes(net, seq->type, seq->lower,
790 seq->upper, &dsts);
791 if (!dsts.local && !dsts.remote)
792 return -EHOSTUNREACH;
794 /* Build message header */
795 msg_set_type(hdr, TIPC_MCAST_MSG);
796 msg_set_hdr_sz(hdr, MCAST_H_SIZE);
797 msg_set_lookup_scope(hdr, TIPC_CLUSTER_SCOPE);
798 msg_set_destport(hdr, 0);
799 msg_set_destnode(hdr, 0);
800 msg_set_nametype(hdr, seq->type);
801 msg_set_namelower(hdr, seq->lower);
802 msg_set_nameupper(hdr, seq->upper);
804 /* Build message as chain of buffers */
805 skb_queue_head_init(&pkts);
806 rc = tipc_msg_build(hdr, msg, 0, dlen, mtu, &pkts);
808 /* Send message if build was successful */
809 if (unlikely(rc == dlen))
810 rc = tipc_mcast_xmit(net, &pkts, method, &dsts,
811 &tsk->cong_link_cnt);
813 tipc_nlist_purge(&dsts);
815 return rc ? rc : dlen;
819 * tipc_send_group_msg - send a message to a member in the group
820 * @net: network namespace
821 * @m: message to send
822 * @mb: group member
823 * @dnode: destination node
824 * @dport: destination port
825 * @dlen: total length of message data
827 static int tipc_send_group_msg(struct net *net, struct tipc_sock *tsk,
828 struct msghdr *m, struct tipc_member *mb,
829 u32 dnode, u32 dport, int dlen)
831 u16 bc_snd_nxt = tipc_group_bc_snd_nxt(tsk->group);
832 struct tipc_mc_method *method = &tsk->mc_method;
833 int blks = tsk_blocks(GROUP_H_SIZE + dlen);
834 struct tipc_msg *hdr = &tsk->phdr;
835 struct sk_buff_head pkts;
836 int mtu, rc;
838 /* Complete message header */
839 msg_set_type(hdr, TIPC_GRP_UCAST_MSG);
840 msg_set_hdr_sz(hdr, GROUP_H_SIZE);
841 msg_set_destport(hdr, dport);
842 msg_set_destnode(hdr, dnode);
843 msg_set_grp_bc_seqno(hdr, bc_snd_nxt);
845 /* Build message as chain of buffers */
846 skb_queue_head_init(&pkts);
847 mtu = tipc_node_get_mtu(net, dnode, tsk->portid);
848 rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
849 if (unlikely(rc != dlen))
850 return rc;
852 /* Send message */
853 rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
854 if (unlikely(rc == -ELINKCONG)) {
855 tipc_dest_push(&tsk->cong_links, dnode, 0);
856 tsk->cong_link_cnt++;
859 /* Update send window */
860 tipc_group_update_member(mb, blks);
862 /* A broadcast sent within next EXPIRE period must follow same path */
863 method->rcast = true;
864 method->mandatory = true;
865 return dlen;
869 * tipc_send_group_unicast - send message to a member in the group
870 * @sock: socket structure
871 * @m: message to send
872 * @dlen: total length of message data
873 * @timeout: timeout to wait for wakeup
875 * Called from function tipc_sendmsg(), which has done all sanity checks
876 * Returns the number of bytes sent on success, or errno
878 static int tipc_send_group_unicast(struct socket *sock, struct msghdr *m,
879 int dlen, long timeout)
881 struct sock *sk = sock->sk;
882 DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
883 int blks = tsk_blocks(GROUP_H_SIZE + dlen);
884 struct tipc_sock *tsk = tipc_sk(sk);
885 struct tipc_group *grp = tsk->group;
886 struct net *net = sock_net(sk);
887 struct tipc_member *mb = NULL;
888 u32 node, port;
889 int rc;
891 node = dest->addr.id.node;
892 port = dest->addr.id.ref;
893 if (!port && !node)
894 return -EHOSTUNREACH;
896 /* Block or return if destination link or member is congested */
897 rc = tipc_wait_for_cond(sock, &timeout,
898 !tipc_dest_find(&tsk->cong_links, node, 0) &&
899 !tipc_group_cong(grp, node, port, blks, &mb));
900 if (unlikely(rc))
901 return rc;
903 if (unlikely(!mb))
904 return -EHOSTUNREACH;
906 rc = tipc_send_group_msg(net, tsk, m, mb, node, port, dlen);
908 return rc ? rc : dlen;
912 * tipc_send_group_anycast - send message to any member with given identity
913 * @sock: socket structure
914 * @m: message to send
915 * @dlen: total length of message data
916 * @timeout: timeout to wait for wakeup
918 * Called from function tipc_sendmsg(), which has done all sanity checks
919 * Returns the number of bytes sent on success, or errno
921 static int tipc_send_group_anycast(struct socket *sock, struct msghdr *m,
922 int dlen, long timeout)
924 DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
925 struct sock *sk = sock->sk;
926 struct tipc_sock *tsk = tipc_sk(sk);
927 struct list_head *cong_links = &tsk->cong_links;
928 int blks = tsk_blocks(GROUP_H_SIZE + dlen);
929 struct tipc_group *grp = tsk->group;
930 struct tipc_msg *hdr = &tsk->phdr;
931 struct tipc_member *first = NULL;
932 struct tipc_member *mbr = NULL;
933 struct net *net = sock_net(sk);
934 u32 node, port, exclude;
935 struct list_head dsts;
936 u32 type, inst, scope;
937 int lookups = 0;
938 int dstcnt, rc;
939 bool cong;
941 INIT_LIST_HEAD(&dsts);
943 type = msg_nametype(hdr);
944 inst = dest->addr.name.name.instance;
945 scope = msg_lookup_scope(hdr);
946 exclude = tipc_group_exclude(grp);
948 while (++lookups < 4) {
949 first = NULL;
951 /* Look for a non-congested destination member, if any */
952 while (1) {
953 if (!tipc_nametbl_lookup(net, type, inst, scope, &dsts,
954 &dstcnt, exclude, false))
955 return -EHOSTUNREACH;
956 tipc_dest_pop(&dsts, &node, &port);
957 cong = tipc_group_cong(grp, node, port, blks, &mbr);
958 if (!cong)
959 break;
960 if (mbr == first)
961 break;
962 if (!first)
963 first = mbr;
966 /* Start over if destination was not in member list */
967 if (unlikely(!mbr))
968 continue;
970 if (likely(!cong && !tipc_dest_find(cong_links, node, 0)))
971 break;
973 /* Block or return if destination link or member is congested */
974 rc = tipc_wait_for_cond(sock, &timeout,
975 !tipc_dest_find(cong_links, node, 0) &&
976 !tipc_group_cong(grp, node, port,
977 blks, &mbr));
978 if (unlikely(rc))
979 return rc;
981 /* Send, unless destination disappeared while waiting */
982 if (likely(mbr))
983 break;
986 if (unlikely(lookups >= 4))
987 return -EHOSTUNREACH;
989 rc = tipc_send_group_msg(net, tsk, m, mbr, node, port, dlen);
991 return rc ? rc : dlen;
995 * tipc_send_group_bcast - send message to all members in communication group
996 * @sk: socket structure
997 * @m: message to send
998 * @dlen: total length of message data
999 * @timeout: timeout to wait for wakeup
1001 * Called from function tipc_sendmsg(), which has done all sanity checks
1002 * Returns the number of bytes sent on success, or errno
1004 static int tipc_send_group_bcast(struct socket *sock, struct msghdr *m,
1005 int dlen, long timeout)
1007 DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1008 struct sock *sk = sock->sk;
1009 struct net *net = sock_net(sk);
1010 struct tipc_sock *tsk = tipc_sk(sk);
1011 struct tipc_group *grp = tsk->group;
1012 struct tipc_nlist *dsts = tipc_group_dests(grp);
1013 struct tipc_mc_method *method = &tsk->mc_method;
1014 bool ack = method->mandatory && method->rcast;
1015 int blks = tsk_blocks(MCAST_H_SIZE + dlen);
1016 struct tipc_msg *hdr = &tsk->phdr;
1017 int mtu = tipc_bcast_get_mtu(net);
1018 struct sk_buff_head pkts;
1019 int rc = -EHOSTUNREACH;
1021 if (!dsts->local && !dsts->remote)
1022 return -EHOSTUNREACH;
1024 /* Block or return if any destination link or member is congested */
1025 rc = tipc_wait_for_cond(sock, &timeout, !tsk->cong_link_cnt &&
1026 !tipc_group_bc_cong(grp, blks));
1027 if (unlikely(rc))
1028 return rc;
1030 /* Complete message header */
1031 if (dest) {
1032 msg_set_type(hdr, TIPC_GRP_MCAST_MSG);
1033 msg_set_nameinst(hdr, dest->addr.name.name.instance);
1034 } else {
1035 msg_set_type(hdr, TIPC_GRP_BCAST_MSG);
1036 msg_set_nameinst(hdr, 0);
1038 msg_set_hdr_sz(hdr, GROUP_H_SIZE);
1039 msg_set_destport(hdr, 0);
1040 msg_set_destnode(hdr, 0);
1041 msg_set_grp_bc_seqno(hdr, tipc_group_bc_snd_nxt(grp));
1043 /* Avoid getting stuck with repeated forced replicasts */
1044 msg_set_grp_bc_ack_req(hdr, ack);
1046 /* Build message as chain of buffers */
1047 skb_queue_head_init(&pkts);
1048 rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
1049 if (unlikely(rc != dlen))
1050 return rc;
1052 /* Send message */
1053 rc = tipc_mcast_xmit(net, &pkts, method, dsts, &tsk->cong_link_cnt);
1054 if (unlikely(rc))
1055 return rc;
1057 /* Update broadcast sequence number and send windows */
1058 tipc_group_update_bc_members(tsk->group, blks, ack);
1060 /* Broadcast link is now free to choose method for next broadcast */
1061 method->mandatory = false;
1062 method->expires = jiffies;
1064 return dlen;
1068 * tipc_send_group_mcast - send message to all members with given identity
1069 * @sock: socket structure
1070 * @m: message to send
1071 * @dlen: total length of message data
1072 * @timeout: timeout to wait for wakeup
1074 * Called from function tipc_sendmsg(), which has done all sanity checks
1075 * Returns the number of bytes sent on success, or errno
1077 static int tipc_send_group_mcast(struct socket *sock, struct msghdr *m,
1078 int dlen, long timeout)
1080 struct sock *sk = sock->sk;
1081 DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1082 struct tipc_sock *tsk = tipc_sk(sk);
1083 struct tipc_group *grp = tsk->group;
1084 struct tipc_msg *hdr = &tsk->phdr;
1085 struct net *net = sock_net(sk);
1086 u32 type, inst, scope, exclude;
1087 struct list_head dsts;
1088 u32 dstcnt;
1090 INIT_LIST_HEAD(&dsts);
1092 type = msg_nametype(hdr);
1093 inst = dest->addr.name.name.instance;
1094 scope = msg_lookup_scope(hdr);
1095 exclude = tipc_group_exclude(grp);
1097 if (!tipc_nametbl_lookup(net, type, inst, scope, &dsts,
1098 &dstcnt, exclude, true))
1099 return -EHOSTUNREACH;
1101 if (dstcnt == 1) {
1102 tipc_dest_pop(&dsts, &dest->addr.id.node, &dest->addr.id.ref);
1103 return tipc_send_group_unicast(sock, m, dlen, timeout);
1106 tipc_dest_list_purge(&dsts);
1107 return tipc_send_group_bcast(sock, m, dlen, timeout);
1111 * tipc_sk_mcast_rcv - Deliver multicast messages to all destination sockets
1112 * @arrvq: queue with arriving messages, to be cloned after destination lookup
1113 * @inputq: queue with cloned messages, delivered to socket after dest lookup
1115 * Multi-threaded: parallel calls with reference to same queues may occur
1117 void tipc_sk_mcast_rcv(struct net *net, struct sk_buff_head *arrvq,
1118 struct sk_buff_head *inputq)
1120 u32 self = tipc_own_addr(net);
1121 u32 type, lower, upper, scope;
1122 struct sk_buff *skb, *_skb;
1123 u32 portid, oport, onode;
1124 struct sk_buff_head tmpq;
1125 struct list_head dports;
1126 struct tipc_msg *hdr;
1127 int user, mtyp, hlen;
1128 bool exact;
1130 __skb_queue_head_init(&tmpq);
1131 INIT_LIST_HEAD(&dports);
1133 skb = tipc_skb_peek(arrvq, &inputq->lock);
1134 for (; skb; skb = tipc_skb_peek(arrvq, &inputq->lock)) {
1135 hdr = buf_msg(skb);
1136 user = msg_user(hdr);
1137 mtyp = msg_type(hdr);
1138 hlen = skb_headroom(skb) + msg_hdr_sz(hdr);
1139 oport = msg_origport(hdr);
1140 onode = msg_orignode(hdr);
1141 type = msg_nametype(hdr);
1143 if (mtyp == TIPC_GRP_UCAST_MSG || user == GROUP_PROTOCOL) {
1144 spin_lock_bh(&inputq->lock);
1145 if (skb_peek(arrvq) == skb) {
1146 __skb_dequeue(arrvq);
1147 __skb_queue_tail(inputq, skb);
1149 kfree_skb(skb);
1150 spin_unlock_bh(&inputq->lock);
1151 continue;
1154 /* Group messages require exact scope match */
1155 if (msg_in_group(hdr)) {
1156 lower = 0;
1157 upper = ~0;
1158 scope = msg_lookup_scope(hdr);
1159 exact = true;
1160 } else {
1161 /* TIPC_NODE_SCOPE means "any scope" in this context */
1162 if (onode == self)
1163 scope = TIPC_NODE_SCOPE;
1164 else
1165 scope = TIPC_CLUSTER_SCOPE;
1166 exact = false;
1167 lower = msg_namelower(hdr);
1168 upper = msg_nameupper(hdr);
1171 /* Create destination port list: */
1172 tipc_nametbl_mc_lookup(net, type, lower, upper,
1173 scope, exact, &dports);
1175 /* Clone message per destination */
1176 while (tipc_dest_pop(&dports, NULL, &portid)) {
1177 _skb = __pskb_copy(skb, hlen, GFP_ATOMIC);
1178 if (_skb) {
1179 msg_set_destport(buf_msg(_skb), portid);
1180 __skb_queue_tail(&tmpq, _skb);
1181 continue;
1183 pr_warn("Failed to clone mcast rcv buffer\n");
1185 /* Append to inputq if not already done by other thread */
1186 spin_lock_bh(&inputq->lock);
1187 if (skb_peek(arrvq) == skb) {
1188 skb_queue_splice_tail_init(&tmpq, inputq);
1189 kfree_skb(__skb_dequeue(arrvq));
1191 spin_unlock_bh(&inputq->lock);
1192 __skb_queue_purge(&tmpq);
1193 kfree_skb(skb);
1195 tipc_sk_rcv(net, inputq);
1199 * tipc_sk_conn_proto_rcv - receive a connection mng protocol message
1200 * @tsk: receiving socket
1201 * @skb: pointer to message buffer.
1203 static void tipc_sk_conn_proto_rcv(struct tipc_sock *tsk, struct sk_buff *skb,
1204 struct sk_buff_head *xmitq)
1206 struct tipc_msg *hdr = buf_msg(skb);
1207 u32 onode = tsk_own_node(tsk);
1208 struct sock *sk = &tsk->sk;
1209 int mtyp = msg_type(hdr);
1210 bool conn_cong;
1212 /* Ignore if connection cannot be validated: */
1213 if (!tsk_peer_msg(tsk, hdr))
1214 goto exit;
1216 if (unlikely(msg_errcode(hdr))) {
1217 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1218 tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
1219 tsk_peer_port(tsk));
1220 sk->sk_state_change(sk);
1221 goto exit;
1224 tsk->probe_unacked = false;
1226 if (mtyp == CONN_PROBE) {
1227 msg_set_type(hdr, CONN_PROBE_REPLY);
1228 if (tipc_msg_reverse(onode, &skb, TIPC_OK))
1229 __skb_queue_tail(xmitq, skb);
1230 return;
1231 } else if (mtyp == CONN_ACK) {
1232 conn_cong = tsk_conn_cong(tsk);
1233 tsk->snt_unacked -= msg_conn_ack(hdr);
1234 if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
1235 tsk->snd_win = msg_adv_win(hdr);
1236 if (conn_cong)
1237 sk->sk_write_space(sk);
1238 } else if (mtyp != CONN_PROBE_REPLY) {
1239 pr_warn("Received unknown CONN_PROTO msg\n");
1241 exit:
1242 kfree_skb(skb);
1246 * tipc_sendmsg - send message in connectionless manner
1247 * @sock: socket structure
1248 * @m: message to send
1249 * @dsz: amount of user data to be sent
1251 * Message must have an destination specified explicitly.
1252 * Used for SOCK_RDM and SOCK_DGRAM messages,
1253 * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
1254 * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
1256 * Returns the number of bytes sent on success, or errno otherwise
1258 static int tipc_sendmsg(struct socket *sock,
1259 struct msghdr *m, size_t dsz)
1261 struct sock *sk = sock->sk;
1262 int ret;
1264 lock_sock(sk);
1265 ret = __tipc_sendmsg(sock, m, dsz);
1266 release_sock(sk);
1268 return ret;
1271 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)
1273 struct sock *sk = sock->sk;
1274 struct net *net = sock_net(sk);
1275 struct tipc_sock *tsk = tipc_sk(sk);
1276 DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1277 long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1278 struct list_head *clinks = &tsk->cong_links;
1279 bool syn = !tipc_sk_type_connectionless(sk);
1280 struct tipc_group *grp = tsk->group;
1281 struct tipc_msg *hdr = &tsk->phdr;
1282 struct tipc_name_seq *seq;
1283 struct sk_buff_head pkts;
1284 u32 type, inst, domain;
1285 u32 dnode, dport;
1286 int mtu, rc;
1288 if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))
1289 return -EMSGSIZE;
1291 if (likely(dest)) {
1292 if (unlikely(m->msg_namelen < sizeof(*dest)))
1293 return -EINVAL;
1294 if (unlikely(dest->family != AF_TIPC))
1295 return -EINVAL;
1298 if (grp) {
1299 if (!dest)
1300 return tipc_send_group_bcast(sock, m, dlen, timeout);
1301 if (dest->addrtype == TIPC_ADDR_NAME)
1302 return tipc_send_group_anycast(sock, m, dlen, timeout);
1303 if (dest->addrtype == TIPC_ADDR_ID)
1304 return tipc_send_group_unicast(sock, m, dlen, timeout);
1305 if (dest->addrtype == TIPC_ADDR_MCAST)
1306 return tipc_send_group_mcast(sock, m, dlen, timeout);
1307 return -EINVAL;
1310 if (unlikely(!dest)) {
1311 dest = &tsk->peer;
1312 if (!syn || dest->family != AF_TIPC)
1313 return -EDESTADDRREQ;
1316 if (unlikely(syn)) {
1317 if (sk->sk_state == TIPC_LISTEN)
1318 return -EPIPE;
1319 if (sk->sk_state != TIPC_OPEN)
1320 return -EISCONN;
1321 if (tsk->published)
1322 return -EOPNOTSUPP;
1323 if (dest->addrtype == TIPC_ADDR_NAME) {
1324 tsk->conn_type = dest->addr.name.name.type;
1325 tsk->conn_instance = dest->addr.name.name.instance;
1329 seq = &dest->addr.nameseq;
1330 if (dest->addrtype == TIPC_ADDR_MCAST)
1331 return tipc_sendmcast(sock, seq, m, dlen, timeout);
1333 if (dest->addrtype == TIPC_ADDR_NAME) {
1334 type = dest->addr.name.name.type;
1335 inst = dest->addr.name.name.instance;
1336 domain = dest->addr.name.domain;
1337 dnode = domain;
1338 msg_set_type(hdr, TIPC_NAMED_MSG);
1339 msg_set_hdr_sz(hdr, NAMED_H_SIZE);
1340 msg_set_nametype(hdr, type);
1341 msg_set_nameinst(hdr, inst);
1342 msg_set_lookup_scope(hdr, tipc_addr_scope(domain));
1343 dport = tipc_nametbl_translate(net, type, inst, &dnode);
1344 msg_set_destnode(hdr, dnode);
1345 msg_set_destport(hdr, dport);
1346 if (unlikely(!dport && !dnode))
1347 return -EHOSTUNREACH;
1348 } else if (dest->addrtype == TIPC_ADDR_ID) {
1349 dnode = dest->addr.id.node;
1350 msg_set_type(hdr, TIPC_DIRECT_MSG);
1351 msg_set_lookup_scope(hdr, 0);
1352 msg_set_destnode(hdr, dnode);
1353 msg_set_destport(hdr, dest->addr.id.ref);
1354 msg_set_hdr_sz(hdr, BASIC_H_SIZE);
1357 /* Block or return if destination link is congested */
1358 rc = tipc_wait_for_cond(sock, &timeout,
1359 !tipc_dest_find(clinks, dnode, 0));
1360 if (unlikely(rc))
1361 return rc;
1363 skb_queue_head_init(&pkts);
1364 mtu = tipc_node_get_mtu(net, dnode, tsk->portid);
1365 rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
1366 if (unlikely(rc != dlen))
1367 return rc;
1369 rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
1370 if (unlikely(rc == -ELINKCONG)) {
1371 tipc_dest_push(clinks, dnode, 0);
1372 tsk->cong_link_cnt++;
1373 rc = 0;
1376 if (unlikely(syn && !rc))
1377 tipc_set_sk_state(sk, TIPC_CONNECTING);
1379 return rc ? rc : dlen;
1383 * tipc_sendstream - send stream-oriented data
1384 * @sock: socket structure
1385 * @m: data to send
1386 * @dsz: total length of data to be transmitted
1388 * Used for SOCK_STREAM data.
1390 * Returns the number of bytes sent on success (or partial success),
1391 * or errno if no data sent
1393 static int tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz)
1395 struct sock *sk = sock->sk;
1396 int ret;
1398 lock_sock(sk);
1399 ret = __tipc_sendstream(sock, m, dsz);
1400 release_sock(sk);
1402 return ret;
1405 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dlen)
1407 struct sock *sk = sock->sk;
1408 DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1409 long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1410 struct tipc_sock *tsk = tipc_sk(sk);
1411 struct tipc_msg *hdr = &tsk->phdr;
1412 struct net *net = sock_net(sk);
1413 struct sk_buff_head pkts;
1414 u32 dnode = tsk_peer_node(tsk);
1415 int send, sent = 0;
1416 int rc = 0;
1418 skb_queue_head_init(&pkts);
1420 if (unlikely(dlen > INT_MAX))
1421 return -EMSGSIZE;
1423 /* Handle implicit connection setup */
1424 if (unlikely(dest)) {
1425 rc = __tipc_sendmsg(sock, m, dlen);
1426 if (dlen && (dlen == rc))
1427 tsk->snt_unacked = tsk_inc(tsk, dlen + msg_hdr_sz(hdr));
1428 return rc;
1431 do {
1432 rc = tipc_wait_for_cond(sock, &timeout,
1433 (!tsk->cong_link_cnt &&
1434 !tsk_conn_cong(tsk) &&
1435 tipc_sk_connected(sk)));
1436 if (unlikely(rc))
1437 break;
1439 send = min_t(size_t, dlen - sent, TIPC_MAX_USER_MSG_SIZE);
1440 rc = tipc_msg_build(hdr, m, sent, send, tsk->max_pkt, &pkts);
1441 if (unlikely(rc != send))
1442 break;
1444 rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
1445 if (unlikely(rc == -ELINKCONG)) {
1446 tsk->cong_link_cnt = 1;
1447 rc = 0;
1449 if (likely(!rc)) {
1450 tsk->snt_unacked += tsk_inc(tsk, send + MIN_H_SIZE);
1451 sent += send;
1453 } while (sent < dlen && !rc);
1455 return sent ? sent : rc;
1459 * tipc_send_packet - send a connection-oriented message
1460 * @sock: socket structure
1461 * @m: message to send
1462 * @dsz: length of data to be transmitted
1464 * Used for SOCK_SEQPACKET messages.
1466 * Returns the number of bytes sent on success, or errno otherwise
1468 static int tipc_send_packet(struct socket *sock, struct msghdr *m, size_t dsz)
1470 if (dsz > TIPC_MAX_USER_MSG_SIZE)
1471 return -EMSGSIZE;
1473 return tipc_sendstream(sock, m, dsz);
1476 /* tipc_sk_finish_conn - complete the setup of a connection
1478 static void tipc_sk_finish_conn(struct tipc_sock *tsk, u32 peer_port,
1479 u32 peer_node)
1481 struct sock *sk = &tsk->sk;
1482 struct net *net = sock_net(sk);
1483 struct tipc_msg *msg = &tsk->phdr;
1485 msg_set_destnode(msg, peer_node);
1486 msg_set_destport(msg, peer_port);
1487 msg_set_type(msg, TIPC_CONN_MSG);
1488 msg_set_lookup_scope(msg, 0);
1489 msg_set_hdr_sz(msg, SHORT_H_SIZE);
1491 sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTV);
1492 tipc_set_sk_state(sk, TIPC_ESTABLISHED);
1493 tipc_node_add_conn(net, peer_node, tsk->portid, peer_port);
1494 tsk->max_pkt = tipc_node_get_mtu(net, peer_node, tsk->portid);
1495 tsk->peer_caps = tipc_node_get_capabilities(net, peer_node);
1496 if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
1497 return;
1499 /* Fall back to message based flow control */
1500 tsk->rcv_win = FLOWCTL_MSG_WIN;
1501 tsk->snd_win = FLOWCTL_MSG_WIN;
1505 * tipc_sk_set_orig_addr - capture sender's address for received message
1506 * @m: descriptor for message info
1507 * @hdr: received message header
1509 * Note: Address is not captured if not requested by receiver.
1511 static void tipc_sk_set_orig_addr(struct msghdr *m, struct sk_buff *skb)
1513 DECLARE_SOCKADDR(struct sockaddr_pair *, srcaddr, m->msg_name);
1514 struct tipc_msg *hdr = buf_msg(skb);
1516 if (!srcaddr)
1517 return;
1519 srcaddr->sock.family = AF_TIPC;
1520 srcaddr->sock.addrtype = TIPC_ADDR_ID;
1521 srcaddr->sock.scope = 0;
1522 srcaddr->sock.addr.id.ref = msg_origport(hdr);
1523 srcaddr->sock.addr.id.node = msg_orignode(hdr);
1524 srcaddr->sock.addr.name.domain = 0;
1525 m->msg_namelen = sizeof(struct sockaddr_tipc);
1527 if (!msg_in_group(hdr))
1528 return;
1530 /* Group message users may also want to know sending member's id */
1531 srcaddr->member.family = AF_TIPC;
1532 srcaddr->member.addrtype = TIPC_ADDR_NAME;
1533 srcaddr->member.scope = 0;
1534 srcaddr->member.addr.name.name.type = msg_nametype(hdr);
1535 srcaddr->member.addr.name.name.instance = TIPC_SKB_CB(skb)->orig_member;
1536 srcaddr->member.addr.name.domain = 0;
1537 m->msg_namelen = sizeof(*srcaddr);
1541 * tipc_sk_anc_data_recv - optionally capture ancillary data for received message
1542 * @m: descriptor for message info
1543 * @msg: received message header
1544 * @tsk: TIPC port associated with message
1546 * Note: Ancillary data is not captured if not requested by receiver.
1548 * Returns 0 if successful, otherwise errno
1550 static int tipc_sk_anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
1551 struct tipc_sock *tsk)
1553 u32 anc_data[3];
1554 u32 err;
1555 u32 dest_type;
1556 int has_name;
1557 int res;
1559 if (likely(m->msg_controllen == 0))
1560 return 0;
1562 /* Optionally capture errored message object(s) */
1563 err = msg ? msg_errcode(msg) : 0;
1564 if (unlikely(err)) {
1565 anc_data[0] = err;
1566 anc_data[1] = msg_data_sz(msg);
1567 res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1568 if (res)
1569 return res;
1570 if (anc_data[1]) {
1571 res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1572 msg_data(msg));
1573 if (res)
1574 return res;
1578 /* Optionally capture message destination object */
1579 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1580 switch (dest_type) {
1581 case TIPC_NAMED_MSG:
1582 has_name = 1;
1583 anc_data[0] = msg_nametype(msg);
1584 anc_data[1] = msg_namelower(msg);
1585 anc_data[2] = msg_namelower(msg);
1586 break;
1587 case TIPC_MCAST_MSG:
1588 has_name = 1;
1589 anc_data[0] = msg_nametype(msg);
1590 anc_data[1] = msg_namelower(msg);
1591 anc_data[2] = msg_nameupper(msg);
1592 break;
1593 case TIPC_CONN_MSG:
1594 has_name = (tsk->conn_type != 0);
1595 anc_data[0] = tsk->conn_type;
1596 anc_data[1] = tsk->conn_instance;
1597 anc_data[2] = tsk->conn_instance;
1598 break;
1599 default:
1600 has_name = 0;
1602 if (has_name) {
1603 res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1604 if (res)
1605 return res;
1608 return 0;
1611 static void tipc_sk_send_ack(struct tipc_sock *tsk)
1613 struct sock *sk = &tsk->sk;
1614 struct net *net = sock_net(sk);
1615 struct sk_buff *skb = NULL;
1616 struct tipc_msg *msg;
1617 u32 peer_port = tsk_peer_port(tsk);
1618 u32 dnode = tsk_peer_node(tsk);
1620 if (!tipc_sk_connected(sk))
1621 return;
1622 skb = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0,
1623 dnode, tsk_own_node(tsk), peer_port,
1624 tsk->portid, TIPC_OK);
1625 if (!skb)
1626 return;
1627 msg = buf_msg(skb);
1628 msg_set_conn_ack(msg, tsk->rcv_unacked);
1629 tsk->rcv_unacked = 0;
1631 /* Adjust to and advertize the correct window limit */
1632 if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL) {
1633 tsk->rcv_win = tsk_adv_blocks(tsk->sk.sk_rcvbuf);
1634 msg_set_adv_win(msg, tsk->rcv_win);
1636 tipc_node_xmit_skb(net, skb, dnode, msg_link_selector(msg));
1639 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1641 struct sock *sk = sock->sk;
1642 DEFINE_WAIT(wait);
1643 long timeo = *timeop;
1644 int err = sock_error(sk);
1646 if (err)
1647 return err;
1649 for (;;) {
1650 prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1651 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1652 if (sk->sk_shutdown & RCV_SHUTDOWN) {
1653 err = -ENOTCONN;
1654 break;
1656 release_sock(sk);
1657 timeo = schedule_timeout(timeo);
1658 lock_sock(sk);
1660 err = 0;
1661 if (!skb_queue_empty(&sk->sk_receive_queue))
1662 break;
1663 err = -EAGAIN;
1664 if (!timeo)
1665 break;
1666 err = sock_intr_errno(timeo);
1667 if (signal_pending(current))
1668 break;
1670 err = sock_error(sk);
1671 if (err)
1672 break;
1674 finish_wait(sk_sleep(sk), &wait);
1675 *timeop = timeo;
1676 return err;
1680 * tipc_recvmsg - receive packet-oriented message
1681 * @m: descriptor for message info
1682 * @buflen: length of user buffer area
1683 * @flags: receive flags
1685 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1686 * If the complete message doesn't fit in user area, truncate it.
1688 * Returns size of returned message data, errno otherwise
1690 static int tipc_recvmsg(struct socket *sock, struct msghdr *m,
1691 size_t buflen, int flags)
1693 struct sock *sk = sock->sk;
1694 bool connected = !tipc_sk_type_connectionless(sk);
1695 struct tipc_sock *tsk = tipc_sk(sk);
1696 int rc, err, hlen, dlen, copy;
1697 struct sk_buff_head xmitq;
1698 struct tipc_msg *hdr;
1699 struct sk_buff *skb;
1700 bool grp_evt;
1701 long timeout;
1703 /* Catch invalid receive requests */
1704 if (unlikely(!buflen))
1705 return -EINVAL;
1707 lock_sock(sk);
1708 if (unlikely(connected && sk->sk_state == TIPC_OPEN)) {
1709 rc = -ENOTCONN;
1710 goto exit;
1712 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1714 /* Step rcv queue to first msg with data or error; wait if necessary */
1715 do {
1716 rc = tipc_wait_for_rcvmsg(sock, &timeout);
1717 if (unlikely(rc))
1718 goto exit;
1719 skb = skb_peek(&sk->sk_receive_queue);
1720 hdr = buf_msg(skb);
1721 dlen = msg_data_sz(hdr);
1722 hlen = msg_hdr_sz(hdr);
1723 err = msg_errcode(hdr);
1724 grp_evt = msg_is_grp_evt(hdr);
1725 if (likely(dlen || err))
1726 break;
1727 tsk_advance_rx_queue(sk);
1728 } while (1);
1730 /* Collect msg meta data, including error code and rejected data */
1731 tipc_sk_set_orig_addr(m, skb);
1732 rc = tipc_sk_anc_data_recv(m, hdr, tsk);
1733 if (unlikely(rc))
1734 goto exit;
1736 /* Capture data if non-error msg, otherwise just set return value */
1737 if (likely(!err)) {
1738 copy = min_t(int, dlen, buflen);
1739 if (unlikely(copy != dlen))
1740 m->msg_flags |= MSG_TRUNC;
1741 rc = skb_copy_datagram_msg(skb, hlen, m, copy);
1742 } else {
1743 copy = 0;
1744 rc = 0;
1745 if (err != TIPC_CONN_SHUTDOWN && connected && !m->msg_control)
1746 rc = -ECONNRESET;
1748 if (unlikely(rc))
1749 goto exit;
1751 /* Mark message as group event if applicable */
1752 if (unlikely(grp_evt)) {
1753 if (msg_grp_evt(hdr) == TIPC_WITHDRAWN)
1754 m->msg_flags |= MSG_EOR;
1755 m->msg_flags |= MSG_OOB;
1756 copy = 0;
1759 /* Caption of data or error code/rejected data was successful */
1760 if (unlikely(flags & MSG_PEEK))
1761 goto exit;
1763 /* Send group flow control advertisement when applicable */
1764 if (tsk->group && msg_in_group(hdr) && !grp_evt) {
1765 skb_queue_head_init(&xmitq);
1766 tipc_group_update_rcv_win(tsk->group, tsk_blocks(hlen + dlen),
1767 msg_orignode(hdr), msg_origport(hdr),
1768 &xmitq);
1769 tipc_node_distr_xmit(sock_net(sk), &xmitq);
1772 tsk_advance_rx_queue(sk);
1774 if (likely(!connected))
1775 goto exit;
1777 /* Send connection flow control advertisement when applicable */
1778 tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
1779 if (tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE)
1780 tipc_sk_send_ack(tsk);
1781 exit:
1782 release_sock(sk);
1783 return rc ? rc : copy;
1787 * tipc_recvstream - receive stream-oriented data
1788 * @m: descriptor for message info
1789 * @buflen: total size of user buffer area
1790 * @flags: receive flags
1792 * Used for SOCK_STREAM messages only. If not enough data is available
1793 * will optionally wait for more; never truncates data.
1795 * Returns size of returned message data, errno otherwise
1797 static int tipc_recvstream(struct socket *sock, struct msghdr *m,
1798 size_t buflen, int flags)
1800 struct sock *sk = sock->sk;
1801 struct tipc_sock *tsk = tipc_sk(sk);
1802 struct sk_buff *skb;
1803 struct tipc_msg *hdr;
1804 struct tipc_skb_cb *skb_cb;
1805 bool peek = flags & MSG_PEEK;
1806 int offset, required, copy, copied = 0;
1807 int hlen, dlen, err, rc;
1808 long timeout;
1810 /* Catch invalid receive attempts */
1811 if (unlikely(!buflen))
1812 return -EINVAL;
1814 lock_sock(sk);
1816 if (unlikely(sk->sk_state == TIPC_OPEN)) {
1817 rc = -ENOTCONN;
1818 goto exit;
1820 required = sock_rcvlowat(sk, flags & MSG_WAITALL, buflen);
1821 timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1823 do {
1824 /* Look at first msg in receive queue; wait if necessary */
1825 rc = tipc_wait_for_rcvmsg(sock, &timeout);
1826 if (unlikely(rc))
1827 break;
1828 skb = skb_peek(&sk->sk_receive_queue);
1829 skb_cb = TIPC_SKB_CB(skb);
1830 hdr = buf_msg(skb);
1831 dlen = msg_data_sz(hdr);
1832 hlen = msg_hdr_sz(hdr);
1833 err = msg_errcode(hdr);
1835 /* Discard any empty non-errored (SYN-) message */
1836 if (unlikely(!dlen && !err)) {
1837 tsk_advance_rx_queue(sk);
1838 continue;
1841 /* Collect msg meta data, incl. error code and rejected data */
1842 if (!copied) {
1843 tipc_sk_set_orig_addr(m, skb);
1844 rc = tipc_sk_anc_data_recv(m, hdr, tsk);
1845 if (rc)
1846 break;
1849 /* Copy data if msg ok, otherwise return error/partial data */
1850 if (likely(!err)) {
1851 offset = skb_cb->bytes_read;
1852 copy = min_t(int, dlen - offset, buflen - copied);
1853 rc = skb_copy_datagram_msg(skb, hlen + offset, m, copy);
1854 if (unlikely(rc))
1855 break;
1856 copied += copy;
1857 offset += copy;
1858 if (unlikely(offset < dlen)) {
1859 if (!peek)
1860 skb_cb->bytes_read = offset;
1861 break;
1863 } else {
1864 rc = 0;
1865 if ((err != TIPC_CONN_SHUTDOWN) && !m->msg_control)
1866 rc = -ECONNRESET;
1867 if (copied || rc)
1868 break;
1871 if (unlikely(peek))
1872 break;
1874 tsk_advance_rx_queue(sk);
1876 /* Send connection flow control advertisement when applicable */
1877 tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
1878 if (unlikely(tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE))
1879 tipc_sk_send_ack(tsk);
1881 /* Exit if all requested data or FIN/error received */
1882 if (copied == buflen || err)
1883 break;
1885 } while (!skb_queue_empty(&sk->sk_receive_queue) || copied < required);
1886 exit:
1887 release_sock(sk);
1888 return copied ? copied : rc;
1892 * tipc_write_space - wake up thread if port congestion is released
1893 * @sk: socket
1895 static void tipc_write_space(struct sock *sk)
1897 struct socket_wq *wq;
1899 rcu_read_lock();
1900 wq = rcu_dereference(sk->sk_wq);
1901 if (skwq_has_sleeper(wq))
1902 wake_up_interruptible_sync_poll(&wq->wait, EPOLLOUT |
1903 EPOLLWRNORM | EPOLLWRBAND);
1904 rcu_read_unlock();
1908 * tipc_data_ready - wake up threads to indicate messages have been received
1909 * @sk: socket
1910 * @len: the length of messages
1912 static void tipc_data_ready(struct sock *sk)
1914 struct socket_wq *wq;
1916 rcu_read_lock();
1917 wq = rcu_dereference(sk->sk_wq);
1918 if (skwq_has_sleeper(wq))
1919 wake_up_interruptible_sync_poll(&wq->wait, EPOLLIN |
1920 EPOLLRDNORM | EPOLLRDBAND);
1921 rcu_read_unlock();
1924 static void tipc_sock_destruct(struct sock *sk)
1926 __skb_queue_purge(&sk->sk_receive_queue);
1929 static void tipc_sk_proto_rcv(struct sock *sk,
1930 struct sk_buff_head *inputq,
1931 struct sk_buff_head *xmitq)
1933 struct sk_buff *skb = __skb_dequeue(inputq);
1934 struct tipc_sock *tsk = tipc_sk(sk);
1935 struct tipc_msg *hdr = buf_msg(skb);
1936 struct tipc_group *grp = tsk->group;
1937 bool wakeup = false;
1939 switch (msg_user(hdr)) {
1940 case CONN_MANAGER:
1941 tipc_sk_conn_proto_rcv(tsk, skb, xmitq);
1942 return;
1943 case SOCK_WAKEUP:
1944 tipc_dest_del(&tsk->cong_links, msg_orignode(hdr), 0);
1945 tsk->cong_link_cnt--;
1946 wakeup = true;
1947 break;
1948 case GROUP_PROTOCOL:
1949 tipc_group_proto_rcv(grp, &wakeup, hdr, inputq, xmitq);
1950 break;
1951 case TOP_SRV:
1952 tipc_group_member_evt(tsk->group, &wakeup, &sk->sk_rcvbuf,
1953 hdr, inputq, xmitq);
1954 break;
1955 default:
1956 break;
1959 if (wakeup)
1960 sk->sk_write_space(sk);
1962 kfree_skb(skb);
1966 * tipc_filter_connect - Handle incoming message for a connection-based socket
1967 * @tsk: TIPC socket
1968 * @skb: pointer to message buffer. Set to NULL if buffer is consumed
1970 * Returns true if everything ok, false otherwise
1972 static bool tipc_sk_filter_connect(struct tipc_sock *tsk, struct sk_buff *skb)
1974 struct sock *sk = &tsk->sk;
1975 struct net *net = sock_net(sk);
1976 struct tipc_msg *hdr = buf_msg(skb);
1977 u32 pport = msg_origport(hdr);
1978 u32 pnode = msg_orignode(hdr);
1980 if (unlikely(msg_mcast(hdr)))
1981 return false;
1983 switch (sk->sk_state) {
1984 case TIPC_CONNECTING:
1985 /* Accept only ACK or NACK message */
1986 if (unlikely(!msg_connected(hdr))) {
1987 if (pport != tsk_peer_port(tsk) ||
1988 pnode != tsk_peer_node(tsk))
1989 return false;
1991 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1992 sk->sk_err = ECONNREFUSED;
1993 sk->sk_state_change(sk);
1994 return true;
1997 if (unlikely(msg_errcode(hdr))) {
1998 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1999 sk->sk_err = ECONNREFUSED;
2000 sk->sk_state_change(sk);
2001 return true;
2004 if (unlikely(!msg_isdata(hdr))) {
2005 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2006 sk->sk_err = EINVAL;
2007 sk->sk_state_change(sk);
2008 return true;
2011 tipc_sk_finish_conn(tsk, msg_origport(hdr), msg_orignode(hdr));
2012 msg_set_importance(&tsk->phdr, msg_importance(hdr));
2014 /* If 'ACK+' message, add to socket receive queue */
2015 if (msg_data_sz(hdr))
2016 return true;
2018 /* If empty 'ACK-' message, wake up sleeping connect() */
2019 sk->sk_data_ready(sk);
2021 /* 'ACK-' message is neither accepted nor rejected: */
2022 msg_set_dest_droppable(hdr, 1);
2023 return false;
2025 case TIPC_OPEN:
2026 case TIPC_DISCONNECTING:
2027 break;
2028 case TIPC_LISTEN:
2029 /* Accept only SYN message */
2030 if (!msg_connected(hdr) && !(msg_errcode(hdr)))
2031 return true;
2032 break;
2033 case TIPC_ESTABLISHED:
2034 /* Accept only connection-based messages sent by peer */
2035 if (unlikely(!tsk_peer_msg(tsk, hdr)))
2036 return false;
2038 if (unlikely(msg_errcode(hdr))) {
2039 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2040 /* Let timer expire on it's own */
2041 tipc_node_remove_conn(net, tsk_peer_node(tsk),
2042 tsk->portid);
2043 sk->sk_state_change(sk);
2045 return true;
2046 default:
2047 pr_err("Unknown sk_state %u\n", sk->sk_state);
2050 return false;
2054 * rcvbuf_limit - get proper overload limit of socket receive queue
2055 * @sk: socket
2056 * @skb: message
2058 * For connection oriented messages, irrespective of importance,
2059 * default queue limit is 2 MB.
2061 * For connectionless messages, queue limits are based on message
2062 * importance as follows:
2064 * TIPC_LOW_IMPORTANCE (2 MB)
2065 * TIPC_MEDIUM_IMPORTANCE (4 MB)
2066 * TIPC_HIGH_IMPORTANCE (8 MB)
2067 * TIPC_CRITICAL_IMPORTANCE (16 MB)
2069 * Returns overload limit according to corresponding message importance
2071 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *skb)
2073 struct tipc_sock *tsk = tipc_sk(sk);
2074 struct tipc_msg *hdr = buf_msg(skb);
2076 if (unlikely(msg_in_group(hdr)))
2077 return sk->sk_rcvbuf;
2079 if (unlikely(!msg_connected(hdr)))
2080 return sk->sk_rcvbuf << msg_importance(hdr);
2082 if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
2083 return sk->sk_rcvbuf;
2085 return FLOWCTL_MSG_LIM;
2089 * tipc_sk_filter_rcv - validate incoming message
2090 * @sk: socket
2091 * @skb: pointer to message.
2093 * Enqueues message on receive queue if acceptable; optionally handles
2094 * disconnect indication for a connected socket.
2096 * Called with socket lock already taken
2099 static void tipc_sk_filter_rcv(struct sock *sk, struct sk_buff *skb,
2100 struct sk_buff_head *xmitq)
2102 bool sk_conn = !tipc_sk_type_connectionless(sk);
2103 struct tipc_sock *tsk = tipc_sk(sk);
2104 struct tipc_group *grp = tsk->group;
2105 struct tipc_msg *hdr = buf_msg(skb);
2106 struct net *net = sock_net(sk);
2107 struct sk_buff_head inputq;
2108 int limit, err = TIPC_OK;
2110 TIPC_SKB_CB(skb)->bytes_read = 0;
2111 __skb_queue_head_init(&inputq);
2112 __skb_queue_tail(&inputq, skb);
2114 if (unlikely(!msg_isdata(hdr)))
2115 tipc_sk_proto_rcv(sk, &inputq, xmitq);
2117 if (unlikely(grp))
2118 tipc_group_filter_msg(grp, &inputq, xmitq);
2120 /* Validate and add to receive buffer if there is space */
2121 while ((skb = __skb_dequeue(&inputq))) {
2122 hdr = buf_msg(skb);
2123 limit = rcvbuf_limit(sk, skb);
2124 if ((sk_conn && !tipc_sk_filter_connect(tsk, skb)) ||
2125 (!sk_conn && msg_connected(hdr)) ||
2126 (!grp && msg_in_group(hdr)))
2127 err = TIPC_ERR_NO_PORT;
2128 else if (sk_rmem_alloc_get(sk) + skb->truesize >= limit)
2129 err = TIPC_ERR_OVERLOAD;
2131 if (unlikely(err)) {
2132 tipc_skb_reject(net, err, skb, xmitq);
2133 err = TIPC_OK;
2134 continue;
2136 __skb_queue_tail(&sk->sk_receive_queue, skb);
2137 skb_set_owner_r(skb, sk);
2138 sk->sk_data_ready(sk);
2143 * tipc_sk_backlog_rcv - handle incoming message from backlog queue
2144 * @sk: socket
2145 * @skb: message
2147 * Caller must hold socket lock
2149 static int tipc_sk_backlog_rcv(struct sock *sk, struct sk_buff *skb)
2151 unsigned int before = sk_rmem_alloc_get(sk);
2152 struct sk_buff_head xmitq;
2153 unsigned int added;
2155 __skb_queue_head_init(&xmitq);
2157 tipc_sk_filter_rcv(sk, skb, &xmitq);
2158 added = sk_rmem_alloc_get(sk) - before;
2159 atomic_add(added, &tipc_sk(sk)->dupl_rcvcnt);
2161 /* Send pending response/rejected messages, if any */
2162 tipc_node_distr_xmit(sock_net(sk), &xmitq);
2163 return 0;
2167 * tipc_sk_enqueue - extract all buffers with destination 'dport' from
2168 * inputq and try adding them to socket or backlog queue
2169 * @inputq: list of incoming buffers with potentially different destinations
2170 * @sk: socket where the buffers should be enqueued
2171 * @dport: port number for the socket
2173 * Caller must hold socket lock
2175 static void tipc_sk_enqueue(struct sk_buff_head *inputq, struct sock *sk,
2176 u32 dport, struct sk_buff_head *xmitq)
2178 unsigned long time_limit = jiffies + 2;
2179 struct sk_buff *skb;
2180 unsigned int lim;
2181 atomic_t *dcnt;
2182 u32 onode;
2184 while (skb_queue_len(inputq)) {
2185 if (unlikely(time_after_eq(jiffies, time_limit)))
2186 return;
2188 skb = tipc_skb_dequeue(inputq, dport);
2189 if (unlikely(!skb))
2190 return;
2192 /* Add message directly to receive queue if possible */
2193 if (!sock_owned_by_user(sk)) {
2194 tipc_sk_filter_rcv(sk, skb, xmitq);
2195 continue;
2198 /* Try backlog, compensating for double-counted bytes */
2199 dcnt = &tipc_sk(sk)->dupl_rcvcnt;
2200 if (!sk->sk_backlog.len)
2201 atomic_set(dcnt, 0);
2202 lim = rcvbuf_limit(sk, skb) + atomic_read(dcnt);
2203 if (likely(!sk_add_backlog(sk, skb, lim)))
2204 continue;
2206 /* Overload => reject message back to sender */
2207 onode = tipc_own_addr(sock_net(sk));
2208 if (tipc_msg_reverse(onode, &skb, TIPC_ERR_OVERLOAD))
2209 __skb_queue_tail(xmitq, skb);
2210 break;
2215 * tipc_sk_rcv - handle a chain of incoming buffers
2216 * @inputq: buffer list containing the buffers
2217 * Consumes all buffers in list until inputq is empty
2218 * Note: may be called in multiple threads referring to the same queue
2220 void tipc_sk_rcv(struct net *net, struct sk_buff_head *inputq)
2222 struct sk_buff_head xmitq;
2223 u32 dnode, dport = 0;
2224 int err;
2225 struct tipc_sock *tsk;
2226 struct sock *sk;
2227 struct sk_buff *skb;
2229 __skb_queue_head_init(&xmitq);
2230 while (skb_queue_len(inputq)) {
2231 dport = tipc_skb_peek_port(inputq, dport);
2232 tsk = tipc_sk_lookup(net, dport);
2234 if (likely(tsk)) {
2235 sk = &tsk->sk;
2236 if (likely(spin_trylock_bh(&sk->sk_lock.slock))) {
2237 tipc_sk_enqueue(inputq, sk, dport, &xmitq);
2238 spin_unlock_bh(&sk->sk_lock.slock);
2240 /* Send pending response/rejected messages, if any */
2241 tipc_node_distr_xmit(sock_net(sk), &xmitq);
2242 sock_put(sk);
2243 continue;
2245 /* No destination socket => dequeue skb if still there */
2246 skb = tipc_skb_dequeue(inputq, dport);
2247 if (!skb)
2248 return;
2250 /* Try secondary lookup if unresolved named message */
2251 err = TIPC_ERR_NO_PORT;
2252 if (tipc_msg_lookup_dest(net, skb, &err))
2253 goto xmit;
2255 /* Prepare for message rejection */
2256 if (!tipc_msg_reverse(tipc_own_addr(net), &skb, err))
2257 continue;
2258 xmit:
2259 dnode = msg_destnode(buf_msg(skb));
2260 tipc_node_xmit_skb(net, skb, dnode, dport);
2264 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
2266 DEFINE_WAIT_FUNC(wait, woken_wake_function);
2267 struct sock *sk = sock->sk;
2268 int done;
2270 do {
2271 int err = sock_error(sk);
2272 if (err)
2273 return err;
2274 if (!*timeo_p)
2275 return -ETIMEDOUT;
2276 if (signal_pending(current))
2277 return sock_intr_errno(*timeo_p);
2279 add_wait_queue(sk_sleep(sk), &wait);
2280 done = sk_wait_event(sk, timeo_p,
2281 sk->sk_state != TIPC_CONNECTING, &wait);
2282 remove_wait_queue(sk_sleep(sk), &wait);
2283 } while (!done);
2284 return 0;
2288 * tipc_connect - establish a connection to another TIPC port
2289 * @sock: socket structure
2290 * @dest: socket address for destination port
2291 * @destlen: size of socket address data structure
2292 * @flags: file-related flags associated with socket
2294 * Returns 0 on success, errno otherwise
2296 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
2297 int destlen, int flags)
2299 struct sock *sk = sock->sk;
2300 struct tipc_sock *tsk = tipc_sk(sk);
2301 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
2302 struct msghdr m = {NULL,};
2303 long timeout = (flags & O_NONBLOCK) ? 0 : tsk->conn_timeout;
2304 int previous;
2305 int res = 0;
2307 if (destlen != sizeof(struct sockaddr_tipc))
2308 return -EINVAL;
2310 lock_sock(sk);
2312 if (tsk->group) {
2313 res = -EINVAL;
2314 goto exit;
2317 if (dst->family == AF_UNSPEC) {
2318 memset(&tsk->peer, 0, sizeof(struct sockaddr_tipc));
2319 if (!tipc_sk_type_connectionless(sk))
2320 res = -EINVAL;
2321 goto exit;
2322 } else if (dst->family != AF_TIPC) {
2323 res = -EINVAL;
2325 if (dst->addrtype != TIPC_ADDR_ID && dst->addrtype != TIPC_ADDR_NAME)
2326 res = -EINVAL;
2327 if (res)
2328 goto exit;
2330 /* DGRAM/RDM connect(), just save the destaddr */
2331 if (tipc_sk_type_connectionless(sk)) {
2332 memcpy(&tsk->peer, dest, destlen);
2333 goto exit;
2336 previous = sk->sk_state;
2338 switch (sk->sk_state) {
2339 case TIPC_OPEN:
2340 /* Send a 'SYN-' to destination */
2341 m.msg_name = dest;
2342 m.msg_namelen = destlen;
2344 /* If connect is in non-blocking case, set MSG_DONTWAIT to
2345 * indicate send_msg() is never blocked.
2347 if (!timeout)
2348 m.msg_flags = MSG_DONTWAIT;
2350 res = __tipc_sendmsg(sock, &m, 0);
2351 if ((res < 0) && (res != -EWOULDBLOCK))
2352 goto exit;
2354 /* Just entered TIPC_CONNECTING state; the only
2355 * difference is that return value in non-blocking
2356 * case is EINPROGRESS, rather than EALREADY.
2358 res = -EINPROGRESS;
2359 /* fall thru' */
2360 case TIPC_CONNECTING:
2361 if (!timeout) {
2362 if (previous == TIPC_CONNECTING)
2363 res = -EALREADY;
2364 goto exit;
2366 timeout = msecs_to_jiffies(timeout);
2367 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
2368 res = tipc_wait_for_connect(sock, &timeout);
2369 break;
2370 case TIPC_ESTABLISHED:
2371 res = -EISCONN;
2372 break;
2373 default:
2374 res = -EINVAL;
2377 exit:
2378 release_sock(sk);
2379 return res;
2383 * tipc_listen - allow socket to listen for incoming connections
2384 * @sock: socket structure
2385 * @len: (unused)
2387 * Returns 0 on success, errno otherwise
2389 static int tipc_listen(struct socket *sock, int len)
2391 struct sock *sk = sock->sk;
2392 int res;
2394 lock_sock(sk);
2395 res = tipc_set_sk_state(sk, TIPC_LISTEN);
2396 release_sock(sk);
2398 return res;
2401 static int tipc_wait_for_accept(struct socket *sock, long timeo)
2403 struct sock *sk = sock->sk;
2404 DEFINE_WAIT(wait);
2405 int err;
2407 /* True wake-one mechanism for incoming connections: only
2408 * one process gets woken up, not the 'whole herd'.
2409 * Since we do not 'race & poll' for established sockets
2410 * anymore, the common case will execute the loop only once.
2412 for (;;) {
2413 prepare_to_wait_exclusive(sk_sleep(sk), &wait,
2414 TASK_INTERRUPTIBLE);
2415 if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
2416 release_sock(sk);
2417 timeo = schedule_timeout(timeo);
2418 lock_sock(sk);
2420 err = 0;
2421 if (!skb_queue_empty(&sk->sk_receive_queue))
2422 break;
2423 err = -EAGAIN;
2424 if (!timeo)
2425 break;
2426 err = sock_intr_errno(timeo);
2427 if (signal_pending(current))
2428 break;
2430 finish_wait(sk_sleep(sk), &wait);
2431 return err;
2435 * tipc_accept - wait for connection request
2436 * @sock: listening socket
2437 * @newsock: new socket that is to be connected
2438 * @flags: file-related flags associated with socket
2440 * Returns 0 on success, errno otherwise
2442 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
2443 bool kern)
2445 struct sock *new_sk, *sk = sock->sk;
2446 struct sk_buff *buf;
2447 struct tipc_sock *new_tsock;
2448 struct tipc_msg *msg;
2449 long timeo;
2450 int res;
2452 lock_sock(sk);
2454 if (sk->sk_state != TIPC_LISTEN) {
2455 res = -EINVAL;
2456 goto exit;
2458 timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
2459 res = tipc_wait_for_accept(sock, timeo);
2460 if (res)
2461 goto exit;
2463 buf = skb_peek(&sk->sk_receive_queue);
2465 res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, kern);
2466 if (res)
2467 goto exit;
2468 security_sk_clone(sock->sk, new_sock->sk);
2470 new_sk = new_sock->sk;
2471 new_tsock = tipc_sk(new_sk);
2472 msg = buf_msg(buf);
2474 /* we lock on new_sk; but lockdep sees the lock on sk */
2475 lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
2478 * Reject any stray messages received by new socket
2479 * before the socket lock was taken (very, very unlikely)
2481 tsk_rej_rx_queue(new_sk);
2483 /* Connect new socket to it's peer */
2484 tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg));
2486 tsk_set_importance(new_tsock, msg_importance(msg));
2487 if (msg_named(msg)) {
2488 new_tsock->conn_type = msg_nametype(msg);
2489 new_tsock->conn_instance = msg_nameinst(msg);
2493 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
2494 * Respond to 'SYN+' by queuing it on new socket.
2496 if (!msg_data_sz(msg)) {
2497 struct msghdr m = {NULL,};
2499 tsk_advance_rx_queue(sk);
2500 __tipc_sendstream(new_sock, &m, 0);
2501 } else {
2502 __skb_dequeue(&sk->sk_receive_queue);
2503 __skb_queue_head(&new_sk->sk_receive_queue, buf);
2504 skb_set_owner_r(buf, new_sk);
2506 release_sock(new_sk);
2507 exit:
2508 release_sock(sk);
2509 return res;
2513 * tipc_shutdown - shutdown socket connection
2514 * @sock: socket structure
2515 * @how: direction to close (must be SHUT_RDWR)
2517 * Terminates connection (if necessary), then purges socket's receive queue.
2519 * Returns 0 on success, errno otherwise
2521 static int tipc_shutdown(struct socket *sock, int how)
2523 struct sock *sk = sock->sk;
2524 int res;
2526 if (how != SHUT_RDWR)
2527 return -EINVAL;
2529 lock_sock(sk);
2531 __tipc_shutdown(sock, TIPC_CONN_SHUTDOWN);
2532 sk->sk_shutdown = SEND_SHUTDOWN;
2534 if (sk->sk_state == TIPC_DISCONNECTING) {
2535 /* Discard any unreceived messages */
2536 __skb_queue_purge(&sk->sk_receive_queue);
2538 /* Wake up anyone sleeping in poll */
2539 sk->sk_state_change(sk);
2540 res = 0;
2541 } else {
2542 res = -ENOTCONN;
2545 release_sock(sk);
2546 return res;
2549 static void tipc_sk_timeout(struct timer_list *t)
2551 struct sock *sk = from_timer(sk, t, sk_timer);
2552 struct tipc_sock *tsk = tipc_sk(sk);
2553 u32 peer_port = tsk_peer_port(tsk);
2554 u32 peer_node = tsk_peer_node(tsk);
2555 u32 own_node = tsk_own_node(tsk);
2556 u32 own_port = tsk->portid;
2557 struct net *net = sock_net(sk);
2558 struct sk_buff *skb = NULL;
2560 bh_lock_sock(sk);
2561 if (!tipc_sk_connected(sk))
2562 goto exit;
2564 /* Try again later if socket is busy */
2565 if (sock_owned_by_user(sk)) {
2566 sk_reset_timer(sk, &sk->sk_timer, jiffies + HZ / 20);
2567 goto exit;
2570 if (tsk->probe_unacked) {
2571 tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2572 tipc_node_remove_conn(net, peer_node, peer_port);
2573 sk->sk_state_change(sk);
2574 goto exit;
2576 /* Send new probe */
2577 skb = tipc_msg_create(CONN_MANAGER, CONN_PROBE, INT_H_SIZE, 0,
2578 peer_node, own_node, peer_port, own_port,
2579 TIPC_OK);
2580 tsk->probe_unacked = true;
2581 sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTV);
2582 exit:
2583 bh_unlock_sock(sk);
2584 if (skb)
2585 tipc_node_xmit_skb(net, skb, peer_node, own_port);
2586 sock_put(sk);
2589 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
2590 struct tipc_name_seq const *seq)
2592 struct sock *sk = &tsk->sk;
2593 struct net *net = sock_net(sk);
2594 struct publication *publ;
2595 u32 key;
2597 if (tipc_sk_connected(sk))
2598 return -EINVAL;
2599 key = tsk->portid + tsk->pub_count + 1;
2600 if (key == tsk->portid)
2601 return -EADDRINUSE;
2603 publ = tipc_nametbl_publish(net, seq->type, seq->lower, seq->upper,
2604 scope, tsk->portid, key);
2605 if (unlikely(!publ))
2606 return -EINVAL;
2608 list_add(&publ->pport_list, &tsk->publications);
2609 tsk->pub_count++;
2610 tsk->published = 1;
2611 return 0;
2614 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
2615 struct tipc_name_seq const *seq)
2617 struct net *net = sock_net(&tsk->sk);
2618 struct publication *publ;
2619 struct publication *safe;
2620 int rc = -EINVAL;
2622 list_for_each_entry_safe(publ, safe, &tsk->publications, pport_list) {
2623 if (seq) {
2624 if (publ->scope != scope)
2625 continue;
2626 if (publ->type != seq->type)
2627 continue;
2628 if (publ->lower != seq->lower)
2629 continue;
2630 if (publ->upper != seq->upper)
2631 break;
2632 tipc_nametbl_withdraw(net, publ->type, publ->lower,
2633 publ->ref, publ->key);
2634 rc = 0;
2635 break;
2637 tipc_nametbl_withdraw(net, publ->type, publ->lower,
2638 publ->ref, publ->key);
2639 rc = 0;
2641 if (list_empty(&tsk->publications))
2642 tsk->published = 0;
2643 return rc;
2646 /* tipc_sk_reinit: set non-zero address in all existing sockets
2647 * when we go from standalone to network mode.
2649 void tipc_sk_reinit(struct net *net)
2651 struct tipc_net *tn = net_generic(net, tipc_net_id);
2652 struct rhashtable_iter iter;
2653 struct tipc_sock *tsk;
2654 struct tipc_msg *msg;
2656 rhashtable_walk_enter(&tn->sk_rht, &iter);
2658 do {
2659 rhashtable_walk_start(&iter);
2661 while ((tsk = rhashtable_walk_next(&iter)) && !IS_ERR(tsk)) {
2662 spin_lock_bh(&tsk->sk.sk_lock.slock);
2663 msg = &tsk->phdr;
2664 msg_set_prevnode(msg, tn->own_addr);
2665 msg_set_orignode(msg, tn->own_addr);
2666 spin_unlock_bh(&tsk->sk.sk_lock.slock);
2669 rhashtable_walk_stop(&iter);
2670 } while (tsk == ERR_PTR(-EAGAIN));
2673 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid)
2675 struct tipc_net *tn = net_generic(net, tipc_net_id);
2676 struct tipc_sock *tsk;
2678 rcu_read_lock();
2679 tsk = rhashtable_lookup_fast(&tn->sk_rht, &portid, tsk_rht_params);
2680 if (tsk)
2681 sock_hold(&tsk->sk);
2682 rcu_read_unlock();
2684 return tsk;
2687 static int tipc_sk_insert(struct tipc_sock *tsk)
2689 struct sock *sk = &tsk->sk;
2690 struct net *net = sock_net(sk);
2691 struct tipc_net *tn = net_generic(net, tipc_net_id);
2692 u32 remaining = (TIPC_MAX_PORT - TIPC_MIN_PORT) + 1;
2693 u32 portid = prandom_u32() % remaining + TIPC_MIN_PORT;
2695 while (remaining--) {
2696 portid++;
2697 if ((portid < TIPC_MIN_PORT) || (portid > TIPC_MAX_PORT))
2698 portid = TIPC_MIN_PORT;
2699 tsk->portid = portid;
2700 sock_hold(&tsk->sk);
2701 if (!rhashtable_lookup_insert_fast(&tn->sk_rht, &tsk->node,
2702 tsk_rht_params))
2703 return 0;
2704 sock_put(&tsk->sk);
2707 return -1;
2710 static void tipc_sk_remove(struct tipc_sock *tsk)
2712 struct sock *sk = &tsk->sk;
2713 struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
2715 if (!rhashtable_remove_fast(&tn->sk_rht, &tsk->node, tsk_rht_params)) {
2716 WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
2717 __sock_put(sk);
2721 static const struct rhashtable_params tsk_rht_params = {
2722 .nelem_hint = 192,
2723 .head_offset = offsetof(struct tipc_sock, node),
2724 .key_offset = offsetof(struct tipc_sock, portid),
2725 .key_len = sizeof(u32), /* portid */
2726 .max_size = 1048576,
2727 .min_size = 256,
2728 .automatic_shrinking = true,
2731 int tipc_sk_rht_init(struct net *net)
2733 struct tipc_net *tn = net_generic(net, tipc_net_id);
2735 return rhashtable_init(&tn->sk_rht, &tsk_rht_params);
2738 void tipc_sk_rht_destroy(struct net *net)
2740 struct tipc_net *tn = net_generic(net, tipc_net_id);
2742 /* Wait for socket readers to complete */
2743 synchronize_net();
2745 rhashtable_destroy(&tn->sk_rht);
2748 static int tipc_sk_join(struct tipc_sock *tsk, struct tipc_group_req *mreq)
2750 struct net *net = sock_net(&tsk->sk);
2751 struct tipc_group *grp = tsk->group;
2752 struct tipc_msg *hdr = &tsk->phdr;
2753 struct tipc_name_seq seq;
2754 int rc;
2756 if (mreq->type < TIPC_RESERVED_TYPES)
2757 return -EACCES;
2758 if (mreq->scope > TIPC_NODE_SCOPE)
2759 return -EINVAL;
2760 if (grp)
2761 return -EACCES;
2762 grp = tipc_group_create(net, tsk->portid, mreq, &tsk->group_is_open);
2763 if (!grp)
2764 return -ENOMEM;
2765 tsk->group = grp;
2766 msg_set_lookup_scope(hdr, mreq->scope);
2767 msg_set_nametype(hdr, mreq->type);
2768 msg_set_dest_droppable(hdr, true);
2769 seq.type = mreq->type;
2770 seq.lower = mreq->instance;
2771 seq.upper = seq.lower;
2772 tipc_nametbl_build_group(net, grp, mreq->type, mreq->scope);
2773 rc = tipc_sk_publish(tsk, mreq->scope, &seq);
2774 if (rc) {
2775 tipc_group_delete(net, grp);
2776 tsk->group = NULL;
2777 return rc;
2779 /* Eliminate any risk that a broadcast overtakes sent JOINs */
2780 tsk->mc_method.rcast = true;
2781 tsk->mc_method.mandatory = true;
2782 tipc_group_join(net, grp, &tsk->sk.sk_rcvbuf);
2783 return rc;
2786 static int tipc_sk_leave(struct tipc_sock *tsk)
2788 struct net *net = sock_net(&tsk->sk);
2789 struct tipc_group *grp = tsk->group;
2790 struct tipc_name_seq seq;
2791 int scope;
2793 if (!grp)
2794 return -EINVAL;
2795 tipc_group_self(grp, &seq, &scope);
2796 tipc_group_delete(net, grp);
2797 tsk->group = NULL;
2798 tipc_sk_withdraw(tsk, scope, &seq);
2799 return 0;
2803 * tipc_setsockopt - set socket option
2804 * @sock: socket structure
2805 * @lvl: option level
2806 * @opt: option identifier
2807 * @ov: pointer to new option value
2808 * @ol: length of option value
2810 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
2811 * (to ease compatibility).
2813 * Returns 0 on success, errno otherwise
2815 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
2816 char __user *ov, unsigned int ol)
2818 struct sock *sk = sock->sk;
2819 struct tipc_sock *tsk = tipc_sk(sk);
2820 struct tipc_group_req mreq;
2821 u32 value = 0;
2822 int res = 0;
2824 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2825 return 0;
2826 if (lvl != SOL_TIPC)
2827 return -ENOPROTOOPT;
2829 switch (opt) {
2830 case TIPC_IMPORTANCE:
2831 case TIPC_SRC_DROPPABLE:
2832 case TIPC_DEST_DROPPABLE:
2833 case TIPC_CONN_TIMEOUT:
2834 if (ol < sizeof(value))
2835 return -EINVAL;
2836 if (get_user(value, (u32 __user *)ov))
2837 return -EFAULT;
2838 break;
2839 case TIPC_GROUP_JOIN:
2840 if (ol < sizeof(mreq))
2841 return -EINVAL;
2842 if (copy_from_user(&mreq, ov, sizeof(mreq)))
2843 return -EFAULT;
2844 break;
2845 default:
2846 if (ov || ol)
2847 return -EINVAL;
2850 lock_sock(sk);
2852 switch (opt) {
2853 case TIPC_IMPORTANCE:
2854 res = tsk_set_importance(tsk, value);
2855 break;
2856 case TIPC_SRC_DROPPABLE:
2857 if (sock->type != SOCK_STREAM)
2858 tsk_set_unreliable(tsk, value);
2859 else
2860 res = -ENOPROTOOPT;
2861 break;
2862 case TIPC_DEST_DROPPABLE:
2863 tsk_set_unreturnable(tsk, value);
2864 break;
2865 case TIPC_CONN_TIMEOUT:
2866 tipc_sk(sk)->conn_timeout = value;
2867 break;
2868 case TIPC_MCAST_BROADCAST:
2869 tsk->mc_method.rcast = false;
2870 tsk->mc_method.mandatory = true;
2871 break;
2872 case TIPC_MCAST_REPLICAST:
2873 tsk->mc_method.rcast = true;
2874 tsk->mc_method.mandatory = true;
2875 break;
2876 case TIPC_GROUP_JOIN:
2877 res = tipc_sk_join(tsk, &mreq);
2878 break;
2879 case TIPC_GROUP_LEAVE:
2880 res = tipc_sk_leave(tsk);
2881 break;
2882 default:
2883 res = -EINVAL;
2886 release_sock(sk);
2888 return res;
2892 * tipc_getsockopt - get socket option
2893 * @sock: socket structure
2894 * @lvl: option level
2895 * @opt: option identifier
2896 * @ov: receptacle for option value
2897 * @ol: receptacle for length of option value
2899 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
2900 * (to ease compatibility).
2902 * Returns 0 on success, errno otherwise
2904 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
2905 char __user *ov, int __user *ol)
2907 struct sock *sk = sock->sk;
2908 struct tipc_sock *tsk = tipc_sk(sk);
2909 struct tipc_name_seq seq;
2910 int len, scope;
2911 u32 value;
2912 int res;
2914 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2915 return put_user(0, ol);
2916 if (lvl != SOL_TIPC)
2917 return -ENOPROTOOPT;
2918 res = get_user(len, ol);
2919 if (res)
2920 return res;
2922 lock_sock(sk);
2924 switch (opt) {
2925 case TIPC_IMPORTANCE:
2926 value = tsk_importance(tsk);
2927 break;
2928 case TIPC_SRC_DROPPABLE:
2929 value = tsk_unreliable(tsk);
2930 break;
2931 case TIPC_DEST_DROPPABLE:
2932 value = tsk_unreturnable(tsk);
2933 break;
2934 case TIPC_CONN_TIMEOUT:
2935 value = tsk->conn_timeout;
2936 /* no need to set "res", since already 0 at this point */
2937 break;
2938 case TIPC_NODE_RECVQ_DEPTH:
2939 value = 0; /* was tipc_queue_size, now obsolete */
2940 break;
2941 case TIPC_SOCK_RECVQ_DEPTH:
2942 value = skb_queue_len(&sk->sk_receive_queue);
2943 break;
2944 case TIPC_GROUP_JOIN:
2945 seq.type = 0;
2946 if (tsk->group)
2947 tipc_group_self(tsk->group, &seq, &scope);
2948 value = seq.type;
2949 break;
2950 default:
2951 res = -EINVAL;
2954 release_sock(sk);
2956 if (res)
2957 return res; /* "get" failed */
2959 if (len < sizeof(value))
2960 return -EINVAL;
2962 if (copy_to_user(ov, &value, sizeof(value)))
2963 return -EFAULT;
2965 return put_user(sizeof(value), ol);
2968 static int tipc_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
2970 struct sock *sk = sock->sk;
2971 struct tipc_sioc_ln_req lnr;
2972 void __user *argp = (void __user *)arg;
2974 switch (cmd) {
2975 case SIOCGETLINKNAME:
2976 if (copy_from_user(&lnr, argp, sizeof(lnr)))
2977 return -EFAULT;
2978 if (!tipc_node_get_linkname(sock_net(sk),
2979 lnr.bearer_id & 0xffff, lnr.peer,
2980 lnr.linkname, TIPC_MAX_LINK_NAME)) {
2981 if (copy_to_user(argp, &lnr, sizeof(lnr)))
2982 return -EFAULT;
2983 return 0;
2985 return -EADDRNOTAVAIL;
2986 default:
2987 return -ENOIOCTLCMD;
2991 static int tipc_socketpair(struct socket *sock1, struct socket *sock2)
2993 struct tipc_sock *tsk2 = tipc_sk(sock2->sk);
2994 struct tipc_sock *tsk1 = tipc_sk(sock1->sk);
2995 u32 onode = tipc_own_addr(sock_net(sock1->sk));
2997 tsk1->peer.family = AF_TIPC;
2998 tsk1->peer.addrtype = TIPC_ADDR_ID;
2999 tsk1->peer.scope = TIPC_NODE_SCOPE;
3000 tsk1->peer.addr.id.ref = tsk2->portid;
3001 tsk1->peer.addr.id.node = onode;
3002 tsk2->peer.family = AF_TIPC;
3003 tsk2->peer.addrtype = TIPC_ADDR_ID;
3004 tsk2->peer.scope = TIPC_NODE_SCOPE;
3005 tsk2->peer.addr.id.ref = tsk1->portid;
3006 tsk2->peer.addr.id.node = onode;
3008 tipc_sk_finish_conn(tsk1, tsk2->portid, onode);
3009 tipc_sk_finish_conn(tsk2, tsk1->portid, onode);
3010 return 0;
3013 /* Protocol switches for the various types of TIPC sockets */
3015 static const struct proto_ops msg_ops = {
3016 .owner = THIS_MODULE,
3017 .family = AF_TIPC,
3018 .release = tipc_release,
3019 .bind = tipc_bind,
3020 .connect = tipc_connect,
3021 .socketpair = tipc_socketpair,
3022 .accept = sock_no_accept,
3023 .getname = tipc_getname,
3024 .poll = tipc_poll,
3025 .ioctl = tipc_ioctl,
3026 .listen = sock_no_listen,
3027 .shutdown = tipc_shutdown,
3028 .setsockopt = tipc_setsockopt,
3029 .getsockopt = tipc_getsockopt,
3030 .sendmsg = tipc_sendmsg,
3031 .recvmsg = tipc_recvmsg,
3032 .mmap = sock_no_mmap,
3033 .sendpage = sock_no_sendpage
3036 static const struct proto_ops packet_ops = {
3037 .owner = THIS_MODULE,
3038 .family = AF_TIPC,
3039 .release = tipc_release,
3040 .bind = tipc_bind,
3041 .connect = tipc_connect,
3042 .socketpair = tipc_socketpair,
3043 .accept = tipc_accept,
3044 .getname = tipc_getname,
3045 .poll = tipc_poll,
3046 .ioctl = tipc_ioctl,
3047 .listen = tipc_listen,
3048 .shutdown = tipc_shutdown,
3049 .setsockopt = tipc_setsockopt,
3050 .getsockopt = tipc_getsockopt,
3051 .sendmsg = tipc_send_packet,
3052 .recvmsg = tipc_recvmsg,
3053 .mmap = sock_no_mmap,
3054 .sendpage = sock_no_sendpage
3057 static const struct proto_ops stream_ops = {
3058 .owner = THIS_MODULE,
3059 .family = AF_TIPC,
3060 .release = tipc_release,
3061 .bind = tipc_bind,
3062 .connect = tipc_connect,
3063 .socketpair = tipc_socketpair,
3064 .accept = tipc_accept,
3065 .getname = tipc_getname,
3066 .poll = tipc_poll,
3067 .ioctl = tipc_ioctl,
3068 .listen = tipc_listen,
3069 .shutdown = tipc_shutdown,
3070 .setsockopt = tipc_setsockopt,
3071 .getsockopt = tipc_getsockopt,
3072 .sendmsg = tipc_sendstream,
3073 .recvmsg = tipc_recvstream,
3074 .mmap = sock_no_mmap,
3075 .sendpage = sock_no_sendpage
3078 static const struct net_proto_family tipc_family_ops = {
3079 .owner = THIS_MODULE,
3080 .family = AF_TIPC,
3081 .create = tipc_sk_create
3084 static struct proto tipc_proto = {
3085 .name = "TIPC",
3086 .owner = THIS_MODULE,
3087 .obj_size = sizeof(struct tipc_sock),
3088 .sysctl_rmem = sysctl_tipc_rmem
3092 * tipc_socket_init - initialize TIPC socket interface
3094 * Returns 0 on success, errno otherwise
3096 int tipc_socket_init(void)
3098 int res;
3100 res = proto_register(&tipc_proto, 1);
3101 if (res) {
3102 pr_err("Failed to register TIPC protocol type\n");
3103 goto out;
3106 res = sock_register(&tipc_family_ops);
3107 if (res) {
3108 pr_err("Failed to register TIPC socket type\n");
3109 proto_unregister(&tipc_proto);
3110 goto out;
3112 out:
3113 return res;
3117 * tipc_socket_stop - stop TIPC socket interface
3119 void tipc_socket_stop(void)
3121 sock_unregister(tipc_family_ops.family);
3122 proto_unregister(&tipc_proto);
3125 /* Caller should hold socket lock for the passed tipc socket. */
3126 static int __tipc_nl_add_sk_con(struct sk_buff *skb, struct tipc_sock *tsk)
3128 u32 peer_node;
3129 u32 peer_port;
3130 struct nlattr *nest;
3132 peer_node = tsk_peer_node(tsk);
3133 peer_port = tsk_peer_port(tsk);
3135 nest = nla_nest_start(skb, TIPC_NLA_SOCK_CON);
3137 if (nla_put_u32(skb, TIPC_NLA_CON_NODE, peer_node))
3138 goto msg_full;
3139 if (nla_put_u32(skb, TIPC_NLA_CON_SOCK, peer_port))
3140 goto msg_full;
3142 if (tsk->conn_type != 0) {
3143 if (nla_put_flag(skb, TIPC_NLA_CON_FLAG))
3144 goto msg_full;
3145 if (nla_put_u32(skb, TIPC_NLA_CON_TYPE, tsk->conn_type))
3146 goto msg_full;
3147 if (nla_put_u32(skb, TIPC_NLA_CON_INST, tsk->conn_instance))
3148 goto msg_full;
3150 nla_nest_end(skb, nest);
3152 return 0;
3154 msg_full:
3155 nla_nest_cancel(skb, nest);
3157 return -EMSGSIZE;
3160 /* Caller should hold socket lock for the passed tipc socket. */
3161 static int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb,
3162 struct tipc_sock *tsk)
3164 int err;
3165 void *hdr;
3166 struct nlattr *attrs;
3167 struct net *net = sock_net(skb->sk);
3168 struct tipc_net *tn = net_generic(net, tipc_net_id);
3169 struct sock *sk = &tsk->sk;
3171 hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3172 &tipc_genl_family, NLM_F_MULTI, TIPC_NL_SOCK_GET);
3173 if (!hdr)
3174 goto msg_cancel;
3176 attrs = nla_nest_start(skb, TIPC_NLA_SOCK);
3177 if (!attrs)
3178 goto genlmsg_cancel;
3179 if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->portid))
3180 goto attr_msg_cancel;
3181 if (nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tn->own_addr))
3182 goto attr_msg_cancel;
3184 if (tipc_sk_connected(sk)) {
3185 err = __tipc_nl_add_sk_con(skb, tsk);
3186 if (err)
3187 goto attr_msg_cancel;
3188 } else if (!list_empty(&tsk->publications)) {
3189 if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL))
3190 goto attr_msg_cancel;
3192 nla_nest_end(skb, attrs);
3193 genlmsg_end(skb, hdr);
3195 return 0;
3197 attr_msg_cancel:
3198 nla_nest_cancel(skb, attrs);
3199 genlmsg_cancel:
3200 genlmsg_cancel(skb, hdr);
3201 msg_cancel:
3202 return -EMSGSIZE;
3205 int tipc_nl_sk_dump(struct sk_buff *skb, struct netlink_callback *cb)
3207 int err;
3208 struct tipc_sock *tsk;
3209 const struct bucket_table *tbl;
3210 struct rhash_head *pos;
3211 struct net *net = sock_net(skb->sk);
3212 struct tipc_net *tn = net_generic(net, tipc_net_id);
3213 u32 tbl_id = cb->args[0];
3214 u32 prev_portid = cb->args[1];
3216 rcu_read_lock();
3217 tbl = rht_dereference_rcu((&tn->sk_rht)->tbl, &tn->sk_rht);
3218 for (; tbl_id < tbl->size; tbl_id++) {
3219 rht_for_each_entry_rcu(tsk, pos, tbl, tbl_id, node) {
3220 spin_lock_bh(&tsk->sk.sk_lock.slock);
3221 if (prev_portid && prev_portid != tsk->portid) {
3222 spin_unlock_bh(&tsk->sk.sk_lock.slock);
3223 continue;
3226 err = __tipc_nl_add_sk(skb, cb, tsk);
3227 if (err) {
3228 prev_portid = tsk->portid;
3229 spin_unlock_bh(&tsk->sk.sk_lock.slock);
3230 goto out;
3232 prev_portid = 0;
3233 spin_unlock_bh(&tsk->sk.sk_lock.slock);
3236 out:
3237 rcu_read_unlock();
3238 cb->args[0] = tbl_id;
3239 cb->args[1] = prev_portid;
3241 return skb->len;
3244 /* Caller should hold socket lock for the passed tipc socket. */
3245 static int __tipc_nl_add_sk_publ(struct sk_buff *skb,
3246 struct netlink_callback *cb,
3247 struct publication *publ)
3249 void *hdr;
3250 struct nlattr *attrs;
3252 hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
3253 &tipc_genl_family, NLM_F_MULTI, TIPC_NL_PUBL_GET);
3254 if (!hdr)
3255 goto msg_cancel;
3257 attrs = nla_nest_start(skb, TIPC_NLA_PUBL);
3258 if (!attrs)
3259 goto genlmsg_cancel;
3261 if (nla_put_u32(skb, TIPC_NLA_PUBL_KEY, publ->key))
3262 goto attr_msg_cancel;
3263 if (nla_put_u32(skb, TIPC_NLA_PUBL_TYPE, publ->type))
3264 goto attr_msg_cancel;
3265 if (nla_put_u32(skb, TIPC_NLA_PUBL_LOWER, publ->lower))
3266 goto attr_msg_cancel;
3267 if (nla_put_u32(skb, TIPC_NLA_PUBL_UPPER, publ->upper))
3268 goto attr_msg_cancel;
3270 nla_nest_end(skb, attrs);
3271 genlmsg_end(skb, hdr);
3273 return 0;
3275 attr_msg_cancel:
3276 nla_nest_cancel(skb, attrs);
3277 genlmsg_cancel:
3278 genlmsg_cancel(skb, hdr);
3279 msg_cancel:
3280 return -EMSGSIZE;
3283 /* Caller should hold socket lock for the passed tipc socket. */
3284 static int __tipc_nl_list_sk_publ(struct sk_buff *skb,
3285 struct netlink_callback *cb,
3286 struct tipc_sock *tsk, u32 *last_publ)
3288 int err;
3289 struct publication *p;
3291 if (*last_publ) {
3292 list_for_each_entry(p, &tsk->publications, pport_list) {
3293 if (p->key == *last_publ)
3294 break;
3296 if (p->key != *last_publ) {
3297 /* We never set seq or call nl_dump_check_consistent()
3298 * this means that setting prev_seq here will cause the
3299 * consistence check to fail in the netlink callback
3300 * handler. Resulting in the last NLMSG_DONE message
3301 * having the NLM_F_DUMP_INTR flag set.
3303 cb->prev_seq = 1;
3304 *last_publ = 0;
3305 return -EPIPE;
3307 } else {
3308 p = list_first_entry(&tsk->publications, struct publication,
3309 pport_list);
3312 list_for_each_entry_from(p, &tsk->publications, pport_list) {
3313 err = __tipc_nl_add_sk_publ(skb, cb, p);
3314 if (err) {
3315 *last_publ = p->key;
3316 return err;
3319 *last_publ = 0;
3321 return 0;
3324 int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
3326 int err;
3327 u32 tsk_portid = cb->args[0];
3328 u32 last_publ = cb->args[1];
3329 u32 done = cb->args[2];
3330 struct net *net = sock_net(skb->sk);
3331 struct tipc_sock *tsk;
3333 if (!tsk_portid) {
3334 struct nlattr **attrs;
3335 struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
3337 err = tipc_nlmsg_parse(cb->nlh, &attrs);
3338 if (err)
3339 return err;
3341 if (!attrs[TIPC_NLA_SOCK])
3342 return -EINVAL;
3344 err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
3345 attrs[TIPC_NLA_SOCK],
3346 tipc_nl_sock_policy, NULL);
3347 if (err)
3348 return err;
3350 if (!sock[TIPC_NLA_SOCK_REF])
3351 return -EINVAL;
3353 tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
3356 if (done)
3357 return 0;
3359 tsk = tipc_sk_lookup(net, tsk_portid);
3360 if (!tsk)
3361 return -EINVAL;
3363 lock_sock(&tsk->sk);
3364 err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
3365 if (!err)
3366 done = 1;
3367 release_sock(&tsk->sk);
3368 sock_put(&tsk->sk);
3370 cb->args[0] = tsk_portid;
3371 cb->args[1] = last_publ;
3372 cb->args[2] = done;
3374 return skb->len;