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