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