xref: /linux/net/tipc/socket.c (revision 89e47d3b8a273b0eac21e4bf6d7fdb86b654fa16)
1 /*
2  * net/tipc/socket.c: TIPC socket API
3  *
4  * Copyright (c) 2001-2007, 2012 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 "core.h"
38 #include "port.h"
39 
40 #include <linux/export.h>
41 #include <net/sock.h>
42 
43 #define SS_LISTENING	-1	/* socket is listening */
44 #define SS_READY	-2	/* socket is connectionless */
45 
46 #define CONN_TIMEOUT_DEFAULT	8000	/* default connect timeout = 8s */
47 
48 struct tipc_sock {
49 	struct sock sk;
50 	struct tipc_port *p;
51 	struct tipc_portid peer_name;
52 	unsigned int conn_timeout;
53 };
54 
55 #define tipc_sk(sk) ((struct tipc_sock *)(sk))
56 #define tipc_sk_port(sk) (tipc_sk(sk)->p)
57 
58 #define tipc_rx_ready(sock) (!skb_queue_empty(&sock->sk->sk_receive_queue) || \
59 			(sock->state == SS_DISCONNECTING))
60 
61 static int backlog_rcv(struct sock *sk, struct sk_buff *skb);
62 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
63 static void wakeupdispatch(struct tipc_port *tport);
64 static void tipc_data_ready(struct sock *sk, int len);
65 static void tipc_write_space(struct sock *sk);
66 static int release(struct socket *sock);
67 static int accept(struct socket *sock, struct socket *new_sock, int flags);
68 
69 static const struct proto_ops packet_ops;
70 static const struct proto_ops stream_ops;
71 static const struct proto_ops msg_ops;
72 
73 static struct proto tipc_proto;
74 static struct proto tipc_proto_kern;
75 
76 static int sockets_enabled;
77 
78 /*
79  * Revised TIPC socket locking policy:
80  *
81  * Most socket operations take the standard socket lock when they start
82  * and hold it until they finish (or until they need to sleep).  Acquiring
83  * this lock grants the owner exclusive access to the fields of the socket
84  * data structures, with the exception of the backlog queue.  A few socket
85  * operations can be done without taking the socket lock because they only
86  * read socket information that never changes during the life of the socket.
87  *
88  * Socket operations may acquire the lock for the associated TIPC port if they
89  * need to perform an operation on the port.  If any routine needs to acquire
90  * both the socket lock and the port lock it must take the socket lock first
91  * to avoid the risk of deadlock.
92  *
93  * The dispatcher handling incoming messages cannot grab the socket lock in
94  * the standard fashion, since invoked it runs at the BH level and cannot block.
95  * Instead, it checks to see if the socket lock is currently owned by someone,
96  * and either handles the message itself or adds it to the socket's backlog
97  * queue; in the latter case the queued message is processed once the process
98  * owning the socket lock releases it.
99  *
100  * NOTE: Releasing the socket lock while an operation is sleeping overcomes
101  * the problem of a blocked socket operation preventing any other operations
102  * from occurring.  However, applications must be careful if they have
103  * multiple threads trying to send (or receive) on the same socket, as these
104  * operations might interfere with each other.  For example, doing a connect
105  * and a receive at the same time might allow the receive to consume the
106  * ACK message meant for the connect.  While additional work could be done
107  * to try and overcome this, it doesn't seem to be worthwhile at the present.
108  *
109  * NOTE: Releasing the socket lock while an operation is sleeping also ensures
110  * that another operation that must be performed in a non-blocking manner is
111  * not delayed for very long because the lock has already been taken.
112  *
113  * NOTE: This code assumes that certain fields of a port/socket pair are
114  * constant over its lifetime; such fields can be examined without taking
115  * the socket lock and/or port lock, and do not need to be re-read even
116  * after resuming processing after waiting.  These fields include:
117  *   - socket type
118  *   - pointer to socket sk structure (aka tipc_sock structure)
119  *   - pointer to port structure
120  *   - port reference
121  */
122 
123 /**
124  * advance_rx_queue - discard first buffer in socket receive queue
125  *
126  * Caller must hold socket lock
127  */
128 static void advance_rx_queue(struct sock *sk)
129 {
130 	kfree_skb(__skb_dequeue(&sk->sk_receive_queue));
131 }
132 
133 /**
134  * reject_rx_queue - reject all buffers in socket receive queue
135  *
136  * Caller must hold socket lock
137  */
138 static void reject_rx_queue(struct sock *sk)
139 {
140 	struct sk_buff *buf;
141 
142 	while ((buf = __skb_dequeue(&sk->sk_receive_queue)))
143 		tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
144 }
145 
146 /**
147  * tipc_sk_create - create a TIPC socket
148  * @net: network namespace (must be default network)
149  * @sock: pre-allocated socket structure
150  * @protocol: protocol indicator (must be 0)
151  * @kern: caused by kernel or by userspace?
152  *
153  * This routine creates additional data structures used by the TIPC socket,
154  * initializes them, and links them together.
155  *
156  * Returns 0 on success, errno otherwise
157  */
158 static int tipc_sk_create(struct net *net, struct socket *sock, int protocol,
159 			  int kern)
160 {
161 	const struct proto_ops *ops;
162 	socket_state state;
163 	struct sock *sk;
164 	struct tipc_port *tp_ptr;
165 
166 	/* Validate arguments */
167 	if (unlikely(protocol != 0))
168 		return -EPROTONOSUPPORT;
169 
170 	switch (sock->type) {
171 	case SOCK_STREAM:
172 		ops = &stream_ops;
173 		state = SS_UNCONNECTED;
174 		break;
175 	case SOCK_SEQPACKET:
176 		ops = &packet_ops;
177 		state = SS_UNCONNECTED;
178 		break;
179 	case SOCK_DGRAM:
180 	case SOCK_RDM:
181 		ops = &msg_ops;
182 		state = SS_READY;
183 		break;
184 	default:
185 		return -EPROTOTYPE;
186 	}
187 
188 	/* Allocate socket's protocol area */
189 	if (!kern)
190 		sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
191 	else
192 		sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto_kern);
193 
194 	if (sk == NULL)
195 		return -ENOMEM;
196 
197 	/* Allocate TIPC port for socket to use */
198 	tp_ptr = tipc_createport(sk, &dispatch, &wakeupdispatch,
199 				 TIPC_LOW_IMPORTANCE);
200 	if (unlikely(!tp_ptr)) {
201 		sk_free(sk);
202 		return -ENOMEM;
203 	}
204 
205 	/* Finish initializing socket data structures */
206 	sock->ops = ops;
207 	sock->state = state;
208 
209 	sock_init_data(sock, sk);
210 	sk->sk_backlog_rcv = backlog_rcv;
211 	sk->sk_rcvbuf = sysctl_tipc_rmem[1];
212 	sk->sk_data_ready = tipc_data_ready;
213 	sk->sk_write_space = tipc_write_space;
214 	tipc_sk(sk)->p = tp_ptr;
215 	tipc_sk(sk)->conn_timeout = CONN_TIMEOUT_DEFAULT;
216 
217 	spin_unlock_bh(tp_ptr->lock);
218 
219 	if (sock->state == SS_READY) {
220 		tipc_set_portunreturnable(tp_ptr->ref, 1);
221 		if (sock->type == SOCK_DGRAM)
222 			tipc_set_portunreliable(tp_ptr->ref, 1);
223 	}
224 
225 	return 0;
226 }
227 
228 /**
229  * tipc_sock_create_local - create TIPC socket from inside TIPC module
230  * @type: socket type - SOCK_RDM or SOCK_SEQPACKET
231  *
232  * We cannot use sock_creat_kern here because it bumps module user count.
233  * Since socket owner and creator is the same module we must make sure
234  * that module count remains zero for module local sockets, otherwise
235  * we cannot do rmmod.
236  *
237  * Returns 0 on success, errno otherwise
238  */
239 int tipc_sock_create_local(int type, struct socket **res)
240 {
241 	int rc;
242 
243 	rc = sock_create_lite(AF_TIPC, type, 0, res);
244 	if (rc < 0) {
245 		pr_err("Failed to create kernel socket\n");
246 		return rc;
247 	}
248 	tipc_sk_create(&init_net, *res, 0, 1);
249 
250 	return 0;
251 }
252 
253 /**
254  * tipc_sock_release_local - release socket created by tipc_sock_create_local
255  * @sock: the socket to be released.
256  *
257  * Module reference count is not incremented when such sockets are created,
258  * so we must keep it from being decremented when they are released.
259  */
260 void tipc_sock_release_local(struct socket *sock)
261 {
262 	release(sock);
263 	sock->ops = NULL;
264 	sock_release(sock);
265 }
266 
267 /**
268  * tipc_sock_accept_local - accept a connection on a socket created
269  * with tipc_sock_create_local. Use this function to avoid that
270  * module reference count is inadvertently incremented.
271  *
272  * @sock:    the accepting socket
273  * @newsock: reference to the new socket to be created
274  * @flags:   socket flags
275  */
276 
277 int tipc_sock_accept_local(struct socket *sock, struct socket **newsock,
278 			   int flags)
279 {
280 	struct sock *sk = sock->sk;
281 	int ret;
282 
283 	ret = sock_create_lite(sk->sk_family, sk->sk_type,
284 			       sk->sk_protocol, newsock);
285 	if (ret < 0)
286 		return ret;
287 
288 	ret = accept(sock, *newsock, flags);
289 	if (ret < 0) {
290 		sock_release(*newsock);
291 		return ret;
292 	}
293 	(*newsock)->ops = sock->ops;
294 	return ret;
295 }
296 
297 /**
298  * release - destroy a TIPC socket
299  * @sock: socket to destroy
300  *
301  * This routine cleans up any messages that are still queued on the socket.
302  * For DGRAM and RDM socket types, all queued messages are rejected.
303  * For SEQPACKET and STREAM socket types, the first message is rejected
304  * and any others are discarded.  (If the first message on a STREAM socket
305  * is partially-read, it is discarded and the next one is rejected instead.)
306  *
307  * NOTE: Rejected messages are not necessarily returned to the sender!  They
308  * are returned or discarded according to the "destination droppable" setting
309  * specified for the message by the sender.
310  *
311  * Returns 0 on success, errno otherwise
312  */
313 static int release(struct socket *sock)
314 {
315 	struct sock *sk = sock->sk;
316 	struct tipc_port *tport;
317 	struct sk_buff *buf;
318 	int res;
319 
320 	/*
321 	 * Exit if socket isn't fully initialized (occurs when a failed accept()
322 	 * releases a pre-allocated child socket that was never used)
323 	 */
324 	if (sk == NULL)
325 		return 0;
326 
327 	tport = tipc_sk_port(sk);
328 	lock_sock(sk);
329 
330 	/*
331 	 * Reject all unreceived messages, except on an active connection
332 	 * (which disconnects locally & sends a 'FIN+' to peer)
333 	 */
334 	while (sock->state != SS_DISCONNECTING) {
335 		buf = __skb_dequeue(&sk->sk_receive_queue);
336 		if (buf == NULL)
337 			break;
338 		if (TIPC_SKB_CB(buf)->handle != NULL)
339 			kfree_skb(buf);
340 		else {
341 			if ((sock->state == SS_CONNECTING) ||
342 			    (sock->state == SS_CONNECTED)) {
343 				sock->state = SS_DISCONNECTING;
344 				tipc_disconnect(tport->ref);
345 			}
346 			tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
347 		}
348 	}
349 
350 	/*
351 	 * Delete TIPC port; this ensures no more messages are queued
352 	 * (also disconnects an active connection & sends a 'FIN-' to peer)
353 	 */
354 	res = tipc_deleteport(tport->ref);
355 
356 	/* Discard any remaining (connection-based) messages in receive queue */
357 	__skb_queue_purge(&sk->sk_receive_queue);
358 
359 	/* Reject any messages that accumulated in backlog queue */
360 	sock->state = SS_DISCONNECTING;
361 	release_sock(sk);
362 
363 	sock_put(sk);
364 	sock->sk = NULL;
365 
366 	return res;
367 }
368 
369 /**
370  * bind - associate or disassocate TIPC name(s) with a socket
371  * @sock: socket structure
372  * @uaddr: socket address describing name(s) and desired operation
373  * @uaddr_len: size of socket address data structure
374  *
375  * Name and name sequence binding is indicated using a positive scope value;
376  * a negative scope value unbinds the specified name.  Specifying no name
377  * (i.e. a socket address length of 0) unbinds all names from the socket.
378  *
379  * Returns 0 on success, errno otherwise
380  *
381  * NOTE: This routine doesn't need to take the socket lock since it doesn't
382  *       access any non-constant socket information.
383  */
384 static int bind(struct socket *sock, struct sockaddr *uaddr, int uaddr_len)
385 {
386 	struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
387 	u32 portref = tipc_sk_port(sock->sk)->ref;
388 
389 	if (unlikely(!uaddr_len))
390 		return tipc_withdraw(portref, 0, NULL);
391 
392 	if (uaddr_len < sizeof(struct sockaddr_tipc))
393 		return -EINVAL;
394 	if (addr->family != AF_TIPC)
395 		return -EAFNOSUPPORT;
396 
397 	if (addr->addrtype == TIPC_ADDR_NAME)
398 		addr->addr.nameseq.upper = addr->addr.nameseq.lower;
399 	else if (addr->addrtype != TIPC_ADDR_NAMESEQ)
400 		return -EAFNOSUPPORT;
401 
402 	if ((addr->addr.nameseq.type < TIPC_RESERVED_TYPES) &&
403 	    (addr->addr.nameseq.type != TIPC_TOP_SRV) &&
404 	    (addr->addr.nameseq.type != TIPC_CFG_SRV))
405 		return -EACCES;
406 
407 	return (addr->scope > 0) ?
408 		tipc_publish(portref, addr->scope, &addr->addr.nameseq) :
409 		tipc_withdraw(portref, -addr->scope, &addr->addr.nameseq);
410 }
411 
412 /**
413  * get_name - get port ID of socket or peer socket
414  * @sock: socket structure
415  * @uaddr: area for returned socket address
416  * @uaddr_len: area for returned length of socket address
417  * @peer: 0 = own ID, 1 = current peer ID, 2 = current/former peer ID
418  *
419  * Returns 0 on success, errno otherwise
420  *
421  * NOTE: This routine doesn't need to take the socket lock since it only
422  *       accesses socket information that is unchanging (or which changes in
423  *       a completely predictable manner).
424  */
425 static int get_name(struct socket *sock, struct sockaddr *uaddr,
426 		    int *uaddr_len, int peer)
427 {
428 	struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
429 	struct tipc_sock *tsock = tipc_sk(sock->sk);
430 
431 	memset(addr, 0, sizeof(*addr));
432 	if (peer) {
433 		if ((sock->state != SS_CONNECTED) &&
434 			((peer != 2) || (sock->state != SS_DISCONNECTING)))
435 			return -ENOTCONN;
436 		addr->addr.id.ref = tsock->peer_name.ref;
437 		addr->addr.id.node = tsock->peer_name.node;
438 	} else {
439 		addr->addr.id.ref = tsock->p->ref;
440 		addr->addr.id.node = tipc_own_addr;
441 	}
442 
443 	*uaddr_len = sizeof(*addr);
444 	addr->addrtype = TIPC_ADDR_ID;
445 	addr->family = AF_TIPC;
446 	addr->scope = 0;
447 	addr->addr.name.domain = 0;
448 
449 	return 0;
450 }
451 
452 /**
453  * poll - read and possibly block on pollmask
454  * @file: file structure associated with the socket
455  * @sock: socket for which to calculate the poll bits
456  * @wait: ???
457  *
458  * Returns pollmask value
459  *
460  * COMMENTARY:
461  * It appears that the usual socket locking mechanisms are not useful here
462  * since the pollmask info is potentially out-of-date the moment this routine
463  * exits.  TCP and other protocols seem to rely on higher level poll routines
464  * to handle any preventable race conditions, so TIPC will do the same ...
465  *
466  * TIPC sets the returned events as follows:
467  *
468  * socket state		flags set
469  * ------------		---------
470  * unconnected		no read flags
471  *			POLLOUT if port is not congested
472  *
473  * connecting		POLLIN/POLLRDNORM if ACK/NACK in rx queue
474  *			no write flags
475  *
476  * connected		POLLIN/POLLRDNORM if data in rx queue
477  *			POLLOUT if port is not congested
478  *
479  * disconnecting	POLLIN/POLLRDNORM/POLLHUP
480  *			no write flags
481  *
482  * listening		POLLIN if SYN in rx queue
483  *			no write flags
484  *
485  * ready		POLLIN/POLLRDNORM if data in rx queue
486  * [connectionless]	POLLOUT (since port cannot be congested)
487  *
488  * IMPORTANT: The fact that a read or write operation is indicated does NOT
489  * imply that the operation will succeed, merely that it should be performed
490  * and will not block.
491  */
492 static unsigned int poll(struct file *file, struct socket *sock,
493 			 poll_table *wait)
494 {
495 	struct sock *sk = sock->sk;
496 	u32 mask = 0;
497 
498 	sock_poll_wait(file, sk_sleep(sk), wait);
499 
500 	switch ((int)sock->state) {
501 	case SS_UNCONNECTED:
502 		if (!tipc_sk_port(sk)->congested)
503 			mask |= POLLOUT;
504 		break;
505 	case SS_READY:
506 	case SS_CONNECTED:
507 		if (!tipc_sk_port(sk)->congested)
508 			mask |= POLLOUT;
509 		/* fall thru' */
510 	case SS_CONNECTING:
511 	case SS_LISTENING:
512 		if (!skb_queue_empty(&sk->sk_receive_queue))
513 			mask |= (POLLIN | POLLRDNORM);
514 		break;
515 	case SS_DISCONNECTING:
516 		mask = (POLLIN | POLLRDNORM | POLLHUP);
517 		break;
518 	}
519 
520 	return mask;
521 }
522 
523 /**
524  * dest_name_check - verify user is permitted to send to specified port name
525  * @dest: destination address
526  * @m: descriptor for message to be sent
527  *
528  * Prevents restricted configuration commands from being issued by
529  * unauthorized users.
530  *
531  * Returns 0 if permission is granted, otherwise errno
532  */
533 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
534 {
535 	struct tipc_cfg_msg_hdr hdr;
536 
537 	if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
538 		return 0;
539 	if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
540 		return 0;
541 	if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
542 		return -EACCES;
543 
544 	if (!m->msg_iovlen || (m->msg_iov[0].iov_len < sizeof(hdr)))
545 		return -EMSGSIZE;
546 	if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
547 		return -EFAULT;
548 	if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
549 		return -EACCES;
550 
551 	return 0;
552 }
553 
554 /**
555  * send_msg - send message in connectionless manner
556  * @iocb: if NULL, indicates that socket lock is already held
557  * @sock: socket structure
558  * @m: message to send
559  * @total_len: length of message
560  *
561  * Message must have an destination specified explicitly.
562  * Used for SOCK_RDM and SOCK_DGRAM messages,
563  * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
564  * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
565  *
566  * Returns the number of bytes sent on success, or errno otherwise
567  */
568 static int send_msg(struct kiocb *iocb, struct socket *sock,
569 		    struct msghdr *m, size_t total_len)
570 {
571 	struct sock *sk = sock->sk;
572 	struct tipc_port *tport = tipc_sk_port(sk);
573 	struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
574 	int needs_conn;
575 	long timeout_val;
576 	int res = -EINVAL;
577 
578 	if (unlikely(!dest))
579 		return -EDESTADDRREQ;
580 	if (unlikely((m->msg_namelen < sizeof(*dest)) ||
581 		     (dest->family != AF_TIPC)))
582 		return -EINVAL;
583 	if (total_len > TIPC_MAX_USER_MSG_SIZE)
584 		return -EMSGSIZE;
585 
586 	if (iocb)
587 		lock_sock(sk);
588 
589 	needs_conn = (sock->state != SS_READY);
590 	if (unlikely(needs_conn)) {
591 		if (sock->state == SS_LISTENING) {
592 			res = -EPIPE;
593 			goto exit;
594 		}
595 		if (sock->state != SS_UNCONNECTED) {
596 			res = -EISCONN;
597 			goto exit;
598 		}
599 		if (tport->published) {
600 			res = -EOPNOTSUPP;
601 			goto exit;
602 		}
603 		if (dest->addrtype == TIPC_ADDR_NAME) {
604 			tport->conn_type = dest->addr.name.name.type;
605 			tport->conn_instance = dest->addr.name.name.instance;
606 		}
607 
608 		/* Abort any pending connection attempts (very unlikely) */
609 		reject_rx_queue(sk);
610 	}
611 
612 	timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
613 
614 	do {
615 		if (dest->addrtype == TIPC_ADDR_NAME) {
616 			res = dest_name_check(dest, m);
617 			if (res)
618 				break;
619 			res = tipc_send2name(tport->ref,
620 					     &dest->addr.name.name,
621 					     dest->addr.name.domain,
622 					     m->msg_iov,
623 					     total_len);
624 		} else if (dest->addrtype == TIPC_ADDR_ID) {
625 			res = tipc_send2port(tport->ref,
626 					     &dest->addr.id,
627 					     m->msg_iov,
628 					     total_len);
629 		} else if (dest->addrtype == TIPC_ADDR_MCAST) {
630 			if (needs_conn) {
631 				res = -EOPNOTSUPP;
632 				break;
633 			}
634 			res = dest_name_check(dest, m);
635 			if (res)
636 				break;
637 			res = tipc_multicast(tport->ref,
638 					     &dest->addr.nameseq,
639 					     m->msg_iov,
640 					     total_len);
641 		}
642 		if (likely(res != -ELINKCONG)) {
643 			if (needs_conn && (res >= 0))
644 				sock->state = SS_CONNECTING;
645 			break;
646 		}
647 		if (timeout_val <= 0L) {
648 			res = timeout_val ? timeout_val : -EWOULDBLOCK;
649 			break;
650 		}
651 		release_sock(sk);
652 		timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
653 					       !tport->congested, timeout_val);
654 		lock_sock(sk);
655 	} while (1);
656 
657 exit:
658 	if (iocb)
659 		release_sock(sk);
660 	return res;
661 }
662 
663 /**
664  * send_packet - send a connection-oriented message
665  * @iocb: if NULL, indicates that socket lock is already held
666  * @sock: socket structure
667  * @m: message to send
668  * @total_len: length of message
669  *
670  * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
671  *
672  * Returns the number of bytes sent on success, or errno otherwise
673  */
674 static int send_packet(struct kiocb *iocb, struct socket *sock,
675 		       struct msghdr *m, size_t total_len)
676 {
677 	struct sock *sk = sock->sk;
678 	struct tipc_port *tport = tipc_sk_port(sk);
679 	struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
680 	long timeout_val;
681 	int res;
682 
683 	/* Handle implied connection establishment */
684 	if (unlikely(dest))
685 		return send_msg(iocb, sock, m, total_len);
686 
687 	if (total_len > TIPC_MAX_USER_MSG_SIZE)
688 		return -EMSGSIZE;
689 
690 	if (iocb)
691 		lock_sock(sk);
692 
693 	timeout_val = sock_sndtimeo(sk, m->msg_flags & MSG_DONTWAIT);
694 
695 	do {
696 		if (unlikely(sock->state != SS_CONNECTED)) {
697 			if (sock->state == SS_DISCONNECTING)
698 				res = -EPIPE;
699 			else
700 				res = -ENOTCONN;
701 			break;
702 		}
703 
704 		res = tipc_send(tport->ref, m->msg_iov, total_len);
705 		if (likely(res != -ELINKCONG))
706 			break;
707 		if (timeout_val <= 0L) {
708 			res = timeout_val ? timeout_val : -EWOULDBLOCK;
709 			break;
710 		}
711 		release_sock(sk);
712 		timeout_val = wait_event_interruptible_timeout(*sk_sleep(sk),
713 			(!tport->congested || !tport->connected), timeout_val);
714 		lock_sock(sk);
715 	} while (1);
716 
717 	if (iocb)
718 		release_sock(sk);
719 	return res;
720 }
721 
722 /**
723  * send_stream - send stream-oriented data
724  * @iocb: (unused)
725  * @sock: socket structure
726  * @m: data to send
727  * @total_len: total length of data to be sent
728  *
729  * Used for SOCK_STREAM data.
730  *
731  * Returns the number of bytes sent on success (or partial success),
732  * or errno if no data sent
733  */
734 static int send_stream(struct kiocb *iocb, struct socket *sock,
735 		       struct msghdr *m, size_t total_len)
736 {
737 	struct sock *sk = sock->sk;
738 	struct tipc_port *tport = tipc_sk_port(sk);
739 	struct msghdr my_msg;
740 	struct iovec my_iov;
741 	struct iovec *curr_iov;
742 	int curr_iovlen;
743 	char __user *curr_start;
744 	u32 hdr_size;
745 	int curr_left;
746 	int bytes_to_send;
747 	int bytes_sent;
748 	int res;
749 
750 	lock_sock(sk);
751 
752 	/* Handle special cases where there is no connection */
753 	if (unlikely(sock->state != SS_CONNECTED)) {
754 		res = -ENOTCONN;
755 
756 		if (sock->state == SS_UNCONNECTED)
757 			res = send_packet(NULL, sock, m, total_len);
758 		else if (sock->state == SS_DISCONNECTING)
759 			res = -EPIPE;
760 
761 		goto exit;
762 	}
763 
764 	if (unlikely(m->msg_name)) {
765 		res = -EISCONN;
766 		goto exit;
767 	}
768 
769 	if (total_len > (unsigned int)INT_MAX) {
770 		res = -EMSGSIZE;
771 		goto exit;
772 	}
773 
774 	/*
775 	 * Send each iovec entry using one or more messages
776 	 *
777 	 * Note: This algorithm is good for the most likely case
778 	 * (i.e. one large iovec entry), but could be improved to pass sets
779 	 * of small iovec entries into send_packet().
780 	 */
781 	curr_iov = m->msg_iov;
782 	curr_iovlen = m->msg_iovlen;
783 	my_msg.msg_iov = &my_iov;
784 	my_msg.msg_iovlen = 1;
785 	my_msg.msg_flags = m->msg_flags;
786 	my_msg.msg_name = NULL;
787 	bytes_sent = 0;
788 
789 	hdr_size = msg_hdr_sz(&tport->phdr);
790 
791 	while (curr_iovlen--) {
792 		curr_start = curr_iov->iov_base;
793 		curr_left = curr_iov->iov_len;
794 
795 		while (curr_left) {
796 			bytes_to_send = tport->max_pkt - hdr_size;
797 			if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
798 				bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
799 			if (curr_left < bytes_to_send)
800 				bytes_to_send = curr_left;
801 			my_iov.iov_base = curr_start;
802 			my_iov.iov_len = bytes_to_send;
803 			res = send_packet(NULL, sock, &my_msg, bytes_to_send);
804 			if (res < 0) {
805 				if (bytes_sent)
806 					res = bytes_sent;
807 				goto exit;
808 			}
809 			curr_left -= bytes_to_send;
810 			curr_start += bytes_to_send;
811 			bytes_sent += bytes_to_send;
812 		}
813 
814 		curr_iov++;
815 	}
816 	res = bytes_sent;
817 exit:
818 	release_sock(sk);
819 	return res;
820 }
821 
822 /**
823  * auto_connect - complete connection setup to a remote port
824  * @sock: socket structure
825  * @msg: peer's response message
826  *
827  * Returns 0 on success, errno otherwise
828  */
829 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
830 {
831 	struct tipc_sock *tsock = tipc_sk(sock->sk);
832 	struct tipc_port *p_ptr;
833 
834 	tsock->peer_name.ref = msg_origport(msg);
835 	tsock->peer_name.node = msg_orignode(msg);
836 	p_ptr = tipc_port_deref(tsock->p->ref);
837 	if (!p_ptr)
838 		return -EINVAL;
839 
840 	__tipc_connect(tsock->p->ref, p_ptr, &tsock->peer_name);
841 
842 	if (msg_importance(msg) > TIPC_CRITICAL_IMPORTANCE)
843 		return -EINVAL;
844 	msg_set_importance(&p_ptr->phdr, (u32)msg_importance(msg));
845 	sock->state = SS_CONNECTED;
846 	return 0;
847 }
848 
849 /**
850  * set_orig_addr - capture sender's address for received message
851  * @m: descriptor for message info
852  * @msg: received message header
853  *
854  * Note: Address is not captured if not requested by receiver.
855  */
856 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
857 {
858 	struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
859 
860 	if (addr) {
861 		addr->family = AF_TIPC;
862 		addr->addrtype = TIPC_ADDR_ID;
863 		memset(&addr->addr, 0, sizeof(addr->addr));
864 		addr->addr.id.ref = msg_origport(msg);
865 		addr->addr.id.node = msg_orignode(msg);
866 		addr->addr.name.domain = 0;	/* could leave uninitialized */
867 		addr->scope = 0;		/* could leave uninitialized */
868 		m->msg_namelen = sizeof(struct sockaddr_tipc);
869 	}
870 }
871 
872 /**
873  * anc_data_recv - optionally capture ancillary data for received message
874  * @m: descriptor for message info
875  * @msg: received message header
876  * @tport: TIPC port associated with message
877  *
878  * Note: Ancillary data is not captured if not requested by receiver.
879  *
880  * Returns 0 if successful, otherwise errno
881  */
882 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
883 			 struct tipc_port *tport)
884 {
885 	u32 anc_data[3];
886 	u32 err;
887 	u32 dest_type;
888 	int has_name;
889 	int res;
890 
891 	if (likely(m->msg_controllen == 0))
892 		return 0;
893 
894 	/* Optionally capture errored message object(s) */
895 	err = msg ? msg_errcode(msg) : 0;
896 	if (unlikely(err)) {
897 		anc_data[0] = err;
898 		anc_data[1] = msg_data_sz(msg);
899 		res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data);
900 		if (res)
901 			return res;
902 		if (anc_data[1]) {
903 			res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
904 				       msg_data(msg));
905 			if (res)
906 				return res;
907 		}
908 	}
909 
910 	/* Optionally capture message destination object */
911 	dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
912 	switch (dest_type) {
913 	case TIPC_NAMED_MSG:
914 		has_name = 1;
915 		anc_data[0] = msg_nametype(msg);
916 		anc_data[1] = msg_namelower(msg);
917 		anc_data[2] = msg_namelower(msg);
918 		break;
919 	case TIPC_MCAST_MSG:
920 		has_name = 1;
921 		anc_data[0] = msg_nametype(msg);
922 		anc_data[1] = msg_namelower(msg);
923 		anc_data[2] = msg_nameupper(msg);
924 		break;
925 	case TIPC_CONN_MSG:
926 		has_name = (tport->conn_type != 0);
927 		anc_data[0] = tport->conn_type;
928 		anc_data[1] = tport->conn_instance;
929 		anc_data[2] = tport->conn_instance;
930 		break;
931 	default:
932 		has_name = 0;
933 	}
934 	if (has_name) {
935 		res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data);
936 		if (res)
937 			return res;
938 	}
939 
940 	return 0;
941 }
942 
943 /**
944  * recv_msg - receive packet-oriented message
945  * @iocb: (unused)
946  * @m: descriptor for message info
947  * @buf_len: total size of user buffer area
948  * @flags: receive flags
949  *
950  * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
951  * If the complete message doesn't fit in user area, truncate it.
952  *
953  * Returns size of returned message data, errno otherwise
954  */
955 static int recv_msg(struct kiocb *iocb, struct socket *sock,
956 		    struct msghdr *m, size_t buf_len, int flags)
957 {
958 	struct sock *sk = sock->sk;
959 	struct tipc_port *tport = tipc_sk_port(sk);
960 	struct sk_buff *buf;
961 	struct tipc_msg *msg;
962 	long timeout;
963 	unsigned int sz;
964 	u32 err;
965 	int res;
966 
967 	/* Catch invalid receive requests */
968 	if (unlikely(!buf_len))
969 		return -EINVAL;
970 
971 	lock_sock(sk);
972 
973 	if (unlikely(sock->state == SS_UNCONNECTED)) {
974 		res = -ENOTCONN;
975 		goto exit;
976 	}
977 
978 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
979 restart:
980 
981 	/* Look for a message in receive queue; wait if necessary */
982 	while (skb_queue_empty(&sk->sk_receive_queue)) {
983 		if (sock->state == SS_DISCONNECTING) {
984 			res = -ENOTCONN;
985 			goto exit;
986 		}
987 		if (timeout <= 0L) {
988 			res = timeout ? timeout : -EWOULDBLOCK;
989 			goto exit;
990 		}
991 		release_sock(sk);
992 		timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
993 							   tipc_rx_ready(sock),
994 							   timeout);
995 		lock_sock(sk);
996 	}
997 
998 	/* Look at first message in receive queue */
999 	buf = skb_peek(&sk->sk_receive_queue);
1000 	msg = buf_msg(buf);
1001 	sz = msg_data_sz(msg);
1002 	err = msg_errcode(msg);
1003 
1004 	/* Discard an empty non-errored message & try again */
1005 	if ((!sz) && (!err)) {
1006 		advance_rx_queue(sk);
1007 		goto restart;
1008 	}
1009 
1010 	/* Capture sender's address (optional) */
1011 	set_orig_addr(m, msg);
1012 
1013 	/* Capture ancillary data (optional) */
1014 	res = anc_data_recv(m, msg, tport);
1015 	if (res)
1016 		goto exit;
1017 
1018 	/* Capture message data (if valid) & compute return value (always) */
1019 	if (!err) {
1020 		if (unlikely(buf_len < sz)) {
1021 			sz = buf_len;
1022 			m->msg_flags |= MSG_TRUNC;
1023 		}
1024 		res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg),
1025 					      m->msg_iov, sz);
1026 		if (res)
1027 			goto exit;
1028 		res = sz;
1029 	} else {
1030 		if ((sock->state == SS_READY) ||
1031 		    ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
1032 			res = 0;
1033 		else
1034 			res = -ECONNRESET;
1035 	}
1036 
1037 	/* Consume received message (optional) */
1038 	if (likely(!(flags & MSG_PEEK))) {
1039 		if ((sock->state != SS_READY) &&
1040 		    (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1041 			tipc_acknowledge(tport->ref, tport->conn_unacked);
1042 		advance_rx_queue(sk);
1043 	}
1044 exit:
1045 	release_sock(sk);
1046 	return res;
1047 }
1048 
1049 /**
1050  * recv_stream - receive stream-oriented data
1051  * @iocb: (unused)
1052  * @m: descriptor for message info
1053  * @buf_len: total size of user buffer area
1054  * @flags: receive flags
1055  *
1056  * Used for SOCK_STREAM messages only.  If not enough data is available
1057  * will optionally wait for more; never truncates data.
1058  *
1059  * Returns size of returned message data, errno otherwise
1060  */
1061 static int recv_stream(struct kiocb *iocb, struct socket *sock,
1062 		       struct msghdr *m, size_t buf_len, int flags)
1063 {
1064 	struct sock *sk = sock->sk;
1065 	struct tipc_port *tport = tipc_sk_port(sk);
1066 	struct sk_buff *buf;
1067 	struct tipc_msg *msg;
1068 	long timeout;
1069 	unsigned int sz;
1070 	int sz_to_copy, target, needed;
1071 	int sz_copied = 0;
1072 	u32 err;
1073 	int res = 0;
1074 
1075 	/* Catch invalid receive attempts */
1076 	if (unlikely(!buf_len))
1077 		return -EINVAL;
1078 
1079 	lock_sock(sk);
1080 
1081 	if (unlikely((sock->state == SS_UNCONNECTED))) {
1082 		res = -ENOTCONN;
1083 		goto exit;
1084 	}
1085 
1086 	target = sock_rcvlowat(sk, flags & MSG_WAITALL, buf_len);
1087 	timeout = sock_rcvtimeo(sk, flags & MSG_DONTWAIT);
1088 
1089 restart:
1090 	/* Look for a message in receive queue; wait if necessary */
1091 	while (skb_queue_empty(&sk->sk_receive_queue)) {
1092 		if (sock->state == SS_DISCONNECTING) {
1093 			res = -ENOTCONN;
1094 			goto exit;
1095 		}
1096 		if (timeout <= 0L) {
1097 			res = timeout ? timeout : -EWOULDBLOCK;
1098 			goto exit;
1099 		}
1100 		release_sock(sk);
1101 		timeout = wait_event_interruptible_timeout(*sk_sleep(sk),
1102 							   tipc_rx_ready(sock),
1103 							   timeout);
1104 		lock_sock(sk);
1105 	}
1106 
1107 	/* Look at first message in receive queue */
1108 	buf = skb_peek(&sk->sk_receive_queue);
1109 	msg = buf_msg(buf);
1110 	sz = msg_data_sz(msg);
1111 	err = msg_errcode(msg);
1112 
1113 	/* Discard an empty non-errored message & try again */
1114 	if ((!sz) && (!err)) {
1115 		advance_rx_queue(sk);
1116 		goto restart;
1117 	}
1118 
1119 	/* Optionally capture sender's address & ancillary data of first msg */
1120 	if (sz_copied == 0) {
1121 		set_orig_addr(m, msg);
1122 		res = anc_data_recv(m, msg, tport);
1123 		if (res)
1124 			goto exit;
1125 	}
1126 
1127 	/* Capture message data (if valid) & compute return value (always) */
1128 	if (!err) {
1129 		u32 offset = (u32)(unsigned long)(TIPC_SKB_CB(buf)->handle);
1130 
1131 		sz -= offset;
1132 		needed = (buf_len - sz_copied);
1133 		sz_to_copy = (sz <= needed) ? sz : needed;
1134 
1135 		res = skb_copy_datagram_iovec(buf, msg_hdr_sz(msg) + offset,
1136 					      m->msg_iov, sz_to_copy);
1137 		if (res)
1138 			goto exit;
1139 
1140 		sz_copied += sz_to_copy;
1141 
1142 		if (sz_to_copy < sz) {
1143 			if (!(flags & MSG_PEEK))
1144 				TIPC_SKB_CB(buf)->handle =
1145 				(void *)(unsigned long)(offset + sz_to_copy);
1146 			goto exit;
1147 		}
1148 	} else {
1149 		if (sz_copied != 0)
1150 			goto exit; /* can't add error msg to valid data */
1151 
1152 		if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1153 			res = 0;
1154 		else
1155 			res = -ECONNRESET;
1156 	}
1157 
1158 	/* Consume received message (optional) */
1159 	if (likely(!(flags & MSG_PEEK))) {
1160 		if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1161 			tipc_acknowledge(tport->ref, tport->conn_unacked);
1162 		advance_rx_queue(sk);
1163 	}
1164 
1165 	/* Loop around if more data is required */
1166 	if ((sz_copied < buf_len) &&	/* didn't get all requested data */
1167 	    (!skb_queue_empty(&sk->sk_receive_queue) ||
1168 	    (sz_copied < target)) &&	/* and more is ready or required */
1169 	    (!(flags & MSG_PEEK)) &&	/* and aren't just peeking at data */
1170 	    (!err))			/* and haven't reached a FIN */
1171 		goto restart;
1172 
1173 exit:
1174 	release_sock(sk);
1175 	return sz_copied ? sz_copied : res;
1176 }
1177 
1178 /**
1179  * tipc_write_space - wake up thread if port congestion is released
1180  * @sk: socket
1181  */
1182 static void tipc_write_space(struct sock *sk)
1183 {
1184 	struct socket_wq *wq;
1185 
1186 	rcu_read_lock();
1187 	wq = rcu_dereference(sk->sk_wq);
1188 	if (wq_has_sleeper(wq))
1189 		wake_up_interruptible_sync_poll(&wq->wait, POLLOUT |
1190 						POLLWRNORM | POLLWRBAND);
1191 	rcu_read_unlock();
1192 }
1193 
1194 /**
1195  * tipc_data_ready - wake up threads to indicate messages have been received
1196  * @sk: socket
1197  * @len: the length of messages
1198  */
1199 static void tipc_data_ready(struct sock *sk, int len)
1200 {
1201 	struct socket_wq *wq;
1202 
1203 	rcu_read_lock();
1204 	wq = rcu_dereference(sk->sk_wq);
1205 	if (wq_has_sleeper(wq))
1206 		wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
1207 						POLLRDNORM | POLLRDBAND);
1208 	rcu_read_unlock();
1209 }
1210 
1211 /**
1212  * filter_connect - Handle all incoming messages for a connection-based socket
1213  * @tsock: TIPC socket
1214  * @msg: message
1215  *
1216  * Returns TIPC error status code and socket error status code
1217  * once it encounters some errors
1218  */
1219 static u32 filter_connect(struct tipc_sock *tsock, struct sk_buff **buf)
1220 {
1221 	struct socket *sock = tsock->sk.sk_socket;
1222 	struct tipc_msg *msg = buf_msg(*buf);
1223 	struct sock *sk = &tsock->sk;
1224 	u32 retval = TIPC_ERR_NO_PORT;
1225 	int res;
1226 
1227 	if (msg_mcast(msg))
1228 		return retval;
1229 
1230 	switch ((int)sock->state) {
1231 	case SS_CONNECTED:
1232 		/* Accept only connection-based messages sent by peer */
1233 		if (msg_connected(msg) && tipc_port_peer_msg(tsock->p, msg)) {
1234 			if (unlikely(msg_errcode(msg))) {
1235 				sock->state = SS_DISCONNECTING;
1236 				__tipc_disconnect(tsock->p);
1237 			}
1238 			retval = TIPC_OK;
1239 		}
1240 		break;
1241 	case SS_CONNECTING:
1242 		/* Accept only ACK or NACK message */
1243 		if (unlikely(msg_errcode(msg))) {
1244 			sock->state = SS_DISCONNECTING;
1245 			sk->sk_err = ECONNREFUSED;
1246 			retval = TIPC_OK;
1247 			break;
1248 		}
1249 
1250 		if (unlikely(!msg_connected(msg)))
1251 			break;
1252 
1253 		res = auto_connect(sock, msg);
1254 		if (res) {
1255 			sock->state = SS_DISCONNECTING;
1256 			sk->sk_err = -res;
1257 			retval = TIPC_OK;
1258 			break;
1259 		}
1260 
1261 		/* If an incoming message is an 'ACK-', it should be
1262 		 * discarded here because it doesn't contain useful
1263 		 * data. In addition, we should try to wake up
1264 		 * connect() routine if sleeping.
1265 		 */
1266 		if (msg_data_sz(msg) == 0) {
1267 			kfree_skb(*buf);
1268 			*buf = NULL;
1269 			if (waitqueue_active(sk_sleep(sk)))
1270 				wake_up_interruptible(sk_sleep(sk));
1271 		}
1272 		retval = TIPC_OK;
1273 		break;
1274 	case SS_LISTENING:
1275 	case SS_UNCONNECTED:
1276 		/* Accept only SYN message */
1277 		if (!msg_connected(msg) && !(msg_errcode(msg)))
1278 			retval = TIPC_OK;
1279 		break;
1280 	case SS_DISCONNECTING:
1281 		break;
1282 	default:
1283 		pr_err("Unknown socket state %u\n", sock->state);
1284 	}
1285 	return retval;
1286 }
1287 
1288 /**
1289  * rcvbuf_limit - get proper overload limit of socket receive queue
1290  * @sk: socket
1291  * @buf: message
1292  *
1293  * For all connection oriented messages, irrespective of importance,
1294  * the default overload value (i.e. 67MB) is set as limit.
1295  *
1296  * For all connectionless messages, by default new queue limits are
1297  * as belows:
1298  *
1299  * TIPC_LOW_IMPORTANCE       (4 MB)
1300  * TIPC_MEDIUM_IMPORTANCE    (8 MB)
1301  * TIPC_HIGH_IMPORTANCE      (16 MB)
1302  * TIPC_CRITICAL_IMPORTANCE  (32 MB)
1303  *
1304  * Returns overload limit according to corresponding message importance
1305  */
1306 static unsigned int rcvbuf_limit(struct sock *sk, struct sk_buff *buf)
1307 {
1308 	struct tipc_msg *msg = buf_msg(buf);
1309 
1310 	if (msg_connected(msg))
1311 		return sysctl_tipc_rmem[2];
1312 
1313 	return sk->sk_rcvbuf >> TIPC_CRITICAL_IMPORTANCE <<
1314 		msg_importance(msg);
1315 }
1316 
1317 /**
1318  * filter_rcv - validate incoming message
1319  * @sk: socket
1320  * @buf: message
1321  *
1322  * Enqueues message on receive queue if acceptable; optionally handles
1323  * disconnect indication for a connected socket.
1324  *
1325  * Called with socket lock already taken; port lock may also be taken.
1326  *
1327  * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1328  */
1329 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1330 {
1331 	struct socket *sock = sk->sk_socket;
1332 	struct tipc_msg *msg = buf_msg(buf);
1333 	unsigned int limit = rcvbuf_limit(sk, buf);
1334 	u32 res = TIPC_OK;
1335 
1336 	/* Reject message if it is wrong sort of message for socket */
1337 	if (msg_type(msg) > TIPC_DIRECT_MSG)
1338 		return TIPC_ERR_NO_PORT;
1339 
1340 	if (sock->state == SS_READY) {
1341 		if (msg_connected(msg))
1342 			return TIPC_ERR_NO_PORT;
1343 	} else {
1344 		res = filter_connect(tipc_sk(sk), &buf);
1345 		if (res != TIPC_OK || buf == NULL)
1346 			return res;
1347 	}
1348 
1349 	/* Reject message if there isn't room to queue it */
1350 	if (sk_rmem_alloc_get(sk) + buf->truesize >= limit)
1351 		return TIPC_ERR_OVERLOAD;
1352 
1353 	/* Enqueue message */
1354 	TIPC_SKB_CB(buf)->handle = NULL;
1355 	__skb_queue_tail(&sk->sk_receive_queue, buf);
1356 	skb_set_owner_r(buf, sk);
1357 
1358 	sk->sk_data_ready(sk, 0);
1359 	return TIPC_OK;
1360 }
1361 
1362 /**
1363  * backlog_rcv - handle incoming message from backlog queue
1364  * @sk: socket
1365  * @buf: message
1366  *
1367  * Caller must hold socket lock, but not port lock.
1368  *
1369  * Returns 0
1370  */
1371 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1372 {
1373 	u32 res;
1374 
1375 	res = filter_rcv(sk, buf);
1376 	if (res)
1377 		tipc_reject_msg(buf, res);
1378 	return 0;
1379 }
1380 
1381 /**
1382  * dispatch - handle incoming message
1383  * @tport: TIPC port that received message
1384  * @buf: message
1385  *
1386  * Called with port lock already taken.
1387  *
1388  * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1389  */
1390 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1391 {
1392 	struct sock *sk = tport->sk;
1393 	u32 res;
1394 
1395 	/*
1396 	 * Process message if socket is unlocked; otherwise add to backlog queue
1397 	 *
1398 	 * This code is based on sk_receive_skb(), but must be distinct from it
1399 	 * since a TIPC-specific filter/reject mechanism is utilized
1400 	 */
1401 	bh_lock_sock(sk);
1402 	if (!sock_owned_by_user(sk)) {
1403 		res = filter_rcv(sk, buf);
1404 	} else {
1405 		if (sk_add_backlog(sk, buf, rcvbuf_limit(sk, buf)))
1406 			res = TIPC_ERR_OVERLOAD;
1407 		else
1408 			res = TIPC_OK;
1409 	}
1410 	bh_unlock_sock(sk);
1411 
1412 	return res;
1413 }
1414 
1415 /**
1416  * wakeupdispatch - wake up port after congestion
1417  * @tport: port to wakeup
1418  *
1419  * Called with port lock already taken.
1420  */
1421 static void wakeupdispatch(struct tipc_port *tport)
1422 {
1423 	struct sock *sk = tport->sk;
1424 
1425 	sk->sk_write_space(sk);
1426 }
1427 
1428 /**
1429  * connect - establish a connection to another TIPC port
1430  * @sock: socket structure
1431  * @dest: socket address for destination port
1432  * @destlen: size of socket address data structure
1433  * @flags: file-related flags associated with socket
1434  *
1435  * Returns 0 on success, errno otherwise
1436  */
1437 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1438 		   int flags)
1439 {
1440 	struct sock *sk = sock->sk;
1441 	struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1442 	struct msghdr m = {NULL,};
1443 	unsigned int timeout;
1444 	int res;
1445 
1446 	lock_sock(sk);
1447 
1448 	/* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1449 	if (sock->state == SS_READY) {
1450 		res = -EOPNOTSUPP;
1451 		goto exit;
1452 	}
1453 
1454 	/*
1455 	 * Reject connection attempt using multicast address
1456 	 *
1457 	 * Note: send_msg() validates the rest of the address fields,
1458 	 *       so there's no need to do it here
1459 	 */
1460 	if (dst->addrtype == TIPC_ADDR_MCAST) {
1461 		res = -EINVAL;
1462 		goto exit;
1463 	}
1464 
1465 	timeout = (flags & O_NONBLOCK) ? 0 : tipc_sk(sk)->conn_timeout;
1466 
1467 	switch (sock->state) {
1468 	case SS_UNCONNECTED:
1469 		/* Send a 'SYN-' to destination */
1470 		m.msg_name = dest;
1471 		m.msg_namelen = destlen;
1472 
1473 		/* If connect is in non-blocking case, set MSG_DONTWAIT to
1474 		 * indicate send_msg() is never blocked.
1475 		 */
1476 		if (!timeout)
1477 			m.msg_flags = MSG_DONTWAIT;
1478 
1479 		res = send_msg(NULL, sock, &m, 0);
1480 		if ((res < 0) && (res != -EWOULDBLOCK))
1481 			goto exit;
1482 
1483 		/* Just entered SS_CONNECTING state; the only
1484 		 * difference is that return value in non-blocking
1485 		 * case is EINPROGRESS, rather than EALREADY.
1486 		 */
1487 		res = -EINPROGRESS;
1488 		break;
1489 	case SS_CONNECTING:
1490 		res = -EALREADY;
1491 		break;
1492 	case SS_CONNECTED:
1493 		res = -EISCONN;
1494 		break;
1495 	default:
1496 		res = -EINVAL;
1497 		goto exit;
1498 	}
1499 
1500 	if (sock->state == SS_CONNECTING) {
1501 		if (!timeout)
1502 			goto exit;
1503 
1504 		/* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1505 		release_sock(sk);
1506 		res = wait_event_interruptible_timeout(*sk_sleep(sk),
1507 				sock->state != SS_CONNECTING,
1508 				timeout ? (long)msecs_to_jiffies(timeout)
1509 					: MAX_SCHEDULE_TIMEOUT);
1510 		if (res <= 0) {
1511 			if (res == 0)
1512 				res = -ETIMEDOUT;
1513 			return res;
1514 		}
1515 		lock_sock(sk);
1516 	}
1517 
1518 	if (unlikely(sock->state == SS_DISCONNECTING))
1519 		res = sock_error(sk);
1520 	else
1521 		res = 0;
1522 
1523 exit:
1524 	release_sock(sk);
1525 	return res;
1526 }
1527 
1528 /**
1529  * listen - allow socket to listen for incoming connections
1530  * @sock: socket structure
1531  * @len: (unused)
1532  *
1533  * Returns 0 on success, errno otherwise
1534  */
1535 static int listen(struct socket *sock, int len)
1536 {
1537 	struct sock *sk = sock->sk;
1538 	int res;
1539 
1540 	lock_sock(sk);
1541 
1542 	if (sock->state != SS_UNCONNECTED)
1543 		res = -EINVAL;
1544 	else {
1545 		sock->state = SS_LISTENING;
1546 		res = 0;
1547 	}
1548 
1549 	release_sock(sk);
1550 	return res;
1551 }
1552 
1553 /**
1554  * accept - wait for connection request
1555  * @sock: listening socket
1556  * @newsock: new socket that is to be connected
1557  * @flags: file-related flags associated with socket
1558  *
1559  * Returns 0 on success, errno otherwise
1560  */
1561 static int accept(struct socket *sock, struct socket *new_sock, int flags)
1562 {
1563 	struct sock *new_sk, *sk = sock->sk;
1564 	struct sk_buff *buf;
1565 	struct tipc_sock *new_tsock;
1566 	struct tipc_port *new_tport;
1567 	struct tipc_msg *msg;
1568 	u32 new_ref;
1569 
1570 	int res;
1571 
1572 	lock_sock(sk);
1573 
1574 	if (sock->state != SS_LISTENING) {
1575 		res = -EINVAL;
1576 		goto exit;
1577 	}
1578 
1579 	while (skb_queue_empty(&sk->sk_receive_queue)) {
1580 		if (flags & O_NONBLOCK) {
1581 			res = -EWOULDBLOCK;
1582 			goto exit;
1583 		}
1584 		release_sock(sk);
1585 		res = wait_event_interruptible(*sk_sleep(sk),
1586 				(!skb_queue_empty(&sk->sk_receive_queue)));
1587 		lock_sock(sk);
1588 		if (res)
1589 			goto exit;
1590 	}
1591 
1592 	buf = skb_peek(&sk->sk_receive_queue);
1593 
1594 	res = tipc_sk_create(sock_net(sock->sk), new_sock, 0, 1);
1595 	if (res)
1596 		goto exit;
1597 
1598 	new_sk = new_sock->sk;
1599 	new_tsock = tipc_sk(new_sk);
1600 	new_tport = new_tsock->p;
1601 	new_ref = new_tport->ref;
1602 	msg = buf_msg(buf);
1603 
1604 	/* we lock on new_sk; but lockdep sees the lock on sk */
1605 	lock_sock_nested(new_sk, SINGLE_DEPTH_NESTING);
1606 
1607 	/*
1608 	 * Reject any stray messages received by new socket
1609 	 * before the socket lock was taken (very, very unlikely)
1610 	 */
1611 	reject_rx_queue(new_sk);
1612 
1613 	/* Connect new socket to it's peer */
1614 	new_tsock->peer_name.ref = msg_origport(msg);
1615 	new_tsock->peer_name.node = msg_orignode(msg);
1616 	tipc_connect(new_ref, &new_tsock->peer_name);
1617 	new_sock->state = SS_CONNECTED;
1618 
1619 	tipc_set_portimportance(new_ref, msg_importance(msg));
1620 	if (msg_named(msg)) {
1621 		new_tport->conn_type = msg_nametype(msg);
1622 		new_tport->conn_instance = msg_nameinst(msg);
1623 	}
1624 
1625 	/*
1626 	 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1627 	 * Respond to 'SYN+' by queuing it on new socket.
1628 	 */
1629 	if (!msg_data_sz(msg)) {
1630 		struct msghdr m = {NULL,};
1631 
1632 		advance_rx_queue(sk);
1633 		send_packet(NULL, new_sock, &m, 0);
1634 	} else {
1635 		__skb_dequeue(&sk->sk_receive_queue);
1636 		__skb_queue_head(&new_sk->sk_receive_queue, buf);
1637 		skb_set_owner_r(buf, new_sk);
1638 	}
1639 	release_sock(new_sk);
1640 
1641 exit:
1642 	release_sock(sk);
1643 	return res;
1644 }
1645 
1646 /**
1647  * shutdown - shutdown socket connection
1648  * @sock: socket structure
1649  * @how: direction to close (must be SHUT_RDWR)
1650  *
1651  * Terminates connection (if necessary), then purges socket's receive queue.
1652  *
1653  * Returns 0 on success, errno otherwise
1654  */
1655 static int shutdown(struct socket *sock, int how)
1656 {
1657 	struct sock *sk = sock->sk;
1658 	struct tipc_port *tport = tipc_sk_port(sk);
1659 	struct sk_buff *buf;
1660 	int res;
1661 
1662 	if (how != SHUT_RDWR)
1663 		return -EINVAL;
1664 
1665 	lock_sock(sk);
1666 
1667 	switch (sock->state) {
1668 	case SS_CONNECTING:
1669 	case SS_CONNECTED:
1670 
1671 restart:
1672 		/* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1673 		buf = __skb_dequeue(&sk->sk_receive_queue);
1674 		if (buf) {
1675 			if (TIPC_SKB_CB(buf)->handle != NULL) {
1676 				kfree_skb(buf);
1677 				goto restart;
1678 			}
1679 			tipc_disconnect(tport->ref);
1680 			tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1681 		} else {
1682 			tipc_shutdown(tport->ref);
1683 		}
1684 
1685 		sock->state = SS_DISCONNECTING;
1686 
1687 		/* fall through */
1688 
1689 	case SS_DISCONNECTING:
1690 
1691 		/* Discard any unreceived messages */
1692 		__skb_queue_purge(&sk->sk_receive_queue);
1693 
1694 		/* Wake up anyone sleeping in poll */
1695 		sk->sk_state_change(sk);
1696 		res = 0;
1697 		break;
1698 
1699 	default:
1700 		res = -ENOTCONN;
1701 	}
1702 
1703 	release_sock(sk);
1704 	return res;
1705 }
1706 
1707 /**
1708  * setsockopt - set socket option
1709  * @sock: socket structure
1710  * @lvl: option level
1711  * @opt: option identifier
1712  * @ov: pointer to new option value
1713  * @ol: length of option value
1714  *
1715  * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1716  * (to ease compatibility).
1717  *
1718  * Returns 0 on success, errno otherwise
1719  */
1720 static int setsockopt(struct socket *sock, int lvl, int opt, char __user *ov,
1721 		      unsigned int ol)
1722 {
1723 	struct sock *sk = sock->sk;
1724 	struct tipc_port *tport = tipc_sk_port(sk);
1725 	u32 value;
1726 	int res;
1727 
1728 	if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1729 		return 0;
1730 	if (lvl != SOL_TIPC)
1731 		return -ENOPROTOOPT;
1732 	if (ol < sizeof(value))
1733 		return -EINVAL;
1734 	res = get_user(value, (u32 __user *)ov);
1735 	if (res)
1736 		return res;
1737 
1738 	lock_sock(sk);
1739 
1740 	switch (opt) {
1741 	case TIPC_IMPORTANCE:
1742 		res = tipc_set_portimportance(tport->ref, value);
1743 		break;
1744 	case TIPC_SRC_DROPPABLE:
1745 		if (sock->type != SOCK_STREAM)
1746 			res = tipc_set_portunreliable(tport->ref, value);
1747 		else
1748 			res = -ENOPROTOOPT;
1749 		break;
1750 	case TIPC_DEST_DROPPABLE:
1751 		res = tipc_set_portunreturnable(tport->ref, value);
1752 		break;
1753 	case TIPC_CONN_TIMEOUT:
1754 		tipc_sk(sk)->conn_timeout = value;
1755 		/* no need to set "res", since already 0 at this point */
1756 		break;
1757 	default:
1758 		res = -EINVAL;
1759 	}
1760 
1761 	release_sock(sk);
1762 
1763 	return res;
1764 }
1765 
1766 /**
1767  * getsockopt - get socket option
1768  * @sock: socket structure
1769  * @lvl: option level
1770  * @opt: option identifier
1771  * @ov: receptacle for option value
1772  * @ol: receptacle for length of option value
1773  *
1774  * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1775  * (to ease compatibility).
1776  *
1777  * Returns 0 on success, errno otherwise
1778  */
1779 static int getsockopt(struct socket *sock, int lvl, int opt, char __user *ov,
1780 		      int __user *ol)
1781 {
1782 	struct sock *sk = sock->sk;
1783 	struct tipc_port *tport = tipc_sk_port(sk);
1784 	int len;
1785 	u32 value;
1786 	int res;
1787 
1788 	if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1789 		return put_user(0, ol);
1790 	if (lvl != SOL_TIPC)
1791 		return -ENOPROTOOPT;
1792 	res = get_user(len, ol);
1793 	if (res)
1794 		return res;
1795 
1796 	lock_sock(sk);
1797 
1798 	switch (opt) {
1799 	case TIPC_IMPORTANCE:
1800 		res = tipc_portimportance(tport->ref, &value);
1801 		break;
1802 	case TIPC_SRC_DROPPABLE:
1803 		res = tipc_portunreliable(tport->ref, &value);
1804 		break;
1805 	case TIPC_DEST_DROPPABLE:
1806 		res = tipc_portunreturnable(tport->ref, &value);
1807 		break;
1808 	case TIPC_CONN_TIMEOUT:
1809 		value = tipc_sk(sk)->conn_timeout;
1810 		/* no need to set "res", since already 0 at this point */
1811 		break;
1812 	case TIPC_NODE_RECVQ_DEPTH:
1813 		value = 0; /* was tipc_queue_size, now obsolete */
1814 		break;
1815 	case TIPC_SOCK_RECVQ_DEPTH:
1816 		value = skb_queue_len(&sk->sk_receive_queue);
1817 		break;
1818 	default:
1819 		res = -EINVAL;
1820 	}
1821 
1822 	release_sock(sk);
1823 
1824 	if (res)
1825 		return res;	/* "get" failed */
1826 
1827 	if (len < sizeof(value))
1828 		return -EINVAL;
1829 
1830 	if (copy_to_user(ov, &value, sizeof(value)))
1831 		return -EFAULT;
1832 
1833 	return put_user(sizeof(value), ol);
1834 }
1835 
1836 /* Protocol switches for the various types of TIPC sockets */
1837 
1838 static const struct proto_ops msg_ops = {
1839 	.owner		= THIS_MODULE,
1840 	.family		= AF_TIPC,
1841 	.release	= release,
1842 	.bind		= bind,
1843 	.connect	= connect,
1844 	.socketpair	= sock_no_socketpair,
1845 	.accept		= sock_no_accept,
1846 	.getname	= get_name,
1847 	.poll		= poll,
1848 	.ioctl		= sock_no_ioctl,
1849 	.listen		= sock_no_listen,
1850 	.shutdown	= shutdown,
1851 	.setsockopt	= setsockopt,
1852 	.getsockopt	= getsockopt,
1853 	.sendmsg	= send_msg,
1854 	.recvmsg	= recv_msg,
1855 	.mmap		= sock_no_mmap,
1856 	.sendpage	= sock_no_sendpage
1857 };
1858 
1859 static const struct proto_ops packet_ops = {
1860 	.owner		= THIS_MODULE,
1861 	.family		= AF_TIPC,
1862 	.release	= release,
1863 	.bind		= bind,
1864 	.connect	= connect,
1865 	.socketpair	= sock_no_socketpair,
1866 	.accept		= accept,
1867 	.getname	= get_name,
1868 	.poll		= poll,
1869 	.ioctl		= sock_no_ioctl,
1870 	.listen		= listen,
1871 	.shutdown	= shutdown,
1872 	.setsockopt	= setsockopt,
1873 	.getsockopt	= getsockopt,
1874 	.sendmsg	= send_packet,
1875 	.recvmsg	= recv_msg,
1876 	.mmap		= sock_no_mmap,
1877 	.sendpage	= sock_no_sendpage
1878 };
1879 
1880 static const struct proto_ops stream_ops = {
1881 	.owner		= THIS_MODULE,
1882 	.family		= AF_TIPC,
1883 	.release	= release,
1884 	.bind		= bind,
1885 	.connect	= connect,
1886 	.socketpair	= sock_no_socketpair,
1887 	.accept		= accept,
1888 	.getname	= get_name,
1889 	.poll		= poll,
1890 	.ioctl		= sock_no_ioctl,
1891 	.listen		= listen,
1892 	.shutdown	= shutdown,
1893 	.setsockopt	= setsockopt,
1894 	.getsockopt	= getsockopt,
1895 	.sendmsg	= send_stream,
1896 	.recvmsg	= recv_stream,
1897 	.mmap		= sock_no_mmap,
1898 	.sendpage	= sock_no_sendpage
1899 };
1900 
1901 static const struct net_proto_family tipc_family_ops = {
1902 	.owner		= THIS_MODULE,
1903 	.family		= AF_TIPC,
1904 	.create		= tipc_sk_create
1905 };
1906 
1907 static struct proto tipc_proto = {
1908 	.name		= "TIPC",
1909 	.owner		= THIS_MODULE,
1910 	.obj_size	= sizeof(struct tipc_sock),
1911 	.sysctl_rmem	= sysctl_tipc_rmem
1912 };
1913 
1914 static struct proto tipc_proto_kern = {
1915 	.name		= "TIPC",
1916 	.obj_size	= sizeof(struct tipc_sock),
1917 	.sysctl_rmem	= sysctl_tipc_rmem
1918 };
1919 
1920 /**
1921  * tipc_socket_init - initialize TIPC socket interface
1922  *
1923  * Returns 0 on success, errno otherwise
1924  */
1925 int tipc_socket_init(void)
1926 {
1927 	int res;
1928 
1929 	res = proto_register(&tipc_proto, 1);
1930 	if (res) {
1931 		pr_err("Failed to register TIPC protocol type\n");
1932 		goto out;
1933 	}
1934 
1935 	res = sock_register(&tipc_family_ops);
1936 	if (res) {
1937 		pr_err("Failed to register TIPC socket type\n");
1938 		proto_unregister(&tipc_proto);
1939 		goto out;
1940 	}
1941 
1942 	sockets_enabled = 1;
1943  out:
1944 	return res;
1945 }
1946 
1947 /**
1948  * tipc_socket_stop - stop TIPC socket interface
1949  */
1950 void tipc_socket_stop(void)
1951 {
1952 	if (!sockets_enabled)
1953 		return;
1954 
1955 	sockets_enabled = 0;
1956 	sock_unregister(tipc_family_ops.family);
1957 	proto_unregister(&tipc_proto);
1958 }
1959