2 * net/tipc/socket.c: TIPC socket API
4 * Copyright (c) 2001-2007, Ericsson AB
5 * Copyright (c) 2004-2007, Wind River Systems
8 * Redistribution and use in source and binary forms, with or without
9 * modification, are permitted provided that the following conditions are met:
11 * 1. Redistributions of source code must retain the above copyright
12 * notice, this list of conditions and the following disclaimer.
13 * 2. Redistributions in binary form must reproduce the above copyright
14 * notice, this list of conditions and the following disclaimer in the
15 * documentation and/or other materials provided with the distribution.
16 * 3. Neither the names of the copyright holders nor the names of its
17 * contributors may be used to endorse or promote products derived from
18 * this software without specific prior written permission.
20 * Alternatively, this software may be distributed under the terms of the
21 * GNU General Public License ("GPL") version 2 as published by the Free
22 * Software Foundation.
24 * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
25 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
26 * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
29 * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
30 * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
31 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
32 * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
33 * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
34 * POSSIBILITY OF SUCH DAMAGE.
37 #include <linux/module.h>
38 #include <linux/types.h>
39 #include <linux/net.h>
40 #include <linux/socket.h>
41 #include <linux/errno.h>
43 #include <linux/slab.h>
44 #include <linux/poll.h>
45 #include <linux/fcntl.h>
46 #include <asm/string.h>
47 #include <asm/atomic.h>
50 #include <linux/tipc.h>
51 #include <linux/tipc_config.h>
52 #include <net/tipc/tipc_msg.h>
53 #include <net/tipc/tipc_port.h>
57 #define SS_LISTENING -1 /* socket is listening */
58 #define SS_READY -2 /* socket is connectionless */
60 #define OVERLOAD_LIMIT_BASE 5000
61 #define CONN_TIMEOUT_DEFAULT 8000 /* default connect timeout = 8s */
68 #define tipc_sk(sk) ((struct tipc_sock *)(sk))
69 #define tipc_sk_port(sk) ((struct tipc_port *)(tipc_sk(sk)->p))
71 static int backlog_rcv(struct sock *sk, struct sk_buff *skb);
72 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf);
73 static void wakeupdispatch(struct tipc_port *tport);
75 static const struct proto_ops packet_ops;
76 static const struct proto_ops stream_ops;
77 static const struct proto_ops msg_ops;
79 static struct proto tipc_proto;
81 static int sockets_enabled = 0;
83 static atomic_t tipc_queue_size = ATOMIC_INIT(0);
86 * Revised TIPC socket locking policy:
88 * Most socket operations take the standard socket lock when they start
89 * and hold it until they finish (or until they need to sleep). Acquiring
90 * this lock grants the owner exclusive access to the fields of the socket
91 * data structures, with the exception of the backlog queue. A few socket
92 * operations can be done without taking the socket lock because they only
93 * read socket information that never changes during the life of the socket.
95 * Socket operations may acquire the lock for the associated TIPC port if they
96 * need to perform an operation on the port. If any routine needs to acquire
97 * both the socket lock and the port lock it must take the socket lock first
98 * to avoid the risk of deadlock.
100 * The dispatcher handling incoming messages cannot grab the socket lock in
101 * the standard fashion, since invoked it runs at the BH level and cannot block.
102 * Instead, it checks to see if the socket lock is currently owned by someone,
103 * and either handles the message itself or adds it to the socket's backlog
104 * queue; in the latter case the queued message is processed once the process
105 * owning the socket lock releases it.
107 * NOTE: Releasing the socket lock while an operation is sleeping overcomes
108 * the problem of a blocked socket operation preventing any other operations
109 * from occurring. However, applications must be careful if they have
110 * multiple threads trying to send (or receive) on the same socket, as these
111 * operations might interfere with each other. For example, doing a connect
112 * and a receive at the same time might allow the receive to consume the
113 * ACK message meant for the connect. While additional work could be done
114 * to try and overcome this, it doesn't seem to be worthwhile at the present.
116 * NOTE: Releasing the socket lock while an operation is sleeping also ensures
117 * that another operation that must be performed in a non-blocking manner is
118 * not delayed for very long because the lock has already been taken.
120 * NOTE: This code assumes that certain fields of a port/socket pair are
121 * constant over its lifetime; such fields can be examined without taking
122 * the socket lock and/or port lock, and do not need to be re-read even
123 * after resuming processing after waiting. These fields include:
125 * - pointer to socket sk structure (aka tipc_sock structure)
126 * - pointer to port structure
131 * advance_rx_queue - discard first buffer in socket receive queue
133 * Caller must hold socket lock
136 static void advance_rx_queue(struct sock *sk)
138 buf_discard(__skb_dequeue(&sk->sk_receive_queue));
139 atomic_dec(&tipc_queue_size);
143 * discard_rx_queue - discard all buffers in socket receive queue
145 * Caller must hold socket lock
148 static void discard_rx_queue(struct sock *sk)
152 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
153 atomic_dec(&tipc_queue_size);
159 * reject_rx_queue - reject all buffers in socket receive queue
161 * Caller must hold socket lock
164 static void reject_rx_queue(struct sock *sk)
168 while ((buf = __skb_dequeue(&sk->sk_receive_queue))) {
169 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
170 atomic_dec(&tipc_queue_size);
175 * tipc_create - create a TIPC socket
176 * @net: network namespace (must be default network)
177 * @sock: pre-allocated socket structure
178 * @protocol: protocol indicator (must be 0)
180 * This routine creates additional data structures used by the TIPC socket,
181 * initializes them, and links them together.
183 * Returns 0 on success, errno otherwise
186 static int tipc_create(struct net *net, struct socket *sock, int protocol)
188 const struct proto_ops *ops;
193 /* Validate arguments */
195 if (net != &init_net)
196 return -EAFNOSUPPORT;
198 if (unlikely(protocol != 0))
199 return -EPROTONOSUPPORT;
201 switch (sock->type) {
204 state = SS_UNCONNECTED;
208 state = SS_UNCONNECTED;
219 /* Allocate socket's protocol area */
221 sk = sk_alloc(net, AF_TIPC, GFP_KERNEL, &tipc_proto);
225 /* Allocate TIPC port for socket to use */
227 portref = tipc_createport_raw(sk, &dispatch, &wakeupdispatch,
228 TIPC_LOW_IMPORTANCE);
229 if (unlikely(portref == 0)) {
234 /* Finish initializing socket data structures */
239 sock_init_data(sock, sk);
240 sk->sk_rcvtimeo = msecs_to_jiffies(CONN_TIMEOUT_DEFAULT);
241 sk->sk_backlog_rcv = backlog_rcv;
242 tipc_sk(sk)->p = tipc_get_port(portref);
244 if (sock->state == SS_READY) {
245 tipc_set_portunreturnable(portref, 1);
246 if (sock->type == SOCK_DGRAM)
247 tipc_set_portunreliable(portref, 1);
250 atomic_inc(&tipc_user_count);
255 * release - destroy a TIPC socket
256 * @sock: socket to destroy
258 * This routine cleans up any messages that are still queued on the socket.
259 * For DGRAM and RDM socket types, all queued messages are rejected.
260 * For SEQPACKET and STREAM socket types, the first message is rejected
261 * and any others are discarded. (If the first message on a STREAM socket
262 * is partially-read, it is discarded and the next one is rejected instead.)
264 * NOTE: Rejected messages are not necessarily returned to the sender! They
265 * are returned or discarded according to the "destination droppable" setting
266 * specified for the message by the sender.
268 * Returns 0 on success, errno otherwise
271 static int release(struct socket *sock)
273 struct sock *sk = sock->sk;
274 struct tipc_port *tport;
279 * Exit if socket isn't fully initialized (occurs when a failed accept()
280 * releases a pre-allocated child socket that was never used)
286 tport = tipc_sk_port(sk);
290 * Reject all unreceived messages, except on an active connection
291 * (which disconnects locally & sends a 'FIN+' to peer)
294 while (sock->state != SS_DISCONNECTING) {
295 buf = __skb_dequeue(&sk->sk_receive_queue);
298 atomic_dec(&tipc_queue_size);
299 if (TIPC_SKB_CB(buf)->handle != msg_data(buf_msg(buf)))
302 if ((sock->state == SS_CONNECTING) ||
303 (sock->state == SS_CONNECTED)) {
304 sock->state = SS_DISCONNECTING;
305 tipc_disconnect(tport->ref);
307 tipc_reject_msg(buf, TIPC_ERR_NO_PORT);
312 * Delete TIPC port; this ensures no more messages are queued
313 * (also disconnects an active connection & sends a 'FIN-' to peer)
316 res = tipc_deleteport(tport->ref);
318 /* Discard any remaining (connection-based) messages in receive queue */
320 discard_rx_queue(sk);
322 /* Reject any messages that accumulated in backlog queue */
324 sock->state = SS_DISCONNECTING;
330 atomic_dec(&tipc_user_count);
335 * bind - associate or disassocate TIPC name(s) with a socket
336 * @sock: socket structure
337 * @uaddr: socket address describing name(s) and desired operation
338 * @uaddr_len: size of socket address data structure
340 * Name and name sequence binding is indicated using a positive scope value;
341 * a negative scope value unbinds the specified name. Specifying no name
342 * (i.e. a socket address length of 0) unbinds all names from the socket.
344 * Returns 0 on success, errno otherwise
346 * NOTE: This routine doesn't need to take the socket lock since it doesn't
347 * access any non-constant socket information.
350 static int bind(struct socket *sock, struct sockaddr *uaddr, int uaddr_len)
352 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
353 u32 portref = tipc_sk_port(sock->sk)->ref;
355 if (unlikely(!uaddr_len))
356 return tipc_withdraw(portref, 0, NULL);
358 if (uaddr_len < sizeof(struct sockaddr_tipc))
360 if (addr->family != AF_TIPC)
361 return -EAFNOSUPPORT;
363 if (addr->addrtype == TIPC_ADDR_NAME)
364 addr->addr.nameseq.upper = addr->addr.nameseq.lower;
365 else if (addr->addrtype != TIPC_ADDR_NAMESEQ)
366 return -EAFNOSUPPORT;
368 return (addr->scope > 0) ?
369 tipc_publish(portref, addr->scope, &addr->addr.nameseq) :
370 tipc_withdraw(portref, -addr->scope, &addr->addr.nameseq);
374 * get_name - get port ID of socket or peer socket
375 * @sock: socket structure
376 * @uaddr: area for returned socket address
377 * @uaddr_len: area for returned length of socket address
378 * @peer: 0 to obtain socket name, 1 to obtain peer socket name
380 * Returns 0 on success, errno otherwise
382 * NOTE: This routine doesn't need to take the socket lock since it doesn't
383 * access any non-constant socket information.
386 static int get_name(struct socket *sock, struct sockaddr *uaddr,
387 int *uaddr_len, int peer)
389 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)uaddr;
390 u32 portref = tipc_sk_port(sock->sk)->ref;
394 res = tipc_peer(portref, &addr->addr.id);
398 tipc_ownidentity(portref, &addr->addr.id);
401 *uaddr_len = sizeof(*addr);
402 addr->addrtype = TIPC_ADDR_ID;
403 addr->family = AF_TIPC;
405 addr->addr.name.domain = 0;
411 * poll - read and possibly block on pollmask
412 * @file: file structure associated with the socket
413 * @sock: socket for which to calculate the poll bits
416 * Returns pollmask value
419 * It appears that the usual socket locking mechanisms are not useful here
420 * since the pollmask info is potentially out-of-date the moment this routine
421 * exits. TCP and other protocols seem to rely on higher level poll routines
422 * to handle any preventable race conditions, so TIPC will do the same ...
424 * TIPC sets the returned events as follows:
425 * a) POLLRDNORM and POLLIN are set if the socket's receive queue is non-empty
426 * or if a connection-oriented socket is does not have an active connection
427 * (i.e. a read operation will not block).
428 * b) POLLOUT is set except when a socket's connection has been terminated
429 * (i.e. a write operation will not block).
430 * c) POLLHUP is set when a socket's connection has been terminated.
432 * IMPORTANT: The fact that a read or write operation will not block does NOT
433 * imply that the operation will succeed!
436 static unsigned int poll(struct file *file, struct socket *sock,
439 struct sock *sk = sock->sk;
442 poll_wait(file, sk->sk_sleep, wait);
444 if (!skb_queue_empty(&sk->sk_receive_queue) ||
445 (sock->state == SS_UNCONNECTED) ||
446 (sock->state == SS_DISCONNECTING))
447 mask = (POLLRDNORM | POLLIN);
451 if (sock->state == SS_DISCONNECTING)
460 * dest_name_check - verify user is permitted to send to specified port name
461 * @dest: destination address
462 * @m: descriptor for message to be sent
464 * Prevents restricted configuration commands from being issued by
465 * unauthorized users.
467 * Returns 0 if permission is granted, otherwise errno
470 static int dest_name_check(struct sockaddr_tipc *dest, struct msghdr *m)
472 struct tipc_cfg_msg_hdr hdr;
474 if (likely(dest->addr.name.name.type >= TIPC_RESERVED_TYPES))
476 if (likely(dest->addr.name.name.type == TIPC_TOP_SRV))
478 if (likely(dest->addr.name.name.type != TIPC_CFG_SRV))
481 if (copy_from_user(&hdr, m->msg_iov[0].iov_base, sizeof(hdr)))
483 if ((ntohs(hdr.tcm_type) & 0xC000) && (!capable(CAP_NET_ADMIN)))
490 * send_msg - send message in connectionless manner
491 * @iocb: if NULL, indicates that socket lock is already held
492 * @sock: socket structure
493 * @m: message to send
494 * @total_len: length of message
496 * Message must have an destination specified explicitly.
497 * Used for SOCK_RDM and SOCK_DGRAM messages,
498 * and for 'SYN' messages on SOCK_SEQPACKET and SOCK_STREAM connections.
499 * (Note: 'SYN+' is prohibited on SOCK_STREAM.)
501 * Returns the number of bytes sent on success, or errno otherwise
504 static int send_msg(struct kiocb *iocb, struct socket *sock,
505 struct msghdr *m, size_t total_len)
507 struct sock *sk = sock->sk;
508 struct tipc_port *tport = tipc_sk_port(sk);
509 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
514 return -EDESTADDRREQ;
515 if (unlikely((m->msg_namelen < sizeof(*dest)) ||
516 (dest->family != AF_TIPC)))
522 needs_conn = (sock->state != SS_READY);
523 if (unlikely(needs_conn)) {
524 if (sock->state == SS_LISTENING) {
528 if (sock->state != SS_UNCONNECTED) {
532 if ((tport->published) ||
533 ((sock->type == SOCK_STREAM) && (total_len != 0))) {
537 if (dest->addrtype == TIPC_ADDR_NAME) {
538 tport->conn_type = dest->addr.name.name.type;
539 tport->conn_instance = dest->addr.name.name.instance;
542 /* Abort any pending connection attempts (very unlikely) */
548 if (dest->addrtype == TIPC_ADDR_NAME) {
549 if ((res = dest_name_check(dest, m)))
551 res = tipc_send2name(tport->ref,
552 &dest->addr.name.name,
553 dest->addr.name.domain,
557 else if (dest->addrtype == TIPC_ADDR_ID) {
558 res = tipc_send2port(tport->ref,
563 else if (dest->addrtype == TIPC_ADDR_MCAST) {
568 if ((res = dest_name_check(dest, m)))
570 res = tipc_multicast(tport->ref,
576 if (likely(res != -ELINKCONG)) {
577 if (needs_conn && (res >= 0)) {
578 sock->state = SS_CONNECTING;
582 if (m->msg_flags & MSG_DONTWAIT) {
587 res = wait_event_interruptible(*sk->sk_sleep,
601 * send_packet - send a connection-oriented message
602 * @iocb: if NULL, indicates that socket lock is already held
603 * @sock: socket structure
604 * @m: message to send
605 * @total_len: length of message
607 * Used for SOCK_SEQPACKET messages and SOCK_STREAM data.
609 * Returns the number of bytes sent on success, or errno otherwise
612 static int send_packet(struct kiocb *iocb, struct socket *sock,
613 struct msghdr *m, size_t total_len)
615 struct sock *sk = sock->sk;
616 struct tipc_port *tport = tipc_sk_port(sk);
617 struct sockaddr_tipc *dest = (struct sockaddr_tipc *)m->msg_name;
620 /* Handle implied connection establishment */
623 return send_msg(iocb, sock, m, total_len);
629 if (unlikely(sock->state != SS_CONNECTED)) {
630 if (sock->state == SS_DISCONNECTING)
637 res = tipc_send(tport->ref, m->msg_iovlen, m->msg_iov);
638 if (likely(res != -ELINKCONG)) {
641 if (m->msg_flags & MSG_DONTWAIT) {
646 res = wait_event_interruptible(*sk->sk_sleep,
647 (!tport->congested || !tport->connected));
659 * send_stream - send stream-oriented data
661 * @sock: socket structure
663 * @total_len: total length of data to be sent
665 * Used for SOCK_STREAM data.
667 * Returns the number of bytes sent on success (or partial success),
668 * or errno if no data sent
671 static int send_stream(struct kiocb *iocb, struct socket *sock,
672 struct msghdr *m, size_t total_len)
674 struct sock *sk = sock->sk;
675 struct tipc_port *tport = tipc_sk_port(sk);
676 struct msghdr my_msg;
678 struct iovec *curr_iov;
680 char __user *curr_start;
689 /* Handle special cases where there is no connection */
691 if (unlikely(sock->state != SS_CONNECTED)) {
692 if (sock->state == SS_UNCONNECTED) {
693 res = send_packet(NULL, sock, m, total_len);
695 } else if (sock->state == SS_DISCONNECTING) {
704 if (unlikely(m->msg_name)) {
710 * Send each iovec entry using one or more messages
712 * Note: This algorithm is good for the most likely case
713 * (i.e. one large iovec entry), but could be improved to pass sets
714 * of small iovec entries into send_packet().
717 curr_iov = m->msg_iov;
718 curr_iovlen = m->msg_iovlen;
719 my_msg.msg_iov = &my_iov;
720 my_msg.msg_iovlen = 1;
721 my_msg.msg_flags = m->msg_flags;
722 my_msg.msg_name = NULL;
725 hdr_size = msg_hdr_sz(&tport->phdr);
727 while (curr_iovlen--) {
728 curr_start = curr_iov->iov_base;
729 curr_left = curr_iov->iov_len;
732 bytes_to_send = tport->max_pkt - hdr_size;
733 if (bytes_to_send > TIPC_MAX_USER_MSG_SIZE)
734 bytes_to_send = TIPC_MAX_USER_MSG_SIZE;
735 if (curr_left < bytes_to_send)
736 bytes_to_send = curr_left;
737 my_iov.iov_base = curr_start;
738 my_iov.iov_len = bytes_to_send;
739 if ((res = send_packet(NULL, sock, &my_msg, 0)) < 0) {
744 curr_left -= bytes_to_send;
745 curr_start += bytes_to_send;
746 bytes_sent += bytes_to_send;
758 * auto_connect - complete connection setup to a remote port
759 * @sock: socket structure
760 * @msg: peer's response message
762 * Returns 0 on success, errno otherwise
765 static int auto_connect(struct socket *sock, struct tipc_msg *msg)
767 struct tipc_port *tport = tipc_sk_port(sock->sk);
768 struct tipc_portid peer;
770 if (msg_errcode(msg)) {
771 sock->state = SS_DISCONNECTING;
772 return -ECONNREFUSED;
775 peer.ref = msg_origport(msg);
776 peer.node = msg_orignode(msg);
777 tipc_connect2port(tport->ref, &peer);
778 tipc_set_portimportance(tport->ref, msg_importance(msg));
779 sock->state = SS_CONNECTED;
784 * set_orig_addr - capture sender's address for received message
785 * @m: descriptor for message info
786 * @msg: received message header
788 * Note: Address is not captured if not requested by receiver.
791 static void set_orig_addr(struct msghdr *m, struct tipc_msg *msg)
793 struct sockaddr_tipc *addr = (struct sockaddr_tipc *)m->msg_name;
796 addr->family = AF_TIPC;
797 addr->addrtype = TIPC_ADDR_ID;
798 addr->addr.id.ref = msg_origport(msg);
799 addr->addr.id.node = msg_orignode(msg);
800 addr->addr.name.domain = 0; /* could leave uninitialized */
801 addr->scope = 0; /* could leave uninitialized */
802 m->msg_namelen = sizeof(struct sockaddr_tipc);
807 * anc_data_recv - optionally capture ancillary data for received message
808 * @m: descriptor for message info
809 * @msg: received message header
810 * @tport: TIPC port associated with message
812 * Note: Ancillary data is not captured if not requested by receiver.
814 * Returns 0 if successful, otherwise errno
817 static int anc_data_recv(struct msghdr *m, struct tipc_msg *msg,
818 struct tipc_port *tport)
826 if (likely(m->msg_controllen == 0))
829 /* Optionally capture errored message object(s) */
831 err = msg ? msg_errcode(msg) : 0;
834 anc_data[1] = msg_data_sz(msg);
835 if ((res = put_cmsg(m, SOL_TIPC, TIPC_ERRINFO, 8, anc_data)))
838 (res = put_cmsg(m, SOL_TIPC, TIPC_RETDATA, anc_data[1],
843 /* Optionally capture message destination object */
845 dest_type = msg ? msg_type(msg) : TIPC_DIRECT_MSG;
849 anc_data[0] = msg_nametype(msg);
850 anc_data[1] = msg_namelower(msg);
851 anc_data[2] = msg_namelower(msg);
855 anc_data[0] = msg_nametype(msg);
856 anc_data[1] = msg_namelower(msg);
857 anc_data[2] = msg_nameupper(msg);
860 has_name = (tport->conn_type != 0);
861 anc_data[0] = tport->conn_type;
862 anc_data[1] = tport->conn_instance;
863 anc_data[2] = tport->conn_instance;
869 (res = put_cmsg(m, SOL_TIPC, TIPC_DESTNAME, 12, anc_data)))
876 * recv_msg - receive packet-oriented message
878 * @m: descriptor for message info
879 * @buf_len: total size of user buffer area
880 * @flags: receive flags
882 * Used for SOCK_DGRAM, SOCK_RDM, and SOCK_SEQPACKET messages.
883 * If the complete message doesn't fit in user area, truncate it.
885 * Returns size of returned message data, errno otherwise
888 static int recv_msg(struct kiocb *iocb, struct socket *sock,
889 struct msghdr *m, size_t buf_len, int flags)
891 struct sock *sk = sock->sk;
892 struct tipc_port *tport = tipc_sk_port(sk);
894 struct tipc_msg *msg;
899 /* Catch invalid receive requests */
901 if (m->msg_iovlen != 1)
902 return -EOPNOTSUPP; /* Don't do multiple iovec entries yet */
904 if (unlikely(!buf_len))
909 if (unlikely(sock->state == SS_UNCONNECTED)) {
916 /* Look for a message in receive queue; wait if necessary */
918 while (skb_queue_empty(&sk->sk_receive_queue)) {
919 if (sock->state == SS_DISCONNECTING) {
923 if (flags & MSG_DONTWAIT) {
928 res = wait_event_interruptible(*sk->sk_sleep,
929 (!skb_queue_empty(&sk->sk_receive_queue) ||
930 (sock->state == SS_DISCONNECTING)));
936 /* Look at first message in receive queue */
938 buf = skb_peek(&sk->sk_receive_queue);
940 sz = msg_data_sz(msg);
941 err = msg_errcode(msg);
943 /* Complete connection setup for an implied connect */
945 if (unlikely(sock->state == SS_CONNECTING)) {
946 res = auto_connect(sock, msg);
951 /* Discard an empty non-errored message & try again */
953 if ((!sz) && (!err)) {
954 advance_rx_queue(sk);
958 /* Capture sender's address (optional) */
960 set_orig_addr(m, msg);
962 /* Capture ancillary data (optional) */
964 res = anc_data_recv(m, msg, tport);
968 /* Capture message data (if valid) & compute return value (always) */
971 if (unlikely(buf_len < sz)) {
973 m->msg_flags |= MSG_TRUNC;
975 if (unlikely(copy_to_user(m->msg_iov->iov_base, msg_data(msg),
982 if ((sock->state == SS_READY) ||
983 ((err == TIPC_CONN_SHUTDOWN) || m->msg_control))
989 /* Consume received message (optional) */
991 if (likely(!(flags & MSG_PEEK))) {
992 if ((sock->state != SS_READY) &&
993 (++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
994 tipc_acknowledge(tport->ref, tport->conn_unacked);
995 advance_rx_queue(sk);
1003 * recv_stream - receive stream-oriented data
1005 * @m: descriptor for message info
1006 * @buf_len: total size of user buffer area
1007 * @flags: receive flags
1009 * Used for SOCK_STREAM messages only. If not enough data is available
1010 * will optionally wait for more; never truncates data.
1012 * Returns size of returned message data, errno otherwise
1015 static int recv_stream(struct kiocb *iocb, struct socket *sock,
1016 struct msghdr *m, size_t buf_len, int flags)
1018 struct sock *sk = sock->sk;
1019 struct tipc_port *tport = tipc_sk_port(sk);
1020 struct sk_buff *buf;
1021 struct tipc_msg *msg;
1026 char __user *crs = m->msg_iov->iov_base;
1027 unsigned char *buf_crs;
1031 /* Catch invalid receive attempts */
1033 if (m->msg_iovlen != 1)
1034 return -EOPNOTSUPP; /* Don't do multiple iovec entries yet */
1036 if (unlikely(!buf_len))
1041 if (unlikely((sock->state == SS_UNCONNECTED) ||
1042 (sock->state == SS_CONNECTING))) {
1049 /* Look for a message in receive queue; wait if necessary */
1051 while (skb_queue_empty(&sk->sk_receive_queue)) {
1052 if (sock->state == SS_DISCONNECTING) {
1056 if (flags & MSG_DONTWAIT) {
1061 res = wait_event_interruptible(*sk->sk_sleep,
1062 (!skb_queue_empty(&sk->sk_receive_queue) ||
1063 (sock->state == SS_DISCONNECTING)));
1069 /* Look at first message in receive queue */
1071 buf = skb_peek(&sk->sk_receive_queue);
1073 sz = msg_data_sz(msg);
1074 err = msg_errcode(msg);
1076 /* Discard an empty non-errored message & try again */
1078 if ((!sz) && (!err)) {
1079 advance_rx_queue(sk);
1083 /* Optionally capture sender's address & ancillary data of first msg */
1085 if (sz_copied == 0) {
1086 set_orig_addr(m, msg);
1087 res = anc_data_recv(m, msg, tport);
1092 /* Capture message data (if valid) & compute return value (always) */
1095 buf_crs = (unsigned char *)(TIPC_SKB_CB(buf)->handle);
1096 sz = (unsigned char *)msg + msg_size(msg) - buf_crs;
1098 needed = (buf_len - sz_copied);
1099 sz_to_copy = (sz <= needed) ? sz : needed;
1100 if (unlikely(copy_to_user(crs, buf_crs, sz_to_copy))) {
1104 sz_copied += sz_to_copy;
1106 if (sz_to_copy < sz) {
1107 if (!(flags & MSG_PEEK))
1108 TIPC_SKB_CB(buf)->handle = buf_crs + sz_to_copy;
1115 goto exit; /* can't add error msg to valid data */
1117 if ((err == TIPC_CONN_SHUTDOWN) || m->msg_control)
1123 /* Consume received message (optional) */
1125 if (likely(!(flags & MSG_PEEK))) {
1126 if (unlikely(++tport->conn_unacked >= TIPC_FLOW_CONTROL_WIN))
1127 tipc_acknowledge(tport->ref, tport->conn_unacked);
1128 advance_rx_queue(sk);
1131 /* Loop around if more data is required */
1133 if ((sz_copied < buf_len) /* didn't get all requested data */
1134 && (!skb_queue_empty(&sock->sk->sk_receive_queue) ||
1135 (flags & MSG_WAITALL))
1136 /* ... and more is ready or required */
1137 && (!(flags & MSG_PEEK)) /* ... and aren't just peeking at data */
1138 && (!err) /* ... and haven't reached a FIN */
1144 return sz_copied ? sz_copied : res;
1148 * rx_queue_full - determine if receive queue can accept another message
1149 * @msg: message to be added to queue
1150 * @queue_size: current size of queue
1151 * @base: nominal maximum size of queue
1153 * Returns 1 if queue is unable to accept message, 0 otherwise
1156 static int rx_queue_full(struct tipc_msg *msg, u32 queue_size, u32 base)
1159 u32 imp = msg_importance(msg);
1161 if (imp == TIPC_LOW_IMPORTANCE)
1163 else if (imp == TIPC_MEDIUM_IMPORTANCE)
1164 threshold = base * 2;
1165 else if (imp == TIPC_HIGH_IMPORTANCE)
1166 threshold = base * 100;
1170 if (msg_connected(msg))
1173 return (queue_size >= threshold);
1177 * filter_rcv - validate incoming message
1181 * Enqueues message on receive queue if acceptable; optionally handles
1182 * disconnect indication for a connected socket.
1184 * Called with socket lock already taken; port lock may also be taken.
1186 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1189 static u32 filter_rcv(struct sock *sk, struct sk_buff *buf)
1191 struct socket *sock = sk->sk_socket;
1192 struct tipc_msg *msg = buf_msg(buf);
1195 /* Reject message if it is wrong sort of message for socket */
1198 * WOULD IT BE BETTER TO JUST DISCARD THESE MESSAGES INSTEAD?
1199 * "NO PORT" ISN'T REALLY THE RIGHT ERROR CODE, AND THERE MAY
1200 * BE SECURITY IMPLICATIONS INHERENT IN REJECTING INVALID TRAFFIC
1203 if (sock->state == SS_READY) {
1204 if (msg_connected(msg)) {
1205 msg_dbg(msg, "dispatch filter 1\n");
1206 return TIPC_ERR_NO_PORT;
1209 if (msg_mcast(msg)) {
1210 msg_dbg(msg, "dispatch filter 2\n");
1211 return TIPC_ERR_NO_PORT;
1213 if (sock->state == SS_CONNECTED) {
1214 if (!msg_connected(msg)) {
1215 msg_dbg(msg, "dispatch filter 3\n");
1216 return TIPC_ERR_NO_PORT;
1219 else if (sock->state == SS_CONNECTING) {
1220 if (!msg_connected(msg) && (msg_errcode(msg) == 0)) {
1221 msg_dbg(msg, "dispatch filter 4\n");
1222 return TIPC_ERR_NO_PORT;
1225 else if (sock->state == SS_LISTENING) {
1226 if (msg_connected(msg) || msg_errcode(msg)) {
1227 msg_dbg(msg, "dispatch filter 5\n");
1228 return TIPC_ERR_NO_PORT;
1231 else if (sock->state == SS_DISCONNECTING) {
1232 msg_dbg(msg, "dispatch filter 6\n");
1233 return TIPC_ERR_NO_PORT;
1235 else /* (sock->state == SS_UNCONNECTED) */ {
1236 if (msg_connected(msg) || msg_errcode(msg)) {
1237 msg_dbg(msg, "dispatch filter 7\n");
1238 return TIPC_ERR_NO_PORT;
1243 /* Reject message if there isn't room to queue it */
1245 recv_q_len = (u32)atomic_read(&tipc_queue_size);
1246 if (unlikely(recv_q_len >= OVERLOAD_LIMIT_BASE)) {
1247 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE))
1248 return TIPC_ERR_OVERLOAD;
1250 recv_q_len = skb_queue_len(&sk->sk_receive_queue);
1251 if (unlikely(recv_q_len >= (OVERLOAD_LIMIT_BASE / 2))) {
1252 if (rx_queue_full(msg, recv_q_len, OVERLOAD_LIMIT_BASE / 2))
1253 return TIPC_ERR_OVERLOAD;
1256 /* Enqueue message (finally!) */
1258 msg_dbg(msg, "<DISP<: ");
1259 TIPC_SKB_CB(buf)->handle = msg_data(msg);
1260 atomic_inc(&tipc_queue_size);
1261 __skb_queue_tail(&sk->sk_receive_queue, buf);
1263 /* Initiate connection termination for an incoming 'FIN' */
1265 if (unlikely(msg_errcode(msg) && (sock->state == SS_CONNECTED))) {
1266 sock->state = SS_DISCONNECTING;
1267 tipc_disconnect_port(tipc_sk_port(sk));
1270 if (waitqueue_active(sk->sk_sleep))
1271 wake_up_interruptible(sk->sk_sleep);
1276 * backlog_rcv - handle incoming message from backlog queue
1280 * Caller must hold socket lock, but not port lock.
1285 static int backlog_rcv(struct sock *sk, struct sk_buff *buf)
1289 res = filter_rcv(sk, buf);
1291 tipc_reject_msg(buf, res);
1296 * dispatch - handle incoming message
1297 * @tport: TIPC port that received message
1300 * Called with port lock already taken.
1302 * Returns TIPC error status code (TIPC_OK if message is not to be rejected)
1305 static u32 dispatch(struct tipc_port *tport, struct sk_buff *buf)
1307 struct sock *sk = (struct sock *)tport->usr_handle;
1311 * Process message if socket is unlocked; otherwise add to backlog queue
1313 * This code is based on sk_receive_skb(), but must be distinct from it
1314 * since a TIPC-specific filter/reject mechanism is utilized
1318 if (!sock_owned_by_user(sk)) {
1319 res = filter_rcv(sk, buf);
1321 sk_add_backlog(sk, buf);
1330 * wakeupdispatch - wake up port after congestion
1331 * @tport: port to wakeup
1333 * Called with port lock already taken.
1336 static void wakeupdispatch(struct tipc_port *tport)
1338 struct sock *sk = (struct sock *)tport->usr_handle;
1340 if (waitqueue_active(sk->sk_sleep))
1341 wake_up_interruptible(sk->sk_sleep);
1345 * connect - establish a connection to another TIPC port
1346 * @sock: socket structure
1347 * @dest: socket address for destination port
1348 * @destlen: size of socket address data structure
1349 * @flags: file-related flags associated with socket
1351 * Returns 0 on success, errno otherwise
1354 static int connect(struct socket *sock, struct sockaddr *dest, int destlen,
1357 struct sock *sk = sock->sk;
1358 struct sockaddr_tipc *dst = (struct sockaddr_tipc *)dest;
1359 struct msghdr m = {NULL,};
1360 struct sk_buff *buf;
1361 struct tipc_msg *msg;
1366 /* For now, TIPC does not allow use of connect() with DGRAM/RDM types */
1368 if (sock->state == SS_READY) {
1373 /* For now, TIPC does not support the non-blocking form of connect() */
1375 if (flags & O_NONBLOCK) {
1380 /* Issue Posix-compliant error code if socket is in the wrong state */
1382 if (sock->state == SS_LISTENING) {
1386 if (sock->state == SS_CONNECTING) {
1390 if (sock->state != SS_UNCONNECTED) {
1396 * Reject connection attempt using multicast address
1398 * Note: send_msg() validates the rest of the address fields,
1399 * so there's no need to do it here
1402 if (dst->addrtype == TIPC_ADDR_MCAST) {
1407 /* Reject any messages already in receive queue (very unlikely) */
1409 reject_rx_queue(sk);
1411 /* Send a 'SYN-' to destination */
1414 m.msg_namelen = destlen;
1415 res = send_msg(NULL, sock, &m, 0);
1420 /* Wait until an 'ACK' or 'RST' arrives, or a timeout occurs */
1423 res = wait_event_interruptible_timeout(*sk->sk_sleep,
1424 (!skb_queue_empty(&sk->sk_receive_queue) ||
1425 (sock->state != SS_CONNECTING)),
1430 buf = skb_peek(&sk->sk_receive_queue);
1433 res = auto_connect(sock, msg);
1435 if (!msg_data_sz(msg))
1436 advance_rx_queue(sk);
1439 if (sock->state == SS_CONNECTED) {
1442 res = -ECONNREFUSED;
1449 ; /* leave "res" unchanged */
1450 sock->state = SS_DISCONNECTING;
1459 * listen - allow socket to listen for incoming connections
1460 * @sock: socket structure
1463 * Returns 0 on success, errno otherwise
1466 static int listen(struct socket *sock, int len)
1468 struct sock *sk = sock->sk;
1473 if (sock->state == SS_READY)
1475 else if (sock->state != SS_UNCONNECTED)
1478 sock->state = SS_LISTENING;
1487 * accept - wait for connection request
1488 * @sock: listening socket
1489 * @newsock: new socket that is to be connected
1490 * @flags: file-related flags associated with socket
1492 * Returns 0 on success, errno otherwise
1495 static int accept(struct socket *sock, struct socket *new_sock, int flags)
1497 struct sock *sk = sock->sk;
1498 struct sk_buff *buf;
1503 if (sock->state == SS_READY) {
1507 if (sock->state != SS_LISTENING) {
1512 while (skb_queue_empty(&sk->sk_receive_queue)) {
1513 if (flags & O_NONBLOCK) {
1518 res = wait_event_interruptible(*sk->sk_sleep,
1519 (!skb_queue_empty(&sk->sk_receive_queue)));
1525 buf = skb_peek(&sk->sk_receive_queue);
1527 res = tipc_create(sock_net(sock->sk), new_sock, 0);
1529 struct sock *new_sk = new_sock->sk;
1530 struct tipc_port *new_tport = tipc_sk_port(new_sk);
1531 u32 new_ref = new_tport->ref;
1532 struct tipc_portid id;
1533 struct tipc_msg *msg = buf_msg(buf);
1538 * Reject any stray messages received by new socket
1539 * before the socket lock was taken (very, very unlikely)
1542 reject_rx_queue(new_sk);
1544 /* Connect new socket to it's peer */
1546 id.ref = msg_origport(msg);
1547 id.node = msg_orignode(msg);
1548 tipc_connect2port(new_ref, &id);
1549 new_sock->state = SS_CONNECTED;
1551 tipc_set_portimportance(new_ref, msg_importance(msg));
1552 if (msg_named(msg)) {
1553 new_tport->conn_type = msg_nametype(msg);
1554 new_tport->conn_instance = msg_nameinst(msg);
1558 * Respond to 'SYN-' by discarding it & returning 'ACK'-.
1559 * Respond to 'SYN+' by queuing it on new socket.
1562 msg_dbg(msg,"<ACC<: ");
1563 if (!msg_data_sz(msg)) {
1564 struct msghdr m = {NULL,};
1566 advance_rx_queue(sk);
1567 send_packet(NULL, new_sock, &m, 0);
1569 __skb_dequeue(&sk->sk_receive_queue);
1570 __skb_queue_head(&new_sk->sk_receive_queue, buf);
1572 release_sock(new_sk);
1580 * shutdown - shutdown socket connection
1581 * @sock: socket structure
1582 * @how: direction to close (must be SHUT_RDWR)
1584 * Terminates connection (if necessary), then purges socket's receive queue.
1586 * Returns 0 on success, errno otherwise
1589 static int shutdown(struct socket *sock, int how)
1591 struct sock *sk = sock->sk;
1592 struct tipc_port *tport = tipc_sk_port(sk);
1593 struct sk_buff *buf;
1596 if (how != SHUT_RDWR)
1601 switch (sock->state) {
1605 /* Disconnect and send a 'FIN+' or 'FIN-' message to peer */
1607 buf = __skb_dequeue(&sk->sk_receive_queue);
1609 atomic_dec(&tipc_queue_size);
1610 if (TIPC_SKB_CB(buf)->handle != msg_data(buf_msg(buf))) {
1614 tipc_disconnect(tport->ref);
1615 tipc_reject_msg(buf, TIPC_CONN_SHUTDOWN);
1617 tipc_shutdown(tport->ref);
1620 sock->state = SS_DISCONNECTING;
1624 case SS_DISCONNECTING:
1626 /* Discard any unreceived messages; wake up sleeping tasks */
1628 discard_rx_queue(sk);
1629 if (waitqueue_active(sk->sk_sleep))
1630 wake_up_interruptible(sk->sk_sleep);
1643 * setsockopt - set socket option
1644 * @sock: socket structure
1645 * @lvl: option level
1646 * @opt: option identifier
1647 * @ov: pointer to new option value
1648 * @ol: length of option value
1650 * For stream sockets only, accepts and ignores all IPPROTO_TCP options
1651 * (to ease compatibility).
1653 * Returns 0 on success, errno otherwise
1656 static int setsockopt(struct socket *sock,
1657 int lvl, int opt, char __user *ov, int ol)
1659 struct sock *sk = sock->sk;
1660 struct tipc_port *tport = tipc_sk_port(sk);
1664 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1666 if (lvl != SOL_TIPC)
1667 return -ENOPROTOOPT;
1668 if (ol < sizeof(value))
1670 if ((res = get_user(value, (u32 __user *)ov)))
1676 case TIPC_IMPORTANCE:
1677 res = tipc_set_portimportance(tport->ref, value);
1679 case TIPC_SRC_DROPPABLE:
1680 if (sock->type != SOCK_STREAM)
1681 res = tipc_set_portunreliable(tport->ref, value);
1685 case TIPC_DEST_DROPPABLE:
1686 res = tipc_set_portunreturnable(tport->ref, value);
1688 case TIPC_CONN_TIMEOUT:
1689 sk->sk_rcvtimeo = msecs_to_jiffies(value);
1690 /* no need to set "res", since already 0 at this point */
1702 * getsockopt - get socket option
1703 * @sock: socket structure
1704 * @lvl: option level
1705 * @opt: option identifier
1706 * @ov: receptacle for option value
1707 * @ol: receptacle for length of option value
1709 * For stream sockets only, returns 0 length result for all IPPROTO_TCP options
1710 * (to ease compatibility).
1712 * Returns 0 on success, errno otherwise
1715 static int getsockopt(struct socket *sock,
1716 int lvl, int opt, char __user *ov, int __user *ol)
1718 struct sock *sk = sock->sk;
1719 struct tipc_port *tport = tipc_sk_port(sk);
1724 if ((lvl == IPPROTO_TCP) && (sock->type == SOCK_STREAM))
1725 return put_user(0, ol);
1726 if (lvl != SOL_TIPC)
1727 return -ENOPROTOOPT;
1728 if ((res = get_user(len, ol)))
1734 case TIPC_IMPORTANCE:
1735 res = tipc_portimportance(tport->ref, &value);
1737 case TIPC_SRC_DROPPABLE:
1738 res = tipc_portunreliable(tport->ref, &value);
1740 case TIPC_DEST_DROPPABLE:
1741 res = tipc_portunreturnable(tport->ref, &value);
1743 case TIPC_CONN_TIMEOUT:
1744 value = jiffies_to_msecs(sk->sk_rcvtimeo);
1745 /* no need to set "res", since already 0 at this point */
1756 else if (len < sizeof(value)) {
1759 else if ((res = copy_to_user(ov, &value, sizeof(value)))) {
1760 /* couldn't return value */
1763 res = put_user(sizeof(value), ol);
1770 * Protocol switches for the various types of TIPC sockets
1773 static const struct proto_ops msg_ops = {
1774 .owner = THIS_MODULE,
1779 .socketpair = sock_no_socketpair,
1781 .getname = get_name,
1783 .ioctl = sock_no_ioctl,
1785 .shutdown = shutdown,
1786 .setsockopt = setsockopt,
1787 .getsockopt = getsockopt,
1788 .sendmsg = send_msg,
1789 .recvmsg = recv_msg,
1790 .mmap = sock_no_mmap,
1791 .sendpage = sock_no_sendpage
1794 static const struct proto_ops packet_ops = {
1795 .owner = THIS_MODULE,
1800 .socketpair = sock_no_socketpair,
1802 .getname = get_name,
1804 .ioctl = sock_no_ioctl,
1806 .shutdown = shutdown,
1807 .setsockopt = setsockopt,
1808 .getsockopt = getsockopt,
1809 .sendmsg = send_packet,
1810 .recvmsg = recv_msg,
1811 .mmap = sock_no_mmap,
1812 .sendpage = sock_no_sendpage
1815 static const struct proto_ops stream_ops = {
1816 .owner = THIS_MODULE,
1821 .socketpair = sock_no_socketpair,
1823 .getname = get_name,
1825 .ioctl = sock_no_ioctl,
1827 .shutdown = shutdown,
1828 .setsockopt = setsockopt,
1829 .getsockopt = getsockopt,
1830 .sendmsg = send_stream,
1831 .recvmsg = recv_stream,
1832 .mmap = sock_no_mmap,
1833 .sendpage = sock_no_sendpage
1836 static const struct net_proto_family tipc_family_ops = {
1837 .owner = THIS_MODULE,
1839 .create = tipc_create
1842 static struct proto tipc_proto = {
1844 .owner = THIS_MODULE,
1845 .obj_size = sizeof(struct tipc_sock)
1849 * tipc_socket_init - initialize TIPC socket interface
1851 * Returns 0 on success, errno otherwise
1853 int tipc_socket_init(void)
1857 res = proto_register(&tipc_proto, 1);
1859 err("Failed to register TIPC protocol type\n");
1863 res = sock_register(&tipc_family_ops);
1865 err("Failed to register TIPC socket type\n");
1866 proto_unregister(&tipc_proto);
1870 sockets_enabled = 1;
1876 * tipc_socket_stop - stop TIPC socket interface
1879 void tipc_socket_stop(void)
1881 if (!sockets_enabled)
1884 sockets_enabled = 0;
1885 sock_unregister(tipc_family_ops.family);
1886 proto_unregister(&tipc_proto);