• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, 2012-2016, Ericsson AB
5  * Copyright (c) 2004-2008, 2010-2013, Wind River Systems
6  * All rights reserved.
7  *
8  * Redistribution and use in source and binary forms, with or without
9  * modification, are permitted provided that the following conditions are met:
10  *
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.
19  *
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.
23  *
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.
35  */
36 
37 #include <linux/rhashtable.h>
38 #include <linux/sched/signal.h>
39 
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 
49 #define CONN_TIMEOUT_DEFAULT	8000	/* default connect timeout = 8s */
50 #define CONN_PROBING_INTERVAL	msecs_to_jiffies(3600000)  /* [ms] => 1 h */
51 #define TIPC_FWD_MSG		1
52 #define TIPC_MAX_PORT		0xffffffff
53 #define TIPC_MIN_PORT		1
54 #define TIPC_ACK_RATE		4       /* ACK at 1/4 of of rcv window size */
55 
56 enum {
57 	TIPC_LISTEN = TCP_LISTEN,
58 	TIPC_ESTABLISHED = TCP_ESTABLISHED,
59 	TIPC_OPEN = TCP_CLOSE,
60 	TIPC_DISCONNECTING = TCP_CLOSE_WAIT,
61 	TIPC_CONNECTING = TCP_SYN_SENT,
62 };
63 
64 /**
65  * struct tipc_sock - TIPC socket structure
66  * @sk: socket - interacts with 'port' and with user via the socket API
67  * @conn_type: TIPC type used when connection was established
68  * @conn_instance: TIPC instance used when connection was established
69  * @published: non-zero if port has one or more associated names
70  * @max_pkt: maximum packet size "hint" used when building messages sent by port
71  * @portid: unique port identity in TIPC socket hash table
72  * @phdr: preformatted message header used when sending messages
73  * #cong_links: list of congested links
74  * @publications: list of publications for port
75  * @blocking_link: address of the congested link we are currently sleeping on
76  * @pub_count: total # of publications port has made during its lifetime
77  * @probing_state:
78  * @conn_timeout: the time we can wait for an unresponded setup request
79  * @dupl_rcvcnt: number of bytes counted twice, in both backlog and rcv queue
80  * @cong_link_cnt: number of congested links
81  * @sent_unacked: # messages sent by socket, and not yet acked by peer
82  * @rcv_unacked: # messages read by user, but not yet acked back to peer
83  * @peer: 'connected' peer for dgram/rdm
84  * @node: hash table node
85  * @mc_method: cookie for use between socket and broadcast layer
86  * @rcu: rcu struct for tipc_sock
87  */
88 struct tipc_sock {
89 	struct sock sk;
90 	u32 conn_type;
91 	u32 conn_instance;
92 	int published;
93 	u32 max_pkt;
94 	u32 portid;
95 	struct tipc_msg phdr;
96 	struct list_head cong_links;
97 	struct list_head publications;
98 	u32 pub_count;
99 	uint conn_timeout;
100 	atomic_t dupl_rcvcnt;
101 	bool probe_unacked;
102 	u16 cong_link_cnt;
103 	u16 snt_unacked;
104 	u16 snd_win;
105 	u16 peer_caps;
106 	u16 rcv_unacked;
107 	u16 rcv_win;
108 	struct sockaddr_tipc peer;
109 	struct rhash_head node;
110 	struct tipc_mc_method mc_method;
111 	struct rcu_head rcu;
112 };
113 
114 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb);
115 static void tipc_data_ready(struct sock *sk);
116 static void tipc_write_space(struct sock *sk);
117 static void tipc_sock_destruct(struct sock *sk);
118 static int tipc_release(struct socket *sock);
119 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
120 		       bool kern);
121 static void tipc_sk_timeout(unsigned long data);
122 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
123 			   struct tipc_name_seq const *seq);
124 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
125 			    struct tipc_name_seq const *seq);
126 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid);
127 static int tipc_sk_insert(struct tipc_sock *tsk);
128 static void tipc_sk_remove(struct tipc_sock *tsk);
129 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz);
130 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dsz);
131 
132 static const struct proto_ops packet_ops;
133 static const struct proto_ops stream_ops;
134 static const struct proto_ops msg_ops;
135 static struct proto tipc_proto;
136 static const struct rhashtable_params tsk_rht_params;
137 
tsk_own_node(struct tipc_sock * tsk)138 static u32 tsk_own_node(struct tipc_sock *tsk)
139 {
140 	return msg_prevnode(&tsk->phdr);
141 }
142 
tsk_peer_node(struct tipc_sock * tsk)143 static u32 tsk_peer_node(struct tipc_sock *tsk)
144 {
145 	return msg_destnode(&tsk->phdr);
146 }
147 
tsk_peer_port(struct tipc_sock * tsk)148 static u32 tsk_peer_port(struct tipc_sock *tsk)
149 {
150 	return msg_destport(&tsk->phdr);
151 }
152 
tsk_unreliable(struct tipc_sock * tsk)153 static  bool tsk_unreliable(struct tipc_sock *tsk)
154 {
155 	return msg_src_droppable(&tsk->phdr) != 0;
156 }
157 
tsk_set_unreliable(struct tipc_sock * tsk,bool unreliable)158 static void tsk_set_unreliable(struct tipc_sock *tsk, bool unreliable)
159 {
160 	msg_set_src_droppable(&tsk->phdr, unreliable ? 1 : 0);
161 }
162 
tsk_unreturnable(struct tipc_sock * tsk)163 static bool tsk_unreturnable(struct tipc_sock *tsk)
164 {
165 	return msg_dest_droppable(&tsk->phdr) != 0;
166 }
167 
tsk_set_unreturnable(struct tipc_sock * tsk,bool unreturnable)168 static void tsk_set_unreturnable(struct tipc_sock *tsk, bool unreturnable)
169 {
170 	msg_set_dest_droppable(&tsk->phdr, unreturnable ? 1 : 0);
171 }
172 
tsk_importance(struct tipc_sock * tsk)173 static int tsk_importance(struct tipc_sock *tsk)
174 {
175 	return msg_importance(&tsk->phdr);
176 }
177 
tsk_set_importance(struct tipc_sock * tsk,int imp)178 static int tsk_set_importance(struct tipc_sock *tsk, int imp)
179 {
180 	if (imp > TIPC_CRITICAL_IMPORTANCE)
181 		return -EINVAL;
182 	msg_set_importance(&tsk->phdr, (u32)imp);
183 	return 0;
184 }
185 
tipc_sk(const struct sock * sk)186 static struct tipc_sock *tipc_sk(const struct sock *sk)
187 {
188 	return container_of(sk, struct tipc_sock, sk);
189 }
190 
tsk_conn_cong(struct tipc_sock * tsk)191 static bool tsk_conn_cong(struct tipc_sock *tsk)
192 {
193 	return tsk->snt_unacked > tsk->snd_win;
194 }
195 
196 /* tsk_blocks(): translate a buffer size in bytes to number of
197  * advertisable blocks, taking into account the ratio truesize(len)/len
198  * We can trust that this ratio is always < 4 for len >= FLOWCTL_BLK_SZ
199  */
tsk_adv_blocks(int len)200 static u16 tsk_adv_blocks(int len)
201 {
202 	return len / FLOWCTL_BLK_SZ / 4;
203 }
204 
205 /* tsk_inc(): increment counter for sent or received data
206  * - If block based flow control is not supported by peer we
207  *   fall back to message based ditto, incrementing the counter
208  */
tsk_inc(struct tipc_sock * tsk,int msglen)209 static u16 tsk_inc(struct tipc_sock *tsk, int msglen)
210 {
211 	if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
212 		return ((msglen / FLOWCTL_BLK_SZ) + 1);
213 	return 1;
214 }
215 
216 /**
217  * tsk_advance_rx_queue - discard first buffer in socket receive queue
218  *
219  * Caller must hold socket lock
220  */
tsk_advance_rx_queue(struct sock * sk)221 static void tsk_advance_rx_queue(struct sock *sk)
222 {
223 	kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
224 }
225 
226 /* tipc_sk_respond() : send response message back to sender
227  */
tipc_sk_respond(struct sock * sk,struct sk_buff * skb,int err)228 static void tipc_sk_respond(struct sock *sk, struct sk_buff *skb, int err)
229 {
230 	u32 selector;
231 	u32 dnode;
232 	u32 onode = tipc_own_addr(sock_net(sk));
233 
234 	if (!tipc_msg_reverse(onode, &skb, err))
235 		return;
236 
237 	dnode = msg_destnode(buf_msg(skb));
238 	selector = msg_origport(buf_msg(skb));
239 	tipc_node_xmit_skb(sock_net(sk), skb, dnode, selector);
240 }
241 
242 /**
243  * tsk_rej_rx_queue - reject all buffers in socket receive queue
244  *
245  * Caller must hold socket lock
246  */
tsk_rej_rx_queue(struct sock * sk)247 static void tsk_rej_rx_queue(struct sock *sk)
248 {
249 	struct sk_buff *skb;
250 
251 	while ((skb = __skb_dequeue(&sk->sk_receive_queue)))
252 		tipc_sk_respond(sk, skb, TIPC_ERR_NO_PORT);
253 }
254 
tipc_sk_connected(struct sock * sk)255 static bool tipc_sk_connected(struct sock *sk)
256 {
257 	return sk->sk_state == TIPC_ESTABLISHED;
258 }
259 
260 /* tipc_sk_type_connectionless - check if the socket is datagram socket
261  * @sk: socket
262  *
263  * Returns true if connection less, false otherwise
264  */
tipc_sk_type_connectionless(struct sock * sk)265 static bool tipc_sk_type_connectionless(struct sock *sk)
266 {
267 	return sk->sk_type == SOCK_RDM || sk->sk_type == SOCK_DGRAM;
268 }
269 
270 /* tsk_peer_msg - verify if message was sent by connected port's peer
271  *
272  * Handles cases where the node's network address has changed from
273  * the default of <0.0.0> to its configured setting.
274  */
tsk_peer_msg(struct tipc_sock * tsk,struct tipc_msg * msg)275 static bool tsk_peer_msg(struct tipc_sock *tsk, struct tipc_msg *msg)
276 {
277 	struct sock *sk = &tsk->sk;
278 	struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
279 	u32 peer_port = tsk_peer_port(tsk);
280 	u32 orig_node;
281 	u32 peer_node;
282 
283 	if (unlikely(!tipc_sk_connected(sk)))
284 		return false;
285 
286 	if (unlikely(msg_origport(msg) != peer_port))
287 		return false;
288 
289 	orig_node = msg_orignode(msg);
290 	peer_node = tsk_peer_node(tsk);
291 
292 	if (likely(orig_node == peer_node))
293 		return true;
294 
295 	if (!orig_node && (peer_node == tn->own_addr))
296 		return true;
297 
298 	if (!peer_node && (orig_node == tn->own_addr))
299 		return true;
300 
301 	return false;
302 }
303 
304 /* tipc_set_sk_state - set the sk_state of the socket
305  * @sk: socket
306  *
307  * Caller must hold socket lock
308  *
309  * Returns 0 on success, errno otherwise
310  */
tipc_set_sk_state(struct sock * sk,int state)311 static int tipc_set_sk_state(struct sock *sk, int state)
312 {
313 	int oldsk_state = sk->sk_state;
314 	int res = -EINVAL;
315 
316 	switch (state) {
317 	case TIPC_OPEN:
318 		res = 0;
319 		break;
320 	case TIPC_LISTEN:
321 	case TIPC_CONNECTING:
322 		if (oldsk_state == TIPC_OPEN)
323 			res = 0;
324 		break;
325 	case TIPC_ESTABLISHED:
326 		if (oldsk_state == TIPC_CONNECTING ||
327 		    oldsk_state == TIPC_OPEN)
328 			res = 0;
329 		break;
330 	case TIPC_DISCONNECTING:
331 		if (oldsk_state == TIPC_CONNECTING ||
332 		    oldsk_state == TIPC_ESTABLISHED)
333 			res = 0;
334 		break;
335 	}
336 
337 	if (!res)
338 		sk->sk_state = state;
339 
340 	return res;
341 }
342 
tipc_sk_sock_err(struct socket * sock,long * timeout)343 static int tipc_sk_sock_err(struct socket *sock, long *timeout)
344 {
345 	struct sock *sk = sock->sk;
346 	int err = sock_error(sk);
347 	int typ = sock->type;
348 
349 	if (err)
350 		return err;
351 	if (typ == SOCK_STREAM || typ == SOCK_SEQPACKET) {
352 		if (sk->sk_state == TIPC_DISCONNECTING)
353 			return -EPIPE;
354 		else if (!tipc_sk_connected(sk))
355 			return -ENOTCONN;
356 	}
357 	if (!*timeout)
358 		return -EAGAIN;
359 	if (signal_pending(current))
360 		return sock_intr_errno(*timeout);
361 
362 	return 0;
363 }
364 
365 #define tipc_wait_for_cond(sock_, timeo_, condition_)			       \
366 ({                                                                             \
367 	struct sock *sk_;						       \
368 	int rc_;							       \
369 									       \
370 	while ((rc_ = !(condition_))) {					       \
371 		DEFINE_WAIT_FUNC(wait_, woken_wake_function);	               \
372 		sk_ = (sock_)->sk;					       \
373 		rc_ = tipc_sk_sock_err((sock_), timeo_);		       \
374 		if (rc_)						       \
375 			break;						       \
376 		prepare_to_wait(sk_sleep(sk_), &wait_, TASK_INTERRUPTIBLE);    \
377 		release_sock(sk_);					       \
378 		*(timeo_) = wait_woken(&wait_, TASK_INTERRUPTIBLE, *(timeo_)); \
379 		sched_annotate_sleep();				               \
380 		lock_sock(sk_);						       \
381 		remove_wait_queue(sk_sleep(sk_), &wait_);		       \
382 	}								       \
383 	rc_;								       \
384 })
385 
386 /**
387  * tipc_sk_create - create a TIPC socket
388  * @net: network namespace (must be default network)
389  * @sock: pre-allocated socket structure
390  * @protocol: protocol indicator (must be 0)
391  * @kern: caused by kernel or by userspace?
392  *
393  * This routine creates additional data structures used by the TIPC socket,
394  * initializes them, and links them together.
395  *
396  * Returns 0 on success, errno otherwise
397  */
tipc_sk_create(struct net * net,struct socket * sock,int protocol,int kern)398 static int tipc_sk_create(struct net *net, struct socket *sock,
399 			  int protocol, int kern)
400 {
401 	struct tipc_net *tn;
402 	const struct proto_ops *ops;
403 	struct sock *sk;
404 	struct tipc_sock *tsk;
405 	struct tipc_msg *msg;
406 
407 	/* Validate arguments */
408 	if (unlikely(protocol != 0))
409 		return -EPROTONOSUPPORT;
410 
411 	switch (sock->type) {
412 	case SOCK_STREAM:
413 		ops = &stream_ops;
414 		break;
415 	case SOCK_SEQPACKET:
416 		ops = &packet_ops;
417 		break;
418 	case SOCK_DGRAM:
419 	case SOCK_RDM:
420 		ops = &msg_ops;
421 		break;
422 	default:
423 		return -EPROTOTYPE;
424 	}
425 
426 	/* Allocate socket's protocol area */
427 	sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto, kern);
428 	if (sk == NULL)
429 		return -ENOMEM;
430 
431 	tsk = tipc_sk(sk);
432 	tsk->max_pkt = MAX_PKT_DEFAULT;
433 	INIT_LIST_HEAD(&tsk->publications);
434 	INIT_LIST_HEAD(&tsk->cong_links);
435 	msg = &tsk->phdr;
436 	tn = net_generic(sock_net(sk), tipc_net_id);
437 
438 	/* Finish initializing socket data structures */
439 	sock->ops = ops;
440 	sock_init_data(sock, sk);
441 	tipc_set_sk_state(sk, TIPC_OPEN);
442 	if (tipc_sk_insert(tsk)) {
443 		pr_warn("Socket create failed; port number exhausted\n");
444 		return -EINVAL;
445 	}
446 
447 	/* Ensure tsk is visible before we read own_addr. */
448 	smp_mb();
449 
450 	tipc_msg_init(tn->own_addr, msg, TIPC_LOW_IMPORTANCE, TIPC_NAMED_MSG,
451 		      NAMED_H_SIZE, 0);
452 
453 	msg_set_origport(msg, tsk->portid);
454 	setup_timer(&sk->sk_timer, tipc_sk_timeout, (unsigned long)tsk);
455 	sk->sk_shutdown = 0;
456 	sk->sk_backlog_rcv = tipc_backlog_rcv;
457 	sk->sk_rcvbuf = sysctl_tipc_rmem[1];
458 	sk->sk_data_ready = tipc_data_ready;
459 	sk->sk_write_space = tipc_write_space;
460 	sk->sk_destruct = tipc_sock_destruct;
461 	tsk->conn_timeout = CONN_TIMEOUT_DEFAULT;
462 	atomic_set(&tsk->dupl_rcvcnt, 0);
463 
464 	/* Start out with safe limits until we receive an advertised window */
465 	tsk->snd_win = tsk_adv_blocks(RCVBUF_MIN);
466 	tsk->rcv_win = tsk->snd_win;
467 
468 	if (tipc_sk_type_connectionless(sk)) {
469 		tsk_set_unreturnable(tsk, true);
470 		if (sock->type == SOCK_DGRAM)
471 			tsk_set_unreliable(tsk, true);
472 	}
473 
474 	return 0;
475 }
476 
tipc_sk_callback(struct rcu_head * head)477 static void tipc_sk_callback(struct rcu_head *head)
478 {
479 	struct tipc_sock *tsk = container_of(head, struct tipc_sock, rcu);
480 
481 	sock_put(&tsk->sk);
482 }
483 
484 /* Caller should hold socket lock for the socket. */
__tipc_shutdown(struct socket * sock,int error)485 static void __tipc_shutdown(struct socket *sock, int error)
486 {
487 	struct sock *sk = sock->sk;
488 	struct tipc_sock *tsk = tipc_sk(sk);
489 	struct net *net = sock_net(sk);
490 	long timeout = msecs_to_jiffies(CONN_TIMEOUT_DEFAULT);
491 	u32 dnode = tsk_peer_node(tsk);
492 	struct sk_buff *skb;
493 
494 	/* Avoid that hi-prio shutdown msgs bypass msgs in link wakeup queue */
495 	tipc_wait_for_cond(sock, &timeout, (!tsk->cong_link_cnt &&
496 					    !tsk_conn_cong(tsk)));
497 
498 	/* Reject all unreceived messages, except on an active connection
499 	 * (which disconnects locally & sends a 'FIN+' to peer).
500 	 */
501 	while ((skb = __skb_dequeue(&sk->sk_receive_queue)) != NULL) {
502 		if (TIPC_SKB_CB(skb)->bytes_read) {
503 			kfree_skb(skb);
504 			continue;
505 		}
506 		if (!tipc_sk_type_connectionless(sk) &&
507 		    sk->sk_state != TIPC_DISCONNECTING) {
508 			tipc_set_sk_state(sk, TIPC_DISCONNECTING);
509 			tipc_node_remove_conn(net, dnode, tsk->portid);
510 		}
511 		tipc_sk_respond(sk, skb, error);
512 	}
513 
514 	if (tipc_sk_type_connectionless(sk))
515 		return;
516 
517 	if (sk->sk_state != TIPC_DISCONNECTING) {
518 		skb = tipc_msg_create(TIPC_CRITICAL_IMPORTANCE,
519 				      TIPC_CONN_MSG, SHORT_H_SIZE, 0, dnode,
520 				      tsk_own_node(tsk), tsk_peer_port(tsk),
521 				      tsk->portid, error);
522 		if (skb)
523 			tipc_node_xmit_skb(net, skb, dnode, tsk->portid);
524 		tipc_node_remove_conn(net, dnode, tsk->portid);
525 		tipc_set_sk_state(sk, TIPC_DISCONNECTING);
526 	}
527 }
528 
529 /**
530  * tipc_release - destroy a TIPC socket
531  * @sock: socket to destroy
532  *
533  * This routine cleans up any messages that are still queued on the socket.
534  * For DGRAM and RDM socket types, all queued messages are rejected.
535  * For SEQPACKET and STREAM socket types, the first message is rejected
536  * and any others are discarded.  (If the first message on a STREAM socket
537  * is partially-read, it is discarded and the next one is rejected instead.)
538  *
539  * NOTE: Rejected messages are not necessarily returned to the sender!  They
540  * are returned or discarded according to the "destination droppable" setting
541  * specified for the message by the sender.
542  *
543  * Returns 0 on success, errno otherwise
544  */
tipc_release(struct socket * sock)545 static int tipc_release(struct socket *sock)
546 {
547 	struct sock *sk = sock->sk;
548 	struct tipc_sock *tsk;
549 
550 	/*
551 	 * Exit if socket isn't fully initialized (occurs when a failed accept()
552 	 * releases a pre-allocated child socket that was never used)
553 	 */
554 	if (sk == NULL)
555 		return 0;
556 
557 	tsk = tipc_sk(sk);
558 	lock_sock(sk);
559 
560 	__tipc_shutdown(sock, TIPC_ERR_NO_PORT);
561 	sk->sk_shutdown = SHUTDOWN_MASK;
562 	tipc_sk_withdraw(tsk, 0, NULL);
563 	sk_stop_timer(sk, &sk->sk_timer);
564 	tipc_sk_remove(tsk);
565 
566 	/* Reject any messages that accumulated in backlog queue */
567 	release_sock(sk);
568 	u32_list_purge(&tsk->cong_links);
569 	tsk->cong_link_cnt = 0;
570 	call_rcu(&tsk->rcu, tipc_sk_callback);
571 	sock->sk = NULL;
572 
573 	return 0;
574 }
575 
576 /**
577  * tipc_bind - associate or disassocate TIPC name(s) with a socket
578  * @sock: socket structure
579  * @uaddr: socket address describing name(s) and desired operation
580  * @uaddr_len: size of socket address data structure
581  *
582  * Name and name sequence binding is indicated using a positive scope value;
583  * a negative scope value unbinds the specified name.  Specifying no name
584  * (i.e. a socket address length of 0) unbinds all names from the socket.
585  *
586  * Returns 0 on success, errno otherwise
587  *
588  * NOTE: This routine doesn't need to take the socket lock since it doesn't
589  *       access any non-constant socket information.
590  */
tipc_bind(struct socket * sock,struct sockaddr * uaddr,int uaddr_len)591 static int tipc_bind(struct socket *sock, struct sockaddr *uaddr,
592 		     int uaddr_len)
593 {
594 	struct sock *sk = sock->sk;
595 	struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
596 	struct tipc_sock *tsk = tipc_sk(sk);
597 	int res = -EINVAL;
598 
599 	lock_sock(sk);
600 	if (unlikely(!uaddr_len)) {
601 		res = tipc_sk_withdraw(tsk, 0, NULL);
602 		goto exit;
603 	}
604 
605 	if (uaddr_len < sizeof(struct sockaddr_tipc)) {
606 		res = -EINVAL;
607 		goto exit;
608 	}
609 	if (addr->family != AF_TIPC) {
610 		res = -EAFNOSUPPORT;
611 		goto exit;
612 	}
613 
614 	if (addr->addrtype == TIPC_ADDR_NAME)
615 		addr->addr.nameseq.upper = addr->addr.nameseq.lower;
616 	else if (addr->addrtype != TIPC_ADDR_NAMESEQ) {
617 		res = -EAFNOSUPPORT;
618 		goto exit;
619 	}
620 
621 	if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
622 	    (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
623 	    (addr->addr.nameseq.type != TIPC_CFG_SRV)) {
624 		res = -EACCES;
625 		goto exit;
626 	}
627 
628 	res = (addr->scope > 0) ?
629 		tipc_sk_publish(tsk, addr->scope, &addr->addr.nameseq) :
630 		tipc_sk_withdraw(tsk, -addr->scope, &addr->addr.nameseq);
631 exit:
632 	release_sock(sk);
633 	return res;
634 }
635 
636 /**
637  * tipc_getname - get port ID of socket or peer socket
638  * @sock: socket structure
639  * @uaddr: area for returned socket address
640  * @uaddr_len: area for returned length of socket address
641  * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
642  *
643  * Returns 0 on success, errno otherwise
644  *
645  * NOTE: This routine doesn't need to take the socket lock since it only
646  *       accesses socket information that is unchanging (or which changes in
647  *       a completely predictable manner).
648  */
tipc_getname(struct socket * sock,struct sockaddr * uaddr,int * uaddr_len,int peer)649 static int tipc_getname(struct socket *sock, struct sockaddr *uaddr,
650 			int *uaddr_len, int peer)
651 {
652 	struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
653 	struct sock *sk = sock->sk;
654 	struct tipc_sock *tsk = tipc_sk(sk);
655 	struct tipc_net *tn = net_generic(sock_net(sock->sk), tipc_net_id);
656 
657 	memset(addr, 0, sizeof(*addr));
658 	if (peer) {
659 		if ((!tipc_sk_connected(sk)) &&
660 		    ((peer != 2) || (sk->sk_state != TIPC_DISCONNECTING)))
661 			return -ENOTCONN;
662 		addr->addr.id.ref = tsk_peer_port(tsk);
663 		addr->addr.id.node = tsk_peer_node(tsk);
664 	} else {
665 		addr->addr.id.ref = tsk->portid;
666 		addr->addr.id.node = tn->own_addr;
667 	}
668 
669 	*uaddr_len = sizeof(*addr);
670 	addr->addrtype = TIPC_ADDR_ID;
671 	addr->family = AF_TIPC;
672 	addr->scope = 0;
673 	addr->addr.name.domain = 0;
674 
675 	return 0;
676 }
677 
678 /**
679  * tipc_poll - read and possibly block on pollmask
680  * @file: file structure associated with the socket
681  * @sock: socket for which to calculate the poll bits
682  * @wait: ???
683  *
684  * Returns pollmask value
685  *
686  * COMMENTARY:
687  * It appears that the usual socket locking mechanisms are not useful here
688  * since the pollmask info is potentially out-of-date the moment this routine
689  * exits.  TCP and other protocols seem to rely on higher level poll routines
690  * to handle any preventable race conditions, so TIPC will do the same ...
691  *
692  * IMPORTANT: The fact that a read or write operation is indicated does NOT
693  * imply that the operation will succeed, merely that it should be performed
694  * and will not block.
695  */
tipc_poll(struct file * file,struct socket * sock,poll_table * wait)696 static unsigned int tipc_poll(struct file *file, struct socket *sock,
697 			      poll_table *wait)
698 {
699 	struct sock *sk = sock->sk;
700 	struct tipc_sock *tsk = tipc_sk(sk);
701 	u32 mask = 0;
702 
703 	sock_poll_wait(file, sk_sleep(sk), wait);
704 
705 	if (sk->sk_shutdown & RCV_SHUTDOWN)
706 		mask |= POLLRDHUP | POLLIN | POLLRDNORM;
707 	if (sk->sk_shutdown == SHUTDOWN_MASK)
708 		mask |= POLLHUP;
709 
710 	switch (sk->sk_state) {
711 	case TIPC_ESTABLISHED:
712 		if (!tsk->cong_link_cnt && !tsk_conn_cong(tsk))
713 			mask |= POLLOUT;
714 		/* fall thru' */
715 	case TIPC_LISTEN:
716 	case TIPC_CONNECTING:
717 		if (!skb_queue_empty_lockless(&sk->sk_receive_queue))
718 			mask |= (POLLIN | POLLRDNORM);
719 		break;
720 	case TIPC_OPEN:
721 		if (!tsk->cong_link_cnt)
722 			mask |= POLLOUT;
723 		if (tipc_sk_type_connectionless(sk) &&
724 		    (!skb_queue_empty_lockless(&sk->sk_receive_queue)))
725 			mask |= (POLLIN | POLLRDNORM);
726 		break;
727 	case TIPC_DISCONNECTING:
728 		mask = (POLLIN | POLLRDNORM | POLLHUP);
729 		break;
730 	}
731 
732 	return mask;
733 }
734 
735 /**
736  * tipc_sendmcast - send multicast message
737  * @sock: socket structure
738  * @seq: destination address
739  * @msg: message to send
740  * @dlen: length of data to send
741  * @timeout: timeout to wait for wakeup
742  *
743  * Called from function tipc_sendmsg(), which has done all sanity checks
744  * Returns the number of bytes sent on success, or errno
745  */
tipc_sendmcast(struct socket * sock,struct tipc_name_seq * seq,struct msghdr * msg,size_t dlen,long timeout)746 static int tipc_sendmcast(struct  socket *sock, struct tipc_name_seq *seq,
747 			  struct msghdr *msg, size_t dlen, long timeout)
748 {
749 	struct sock *sk = sock->sk;
750 	struct tipc_sock *tsk = tipc_sk(sk);
751 	struct tipc_msg *hdr = &tsk->phdr;
752 	struct net *net = sock_net(sk);
753 	int mtu = tipc_bcast_get_mtu(net);
754 	struct tipc_mc_method *method = &tsk->mc_method;
755 	u32 domain = addr_domain(net, TIPC_CLUSTER_SCOPE);
756 	struct sk_buff_head pkts;
757 	struct tipc_nlist dsts;
758 	int rc;
759 
760 	/* Block or return if any destination link is congested */
761 	rc = tipc_wait_for_cond(sock, &timeout, !tsk->cong_link_cnt);
762 	if (unlikely(rc))
763 		return rc;
764 
765 	/* Lookup destination nodes */
766 	tipc_nlist_init(&dsts, tipc_own_addr(net));
767 	tipc_nametbl_lookup_dst_nodes(net, seq->type, seq->lower,
768 				      seq->upper, domain, &dsts);
769 	if (!dsts.local && !dsts.remote)
770 		return -EHOSTUNREACH;
771 
772 	/* Build message header */
773 	msg_set_type(hdr, TIPC_MCAST_MSG);
774 	msg_set_hdr_sz(hdr, MCAST_H_SIZE);
775 	msg_set_lookup_scope(hdr, TIPC_CLUSTER_SCOPE);
776 	msg_set_destport(hdr, 0);
777 	msg_set_destnode(hdr, 0);
778 	msg_set_nametype(hdr, seq->type);
779 	msg_set_namelower(hdr, seq->lower);
780 	msg_set_nameupper(hdr, seq->upper);
781 
782 	/* Build message as chain of buffers */
783 	skb_queue_head_init(&pkts);
784 	rc = tipc_msg_build(hdr, msg, 0, dlen, mtu, &pkts);
785 
786 	/* Send message if build was successful */
787 	if (unlikely(rc == dlen))
788 		rc = tipc_mcast_xmit(net, &pkts, method, &dsts,
789 				     &tsk->cong_link_cnt);
790 
791 	tipc_nlist_purge(&dsts);
792 
793 	return rc ? rc : dlen;
794 }
795 
796 /**
797  * tipc_sk_mcast_rcv - Deliver multicast messages to all destination sockets
798  * @arrvq: queue with arriving messages, to be cloned after destination lookup
799  * @inputq: queue with cloned messages, delivered to socket after dest lookup
800  *
801  * Multi-threaded: parallel calls with reference to same queues may occur
802  */
tipc_sk_mcast_rcv(struct net * net,struct sk_buff_head * arrvq,struct sk_buff_head * inputq)803 void tipc_sk_mcast_rcv(struct net *net, struct sk_buff_head *arrvq,
804 		       struct sk_buff_head *inputq)
805 {
806 	struct tipc_msg *msg;
807 	struct list_head dports;
808 	u32 portid;
809 	u32 scope = TIPC_CLUSTER_SCOPE;
810 	struct sk_buff_head tmpq;
811 	uint hsz;
812 	struct sk_buff *skb, *_skb;
813 
814 	__skb_queue_head_init(&tmpq);
815 	INIT_LIST_HEAD(&dports);
816 
817 	skb = tipc_skb_peek(arrvq, &inputq->lock);
818 	for (; skb; skb = tipc_skb_peek(arrvq, &inputq->lock)) {
819 		msg = buf_msg(skb);
820 		hsz = skb_headroom(skb) + msg_hdr_sz(msg);
821 
822 		if (in_own_node(net, msg_orignode(msg)))
823 			scope = TIPC_NODE_SCOPE;
824 
825 		/* Create destination port list and message clones: */
826 		tipc_nametbl_mc_translate(net,
827 					  msg_nametype(msg), msg_namelower(msg),
828 					  msg_nameupper(msg), scope, &dports);
829 		portid = u32_pop(&dports);
830 		for (; portid; portid = u32_pop(&dports)) {
831 			_skb = __pskb_copy(skb, hsz, GFP_ATOMIC);
832 			if (_skb) {
833 				msg_set_destport(buf_msg(_skb), portid);
834 				__skb_queue_tail(&tmpq, _skb);
835 				continue;
836 			}
837 			pr_warn("Failed to clone mcast rcv buffer\n");
838 		}
839 		/* Append to inputq if not already done by other thread */
840 		spin_lock_bh(&inputq->lock);
841 		if (skb_peek(arrvq) == skb) {
842 			skb_queue_splice_tail_init(&tmpq, inputq);
843 			kfree_skb(__skb_dequeue(arrvq));
844 		}
845 		spin_unlock_bh(&inputq->lock);
846 		__skb_queue_purge(&tmpq);
847 		kfree_skb(skb);
848 	}
849 	tipc_sk_rcv(net, inputq);
850 }
851 
852 /**
853  * tipc_sk_proto_rcv - receive a connection mng protocol message
854  * @tsk: receiving socket
855  * @skb: pointer to message buffer.
856  */
tipc_sk_proto_rcv(struct tipc_sock * tsk,struct sk_buff * skb,struct sk_buff_head * xmitq)857 static void tipc_sk_proto_rcv(struct tipc_sock *tsk, struct sk_buff *skb,
858 			      struct sk_buff_head *xmitq)
859 {
860 	struct sock *sk = &tsk->sk;
861 	u32 onode = tsk_own_node(tsk);
862 	struct tipc_msg *hdr = buf_msg(skb);
863 	int mtyp = msg_type(hdr);
864 	bool conn_cong;
865 
866 	/* Ignore if connection cannot be validated: */
867 	if (!tsk_peer_msg(tsk, hdr))
868 		goto exit;
869 
870 	if (unlikely(msg_errcode(hdr))) {
871 		tipc_set_sk_state(sk, TIPC_DISCONNECTING);
872 		tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
873 				      tsk_peer_port(tsk));
874 		sk->sk_state_change(sk);
875 		goto exit;
876 	}
877 
878 	tsk->probe_unacked = false;
879 
880 	if (mtyp == CONN_PROBE) {
881 		msg_set_type(hdr, CONN_PROBE_REPLY);
882 		if (tipc_msg_reverse(onode, &skb, TIPC_OK))
883 			__skb_queue_tail(xmitq, skb);
884 		return;
885 	} else if (mtyp == CONN_ACK) {
886 		conn_cong = tsk_conn_cong(tsk);
887 		tsk->snt_unacked -= msg_conn_ack(hdr);
888 		if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
889 			tsk->snd_win = msg_adv_win(hdr);
890 		if (conn_cong)
891 			sk->sk_write_space(sk);
892 	} else if (mtyp != CONN_PROBE_REPLY) {
893 		pr_warn("Received unknown CONN_PROTO msg\n");
894 	}
895 exit:
896 	kfree_skb(skb);
897 }
898 
899 /**
900  * tipc_sendmsg - send message in connectionless manner
901  * @sock: socket structure
902  * @m: message to send
903  * @dsz: amount of user data to be sent
904  *
905  * Message must have an destination specified explicitly.
906  * Used for SOCK_RDM and SOCK_DGRAM messages,
907  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
908  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
909  *
910  * Returns the number of bytes sent on success, or errno otherwise
911  */
tipc_sendmsg(struct socket * sock,struct msghdr * m,size_t dsz)912 static int tipc_sendmsg(struct socket *sock,
913 			struct msghdr *m, size_t dsz)
914 {
915 	struct sock *sk = sock->sk;
916 	int ret;
917 
918 	lock_sock(sk);
919 	ret = __tipc_sendmsg(sock, m, dsz);
920 	release_sock(sk);
921 
922 	return ret;
923 }
924 
__tipc_sendmsg(struct socket * sock,struct msghdr * m,size_t dlen)925 static int __tipc_sendmsg(struct socket *sock, struct msghdr *m, size_t dlen)
926 {
927 	struct sock *sk = sock->sk;
928 	struct net *net = sock_net(sk);
929 	struct tipc_sock *tsk = tipc_sk(sk);
930 	DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
931 	long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
932 	struct list_head *clinks = &tsk->cong_links;
933 	bool syn = !tipc_sk_type_connectionless(sk);
934 	struct tipc_msg *hdr = &tsk->phdr;
935 	struct tipc_name_seq *seq;
936 	struct sk_buff_head pkts;
937 	u32 type, inst, domain;
938 	u32 dnode, dport;
939 	int mtu, rc;
940 
941 	if (unlikely(dlen > TIPC_MAX_USER_MSG_SIZE))
942 		return -EMSGSIZE;
943 
944 	if (unlikely(!dest)) {
945 		dest = &tsk->peer;
946 		if (!syn && dest->family != AF_TIPC)
947 			return -EDESTADDRREQ;
948 	}
949 
950 	if (unlikely(m->msg_namelen < sizeof(*dest)))
951 		return -EINVAL;
952 
953 	if (unlikely(dest->family != AF_TIPC))
954 		return -EINVAL;
955 
956 	if (unlikely(syn)) {
957 		if (sk->sk_state == TIPC_LISTEN)
958 			return -EPIPE;
959 		if (sk->sk_state != TIPC_OPEN)
960 			return -EISCONN;
961 		if (tsk->published)
962 			return -EOPNOTSUPP;
963 		if (dest->addrtype == TIPC_ADDR_NAME) {
964 			tsk->conn_type = dest->addr.name.name.type;
965 			tsk->conn_instance = dest->addr.name.name.instance;
966 		}
967 	}
968 
969 	seq = &dest->addr.nameseq;
970 	if (dest->addrtype == TIPC_ADDR_MCAST)
971 		return tipc_sendmcast(sock, seq, m, dlen, timeout);
972 
973 	if (dest->addrtype == TIPC_ADDR_NAME) {
974 		type = dest->addr.name.name.type;
975 		inst = dest->addr.name.name.instance;
976 		domain = dest->addr.name.domain;
977 		dnode = domain;
978 		msg_set_type(hdr, TIPC_NAMED_MSG);
979 		msg_set_hdr_sz(hdr, NAMED_H_SIZE);
980 		msg_set_nametype(hdr, type);
981 		msg_set_nameinst(hdr, inst);
982 		msg_set_lookup_scope(hdr, tipc_addr_scope(domain));
983 		dport = tipc_nametbl_translate(net, type, inst, &dnode);
984 		msg_set_destnode(hdr, dnode);
985 		msg_set_destport(hdr, dport);
986 		if (unlikely(!dport && !dnode))
987 			return -EHOSTUNREACH;
988 
989 	} else if (dest->addrtype == TIPC_ADDR_ID) {
990 		dnode = dest->addr.id.node;
991 		msg_set_type(hdr, TIPC_DIRECT_MSG);
992 		msg_set_lookup_scope(hdr, 0);
993 		msg_set_destnode(hdr, dnode);
994 		msg_set_destport(hdr, dest->addr.id.ref);
995 		msg_set_hdr_sz(hdr, BASIC_H_SIZE);
996 	}
997 
998 	/* Block or return if destination link is congested */
999 	rc = tipc_wait_for_cond(sock, &timeout, !u32_find(clinks, dnode));
1000 	if (unlikely(rc))
1001 		return rc;
1002 
1003 	skb_queue_head_init(&pkts);
1004 	mtu = tipc_node_get_mtu(net, dnode, tsk->portid);
1005 	rc = tipc_msg_build(hdr, m, 0, dlen, mtu, &pkts);
1006 	if (unlikely(rc != dlen))
1007 		return rc;
1008 
1009 	rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
1010 	if (unlikely(rc == -ELINKCONG)) {
1011 		u32_push(clinks, dnode);
1012 		tsk->cong_link_cnt++;
1013 		rc = 0;
1014 	}
1015 
1016 	if (unlikely(syn && !rc))
1017 		tipc_set_sk_state(sk, TIPC_CONNECTING);
1018 
1019 	return rc ? rc : dlen;
1020 }
1021 
1022 /**
1023  * tipc_sendstream - send stream-oriented data
1024  * @sock: socket structure
1025  * @m: data to send
1026  * @dsz: total length of data to be transmitted
1027  *
1028  * Used for SOCK_STREAM data.
1029  *
1030  * Returns the number of bytes sent on success (or partial success),
1031  * or errno if no data sent
1032  */
tipc_sendstream(struct socket * sock,struct msghdr * m,size_t dsz)1033 static int tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dsz)
1034 {
1035 	struct sock *sk = sock->sk;
1036 	int ret;
1037 
1038 	lock_sock(sk);
1039 	ret = __tipc_sendstream(sock, m, dsz);
1040 	release_sock(sk);
1041 
1042 	return ret;
1043 }
1044 
__tipc_sendstream(struct socket * sock,struct msghdr * m,size_t dlen)1045 static int __tipc_sendstream(struct socket *sock, struct msghdr *m, size_t dlen)
1046 {
1047 	struct sock *sk = sock->sk;
1048 	DECLARE_SOCKADDR(struct sockaddr_tipc *, dest, m->msg_name);
1049 	long timeout = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
1050 	struct tipc_sock *tsk = tipc_sk(sk);
1051 	struct tipc_msg *hdr = &tsk->phdr;
1052 	struct net *net = sock_net(sk);
1053 	struct sk_buff_head pkts;
1054 	u32 dnode = tsk_peer_node(tsk);
1055 	int send, sent = 0;
1056 	int rc = 0;
1057 
1058 	skb_queue_head_init(&pkts);
1059 
1060 	if (unlikely(dlen > INT_MAX))
1061 		return -EMSGSIZE;
1062 
1063 	/* Handle implicit connection setup */
1064 	if (unlikely(dest)) {
1065 		rc = __tipc_sendmsg(sock, m, dlen);
1066 		if (dlen && dlen == rc) {
1067 			tsk->peer_caps = tipc_node_get_capabilities(net, dnode);
1068 			tsk->snt_unacked = tsk_inc(tsk, dlen + msg_hdr_sz(hdr));
1069 		}
1070 		return rc;
1071 	}
1072 
1073 	do {
1074 		rc = tipc_wait_for_cond(sock, &timeout,
1075 					(!tsk->cong_link_cnt &&
1076 					 !tsk_conn_cong(tsk) &&
1077 					 tipc_sk_connected(sk)));
1078 		if (unlikely(rc))
1079 			break;
1080 
1081 		send = min_t(size_t, dlen - sent, TIPC_MAX_USER_MSG_SIZE);
1082 		rc = tipc_msg_build(hdr, m, sent, send, tsk->max_pkt, &pkts);
1083 		if (unlikely(rc != send))
1084 			break;
1085 
1086 		rc = tipc_node_xmit(net, &pkts, dnode, tsk->portid);
1087 		if (unlikely(rc == -ELINKCONG)) {
1088 			tsk->cong_link_cnt = 1;
1089 			rc = 0;
1090 		}
1091 		if (likely(!rc)) {
1092 			tsk->snt_unacked += tsk_inc(tsk, send + MIN_H_SIZE);
1093 			sent += send;
1094 		}
1095 	} while (sent < dlen && !rc);
1096 
1097 	return sent ? sent : rc;
1098 }
1099 
1100 /**
1101  * tipc_send_packet - send a connection-oriented message
1102  * @sock: socket structure
1103  * @m: message to send
1104  * @dsz: length of data to be transmitted
1105  *
1106  * Used for SOCK_SEQPACKET messages.
1107  *
1108  * Returns the number of bytes sent on success, or errno otherwise
1109  */
tipc_send_packet(struct socket * sock,struct msghdr * m,size_t dsz)1110 static int tipc_send_packet(struct socket *sock, struct msghdr *m, size_t dsz)
1111 {
1112 	if (dsz > TIPC_MAX_USER_MSG_SIZE)
1113 		return -EMSGSIZE;
1114 
1115 	return tipc_sendstream(sock, m, dsz);
1116 }
1117 
1118 /* tipc_sk_finish_conn - complete the setup of a connection
1119  */
tipc_sk_finish_conn(struct tipc_sock * tsk,u32 peer_port,u32 peer_node)1120 static void tipc_sk_finish_conn(struct tipc_sock *tsk, u32 peer_port,
1121 				u32 peer_node)
1122 {
1123 	struct sock *sk = &tsk->sk;
1124 	struct net *net = sock_net(sk);
1125 	struct tipc_msg *msg = &tsk->phdr;
1126 
1127 	msg_set_destnode(msg, peer_node);
1128 	msg_set_destport(msg, peer_port);
1129 	msg_set_type(msg, TIPC_CONN_MSG);
1130 	msg_set_lookup_scope(msg, 0);
1131 	msg_set_hdr_sz(msg, SHORT_H_SIZE);
1132 
1133 	sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTERVAL);
1134 	tipc_set_sk_state(sk, TIPC_ESTABLISHED);
1135 	tipc_node_add_conn(net, peer_node, tsk->portid, peer_port);
1136 	tsk->max_pkt = tipc_node_get_mtu(net, peer_node, tsk->portid);
1137 	tsk->peer_caps = tipc_node_get_capabilities(net, peer_node);
1138 	if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL)
1139 		return;
1140 
1141 	/* Fall back to message based flow control */
1142 	tsk->rcv_win = FLOWCTL_MSG_WIN;
1143 	tsk->snd_win = FLOWCTL_MSG_WIN;
1144 }
1145 
1146 /**
1147  * set_orig_addr - capture sender's address for received message
1148  * @m: descriptor for message info
1149  * @msg: received message header
1150  *
1151  * Note: Address is not captured if not requested by receiver.
1152  */
set_orig_addr(struct msghdr * m,struct tipc_msg * msg)1153 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
1154 {
1155 	DECLARE_SOCKADDR(struct sockaddr_tipc *, addr, m->msg_name);
1156 
1157 	if (addr) {
1158 		addr->family = AF_TIPC;
1159 		addr->addrtype = TIPC_ADDR_ID;
1160 		memset(&addr->addr, 0, sizeof(addr->addr));
1161 		addr->addr.id.ref = msg_origport(msg);
1162 		addr->addr.id.node = msg_orignode(msg);
1163 		addr->addr.name.domain = 0;	/* could leave uninitialized */
1164 		addr->scope = 0;		/* could leave uninitialized */
1165 		m->msg_namelen = sizeof(struct sockaddr_tipc);
1166 	}
1167 }
1168 
1169 /**
1170  * tipc_sk_anc_data_recv - optionally capture ancillary data for received message
1171  * @m: descriptor for message info
1172  * @msg: received message header
1173  * @tsk: TIPC port associated with message
1174  *
1175  * Note: Ancillary data is not captured if not requested by receiver.
1176  *
1177  * Returns 0 if successful, otherwise errno
1178  */
tipc_sk_anc_data_recv(struct msghdr * m,struct tipc_msg * msg,struct tipc_sock * tsk)1179 static int tipc_sk_anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
1180 				 struct tipc_sock *tsk)
1181 {
1182 	u32 anc_data[3];
1183 	u32 err;
1184 	u32 dest_type;
1185 	int has_name;
1186 	int res;
1187 
1188 	if (likely(m->msg_controllen == 0))
1189 		return 0;
1190 
1191 	/* Optionally capture errored message object(s) */
1192 	err = msg ? msg_errcode(msg) : 0;
1193 	if (unlikely(err)) {
1194 		anc_data[0] = err;
1195 		anc_data[1] = msg_data_sz(msg);
1196 		res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
1197 		if (res)
1198 			return res;
1199 		if (anc_data[1]) {
1200 			res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
1201 				       msg_data(msg));
1202 			if (res)
1203 				return res;
1204 		}
1205 	}
1206 
1207 	/* Optionally capture message destination object */
1208 	dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
1209 	switch (dest_type) {
1210 	case TIPC_NAMED_MSG:
1211 		has_name = 1;
1212 		anc_data[0] = msg_nametype(msg);
1213 		anc_data[1] = msg_namelower(msg);
1214 		anc_data[2] = msg_namelower(msg);
1215 		break;
1216 	case TIPC_MCAST_MSG:
1217 		has_name = 1;
1218 		anc_data[0] = msg_nametype(msg);
1219 		anc_data[1] = msg_namelower(msg);
1220 		anc_data[2] = msg_nameupper(msg);
1221 		break;
1222 	case TIPC_CONN_MSG:
1223 		has_name = (tsk->conn_type != 0);
1224 		anc_data[0] = tsk->conn_type;
1225 		anc_data[1] = tsk->conn_instance;
1226 		anc_data[2] = tsk->conn_instance;
1227 		break;
1228 	default:
1229 		has_name = 0;
1230 	}
1231 	if (has_name) {
1232 		res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
1233 		if (res)
1234 			return res;
1235 	}
1236 
1237 	return 0;
1238 }
1239 
tipc_sk_send_ack(struct tipc_sock * tsk)1240 static void tipc_sk_send_ack(struct tipc_sock *tsk)
1241 {
1242 	struct sock *sk = &tsk->sk;
1243 	struct net *net = sock_net(sk);
1244 	struct sk_buff *skb = NULL;
1245 	struct tipc_msg *msg;
1246 	u32 peer_port = tsk_peer_port(tsk);
1247 	u32 dnode = tsk_peer_node(tsk);
1248 
1249 	if (!tipc_sk_connected(sk))
1250 		return;
1251 	skb = tipc_msg_create(CONN_MANAGER, CONN_ACK, INT_H_SIZE, 0,
1252 			      dnode, tsk_own_node(tsk), peer_port,
1253 			      tsk->portid, TIPC_OK);
1254 	if (!skb)
1255 		return;
1256 	msg = buf_msg(skb);
1257 	msg_set_conn_ack(msg, tsk->rcv_unacked);
1258 	tsk->rcv_unacked = 0;
1259 
1260 	/* Adjust to and advertize the correct window limit */
1261 	if (tsk->peer_caps & TIPC_BLOCK_FLOWCTL) {
1262 		tsk->rcv_win = tsk_adv_blocks(tsk->sk.sk_rcvbuf);
1263 		msg_set_adv_win(msg, tsk->rcv_win);
1264 	}
1265 	tipc_node_xmit_skb(net, skb, dnode, msg_link_selector(msg));
1266 }
1267 
tipc_wait_for_rcvmsg(struct socket * sock,long * timeop)1268 static int tipc_wait_for_rcvmsg(struct socket *sock, long *timeop)
1269 {
1270 	struct sock *sk = sock->sk;
1271 	DEFINE_WAIT(wait);
1272 	long timeo = *timeop;
1273 	int err = sock_error(sk);
1274 
1275 	if (err)
1276 		return err;
1277 
1278 	for (;;) {
1279 		prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
1280 		if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
1281 			if (sk->sk_shutdown & RCV_SHUTDOWN) {
1282 				err = -ENOTCONN;
1283 				break;
1284 			}
1285 			release_sock(sk);
1286 			timeo = schedule_timeout(timeo);
1287 			lock_sock(sk);
1288 		}
1289 		err = 0;
1290 		if (!skb_queue_empty(&sk->sk_receive_queue))
1291 			break;
1292 		err = -EAGAIN;
1293 		if (!timeo)
1294 			break;
1295 		err = sock_intr_errno(timeo);
1296 		if (signal_pending(current))
1297 			break;
1298 
1299 		err = sock_error(sk);
1300 		if (err)
1301 			break;
1302 	}
1303 	finish_wait(sk_sleep(sk), &wait);
1304 	*timeop = timeo;
1305 	return err;
1306 }
1307 
1308 /**
1309  * tipc_recvmsg - receive packet-oriented message
1310  * @m: descriptor for message info
1311  * @buflen: length of user buffer area
1312  * @flags: receive flags
1313  *
1314  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
1315  * If the complete message doesn't fit in user area, truncate it.
1316  *
1317  * Returns size of returned message data, errno otherwise
1318  */
tipc_recvmsg(struct socket * sock,struct msghdr * m,size_t buflen,int flags)1319 static int tipc_recvmsg(struct socket *sock, struct msghdr *m,
1320 			size_t buflen,	int flags)
1321 {
1322 	struct sock *sk = sock->sk;
1323 	struct tipc_sock *tsk = tipc_sk(sk);
1324 	struct sk_buff *skb;
1325 	struct tipc_msg *hdr;
1326 	bool connected = !tipc_sk_type_connectionless(sk);
1327 	int rc, err, hlen, dlen, copy;
1328 	long timeout;
1329 
1330 	/* Catch invalid receive requests */
1331 	if (unlikely(!buflen))
1332 		return -EINVAL;
1333 
1334 	lock_sock(sk);
1335 	if (unlikely(connected && sk->sk_state == TIPC_OPEN)) {
1336 		rc = -ENOTCONN;
1337 		goto exit;
1338 	}
1339 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1340 
1341 	do {
1342 		/* Look at first msg in receive queue; wait if necessary */
1343 		rc = tipc_wait_for_rcvmsg(sock, &timeout);
1344 		if (unlikely(rc))
1345 			goto exit;
1346 		skb = skb_peek(&sk->sk_receive_queue);
1347 		hdr = buf_msg(skb);
1348 		dlen = msg_data_sz(hdr);
1349 		hlen = msg_hdr_sz(hdr);
1350 		err = msg_errcode(hdr);
1351 		if (likely(dlen || err))
1352 			break;
1353 		tsk_advance_rx_queue(sk);
1354 	} while (1);
1355 
1356 	/* Collect msg meta data, including error code and rejected data */
1357 	set_orig_addr(m, hdr);
1358 	rc = tipc_sk_anc_data_recv(m, hdr, tsk);
1359 	if (unlikely(rc))
1360 		goto exit;
1361 
1362 	/* Capture data if non-error msg, otherwise just set return value */
1363 	if (likely(!err)) {
1364 		copy = min_t(int, dlen, buflen);
1365 		if (unlikely(copy != dlen))
1366 			m->msg_flags |= MSG_TRUNC;
1367 		rc = skb_copy_datagram_msg(skb, hlen, m, copy);
1368 	} else {
1369 		copy = 0;
1370 		rc = 0;
1371 		if (err != TIPC_CONN_SHUTDOWN && connected && !m->msg_control)
1372 			rc = -ECONNRESET;
1373 	}
1374 	if (unlikely(rc))
1375 		goto exit;
1376 
1377 	/* Caption of data or error code/rejected data was successful */
1378 	if (unlikely(flags & MSG_PEEK))
1379 		goto exit;
1380 
1381 	tsk_advance_rx_queue(sk);
1382 	if (likely(!connected))
1383 		goto exit;
1384 
1385 	/* Send connection flow control ack when applicable */
1386 	tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
1387 	if (tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE)
1388 		tipc_sk_send_ack(tsk);
1389 exit:
1390 	release_sock(sk);
1391 	return rc ? rc : copy;
1392 }
1393 
1394 /**
1395  * tipc_recvstream - receive stream-oriented data
1396  * @m: descriptor for message info
1397  * @buflen: total size of user buffer area
1398  * @flags: receive flags
1399  *
1400  * Used for SOCK_STREAM messages only.  If not enough data is available
1401  * will optionally wait for more; never truncates data.
1402  *
1403  * Returns size of returned message data, errno otherwise
1404  */
tipc_recvstream(struct socket * sock,struct msghdr * m,size_t buflen,int flags)1405 static int tipc_recvstream(struct socket *sock, struct msghdr *m,
1406 			   size_t buflen, int flags)
1407 {
1408 	struct sock *sk = sock->sk;
1409 	struct tipc_sock *tsk = tipc_sk(sk);
1410 	struct sk_buff *skb;
1411 	struct tipc_msg *hdr;
1412 	struct tipc_skb_cb *skb_cb;
1413 	bool peek = flags & MSG_PEEK;
1414 	int offset, required, copy, copied = 0;
1415 	int hlen, dlen, err, rc;
1416 	long timeout;
1417 
1418 	/* Catch invalid receive attempts */
1419 	if (unlikely(!buflen))
1420 		return -EINVAL;
1421 
1422 	lock_sock(sk);
1423 
1424 	if (unlikely(sk->sk_state == TIPC_OPEN)) {
1425 		rc = -ENOTCONN;
1426 		goto exit;
1427 	}
1428 	required = sock_rcvlowat(sk, flags & MSG_WAITALL, buflen);
1429 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1430 
1431 	do {
1432 		/* Look at first msg in receive queue; wait if necessary */
1433 		rc = tipc_wait_for_rcvmsg(sock, &timeout);
1434 		if (unlikely(rc))
1435 			break;
1436 		skb = skb_peek(&sk->sk_receive_queue);
1437 		skb_cb = TIPC_SKB_CB(skb);
1438 		hdr = buf_msg(skb);
1439 		dlen = msg_data_sz(hdr);
1440 		hlen = msg_hdr_sz(hdr);
1441 		err = msg_errcode(hdr);
1442 
1443 		/* Discard any empty non-errored (SYN-) message */
1444 		if (unlikely(!dlen && !err)) {
1445 			tsk_advance_rx_queue(sk);
1446 			continue;
1447 		}
1448 
1449 		/* Collect msg meta data, incl. error code and rejected data */
1450 		if (!copied) {
1451 			set_orig_addr(m, hdr);
1452 			rc = tipc_sk_anc_data_recv(m, hdr, tsk);
1453 			if (rc)
1454 				break;
1455 		}
1456 
1457 		/* Copy data if msg ok, otherwise return error/partial data */
1458 		if (likely(!err)) {
1459 			offset = skb_cb->bytes_read;
1460 			copy = min_t(int, dlen - offset, buflen - copied);
1461 			rc = skb_copy_datagram_msg(skb, hlen + offset, m, copy);
1462 			if (unlikely(rc))
1463 				break;
1464 			copied += copy;
1465 			offset += copy;
1466 			if (unlikely(offset < dlen)) {
1467 				if (!peek)
1468 					skb_cb->bytes_read = offset;
1469 				break;
1470 			}
1471 		} else {
1472 			rc = 0;
1473 			if ((err != TIPC_CONN_SHUTDOWN) && !m->msg_control)
1474 				rc = -ECONNRESET;
1475 			if (copied || rc)
1476 				break;
1477 		}
1478 
1479 		if (unlikely(peek))
1480 			break;
1481 
1482 		tsk_advance_rx_queue(sk);
1483 
1484 		/* Send connection flow control advertisement when applicable */
1485 		tsk->rcv_unacked += tsk_inc(tsk, hlen + dlen);
1486 		if (unlikely(tsk->rcv_unacked >= tsk->rcv_win / TIPC_ACK_RATE))
1487 			tipc_sk_send_ack(tsk);
1488 
1489 		/* Exit if all requested data or FIN/error received */
1490 		if (copied == buflen || err)
1491 			break;
1492 
1493 	} while (!skb_queue_empty(&sk->sk_receive_queue) || copied < required);
1494 exit:
1495 	release_sock(sk);
1496 	return copied ? copied : rc;
1497 }
1498 
1499 /**
1500  * tipc_write_space - wake up thread if port congestion is released
1501  * @sk: socket
1502  */
tipc_write_space(struct sock * sk)1503 static void tipc_write_space(struct sock *sk)
1504 {
1505 	struct socket_wq *wq;
1506 
1507 	rcu_read_lock();
1508 	wq = rcu_dereference(sk->sk_wq);
1509 	if (skwq_has_sleeper(wq))
1510 		wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1511 						POLLWRNORM | POLLWRBAND);
1512 	rcu_read_unlock();
1513 }
1514 
1515 /**
1516  * tipc_data_ready - wake up threads to indicate messages have been received
1517  * @sk: socket
1518  * @len: the length of messages
1519  */
tipc_data_ready(struct sock * sk)1520 static void tipc_data_ready(struct sock *sk)
1521 {
1522 	struct socket_wq *wq;
1523 
1524 	rcu_read_lock();
1525 	wq = rcu_dereference(sk->sk_wq);
1526 	if (skwq_has_sleeper(wq))
1527 		wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1528 						POLLRDNORM | POLLRDBAND);
1529 	rcu_read_unlock();
1530 }
1531 
tipc_sock_destruct(struct sock * sk)1532 static void tipc_sock_destruct(struct sock *sk)
1533 {
1534 	__skb_queue_purge(&sk->sk_receive_queue);
1535 }
1536 
1537 /**
1538  * filter_connect - Handle all incoming messages for a connection-based socket
1539  * @tsk: TIPC socket
1540  * @skb: pointer to message buffer. Set to NULL if buffer is consumed
1541  *
1542  * Returns true if everything ok, false otherwise
1543  */
filter_connect(struct tipc_sock * tsk,struct sk_buff * skb)1544 static bool filter_connect(struct tipc_sock *tsk, struct sk_buff *skb)
1545 {
1546 	struct sock *sk = &tsk->sk;
1547 	struct net *net = sock_net(sk);
1548 	struct tipc_msg *hdr = buf_msg(skb);
1549 	u32 pport = msg_origport(hdr);
1550 	u32 pnode = msg_orignode(hdr);
1551 
1552 	if (unlikely(msg_mcast(hdr)))
1553 		return false;
1554 
1555 	switch (sk->sk_state) {
1556 	case TIPC_CONNECTING:
1557 		/* Accept only ACK or NACK message */
1558 		if (unlikely(!msg_connected(hdr))) {
1559 			if (pport != tsk_peer_port(tsk) ||
1560 			    pnode != tsk_peer_node(tsk))
1561 				return false;
1562 
1563 			tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1564 			sk->sk_err = ECONNREFUSED;
1565 			sk->sk_state_change(sk);
1566 			return true;
1567 		}
1568 
1569 		if (unlikely(msg_errcode(hdr))) {
1570 			tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1571 			sk->sk_err = ECONNREFUSED;
1572 			sk->sk_state_change(sk);
1573 			return true;
1574 		}
1575 
1576 		if (unlikely(!msg_isdata(hdr))) {
1577 			tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1578 			sk->sk_err = EINVAL;
1579 			sk->sk_state_change(sk);
1580 			return true;
1581 		}
1582 
1583 		tipc_sk_finish_conn(tsk, msg_origport(hdr), msg_orignode(hdr));
1584 		msg_set_importance(&tsk->phdr, msg_importance(hdr));
1585 
1586 		/* If 'ACK+' message, add to socket receive queue */
1587 		if (msg_data_sz(hdr))
1588 			return true;
1589 
1590 		/* If empty 'ACK-' message, wake up sleeping connect() */
1591 		sk->sk_state_change(sk);
1592 
1593 		/* 'ACK-' message is neither accepted nor rejected: */
1594 		msg_set_dest_droppable(hdr, 1);
1595 		return false;
1596 
1597 	case TIPC_OPEN:
1598 	case TIPC_DISCONNECTING:
1599 		break;
1600 	case TIPC_LISTEN:
1601 		/* Accept only SYN message */
1602 		if (!msg_connected(hdr) && !(msg_errcode(hdr)))
1603 			return true;
1604 		break;
1605 	case TIPC_ESTABLISHED:
1606 		/* Accept only connection-based messages sent by peer */
1607 		if (unlikely(!tsk_peer_msg(tsk, hdr)))
1608 			return false;
1609 
1610 		if (unlikely(msg_errcode(hdr))) {
1611 			tipc_set_sk_state(sk, TIPC_DISCONNECTING);
1612 			/* Let timer expire on it's own */
1613 			tipc_node_remove_conn(net, tsk_peer_node(tsk),
1614 					      tsk->portid);
1615 			sk->sk_state_change(sk);
1616 		}
1617 		return true;
1618 	default:
1619 		pr_err("Unknown sk_state %u\n", sk->sk_state);
1620 	}
1621 
1622 	return false;
1623 }
1624 
1625 /**
1626  * rcvbuf_limit - get proper overload limit of socket receive queue
1627  * @sk: socket
1628  * @skb: message
1629  *
1630  * For connection oriented messages, irrespective of importance,
1631  * default queue limit is 2 MB.
1632  *
1633  * For connectionless messages, queue limits are based on message
1634  * importance as follows:
1635  *
1636  * TIPC_LOW_IMPORTANCE       (2 MB)
1637  * TIPC_MEDIUM_IMPORTANCE    (4 MB)
1638  * TIPC_HIGH_IMPORTANCE      (8 MB)
1639  * TIPC_CRITICAL_IMPORTANCE  (16 MB)
1640  *
1641  * Returns overload limit according to corresponding message importance
1642  */
rcvbuf_limit(struct sock * sk,struct sk_buff * skb)1643 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *skb)
1644 {
1645 	struct tipc_sock *tsk = tipc_sk(sk);
1646 	struct tipc_msg *hdr = buf_msg(skb);
1647 
1648 	if (unlikely(!msg_connected(hdr)))
1649 		return sk->sk_rcvbuf << msg_importance(hdr);
1650 
1651 	if (likely(tsk->peer_caps & TIPC_BLOCK_FLOWCTL))
1652 		return sk->sk_rcvbuf;
1653 
1654 	return FLOWCTL_MSG_LIM;
1655 }
1656 
1657 /**
1658  * filter_rcv - validate incoming message
1659  * @sk: socket
1660  * @skb: pointer to message.
1661  *
1662  * Enqueues message on receive queue if acceptable; optionally handles
1663  * disconnect indication for a connected socket.
1664  *
1665  * Called with socket lock already taken
1666  *
1667  * Returns true if message was added to socket receive queue, otherwise false
1668  */
filter_rcv(struct sock * sk,struct sk_buff * skb,struct sk_buff_head * xmitq)1669 static bool filter_rcv(struct sock *sk, struct sk_buff *skb,
1670 		       struct sk_buff_head *xmitq)
1671 {
1672 	struct tipc_sock *tsk = tipc_sk(sk);
1673 	struct tipc_msg *hdr = buf_msg(skb);
1674 	unsigned int limit = rcvbuf_limit(sk, skb);
1675 	int err = TIPC_OK;
1676 	int usr = msg_user(hdr);
1677 	u32 onode;
1678 
1679 	if (unlikely(msg_user(hdr) == CONN_MANAGER)) {
1680 		tipc_sk_proto_rcv(tsk, skb, xmitq);
1681 		return false;
1682 	}
1683 
1684 	if (unlikely(usr == SOCK_WAKEUP)) {
1685 		onode = msg_orignode(hdr);
1686 		kfree_skb(skb);
1687 		u32_del(&tsk->cong_links, onode);
1688 		tsk->cong_link_cnt--;
1689 		sk->sk_write_space(sk);
1690 		return false;
1691 	}
1692 
1693 	/* Drop if illegal message type */
1694 	if (unlikely(msg_type(hdr) > TIPC_DIRECT_MSG)) {
1695 		kfree_skb(skb);
1696 		return false;
1697 	}
1698 
1699 	/* Reject if wrong message type for current socket state */
1700 	if (tipc_sk_type_connectionless(sk)) {
1701 		if (msg_connected(hdr)) {
1702 			err = TIPC_ERR_NO_PORT;
1703 			goto reject;
1704 		}
1705 	} else if (unlikely(!filter_connect(tsk, skb))) {
1706 		err = TIPC_ERR_NO_PORT;
1707 		goto reject;
1708 	}
1709 
1710 	/* Reject message if there isn't room to queue it */
1711 	if (unlikely(sk_rmem_alloc_get(sk) + skb->truesize >= limit)) {
1712 		err = TIPC_ERR_OVERLOAD;
1713 		goto reject;
1714 	}
1715 
1716 	/* Enqueue message */
1717 	TIPC_SKB_CB(skb)->bytes_read = 0;
1718 	__skb_queue_tail(&sk->sk_receive_queue, skb);
1719 	skb_set_owner_r(skb, sk);
1720 
1721 	sk->sk_data_ready(sk);
1722 	return true;
1723 
1724 reject:
1725 	if (tipc_msg_reverse(tsk_own_node(tsk), &skb, err))
1726 		__skb_queue_tail(xmitq, skb);
1727 	return false;
1728 }
1729 
1730 /**
1731  * tipc_backlog_rcv - handle incoming message from backlog queue
1732  * @sk: socket
1733  * @skb: message
1734  *
1735  * Caller must hold socket lock
1736  *
1737  * Returns 0
1738  */
tipc_backlog_rcv(struct sock * sk,struct sk_buff * skb)1739 static int tipc_backlog_rcv(struct sock *sk, struct sk_buff *skb)
1740 {
1741 	unsigned int truesize = skb->truesize;
1742 	struct sk_buff_head xmitq;
1743 	u32 dnode, selector;
1744 
1745 	__skb_queue_head_init(&xmitq);
1746 
1747 	if (likely(filter_rcv(sk, skb, &xmitq))) {
1748 		atomic_add(truesize, &tipc_sk(sk)->dupl_rcvcnt);
1749 		return 0;
1750 	}
1751 
1752 	if (skb_queue_empty(&xmitq))
1753 		return 0;
1754 
1755 	/* Send response/rejected message */
1756 	skb = __skb_dequeue(&xmitq);
1757 	dnode = msg_destnode(buf_msg(skb));
1758 	selector = msg_origport(buf_msg(skb));
1759 	tipc_node_xmit_skb(sock_net(sk), skb, dnode, selector);
1760 	return 0;
1761 }
1762 
1763 /**
1764  * tipc_sk_enqueue - extract all buffers with destination 'dport' from
1765  *                   inputq and try adding them to socket or backlog queue
1766  * @inputq: list of incoming buffers with potentially different destinations
1767  * @sk: socket where the buffers should be enqueued
1768  * @dport: port number for the socket
1769  *
1770  * Caller must hold socket lock
1771  */
tipc_sk_enqueue(struct sk_buff_head * inputq,struct sock * sk,u32 dport,struct sk_buff_head * xmitq)1772 static void tipc_sk_enqueue(struct sk_buff_head *inputq, struct sock *sk,
1773 			    u32 dport, struct sk_buff_head *xmitq)
1774 {
1775 	unsigned long time_limit = jiffies + 2;
1776 	struct sk_buff *skb;
1777 	unsigned int lim;
1778 	atomic_t *dcnt;
1779 	u32 onode;
1780 
1781 	while (skb_queue_len(inputq)) {
1782 		if (unlikely(time_after_eq(jiffies, time_limit)))
1783 			return;
1784 
1785 		skb = tipc_skb_dequeue(inputq, dport);
1786 		if (unlikely(!skb))
1787 			return;
1788 
1789 		/* Add message directly to receive queue if possible */
1790 		if (!sock_owned_by_user(sk)) {
1791 			filter_rcv(sk, skb, xmitq);
1792 			continue;
1793 		}
1794 
1795 		/* Try backlog, compensating for double-counted bytes */
1796 		dcnt = &tipc_sk(sk)->dupl_rcvcnt;
1797 		if (!sk->sk_backlog.len)
1798 			atomic_set(dcnt, 0);
1799 		lim = rcvbuf_limit(sk, skb) + atomic_read(dcnt);
1800 		if (likely(!sk_add_backlog(sk, skb, lim)))
1801 			continue;
1802 
1803 		/* Overload => reject message back to sender */
1804 		onode = tipc_own_addr(sock_net(sk));
1805 		if (tipc_msg_reverse(onode, &skb, TIPC_ERR_OVERLOAD))
1806 			__skb_queue_tail(xmitq, skb);
1807 		break;
1808 	}
1809 }
1810 
1811 /**
1812  * tipc_sk_rcv - handle a chain of incoming buffers
1813  * @inputq: buffer list containing the buffers
1814  * Consumes all buffers in list until inputq is empty
1815  * Note: may be called in multiple threads referring to the same queue
1816  */
tipc_sk_rcv(struct net * net,struct sk_buff_head * inputq)1817 void tipc_sk_rcv(struct net *net, struct sk_buff_head *inputq)
1818 {
1819 	struct sk_buff_head xmitq;
1820 	u32 dnode, dport = 0;
1821 	int err;
1822 	struct tipc_sock *tsk;
1823 	struct sock *sk;
1824 	struct sk_buff *skb;
1825 
1826 	__skb_queue_head_init(&xmitq);
1827 	while (skb_queue_len(inputq)) {
1828 		dport = tipc_skb_peek_port(inputq, dport);
1829 		tsk = tipc_sk_lookup(net, dport);
1830 
1831 		if (likely(tsk)) {
1832 			sk = &tsk->sk;
1833 			if (likely(spin_trylock_bh(&sk->sk_lock.slock))) {
1834 				tipc_sk_enqueue(inputq, sk, dport, &xmitq);
1835 				spin_unlock_bh(&sk->sk_lock.slock);
1836 			}
1837 			/* Send pending response/rejected messages, if any */
1838 			while ((skb = __skb_dequeue(&xmitq))) {
1839 				dnode = msg_destnode(buf_msg(skb));
1840 				tipc_node_xmit_skb(net, skb, dnode, dport);
1841 			}
1842 			sock_put(sk);
1843 			continue;
1844 		}
1845 
1846 		/* No destination socket => dequeue skb if still there */
1847 		skb = tipc_skb_dequeue(inputq, dport);
1848 		if (!skb)
1849 			return;
1850 
1851 		/* Try secondary lookup if unresolved named message */
1852 		err = TIPC_ERR_NO_PORT;
1853 		if (tipc_msg_lookup_dest(net, skb, &err))
1854 			goto xmit;
1855 
1856 		/* Prepare for message rejection */
1857 		if (!tipc_msg_reverse(tipc_own_addr(net), &skb, err))
1858 			continue;
1859 xmit:
1860 		dnode = msg_destnode(buf_msg(skb));
1861 		tipc_node_xmit_skb(net, skb, dnode, dport);
1862 	}
1863 }
1864 
tipc_wait_for_connect(struct socket * sock,long * timeo_p)1865 static int tipc_wait_for_connect(struct socket *sock, long *timeo_p)
1866 {
1867 	DEFINE_WAIT_FUNC(wait, woken_wake_function);
1868 	struct sock *sk = sock->sk;
1869 	int done;
1870 
1871 	do {
1872 		int err = sock_error(sk);
1873 		if (err)
1874 			return err;
1875 		if (!*timeo_p)
1876 			return -ETIMEDOUT;
1877 		if (signal_pending(current))
1878 			return sock_intr_errno(*timeo_p);
1879 
1880 		add_wait_queue(sk_sleep(sk), &wait);
1881 		done = sk_wait_event(sk, timeo_p,
1882 				     sk->sk_state != TIPC_CONNECTING, &wait);
1883 		remove_wait_queue(sk_sleep(sk), &wait);
1884 	} while (!done);
1885 	return 0;
1886 }
1887 
1888 /**
1889  * tipc_connect - establish a connection to another TIPC port
1890  * @sock: socket structure
1891  * @dest: socket address for destination port
1892  * @destlen: size of socket address data structure
1893  * @flags: file-related flags associated with socket
1894  *
1895  * Returns 0 on success, errno otherwise
1896  */
tipc_connect(struct socket * sock,struct sockaddr * dest,int destlen,int flags)1897 static int tipc_connect(struct socket *sock, struct sockaddr *dest,
1898 			int destlen, int flags)
1899 {
1900 	struct sock *sk = sock->sk;
1901 	struct tipc_sock *tsk = tipc_sk(sk);
1902 	struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1903 	struct msghdr m = {NULL,};
1904 	long timeout = (flags & O_NONBLOCK) ? 0 : tsk->conn_timeout;
1905 	int previous;
1906 	int res = 0;
1907 
1908 	lock_sock(sk);
1909 
1910 	/* DGRAM/RDM connect(), just save the destaddr */
1911 	if (tipc_sk_type_connectionless(sk)) {
1912 		if (dst->family == AF_UNSPEC) {
1913 			memset(&tsk->peer, 0, sizeof(struct sockaddr_tipc));
1914 		} else if (destlen != sizeof(struct sockaddr_tipc)) {
1915 			res = -EINVAL;
1916 		} else {
1917 			memcpy(&tsk->peer, dest, destlen);
1918 		}
1919 		goto exit;
1920 	}
1921 
1922 	/*
1923 	 * Reject connection attempt using multicast address
1924 	 *
1925 	 * Note: send_msg() validates the rest of the address fields,
1926 	 *       so there's no need to do it here
1927 	 */
1928 	if (dst->addrtype == TIPC_ADDR_MCAST) {
1929 		res = -EINVAL;
1930 		goto exit;
1931 	}
1932 
1933 	previous = sk->sk_state;
1934 
1935 	switch (sk->sk_state) {
1936 	case TIPC_OPEN:
1937 		/* Send a 'SYN-' to destination */
1938 		m.msg_name = dest;
1939 		m.msg_namelen = destlen;
1940 
1941 		/* If connect is in non-blocking case, set MSG_DONTWAIT to
1942 		 * indicate send_msg() is never blocked.
1943 		 */
1944 		if (!timeout)
1945 			m.msg_flags = MSG_DONTWAIT;
1946 
1947 		res = __tipc_sendmsg(sock, &m, 0);
1948 		if ((res < 0) && (res != -EWOULDBLOCK))
1949 			goto exit;
1950 
1951 		/* Just entered TIPC_CONNECTING state; the only
1952 		 * difference is that return value in non-blocking
1953 		 * case is EINPROGRESS, rather than EALREADY.
1954 		 */
1955 		res = -EINPROGRESS;
1956 		/* fall thru' */
1957 	case TIPC_CONNECTING:
1958 		if (!timeout) {
1959 			if (previous == TIPC_CONNECTING)
1960 				res = -EALREADY;
1961 			goto exit;
1962 		}
1963 		timeout = msecs_to_jiffies(timeout);
1964 		/* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1965 		res = tipc_wait_for_connect(sock, &timeout);
1966 		break;
1967 	case TIPC_ESTABLISHED:
1968 		res = -EISCONN;
1969 		break;
1970 	default:
1971 		res = -EINVAL;
1972 	}
1973 
1974 exit:
1975 	release_sock(sk);
1976 	return res;
1977 }
1978 
1979 /**
1980  * tipc_listen - allow socket to listen for incoming connections
1981  * @sock: socket structure
1982  * @len: (unused)
1983  *
1984  * Returns 0 on success, errno otherwise
1985  */
tipc_listen(struct socket * sock,int len)1986 static int tipc_listen(struct socket *sock, int len)
1987 {
1988 	struct sock *sk = sock->sk;
1989 	int res;
1990 
1991 	lock_sock(sk);
1992 	res = tipc_set_sk_state(sk, TIPC_LISTEN);
1993 	release_sock(sk);
1994 
1995 	return res;
1996 }
1997 
tipc_wait_for_accept(struct socket * sock,long timeo)1998 static int tipc_wait_for_accept(struct socket *sock, long timeo)
1999 {
2000 	struct sock *sk = sock->sk;
2001 	DEFINE_WAIT(wait);
2002 	int err;
2003 
2004 	/* True wake-one mechanism for incoming connections: only
2005 	 * one process gets woken up, not the 'whole herd'.
2006 	 * Since we do not 'race & poll' for established sockets
2007 	 * anymore, the common case will execute the loop only once.
2008 	*/
2009 	for (;;) {
2010 		prepare_to_wait_exclusive(sk_sleep(sk), &wait,
2011 					  TASK_INTERRUPTIBLE);
2012 		if (timeo && skb_queue_empty(&sk->sk_receive_queue)) {
2013 			release_sock(sk);
2014 			timeo = schedule_timeout(timeo);
2015 			lock_sock(sk);
2016 		}
2017 		err = 0;
2018 		if (!skb_queue_empty(&sk->sk_receive_queue))
2019 			break;
2020 		err = -EAGAIN;
2021 		if (!timeo)
2022 			break;
2023 		err = sock_intr_errno(timeo);
2024 		if (signal_pending(current))
2025 			break;
2026 	}
2027 	finish_wait(sk_sleep(sk), &wait);
2028 	return err;
2029 }
2030 
2031 /**
2032  * tipc_accept - wait for connection request
2033  * @sock: listening socket
2034  * @newsock: new socket that is to be connected
2035  * @flags: file-related flags associated with socket
2036  *
2037  * Returns 0 on success, errno otherwise
2038  */
tipc_accept(struct socket * sock,struct socket * new_sock,int flags,bool kern)2039 static int tipc_accept(struct socket *sock, struct socket *new_sock, int flags,
2040 		       bool kern)
2041 {
2042 	struct sock *new_sk, *sk = sock->sk;
2043 	struct sk_buff *buf;
2044 	struct tipc_sock *new_tsock;
2045 	struct tipc_msg *msg;
2046 	long timeo;
2047 	int res;
2048 
2049 	lock_sock(sk);
2050 
2051 	if (sk->sk_state != TIPC_LISTEN) {
2052 		res = -EINVAL;
2053 		goto exit;
2054 	}
2055 	timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
2056 	res = tipc_wait_for_accept(sock, timeo);
2057 	if (res)
2058 		goto exit;
2059 
2060 	buf = skb_peek(&sk->sk_receive_queue);
2061 
2062 	res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, kern);
2063 	if (res)
2064 		goto exit;
2065 	security_sk_clone(sock->sk, new_sock->sk);
2066 
2067 	new_sk = new_sock->sk;
2068 	new_tsock = tipc_sk(new_sk);
2069 	msg = buf_msg(buf);
2070 
2071 	/* we lock on new_sk; but lockdep sees the lock on sk */
2072 	lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
2073 
2074 	/*
2075 	 * Reject any stray messages received by new socket
2076 	 * before the socket lock was taken (very, very unlikely)
2077 	 */
2078 	tsk_rej_rx_queue(new_sk);
2079 
2080 	/* Connect new socket to it's peer */
2081 	tipc_sk_finish_conn(new_tsock, msg_origport(msg), msg_orignode(msg));
2082 
2083 	tsk_set_importance(new_tsock, msg_importance(msg));
2084 	if (msg_named(msg)) {
2085 		new_tsock->conn_type = msg_nametype(msg);
2086 		new_tsock->conn_instance = msg_nameinst(msg);
2087 	}
2088 
2089 	/*
2090 	 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
2091 	 * Respond to 'SYN+' by queuing it on new socket.
2092 	 */
2093 	if (!msg_data_sz(msg)) {
2094 		struct msghdr m = {NULL,};
2095 
2096 		tsk_advance_rx_queue(sk);
2097 		__tipc_sendstream(new_sock, &m, 0);
2098 	} else {
2099 		__skb_dequeue(&sk->sk_receive_queue);
2100 		__skb_queue_head(&new_sk->sk_receive_queue, buf);
2101 		skb_set_owner_r(buf, new_sk);
2102 	}
2103 	release_sock(new_sk);
2104 exit:
2105 	release_sock(sk);
2106 	return res;
2107 }
2108 
2109 /**
2110  * tipc_shutdown - shutdown socket connection
2111  * @sock: socket structure
2112  * @how: direction to close (must be SHUT_RDWR)
2113  *
2114  * Terminates connection (if necessary), then purges socket's receive queue.
2115  *
2116  * Returns 0 on success, errno otherwise
2117  */
tipc_shutdown(struct socket * sock,int how)2118 static int tipc_shutdown(struct socket *sock, int how)
2119 {
2120 	struct sock *sk = sock->sk;
2121 	int res;
2122 
2123 	if (how != SHUT_RDWR)
2124 		return -EINVAL;
2125 
2126 	lock_sock(sk);
2127 
2128 	__tipc_shutdown(sock, TIPC_CONN_SHUTDOWN);
2129 	sk->sk_shutdown = SEND_SHUTDOWN;
2130 
2131 	if (sk->sk_state == TIPC_DISCONNECTING) {
2132 		/* Discard any unreceived messages */
2133 		__skb_queue_purge(&sk->sk_receive_queue);
2134 
2135 		/* Wake up anyone sleeping in poll */
2136 		sk->sk_state_change(sk);
2137 		res = 0;
2138 	} else {
2139 		res = -ENOTCONN;
2140 	}
2141 
2142 	release_sock(sk);
2143 	return res;
2144 }
2145 
tipc_sk_timeout(unsigned long data)2146 static void tipc_sk_timeout(unsigned long data)
2147 {
2148 	struct tipc_sock *tsk = (struct tipc_sock *)data;
2149 	struct sock *sk = &tsk->sk;
2150 	struct sk_buff *skb = NULL;
2151 	u32 peer_port, peer_node;
2152 	u32 own_node = tsk_own_node(tsk);
2153 
2154 	bh_lock_sock(sk);
2155 	if (!tipc_sk_connected(sk)) {
2156 		bh_unlock_sock(sk);
2157 		goto exit;
2158 	}
2159 	peer_port = tsk_peer_port(tsk);
2160 	peer_node = tsk_peer_node(tsk);
2161 
2162 	if (tsk->probe_unacked) {
2163 		if (!sock_owned_by_user(sk)) {
2164 			tipc_set_sk_state(sk, TIPC_DISCONNECTING);
2165 			tipc_node_remove_conn(sock_net(sk), tsk_peer_node(tsk),
2166 					      tsk_peer_port(tsk));
2167 			sk->sk_state_change(sk);
2168 		} else {
2169 			/* Try again later */
2170 			sk_reset_timer(sk, &sk->sk_timer, (HZ / 20));
2171 		}
2172 
2173 		bh_unlock_sock(sk);
2174 		goto exit;
2175 	}
2176 
2177 	skb = tipc_msg_create(CONN_MANAGER, CONN_PROBE,
2178 			      INT_H_SIZE, 0, peer_node, own_node,
2179 			      peer_port, tsk->portid, TIPC_OK);
2180 	tsk->probe_unacked = true;
2181 	sk_reset_timer(sk, &sk->sk_timer, jiffies + CONN_PROBING_INTERVAL);
2182 	bh_unlock_sock(sk);
2183 	if (skb)
2184 		tipc_node_xmit_skb(sock_net(sk), skb, peer_node, tsk->portid);
2185 exit:
2186 	sock_put(sk);
2187 }
2188 
tipc_sk_publish(struct tipc_sock * tsk,uint scope,struct tipc_name_seq const * seq)2189 static int tipc_sk_publish(struct tipc_sock *tsk, uint scope,
2190 			   struct tipc_name_seq const *seq)
2191 {
2192 	struct sock *sk = &tsk->sk;
2193 	struct net *net = sock_net(sk);
2194 	struct publication *publ;
2195 	u32 key;
2196 
2197 	if (tipc_sk_connected(sk))
2198 		return -EINVAL;
2199 	key = tsk->portid + tsk->pub_count + 1;
2200 	if (key == tsk->portid)
2201 		return -EADDRINUSE;
2202 
2203 	publ = tipc_nametbl_publish(net, seq->type, seq->lower, seq->upper,
2204 				    scope, tsk->portid, key);
2205 	if (unlikely(!publ))
2206 		return -EINVAL;
2207 
2208 	list_add(&publ->pport_list, &tsk->publications);
2209 	tsk->pub_count++;
2210 	tsk->published = 1;
2211 	return 0;
2212 }
2213 
tipc_sk_withdraw(struct tipc_sock * tsk,uint scope,struct tipc_name_seq const * seq)2214 static int tipc_sk_withdraw(struct tipc_sock *tsk, uint scope,
2215 			    struct tipc_name_seq const *seq)
2216 {
2217 	struct net *net = sock_net(&tsk->sk);
2218 	struct publication *publ;
2219 	struct publication *safe;
2220 	int rc = -EINVAL;
2221 
2222 	list_for_each_entry_safe(publ, safe, &tsk->publications, pport_list) {
2223 		if (seq) {
2224 			if (publ->scope != scope)
2225 				continue;
2226 			if (publ->type != seq->type)
2227 				continue;
2228 			if (publ->lower != seq->lower)
2229 				continue;
2230 			if (publ->upper != seq->upper)
2231 				break;
2232 			tipc_nametbl_withdraw(net, publ->type, publ->lower,
2233 					      publ->ref, publ->key);
2234 			rc = 0;
2235 			break;
2236 		}
2237 		tipc_nametbl_withdraw(net, publ->type, publ->lower,
2238 				      publ->ref, publ->key);
2239 		rc = 0;
2240 	}
2241 	if (list_empty(&tsk->publications))
2242 		tsk->published = 0;
2243 	return rc;
2244 }
2245 
2246 /* tipc_sk_reinit: set non-zero address in all existing sockets
2247  *                 when we go from standalone to network mode.
2248  */
tipc_sk_reinit(struct net * net)2249 void tipc_sk_reinit(struct net *net)
2250 {
2251 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2252 	struct rhashtable_iter iter;
2253 	struct tipc_sock *tsk;
2254 	struct tipc_msg *msg;
2255 
2256 	rhashtable_walk_enter(&tn->sk_rht, &iter);
2257 
2258 	do {
2259 		tsk = ERR_PTR(rhashtable_walk_start(&iter));
2260 		if (IS_ERR(tsk))
2261 			goto walk_stop;
2262 
2263 		while ((tsk = rhashtable_walk_next(&iter)) && !IS_ERR(tsk)) {
2264 			sock_hold(&tsk->sk);
2265 			rhashtable_walk_stop(&iter);
2266 			lock_sock(&tsk->sk);
2267 			msg = &tsk->phdr;
2268 			msg_set_prevnode(msg, tn->own_addr);
2269 			msg_set_orignode(msg, tn->own_addr);
2270 			release_sock(&tsk->sk);
2271 			rhashtable_walk_start(&iter);
2272 			sock_put(&tsk->sk);
2273 		}
2274 walk_stop:
2275 		rhashtable_walk_stop(&iter);
2276 	} while (tsk == ERR_PTR(-EAGAIN));
2277 
2278 	rhashtable_walk_exit(&iter);
2279 }
2280 
tipc_sk_lookup(struct net * net,u32 portid)2281 static struct tipc_sock *tipc_sk_lookup(struct net *net, u32 portid)
2282 {
2283 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2284 	struct tipc_sock *tsk;
2285 
2286 	rcu_read_lock();
2287 	tsk = rhashtable_lookup_fast(&tn->sk_rht, &portid, tsk_rht_params);
2288 	if (tsk)
2289 		sock_hold(&tsk->sk);
2290 	rcu_read_unlock();
2291 
2292 	return tsk;
2293 }
2294 
tipc_sk_insert(struct tipc_sock * tsk)2295 static int tipc_sk_insert(struct tipc_sock *tsk)
2296 {
2297 	struct sock *sk = &tsk->sk;
2298 	struct net *net = sock_net(sk);
2299 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2300 	u32 remaining = (TIPC_MAX_PORT - TIPC_MIN_PORT) + 1;
2301 	u32 portid = prandom_u32() % remaining + TIPC_MIN_PORT;
2302 
2303 	while (remaining--) {
2304 		portid++;
2305 		if ((portid < TIPC_MIN_PORT) || (portid > TIPC_MAX_PORT))
2306 			portid = TIPC_MIN_PORT;
2307 		tsk->portid = portid;
2308 		sock_hold(&tsk->sk);
2309 		if (!rhashtable_lookup_insert_fast(&tn->sk_rht, &tsk->node,
2310 						   tsk_rht_params))
2311 			return 0;
2312 		sock_put(&tsk->sk);
2313 	}
2314 
2315 	return -1;
2316 }
2317 
tipc_sk_remove(struct tipc_sock * tsk)2318 static void tipc_sk_remove(struct tipc_sock *tsk)
2319 {
2320 	struct sock *sk = &tsk->sk;
2321 	struct tipc_net *tn = net_generic(sock_net(sk), tipc_net_id);
2322 
2323 	if (!rhashtable_remove_fast(&tn->sk_rht, &tsk->node, tsk_rht_params)) {
2324 		WARN_ON(refcount_read(&sk->sk_refcnt) == 1);
2325 		__sock_put(sk);
2326 	}
2327 }
2328 
2329 static const struct rhashtable_params tsk_rht_params = {
2330 	.nelem_hint = 192,
2331 	.head_offset = offsetof(struct tipc_sock, node),
2332 	.key_offset = offsetof(struct tipc_sock, portid),
2333 	.key_len = sizeof(u32), /* portid */
2334 	.max_size = 1048576,
2335 	.min_size = 256,
2336 	.automatic_shrinking = true,
2337 };
2338 
tipc_sk_rht_init(struct net * net)2339 int tipc_sk_rht_init(struct net *net)
2340 {
2341 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2342 
2343 	return rhashtable_init(&tn->sk_rht, &tsk_rht_params);
2344 }
2345 
tipc_sk_rht_destroy(struct net * net)2346 void tipc_sk_rht_destroy(struct net *net)
2347 {
2348 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2349 
2350 	/* Wait for socket readers to complete */
2351 	synchronize_net();
2352 
2353 	rhashtable_destroy(&tn->sk_rht);
2354 }
2355 
2356 /**
2357  * tipc_setsockopt - set socket option
2358  * @sock: socket structure
2359  * @lvl: option level
2360  * @opt: option identifier
2361  * @ov: pointer to new option value
2362  * @ol: length of option value
2363  *
2364  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
2365  * (to ease compatibility).
2366  *
2367  * Returns 0 on success, errno otherwise
2368  */
tipc_setsockopt(struct socket * sock,int lvl,int opt,char __user * ov,unsigned int ol)2369 static int tipc_setsockopt(struct socket *sock, int lvl, int opt,
2370 			   char __user *ov, unsigned int ol)
2371 {
2372 	struct sock *sk = sock->sk;
2373 	struct tipc_sock *tsk = tipc_sk(sk);
2374 	u32 value = 0;
2375 	int res = 0;
2376 
2377 	if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2378 		return 0;
2379 	if (lvl != SOL_TIPC)
2380 		return -ENOPROTOOPT;
2381 
2382 	switch (opt) {
2383 	case TIPC_IMPORTANCE:
2384 	case TIPC_SRC_DROPPABLE:
2385 	case TIPC_DEST_DROPPABLE:
2386 	case TIPC_CONN_TIMEOUT:
2387 		if (ol < sizeof(value))
2388 			return -EINVAL;
2389 		res = get_user(value, (u32 __user *)ov);
2390 		if (res)
2391 			return res;
2392 		break;
2393 	default:
2394 		if (ov || ol)
2395 			return -EINVAL;
2396 	}
2397 
2398 	lock_sock(sk);
2399 
2400 	switch (opt) {
2401 	case TIPC_IMPORTANCE:
2402 		res = tsk_set_importance(tsk, value);
2403 		break;
2404 	case TIPC_SRC_DROPPABLE:
2405 		if (sock->type != SOCK_STREAM)
2406 			tsk_set_unreliable(tsk, value);
2407 		else
2408 			res = -ENOPROTOOPT;
2409 		break;
2410 	case TIPC_DEST_DROPPABLE:
2411 		tsk_set_unreturnable(tsk, value);
2412 		break;
2413 	case TIPC_CONN_TIMEOUT:
2414 		tipc_sk(sk)->conn_timeout = value;
2415 		break;
2416 	case TIPC_MCAST_BROADCAST:
2417 		tsk->mc_method.rcast = false;
2418 		tsk->mc_method.mandatory = true;
2419 		break;
2420 	case TIPC_MCAST_REPLICAST:
2421 		tsk->mc_method.rcast = true;
2422 		tsk->mc_method.mandatory = true;
2423 		break;
2424 	default:
2425 		res = -EINVAL;
2426 	}
2427 
2428 	release_sock(sk);
2429 
2430 	return res;
2431 }
2432 
2433 /**
2434  * tipc_getsockopt - get socket option
2435  * @sock: socket structure
2436  * @lvl: option level
2437  * @opt: option identifier
2438  * @ov: receptacle for option value
2439  * @ol: receptacle for length of option value
2440  *
2441  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
2442  * (to ease compatibility).
2443  *
2444  * Returns 0 on success, errno otherwise
2445  */
tipc_getsockopt(struct socket * sock,int lvl,int opt,char __user * ov,int __user * ol)2446 static int tipc_getsockopt(struct socket *sock, int lvl, int opt,
2447 			   char __user *ov, int __user *ol)
2448 {
2449 	struct sock *sk = sock->sk;
2450 	struct tipc_sock *tsk = tipc_sk(sk);
2451 	int len;
2452 	u32 value;
2453 	int res;
2454 
2455 	if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
2456 		return put_user(0, ol);
2457 	if (lvl != SOL_TIPC)
2458 		return -ENOPROTOOPT;
2459 	res = get_user(len, ol);
2460 	if (res)
2461 		return res;
2462 
2463 	lock_sock(sk);
2464 
2465 	switch (opt) {
2466 	case TIPC_IMPORTANCE:
2467 		value = tsk_importance(tsk);
2468 		break;
2469 	case TIPC_SRC_DROPPABLE:
2470 		value = tsk_unreliable(tsk);
2471 		break;
2472 	case TIPC_DEST_DROPPABLE:
2473 		value = tsk_unreturnable(tsk);
2474 		break;
2475 	case TIPC_CONN_TIMEOUT:
2476 		value = tsk->conn_timeout;
2477 		/* no need to set "res", since already 0 at this point */
2478 		break;
2479 	case TIPC_NODE_RECVQ_DEPTH:
2480 		value = 0; /* was tipc_queue_size, now obsolete */
2481 		break;
2482 	case TIPC_SOCK_RECVQ_DEPTH:
2483 		value = skb_queue_len(&sk->sk_receive_queue);
2484 		break;
2485 	default:
2486 		res = -EINVAL;
2487 	}
2488 
2489 	release_sock(sk);
2490 
2491 	if (res)
2492 		return res;	/* "get" failed */
2493 
2494 	if (len < sizeof(value))
2495 		return -EINVAL;
2496 
2497 	if (copy_to_user(ov, &value, sizeof(value)))
2498 		return -EFAULT;
2499 
2500 	return put_user(sizeof(value), ol);
2501 }
2502 
tipc_ioctl(struct socket * sock,unsigned int cmd,unsigned long arg)2503 static int tipc_ioctl(struct socket *sock, unsigned int cmd, unsigned long arg)
2504 {
2505 	struct sock *sk = sock->sk;
2506 	struct tipc_sioc_ln_req lnr;
2507 	void __user *argp = (void __user *)arg;
2508 
2509 	switch (cmd) {
2510 	case SIOCGETLINKNAME:
2511 		if (copy_from_user(&lnr, argp, sizeof(lnr)))
2512 			return -EFAULT;
2513 		if (!tipc_node_get_linkname(sock_net(sk),
2514 					    lnr.bearer_id & 0xffff, lnr.peer,
2515 					    lnr.linkname, TIPC_MAX_LINK_NAME)) {
2516 			if (copy_to_user(argp, &lnr, sizeof(lnr)))
2517 				return -EFAULT;
2518 			return 0;
2519 		}
2520 		return -EADDRNOTAVAIL;
2521 	default:
2522 		return -ENOIOCTLCMD;
2523 	}
2524 }
2525 
tipc_socketpair(struct socket * sock1,struct socket * sock2)2526 static int tipc_socketpair(struct socket *sock1, struct socket *sock2)
2527 {
2528 	struct tipc_sock *tsk2 = tipc_sk(sock2->sk);
2529 	struct tipc_sock *tsk1 = tipc_sk(sock1->sk);
2530 	u32 onode = tipc_own_addr(sock_net(sock1->sk));
2531 
2532 	tsk1->peer.family = AF_TIPC;
2533 	tsk1->peer.addrtype = TIPC_ADDR_ID;
2534 	tsk1->peer.scope = TIPC_NODE_SCOPE;
2535 	tsk1->peer.addr.id.ref = tsk2->portid;
2536 	tsk1->peer.addr.id.node = onode;
2537 	tsk2->peer.family = AF_TIPC;
2538 	tsk2->peer.addrtype = TIPC_ADDR_ID;
2539 	tsk2->peer.scope = TIPC_NODE_SCOPE;
2540 	tsk2->peer.addr.id.ref = tsk1->portid;
2541 	tsk2->peer.addr.id.node = onode;
2542 
2543 	tipc_sk_finish_conn(tsk1, tsk2->portid, onode);
2544 	tipc_sk_finish_conn(tsk2, tsk1->portid, onode);
2545 	return 0;
2546 }
2547 
2548 /* Protocol switches for the various types of TIPC sockets */
2549 
2550 static const struct proto_ops msg_ops = {
2551 	.owner		= THIS_MODULE,
2552 	.family		= AF_TIPC,
2553 	.release	= tipc_release,
2554 	.bind		= tipc_bind,
2555 	.connect	= tipc_connect,
2556 	.socketpair	= tipc_socketpair,
2557 	.accept		= sock_no_accept,
2558 	.getname	= tipc_getname,
2559 	.poll		= tipc_poll,
2560 	.ioctl		= tipc_ioctl,
2561 	.listen		= sock_no_listen,
2562 	.shutdown	= tipc_shutdown,
2563 	.setsockopt	= tipc_setsockopt,
2564 	.getsockopt	= tipc_getsockopt,
2565 	.sendmsg	= tipc_sendmsg,
2566 	.recvmsg	= tipc_recvmsg,
2567 	.mmap		= sock_no_mmap,
2568 	.sendpage	= sock_no_sendpage
2569 };
2570 
2571 static const struct proto_ops packet_ops = {
2572 	.owner		= THIS_MODULE,
2573 	.family		= AF_TIPC,
2574 	.release	= tipc_release,
2575 	.bind		= tipc_bind,
2576 	.connect	= tipc_connect,
2577 	.socketpair	= tipc_socketpair,
2578 	.accept		= tipc_accept,
2579 	.getname	= tipc_getname,
2580 	.poll		= tipc_poll,
2581 	.ioctl		= tipc_ioctl,
2582 	.listen		= tipc_listen,
2583 	.shutdown	= tipc_shutdown,
2584 	.setsockopt	= tipc_setsockopt,
2585 	.getsockopt	= tipc_getsockopt,
2586 	.sendmsg	= tipc_send_packet,
2587 	.recvmsg	= tipc_recvmsg,
2588 	.mmap		= sock_no_mmap,
2589 	.sendpage	= sock_no_sendpage
2590 };
2591 
2592 static const struct proto_ops stream_ops = {
2593 	.owner		= THIS_MODULE,
2594 	.family		= AF_TIPC,
2595 	.release	= tipc_release,
2596 	.bind		= tipc_bind,
2597 	.connect	= tipc_connect,
2598 	.socketpair	= tipc_socketpair,
2599 	.accept		= tipc_accept,
2600 	.getname	= tipc_getname,
2601 	.poll		= tipc_poll,
2602 	.ioctl		= tipc_ioctl,
2603 	.listen		= tipc_listen,
2604 	.shutdown	= tipc_shutdown,
2605 	.setsockopt	= tipc_setsockopt,
2606 	.getsockopt	= tipc_getsockopt,
2607 	.sendmsg	= tipc_sendstream,
2608 	.recvmsg	= tipc_recvstream,
2609 	.mmap		= sock_no_mmap,
2610 	.sendpage	= sock_no_sendpage
2611 };
2612 
2613 static const struct net_proto_family tipc_family_ops = {
2614 	.owner		= THIS_MODULE,
2615 	.family		= AF_TIPC,
2616 	.create		= tipc_sk_create
2617 };
2618 
2619 static struct proto tipc_proto = {
2620 	.name		= "TIPC",
2621 	.owner		= THIS_MODULE,
2622 	.obj_size	= sizeof(struct tipc_sock),
2623 	.sysctl_rmem	= sysctl_tipc_rmem
2624 };
2625 
2626 /**
2627  * tipc_socket_init - initialize TIPC socket interface
2628  *
2629  * Returns 0 on success, errno otherwise
2630  */
tipc_socket_init(void)2631 int tipc_socket_init(void)
2632 {
2633 	int res;
2634 
2635 	res = proto_register(&tipc_proto, 1);
2636 	if (res) {
2637 		pr_err("Failed to register TIPC protocol type\n");
2638 		goto out;
2639 	}
2640 
2641 	res = sock_register(&tipc_family_ops);
2642 	if (res) {
2643 		pr_err("Failed to register TIPC socket type\n");
2644 		proto_unregister(&tipc_proto);
2645 		goto out;
2646 	}
2647  out:
2648 	return res;
2649 }
2650 
2651 /**
2652  * tipc_socket_stop - stop TIPC socket interface
2653  */
tipc_socket_stop(void)2654 void tipc_socket_stop(void)
2655 {
2656 	sock_unregister(tipc_family_ops.family);
2657 	proto_unregister(&tipc_proto);
2658 }
2659 
2660 /* Caller should hold socket lock for the passed tipc socket. */
__tipc_nl_add_sk_con(struct sk_buff * skb,struct tipc_sock * tsk)2661 static int __tipc_nl_add_sk_con(struct sk_buff *skb, struct tipc_sock *tsk)
2662 {
2663 	u32 peer_node;
2664 	u32 peer_port;
2665 	struct nlattr *nest;
2666 
2667 	peer_node = tsk_peer_node(tsk);
2668 	peer_port = tsk_peer_port(tsk);
2669 
2670 	nest = nla_nest_start(skb, TIPC_NLA_SOCK_CON);
2671 
2672 	if (nla_put_u32(skb, TIPC_NLA_CON_NODE, peer_node))
2673 		goto msg_full;
2674 	if (nla_put_u32(skb, TIPC_NLA_CON_SOCK, peer_port))
2675 		goto msg_full;
2676 
2677 	if (tsk->conn_type != 0) {
2678 		if (nla_put_flag(skb, TIPC_NLA_CON_FLAG))
2679 			goto msg_full;
2680 		if (nla_put_u32(skb, TIPC_NLA_CON_TYPE, tsk->conn_type))
2681 			goto msg_full;
2682 		if (nla_put_u32(skb, TIPC_NLA_CON_INST, tsk->conn_instance))
2683 			goto msg_full;
2684 	}
2685 	nla_nest_end(skb, nest);
2686 
2687 	return 0;
2688 
2689 msg_full:
2690 	nla_nest_cancel(skb, nest);
2691 
2692 	return -EMSGSIZE;
2693 }
2694 
2695 /* Caller should hold socket lock for the passed tipc socket. */
__tipc_nl_add_sk(struct sk_buff * skb,struct netlink_callback * cb,struct tipc_sock * tsk)2696 static int __tipc_nl_add_sk(struct sk_buff *skb, struct netlink_callback *cb,
2697 			    struct tipc_sock *tsk)
2698 {
2699 	int err;
2700 	void *hdr;
2701 	struct nlattr *attrs;
2702 	struct net *net = sock_net(skb->sk);
2703 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2704 	struct sock *sk = &tsk->sk;
2705 
2706 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2707 			  &tipc_genl_family, NLM_F_MULTI, TIPC_NL_SOCK_GET);
2708 	if (!hdr)
2709 		goto msg_cancel;
2710 
2711 	attrs = nla_nest_start(skb, TIPC_NLA_SOCK);
2712 	if (!attrs)
2713 		goto genlmsg_cancel;
2714 	if (nla_put_u32(skb, TIPC_NLA_SOCK_REF, tsk->portid))
2715 		goto attr_msg_cancel;
2716 	if (nla_put_u32(skb, TIPC_NLA_SOCK_ADDR, tn->own_addr))
2717 		goto attr_msg_cancel;
2718 
2719 	if (tipc_sk_connected(sk)) {
2720 		err = __tipc_nl_add_sk_con(skb, tsk);
2721 		if (err)
2722 			goto attr_msg_cancel;
2723 	} else if (!list_empty(&tsk->publications)) {
2724 		if (nla_put_flag(skb, TIPC_NLA_SOCK_HAS_PUBL))
2725 			goto attr_msg_cancel;
2726 	}
2727 	nla_nest_end(skb, attrs);
2728 	genlmsg_end(skb, hdr);
2729 
2730 	return 0;
2731 
2732 attr_msg_cancel:
2733 	nla_nest_cancel(skb, attrs);
2734 genlmsg_cancel:
2735 	genlmsg_cancel(skb, hdr);
2736 msg_cancel:
2737 	return -EMSGSIZE;
2738 }
2739 
tipc_nl_sk_dump(struct sk_buff * skb,struct netlink_callback * cb)2740 int tipc_nl_sk_dump(struct sk_buff *skb, struct netlink_callback *cb)
2741 {
2742 	int err;
2743 	struct tipc_sock *tsk;
2744 	const struct bucket_table *tbl;
2745 	struct rhash_head *pos;
2746 	struct net *net = sock_net(skb->sk);
2747 	struct tipc_net *tn = net_generic(net, tipc_net_id);
2748 	u32 tbl_id = cb->args[0];
2749 	u32 prev_portid = cb->args[1];
2750 
2751 	rcu_read_lock();
2752 	tbl = rht_dereference_rcu((&tn->sk_rht)->tbl, &tn->sk_rht);
2753 	for (; tbl_id < tbl->size; tbl_id++) {
2754 		rht_for_each_entry_rcu(tsk, pos, tbl, tbl_id, node) {
2755 			spin_lock_bh(&tsk->sk.sk_lock.slock);
2756 			if (prev_portid && prev_portid != tsk->portid) {
2757 				spin_unlock_bh(&tsk->sk.sk_lock.slock);
2758 				continue;
2759 			}
2760 
2761 			err = __tipc_nl_add_sk(skb, cb, tsk);
2762 			if (err) {
2763 				prev_portid = tsk->portid;
2764 				spin_unlock_bh(&tsk->sk.sk_lock.slock);
2765 				goto out;
2766 			}
2767 			prev_portid = 0;
2768 			spin_unlock_bh(&tsk->sk.sk_lock.slock);
2769 		}
2770 	}
2771 out:
2772 	rcu_read_unlock();
2773 	cb->args[0] = tbl_id;
2774 	cb->args[1] = prev_portid;
2775 
2776 	return skb->len;
2777 }
2778 
2779 /* Caller should hold socket lock for the passed tipc socket. */
__tipc_nl_add_sk_publ(struct sk_buff * skb,struct netlink_callback * cb,struct publication * publ)2780 static int __tipc_nl_add_sk_publ(struct sk_buff *skb,
2781 				 struct netlink_callback *cb,
2782 				 struct publication *publ)
2783 {
2784 	void *hdr;
2785 	struct nlattr *attrs;
2786 
2787 	hdr = genlmsg_put(skb, NETLINK_CB(cb->skb).portid, cb->nlh->nlmsg_seq,
2788 			  &tipc_genl_family, NLM_F_MULTI, TIPC_NL_PUBL_GET);
2789 	if (!hdr)
2790 		goto msg_cancel;
2791 
2792 	attrs = nla_nest_start(skb, TIPC_NLA_PUBL);
2793 	if (!attrs)
2794 		goto genlmsg_cancel;
2795 
2796 	if (nla_put_u32(skb, TIPC_NLA_PUBL_KEY, publ->key))
2797 		goto attr_msg_cancel;
2798 	if (nla_put_u32(skb, TIPC_NLA_PUBL_TYPE, publ->type))
2799 		goto attr_msg_cancel;
2800 	if (nla_put_u32(skb, TIPC_NLA_PUBL_LOWER, publ->lower))
2801 		goto attr_msg_cancel;
2802 	if (nla_put_u32(skb, TIPC_NLA_PUBL_UPPER, publ->upper))
2803 		goto attr_msg_cancel;
2804 
2805 	nla_nest_end(skb, attrs);
2806 	genlmsg_end(skb, hdr);
2807 
2808 	return 0;
2809 
2810 attr_msg_cancel:
2811 	nla_nest_cancel(skb, attrs);
2812 genlmsg_cancel:
2813 	genlmsg_cancel(skb, hdr);
2814 msg_cancel:
2815 	return -EMSGSIZE;
2816 }
2817 
2818 /* Caller should hold socket lock for the passed tipc socket. */
__tipc_nl_list_sk_publ(struct sk_buff * skb,struct netlink_callback * cb,struct tipc_sock * tsk,u32 * last_publ)2819 static int __tipc_nl_list_sk_publ(struct sk_buff *skb,
2820 				  struct netlink_callback *cb,
2821 				  struct tipc_sock *tsk, u32 *last_publ)
2822 {
2823 	int err;
2824 	struct publication *p;
2825 
2826 	if (*last_publ) {
2827 		list_for_each_entry(p, &tsk->publications, pport_list) {
2828 			if (p->key == *last_publ)
2829 				break;
2830 		}
2831 		if (p->key != *last_publ) {
2832 			/* We never set seq or call nl_dump_check_consistent()
2833 			 * this means that setting prev_seq here will cause the
2834 			 * consistence check to fail in the netlink callback
2835 			 * handler. Resulting in the last NLMSG_DONE message
2836 			 * having the NLM_F_DUMP_INTR flag set.
2837 			 */
2838 			cb->prev_seq = 1;
2839 			*last_publ = 0;
2840 			return -EPIPE;
2841 		}
2842 	} else {
2843 		p = list_first_entry(&tsk->publications, struct publication,
2844 				     pport_list);
2845 	}
2846 
2847 	list_for_each_entry_from(p, &tsk->publications, pport_list) {
2848 		err = __tipc_nl_add_sk_publ(skb, cb, p);
2849 		if (err) {
2850 			*last_publ = p->key;
2851 			return err;
2852 		}
2853 	}
2854 	*last_publ = 0;
2855 
2856 	return 0;
2857 }
2858 
tipc_nl_publ_dump(struct sk_buff * skb,struct netlink_callback * cb)2859 int tipc_nl_publ_dump(struct sk_buff *skb, struct netlink_callback *cb)
2860 {
2861 	int err;
2862 	u32 tsk_portid = cb->args[0];
2863 	u32 last_publ = cb->args[1];
2864 	u32 done = cb->args[2];
2865 	struct net *net = sock_net(skb->sk);
2866 	struct tipc_sock *tsk;
2867 
2868 	if (!tsk_portid) {
2869 		struct nlattr **attrs;
2870 		struct nlattr *sock[TIPC_NLA_SOCK_MAX + 1];
2871 
2872 		err = tipc_nlmsg_parse(cb->nlh, &attrs);
2873 		if (err)
2874 			return err;
2875 
2876 		if (!attrs[TIPC_NLA_SOCK])
2877 			return -EINVAL;
2878 
2879 		err = nla_parse_nested(sock, TIPC_NLA_SOCK_MAX,
2880 				       attrs[TIPC_NLA_SOCK],
2881 				       tipc_nl_sock_policy, NULL);
2882 		if (err)
2883 			return err;
2884 
2885 		if (!sock[TIPC_NLA_SOCK_REF])
2886 			return -EINVAL;
2887 
2888 		tsk_portid = nla_get_u32(sock[TIPC_NLA_SOCK_REF]);
2889 	}
2890 
2891 	if (done)
2892 		return 0;
2893 
2894 	tsk = tipc_sk_lookup(net, tsk_portid);
2895 	if (!tsk)
2896 		return -EINVAL;
2897 
2898 	lock_sock(&tsk->sk);
2899 	err = __tipc_nl_list_sk_publ(skb, cb, tsk, &last_publ);
2900 	if (!err)
2901 		done = 1;
2902 	release_sock(&tsk->sk);
2903 	sock_put(&tsk->sk);
2904 
2905 	cb->args[0] = tsk_portid;
2906 	cb->args[1] = last_publ;
2907 	cb->args[2] = done;
2908 
2909 	return skb->len;
2910 }
2911