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