linux/net/sctp/socket.c
<<
>>
Prefs
   1/* SCTP kernel implementation
   2 * (C) Copyright IBM Corp. 2001, 2004
   3 * Copyright (c) 1999-2000 Cisco, Inc.
   4 * Copyright (c) 1999-2001 Motorola, Inc.
   5 * Copyright (c) 2001-2003 Intel Corp.
   6 * Copyright (c) 2001-2002 Nokia, Inc.
   7 * Copyright (c) 2001 La Monte H.P. Yarroll
   8 *
   9 * This file is part of the SCTP kernel implementation
  10 *
  11 * These functions interface with the sockets layer to implement the
  12 * SCTP Extensions for the Sockets API.
  13 *
  14 * Note that the descriptions from the specification are USER level
  15 * functions--this file is the functions which populate the struct proto
  16 * for SCTP which is the BOTTOM of the sockets interface.
  17 *
  18 * This SCTP implementation is free software;
  19 * you can redistribute it and/or modify it under the terms of
  20 * the GNU General Public License as published by
  21 * the Free Software Foundation; either version 2, or (at your option)
  22 * any later version.
  23 *
  24 * This SCTP implementation is distributed in the hope that it
  25 * will be useful, but WITHOUT ANY WARRANTY; without even the implied
  26 *                 ************************
  27 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
  28 * See the GNU General Public License for more details.
  29 *
  30 * You should have received a copy of the GNU General Public License
  31 * along with GNU CC; see the file COPYING.  If not, write to
  32 * the Free Software Foundation, 59 Temple Place - Suite 330,
  33 * Boston, MA 02111-1307, USA.
  34 *
  35 * Please send any bug reports or fixes you make to the
  36 * email address(es):
  37 *    lksctp developers <lksctp-developers@lists.sourceforge.net>
  38 *
  39 * Or submit a bug report through the following website:
  40 *    http://www.sf.net/projects/lksctp
  41 *
  42 * Written or modified by:
  43 *    La Monte H.P. Yarroll <piggy@acm.org>
  44 *    Narasimha Budihal     <narsi@refcode.org>
  45 *    Karl Knutson          <karl@athena.chicago.il.us>
  46 *    Jon Grimm             <jgrimm@us.ibm.com>
  47 *    Xingang Guo           <xingang.guo@intel.com>
  48 *    Daisy Chang           <daisyc@us.ibm.com>
  49 *    Sridhar Samudrala     <samudrala@us.ibm.com>
  50 *    Inaky Perez-Gonzalez  <inaky.gonzalez@intel.com>
  51 *    Ardelle Fan           <ardelle.fan@intel.com>
  52 *    Ryan Layer            <rmlayer@us.ibm.com>
  53 *    Anup Pemmaiah         <pemmaiah@cc.usu.edu>
  54 *    Kevin Gao             <kevin.gao@intel.com>
  55 *
  56 * Any bugs reported given to us we will try to fix... any fixes shared will
  57 * be incorporated into the next SCTP release.
  58 */
  59
  60#define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
  61
  62#include <linux/types.h>
  63#include <linux/kernel.h>
  64#include <linux/wait.h>
  65#include <linux/time.h>
  66#include <linux/ip.h>
  67#include <linux/capability.h>
  68#include <linux/fcntl.h>
  69#include <linux/poll.h>
  70#include <linux/init.h>
  71#include <linux/crypto.h>
  72#include <linux/slab.h>
  73#include <linux/file.h>
  74#include <linux/compat.h>
  75
  76#include <net/ip.h>
  77#include <net/icmp.h>
  78#include <net/route.h>
  79#include <net/ipv6.h>
  80#include <net/inet_common.h>
  81
  82#include <linux/socket.h> /* for sa_family_t */
  83#include <linux/export.h>
  84#include <net/sock.h>
  85#include <net/sctp/sctp.h>
  86#include <net/sctp/sm.h>
  87
  88/* Forward declarations for internal helper functions. */
  89static int sctp_writeable(struct sock *sk);
  90static void sctp_wfree(struct sk_buff *skb);
  91static int sctp_wait_for_sndbuf(struct sctp_association *, long *timeo_p,
  92                                size_t msg_len);
  93static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p);
  94static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
  95static int sctp_wait_for_accept(struct sock *sk, long timeo);
  96static void sctp_wait_for_close(struct sock *sk, long timeo);
  97static void sctp_destruct_sock(struct sock *sk);
  98static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
  99                                        union sctp_addr *addr, int len);
 100static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
 101static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
 102static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
 103static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
 104static int sctp_send_asconf(struct sctp_association *asoc,
 105                            struct sctp_chunk *chunk);
 106static int sctp_do_bind(struct sock *, union sctp_addr *, int);
 107static int sctp_autobind(struct sock *sk);
 108static void sctp_sock_migrate(struct sock *, struct sock *,
 109                              struct sctp_association *, sctp_socket_type_t);
 110
 111extern struct kmem_cache *sctp_bucket_cachep;
 112extern long sysctl_sctp_mem[3];
 113extern int sysctl_sctp_rmem[3];
 114extern int sysctl_sctp_wmem[3];
 115
 116static int sctp_memory_pressure;
 117static atomic_long_t sctp_memory_allocated;
 118struct percpu_counter sctp_sockets_allocated;
 119
 120static void sctp_enter_memory_pressure(struct sock *sk)
 121{
 122        sctp_memory_pressure = 1;
 123}
 124
 125
 126/* Get the sndbuf space available at the time on the association.  */
 127static inline int sctp_wspace(struct sctp_association *asoc)
 128{
 129        int amt;
 130
 131        if (asoc->ep->sndbuf_policy)
 132                amt = asoc->sndbuf_used;
 133        else
 134                amt = sk_wmem_alloc_get(asoc->base.sk);
 135
 136        if (amt >= asoc->base.sk->sk_sndbuf) {
 137                if (asoc->base.sk->sk_userlocks & SOCK_SNDBUF_LOCK)
 138                        amt = 0;
 139                else {
 140                        amt = sk_stream_wspace(asoc->base.sk);
 141                        if (amt < 0)
 142                                amt = 0;
 143                }
 144        } else {
 145                amt = asoc->base.sk->sk_sndbuf - amt;
 146        }
 147        return amt;
 148}
 149
 150/* Increment the used sndbuf space count of the corresponding association by
 151 * the size of the outgoing data chunk.
 152 * Also, set the skb destructor for sndbuf accounting later.
 153 *
 154 * Since it is always 1-1 between chunk and skb, and also a new skb is always
 155 * allocated for chunk bundling in sctp_packet_transmit(), we can use the
 156 * destructor in the data chunk skb for the purpose of the sndbuf space
 157 * tracking.
 158 */
 159static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
 160{
 161        struct sctp_association *asoc = chunk->asoc;
 162        struct sock *sk = asoc->base.sk;
 163
 164        /* The sndbuf space is tracked per association.  */
 165        sctp_association_hold(asoc);
 166
 167        skb_set_owner_w(chunk->skb, sk);
 168
 169        chunk->skb->destructor = sctp_wfree;
 170        /* Save the chunk pointer in skb for sctp_wfree to use later.  */
 171        skb_shinfo(chunk->skb)->destructor_arg = chunk;
 172
 173        asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk) +
 174                                sizeof(struct sk_buff) +
 175                                sizeof(struct sctp_chunk);
 176
 177        atomic_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
 178        sk->sk_wmem_queued += chunk->skb->truesize;
 179        sk_mem_charge(sk, chunk->skb->truesize);
 180}
 181
 182/* Verify that this is a valid address. */
 183static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
 184                                   int len)
 185{
 186        struct sctp_af *af;
 187
 188        /* Verify basic sockaddr. */
 189        af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
 190        if (!af)
 191                return -EINVAL;
 192
 193        /* Is this a valid SCTP address?  */
 194        if (!af->addr_valid(addr, sctp_sk(sk), NULL))
 195                return -EINVAL;
 196
 197        if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
 198                return -EINVAL;
 199
 200        return 0;
 201}
 202
 203/* Look up the association by its id.  If this is not a UDP-style
 204 * socket, the ID field is always ignored.
 205 */
 206struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
 207{
 208        struct sctp_association *asoc = NULL;
 209
 210        /* If this is not a UDP-style socket, assoc id should be ignored. */
 211        if (!sctp_style(sk, UDP)) {
 212                /* Return NULL if the socket state is not ESTABLISHED. It
 213                 * could be a TCP-style listening socket or a socket which
 214                 * hasn't yet called connect() to establish an association.
 215                 */
 216                if (!sctp_sstate(sk, ESTABLISHED) && !sctp_sstate(sk, CLOSING))
 217                        return NULL;
 218
 219                /* Get the first and the only association from the list. */
 220                if (!list_empty(&sctp_sk(sk)->ep->asocs))
 221                        asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
 222                                          struct sctp_association, asocs);
 223                return asoc;
 224        }
 225
 226        /* Otherwise this is a UDP-style socket. */
 227        if (!id || (id == (sctp_assoc_t)-1))
 228                return NULL;
 229
 230        spin_lock_bh(&sctp_assocs_id_lock);
 231        asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
 232        spin_unlock_bh(&sctp_assocs_id_lock);
 233
 234        if (!asoc || (asoc->base.sk != sk) || asoc->base.dead)
 235                return NULL;
 236
 237        return asoc;
 238}
 239
 240/* Look up the transport from an address and an assoc id. If both address and
 241 * id are specified, the associations matching the address and the id should be
 242 * the same.
 243 */
 244static struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
 245                                              struct sockaddr_storage *addr,
 246                                              sctp_assoc_t id)
 247{
 248        struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
 249        struct sctp_af *af = sctp_get_af_specific(addr->ss_family);
 250        union sctp_addr *laddr = (union sctp_addr *)addr;
 251        struct sctp_transport *transport;
 252
 253        if (!af || sctp_verify_addr(sk, laddr, af->sockaddr_len))
 254                return NULL;
 255
 256        addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
 257                                               laddr,
 258                                               &transport);
 259
 260        if (!addr_asoc)
 261                return NULL;
 262
 263        id_asoc = sctp_id2assoc(sk, id);
 264        if (id_asoc && (id_asoc != addr_asoc))
 265                return NULL;
 266
 267        sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
 268                                                (union sctp_addr *)addr);
 269
 270        return transport;
 271}
 272
 273/* API 3.1.2 bind() - UDP Style Syntax
 274 * The syntax of bind() is,
 275 *
 276 *   ret = bind(int sd, struct sockaddr *addr, int addrlen);
 277 *
 278 *   sd      - the socket descriptor returned by socket().
 279 *   addr    - the address structure (struct sockaddr_in or struct
 280 *             sockaddr_in6 [RFC 2553]),
 281 *   addr_len - the size of the address structure.
 282 */
 283static int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len)
 284{
 285        int retval = 0;
 286
 287        lock_sock(sk);
 288
 289        pr_debug("%s: sk:%p, addr:%p, addr_len:%d\n", __func__, sk,
 290                 addr, addr_len);
 291
 292        /* Disallow binding twice. */
 293        if (!sctp_sk(sk)->ep->base.bind_addr.port)
 294                retval = sctp_do_bind(sk, (union sctp_addr *)addr,
 295                                      addr_len);
 296        else
 297                retval = -EINVAL;
 298
 299        release_sock(sk);
 300
 301        return retval;
 302}
 303
 304static long sctp_get_port_local(struct sock *, union sctp_addr *);
 305
 306/* Verify this is a valid sockaddr. */
 307static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
 308                                        union sctp_addr *addr, int len)
 309{
 310        struct sctp_af *af;
 311
 312        /* Check minimum size.  */
 313        if (len < sizeof (struct sockaddr))
 314                return NULL;
 315
 316        /* V4 mapped address are really of AF_INET family */
 317        if (addr->sa.sa_family == AF_INET6 &&
 318            ipv6_addr_v4mapped(&addr->v6.sin6_addr)) {
 319                if (!opt->pf->af_supported(AF_INET, opt))
 320                        return NULL;
 321        } else {
 322                /* Does this PF support this AF? */
 323                if (!opt->pf->af_supported(addr->sa.sa_family, opt))
 324                        return NULL;
 325        }
 326
 327        /* If we get this far, af is valid. */
 328        af = sctp_get_af_specific(addr->sa.sa_family);
 329
 330        if (len < af->sockaddr_len)
 331                return NULL;
 332
 333        return af;
 334}
 335
 336/* Bind a local address either to an endpoint or to an association.  */
 337static int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
 338{
 339        struct net *net = sock_net(sk);
 340        struct sctp_sock *sp = sctp_sk(sk);
 341        struct sctp_endpoint *ep = sp->ep;
 342        struct sctp_bind_addr *bp = &ep->base.bind_addr;
 343        struct sctp_af *af;
 344        unsigned short snum;
 345        int ret = 0;
 346
 347        /* Common sockaddr verification. */
 348        af = sctp_sockaddr_af(sp, addr, len);
 349        if (!af) {
 350                pr_debug("%s: sk:%p, newaddr:%p, len:%d EINVAL\n",
 351                         __func__, sk, addr, len);
 352                return -EINVAL;
 353        }
 354
 355        snum = ntohs(addr->v4.sin_port);
 356
 357        pr_debug("%s: sk:%p, new addr:%pISc, port:%d, new port:%d, len:%d\n",
 358                 __func__, sk, &addr->sa, bp->port, snum, len);
 359
 360        /* PF specific bind() address verification. */
 361        if (!sp->pf->bind_verify(sp, addr))
 362                return -EADDRNOTAVAIL;
 363
 364        /* We must either be unbound, or bind to the same port.
 365         * It's OK to allow 0 ports if we are already bound.
 366         * We'll just inhert an already bound port in this case
 367         */
 368        if (bp->port) {
 369                if (!snum)
 370                        snum = bp->port;
 371                else if (snum != bp->port) {
 372                        pr_debug("%s: new port %d doesn't match existing port "
 373                                 "%d\n", __func__, snum, bp->port);
 374                        return -EINVAL;
 375                }
 376        }
 377
 378        if (snum && snum < PROT_SOCK &&
 379            !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE))
 380                return -EACCES;
 381
 382        /* See if the address matches any of the addresses we may have
 383         * already bound before checking against other endpoints.
 384         */
 385        if (sctp_bind_addr_match(bp, addr, sp))
 386                return -EINVAL;
 387
 388        /* Make sure we are allowed to bind here.
 389         * The function sctp_get_port_local() does duplicate address
 390         * detection.
 391         */
 392        addr->v4.sin_port = htons(snum);
 393        if ((ret = sctp_get_port_local(sk, addr))) {
 394                return -EADDRINUSE;
 395        }
 396
 397        /* Refresh ephemeral port.  */
 398        if (!bp->port)
 399                bp->port = inet_sk(sk)->inet_num;
 400
 401        /* Add the address to the bind address list.
 402         * Use GFP_ATOMIC since BHs will be disabled.
 403         */
 404        ret = sctp_add_bind_addr(bp, addr, af->sockaddr_len,
 405                                 SCTP_ADDR_SRC, GFP_ATOMIC);
 406
 407        /* Copy back into socket for getsockname() use. */
 408        if (!ret) {
 409                inet_sk(sk)->inet_sport = htons(inet_sk(sk)->inet_num);
 410                sp->pf->to_sk_saddr(addr, sk);
 411        }
 412
 413        return ret;
 414}
 415
 416 /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
 417 *
 418 * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged
 419 * at any one time.  If a sender, after sending an ASCONF chunk, decides
 420 * it needs to transfer another ASCONF Chunk, it MUST wait until the
 421 * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
 422 * subsequent ASCONF. Note this restriction binds each side, so at any
 423 * time two ASCONF may be in-transit on any given association (one sent
 424 * from each endpoint).
 425 */
 426static int sctp_send_asconf(struct sctp_association *asoc,
 427                            struct sctp_chunk *chunk)
 428{
 429        struct net      *net = sock_net(asoc->base.sk);
 430        int             retval = 0;
 431
 432        /* If there is an outstanding ASCONF chunk, queue it for later
 433         * transmission.
 434         */
 435        if (asoc->addip_last_asconf) {
 436                list_add_tail(&chunk->list, &asoc->addip_chunk_list);
 437                goto out;
 438        }
 439
 440        /* Hold the chunk until an ASCONF_ACK is received. */
 441        sctp_chunk_hold(chunk);
 442        retval = sctp_primitive_ASCONF(net, asoc, chunk);
 443        if (retval)
 444                sctp_chunk_free(chunk);
 445        else
 446                asoc->addip_last_asconf = chunk;
 447
 448out:
 449        return retval;
 450}
 451
 452/* Add a list of addresses as bind addresses to local endpoint or
 453 * association.
 454 *
 455 * Basically run through each address specified in the addrs/addrcnt
 456 * array/length pair, determine if it is IPv6 or IPv4 and call
 457 * sctp_do_bind() on it.
 458 *
 459 * If any of them fails, then the operation will be reversed and the
 460 * ones that were added will be removed.
 461 *
 462 * Only sctp_setsockopt_bindx() is supposed to call this function.
 463 */
 464static int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
 465{
 466        int cnt;
 467        int retval = 0;
 468        void *addr_buf;
 469        struct sockaddr *sa_addr;
 470        struct sctp_af *af;
 471
 472        pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n", __func__, sk,
 473                 addrs, addrcnt);
 474
 475        addr_buf = addrs;
 476        for (cnt = 0; cnt < addrcnt; cnt++) {
 477                /* The list may contain either IPv4 or IPv6 address;
 478                 * determine the address length for walking thru the list.
 479                 */
 480                sa_addr = addr_buf;
 481                af = sctp_get_af_specific(sa_addr->sa_family);
 482                if (!af) {
 483                        retval = -EINVAL;
 484                        goto err_bindx_add;
 485                }
 486
 487                retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr,
 488                                      af->sockaddr_len);
 489
 490                addr_buf += af->sockaddr_len;
 491
 492err_bindx_add:
 493                if (retval < 0) {
 494                        /* Failed. Cleanup the ones that have been added */
 495                        if (cnt > 0)
 496                                sctp_bindx_rem(sk, addrs, cnt);
 497                        return retval;
 498                }
 499        }
 500
 501        return retval;
 502}
 503
 504/* Send an ASCONF chunk with Add IP address parameters to all the peers of the
 505 * associations that are part of the endpoint indicating that a list of local
 506 * addresses are added to the endpoint.
 507 *
 508 * If any of the addresses is already in the bind address list of the
 509 * association, we do not send the chunk for that association.  But it will not
 510 * affect other associations.
 511 *
 512 * Only sctp_setsockopt_bindx() is supposed to call this function.
 513 */
 514static int sctp_send_asconf_add_ip(struct sock          *sk,
 515                                   struct sockaddr      *addrs,
 516                                   int                  addrcnt)
 517{
 518        struct net *net = sock_net(sk);
 519        struct sctp_sock                *sp;
 520        struct sctp_endpoint            *ep;
 521        struct sctp_association         *asoc;
 522        struct sctp_bind_addr           *bp;
 523        struct sctp_chunk               *chunk;
 524        struct sctp_sockaddr_entry      *laddr;
 525        union sctp_addr                 *addr;
 526        union sctp_addr                 saveaddr;
 527        void                            *addr_buf;
 528        struct sctp_af                  *af;
 529        struct list_head                *p;
 530        int                             i;
 531        int                             retval = 0;
 532
 533        if (!net->sctp.addip_enable)
 534                return retval;
 535
 536        sp = sctp_sk(sk);
 537        ep = sp->ep;
 538
 539        pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
 540                 __func__, sk, addrs, addrcnt);
 541
 542        list_for_each_entry(asoc, &ep->asocs, asocs) {
 543                if (!asoc->peer.asconf_capable)
 544                        continue;
 545
 546                if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
 547                        continue;
 548
 549                if (!sctp_state(asoc, ESTABLISHED))
 550                        continue;
 551
 552                /* Check if any address in the packed array of addresses is
 553                 * in the bind address list of the association. If so,
 554                 * do not send the asconf chunk to its peer, but continue with
 555                 * other associations.
 556                 */
 557                addr_buf = addrs;
 558                for (i = 0; i < addrcnt; i++) {
 559                        addr = addr_buf;
 560                        af = sctp_get_af_specific(addr->v4.sin_family);
 561                        if (!af) {
 562                                retval = -EINVAL;
 563                                goto out;
 564                        }
 565
 566                        if (sctp_assoc_lookup_laddr(asoc, addr))
 567                                break;
 568
 569                        addr_buf += af->sockaddr_len;
 570                }
 571                if (i < addrcnt)
 572                        continue;
 573
 574                /* Use the first valid address in bind addr list of
 575                 * association as Address Parameter of ASCONF CHUNK.
 576                 */
 577                bp = &asoc->base.bind_addr;
 578                p = bp->address_list.next;
 579                laddr = list_entry(p, struct sctp_sockaddr_entry, list);
 580                chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
 581                                                   addrcnt, SCTP_PARAM_ADD_IP);
 582                if (!chunk) {
 583                        retval = -ENOMEM;
 584                        goto out;
 585                }
 586
 587                /* Add the new addresses to the bind address list with
 588                 * use_as_src set to 0.
 589                 */
 590                addr_buf = addrs;
 591                for (i = 0; i < addrcnt; i++) {
 592                        addr = addr_buf;
 593                        af = sctp_get_af_specific(addr->v4.sin_family);
 594                        memcpy(&saveaddr, addr, af->sockaddr_len);
 595                        retval = sctp_add_bind_addr(bp, &saveaddr,
 596                                                    sizeof(saveaddr),
 597                                                    SCTP_ADDR_NEW, GFP_ATOMIC);
 598                        addr_buf += af->sockaddr_len;
 599                }
 600                if (asoc->src_out_of_asoc_ok) {
 601                        struct sctp_transport *trans;
 602
 603                        list_for_each_entry(trans,
 604                            &asoc->peer.transport_addr_list, transports) {
 605                                /* Clear the source and route cache */
 606                                sctp_transport_dst_release(trans);
 607                                trans->cwnd = min(4*asoc->pathmtu, max_t(__u32,
 608                                    2*asoc->pathmtu, 4380));
 609                                trans->ssthresh = asoc->peer.i.a_rwnd;
 610                                trans->rto = asoc->rto_initial;
 611                                sctp_max_rto(asoc, trans);
 612                                trans->rtt = trans->srtt = trans->rttvar = 0;
 613                                sctp_transport_route(trans, NULL,
 614                                    sctp_sk(asoc->base.sk));
 615                        }
 616                }
 617                retval = sctp_send_asconf(asoc, chunk);
 618        }
 619
 620out:
 621        return retval;
 622}
 623
 624/* Remove a list of addresses from bind addresses list.  Do not remove the
 625 * last address.
 626 *
 627 * Basically run through each address specified in the addrs/addrcnt
 628 * array/length pair, determine if it is IPv6 or IPv4 and call
 629 * sctp_del_bind() on it.
 630 *
 631 * If any of them fails, then the operation will be reversed and the
 632 * ones that were removed will be added back.
 633 *
 634 * At least one address has to be left; if only one address is
 635 * available, the operation will return -EBUSY.
 636 *
 637 * Only sctp_setsockopt_bindx() is supposed to call this function.
 638 */
 639static int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
 640{
 641        struct sctp_sock *sp = sctp_sk(sk);
 642        struct sctp_endpoint *ep = sp->ep;
 643        int cnt;
 644        struct sctp_bind_addr *bp = &ep->base.bind_addr;
 645        int retval = 0;
 646        void *addr_buf;
 647        union sctp_addr *sa_addr;
 648        struct sctp_af *af;
 649
 650        pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
 651                 __func__, sk, addrs, addrcnt);
 652
 653        addr_buf = addrs;
 654        for (cnt = 0; cnt < addrcnt; cnt++) {
 655                /* If the bind address list is empty or if there is only one
 656                 * bind address, there is nothing more to be removed (we need
 657                 * at least one address here).
 658                 */
 659                if (list_empty(&bp->address_list) ||
 660                    (sctp_list_single_entry(&bp->address_list))) {
 661                        retval = -EBUSY;
 662                        goto err_bindx_rem;
 663                }
 664
 665                sa_addr = addr_buf;
 666                af = sctp_get_af_specific(sa_addr->sa.sa_family);
 667                if (!af) {
 668                        retval = -EINVAL;
 669                        goto err_bindx_rem;
 670                }
 671
 672                if (!af->addr_valid(sa_addr, sp, NULL)) {
 673                        retval = -EADDRNOTAVAIL;
 674                        goto err_bindx_rem;
 675                }
 676
 677                if (sa_addr->v4.sin_port &&
 678                    sa_addr->v4.sin_port != htons(bp->port)) {
 679                        retval = -EINVAL;
 680                        goto err_bindx_rem;
 681                }
 682
 683                if (!sa_addr->v4.sin_port)
 684                        sa_addr->v4.sin_port = htons(bp->port);
 685
 686                /* FIXME - There is probably a need to check if sk->sk_saddr and
 687                 * sk->sk_rcv_addr are currently set to one of the addresses to
 688                 * be removed. This is something which needs to be looked into
 689                 * when we are fixing the outstanding issues with multi-homing
 690                 * socket routing and failover schemes. Refer to comments in
 691                 * sctp_do_bind(). -daisy
 692                 */
 693                retval = sctp_del_bind_addr(bp, sa_addr);
 694
 695                addr_buf += af->sockaddr_len;
 696err_bindx_rem:
 697                if (retval < 0) {
 698                        /* Failed. Add the ones that has been removed back */
 699                        if (cnt > 0)
 700                                sctp_bindx_add(sk, addrs, cnt);
 701                        return retval;
 702                }
 703        }
 704
 705        return retval;
 706}
 707
 708/* Send an ASCONF chunk with Delete IP address parameters to all the peers of
 709 * the associations that are part of the endpoint indicating that a list of
 710 * local addresses are removed from the endpoint.
 711 *
 712 * If any of the addresses is already in the bind address list of the
 713 * association, we do not send the chunk for that association.  But it will not
 714 * affect other associations.
 715 *
 716 * Only sctp_setsockopt_bindx() is supposed to call this function.
 717 */
 718static int sctp_send_asconf_del_ip(struct sock          *sk,
 719                                   struct sockaddr      *addrs,
 720                                   int                  addrcnt)
 721{
 722        struct net *net = sock_net(sk);
 723        struct sctp_sock        *sp;
 724        struct sctp_endpoint    *ep;
 725        struct sctp_association *asoc;
 726        struct sctp_transport   *transport;
 727        struct sctp_bind_addr   *bp;
 728        struct sctp_chunk       *chunk;
 729        union sctp_addr         *laddr;
 730        void                    *addr_buf;
 731        struct sctp_af          *af;
 732        struct sctp_sockaddr_entry *saddr;
 733        int                     i;
 734        int                     retval = 0;
 735        int                     stored = 0;
 736
 737        chunk = NULL;
 738        if (!net->sctp.addip_enable)
 739                return retval;
 740
 741        sp = sctp_sk(sk);
 742        ep = sp->ep;
 743
 744        pr_debug("%s: sk:%p, addrs:%p, addrcnt:%d\n",
 745                 __func__, sk, addrs, addrcnt);
 746
 747        list_for_each_entry(asoc, &ep->asocs, asocs) {
 748
 749                if (!asoc->peer.asconf_capable)
 750                        continue;
 751
 752                if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
 753                        continue;
 754
 755                if (!sctp_state(asoc, ESTABLISHED))
 756                        continue;
 757
 758                /* Check if any address in the packed array of addresses is
 759                 * not present in the bind address list of the association.
 760                 * If so, do not send the asconf chunk to its peer, but
 761                 * continue with other associations.
 762                 */
 763                addr_buf = addrs;
 764                for (i = 0; i < addrcnt; i++) {
 765                        laddr = addr_buf;
 766                        af = sctp_get_af_specific(laddr->v4.sin_family);
 767                        if (!af) {
 768                                retval = -EINVAL;
 769                                goto out;
 770                        }
 771
 772                        if (!sctp_assoc_lookup_laddr(asoc, laddr))
 773                                break;
 774
 775                        addr_buf += af->sockaddr_len;
 776                }
 777                if (i < addrcnt)
 778                        continue;
 779
 780                /* Find one address in the association's bind address list
 781                 * that is not in the packed array of addresses. This is to
 782                 * make sure that we do not delete all the addresses in the
 783                 * association.
 784                 */
 785                bp = &asoc->base.bind_addr;
 786                laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
 787                                               addrcnt, sp);
 788                if ((laddr == NULL) && (addrcnt == 1)) {
 789                        if (asoc->asconf_addr_del_pending)
 790                                continue;
 791                        asoc->asconf_addr_del_pending =
 792                            kzalloc(sizeof(union sctp_addr), GFP_ATOMIC);
 793                        if (asoc->asconf_addr_del_pending == NULL) {
 794                                retval = -ENOMEM;
 795                                goto out;
 796                        }
 797                        asoc->asconf_addr_del_pending->sa.sa_family =
 798                                    addrs->sa_family;
 799                        asoc->asconf_addr_del_pending->v4.sin_port =
 800                                    htons(bp->port);
 801                        if (addrs->sa_family == AF_INET) {
 802                                struct sockaddr_in *sin;
 803
 804                                sin = (struct sockaddr_in *)addrs;
 805                                asoc->asconf_addr_del_pending->v4.sin_addr.s_addr = sin->sin_addr.s_addr;
 806                        } else if (addrs->sa_family == AF_INET6) {
 807                                struct sockaddr_in6 *sin6;
 808
 809                                sin6 = (struct sockaddr_in6 *)addrs;
 810                                asoc->asconf_addr_del_pending->v6.sin6_addr = sin6->sin6_addr;
 811                        }
 812
 813                        pr_debug("%s: keep the last address asoc:%p %pISc at %p\n",
 814                                 __func__, asoc, &asoc->asconf_addr_del_pending->sa,
 815                                 asoc->asconf_addr_del_pending);
 816
 817                        asoc->src_out_of_asoc_ok = 1;
 818                        stored = 1;
 819                        goto skip_mkasconf;
 820                }
 821
 822                if (laddr == NULL)
 823                        return -EINVAL;
 824
 825                /* We do not need RCU protection throughout this loop
 826                 * because this is done under a socket lock from the
 827                 * setsockopt call.
 828                 */
 829                chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
 830                                                   SCTP_PARAM_DEL_IP);
 831                if (!chunk) {
 832                        retval = -ENOMEM;
 833                        goto out;
 834                }
 835
 836skip_mkasconf:
 837                /* Reset use_as_src flag for the addresses in the bind address
 838                 * list that are to be deleted.
 839                 */
 840                addr_buf = addrs;
 841                for (i = 0; i < addrcnt; i++) {
 842                        laddr = addr_buf;
 843                        af = sctp_get_af_specific(laddr->v4.sin_family);
 844                        list_for_each_entry(saddr, &bp->address_list, list) {
 845                                if (sctp_cmp_addr_exact(&saddr->a, laddr))
 846                                        saddr->state = SCTP_ADDR_DEL;
 847                        }
 848                        addr_buf += af->sockaddr_len;
 849                }
 850
 851                /* Update the route and saddr entries for all the transports
 852                 * as some of the addresses in the bind address list are
 853                 * about to be deleted and cannot be used as source addresses.
 854                 */
 855                list_for_each_entry(transport, &asoc->peer.transport_addr_list,
 856                                        transports) {
 857                        sctp_transport_dst_release(transport);
 858                        sctp_transport_route(transport, NULL,
 859                                             sctp_sk(asoc->base.sk));
 860                }
 861
 862                if (stored)
 863                        /* We don't need to transmit ASCONF */
 864                        continue;
 865                retval = sctp_send_asconf(asoc, chunk);
 866        }
 867out:
 868        return retval;
 869}
 870
 871/* set addr events to assocs in the endpoint.  ep and addr_wq must be locked */
 872int sctp_asconf_mgmt(struct sctp_sock *sp, struct sctp_sockaddr_entry *addrw)
 873{
 874        struct sock *sk = sctp_opt2sk(sp);
 875        union sctp_addr *addr;
 876        struct sctp_af *af;
 877
 878        /* It is safe to write port space in caller. */
 879        addr = &addrw->a;
 880        addr->v4.sin_port = htons(sp->ep->base.bind_addr.port);
 881        af = sctp_get_af_specific(addr->sa.sa_family);
 882        if (!af)
 883                return -EINVAL;
 884        if (sctp_verify_addr(sk, addr, af->sockaddr_len))
 885                return -EINVAL;
 886
 887        if (addrw->state == SCTP_ADDR_NEW)
 888                return sctp_send_asconf_add_ip(sk, (struct sockaddr *)addr, 1);
 889        else
 890                return sctp_send_asconf_del_ip(sk, (struct sockaddr *)addr, 1);
 891}
 892
 893/* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
 894 *
 895 * API 8.1
 896 * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
 897 *                int flags);
 898 *
 899 * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
 900 * If the sd is an IPv6 socket, the addresses passed can either be IPv4
 901 * or IPv6 addresses.
 902 *
 903 * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
 904 * Section 3.1.2 for this usage.
 905 *
 906 * addrs is a pointer to an array of one or more socket addresses. Each
 907 * address is contained in its appropriate structure (i.e. struct
 908 * sockaddr_in or struct sockaddr_in6) the family of the address type
 909 * must be used to distinguish the address length (note that this
 910 * representation is termed a "packed array" of addresses). The caller
 911 * specifies the number of addresses in the array with addrcnt.
 912 *
 913 * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
 914 * -1, and sets errno to the appropriate error code.
 915 *
 916 * For SCTP, the port given in each socket address must be the same, or
 917 * sctp_bindx() will fail, setting errno to EINVAL.
 918 *
 919 * The flags parameter is formed from the bitwise OR of zero or more of
 920 * the following currently defined flags:
 921 *
 922 * SCTP_BINDX_ADD_ADDR
 923 *
 924 * SCTP_BINDX_REM_ADDR
 925 *
 926 * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
 927 * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
 928 * addresses from the association. The two flags are mutually exclusive;
 929 * if both are given, sctp_bindx() will fail with EINVAL. A caller may
 930 * not remove all addresses from an association; sctp_bindx() will
 931 * reject such an attempt with EINVAL.
 932 *
 933 * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
 934 * additional addresses with an endpoint after calling bind().  Or use
 935 * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
 936 * socket is associated with so that no new association accepted will be
 937 * associated with those addresses. If the endpoint supports dynamic
 938 * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
 939 * endpoint to send the appropriate message to the peer to change the
 940 * peers address lists.
 941 *
 942 * Adding and removing addresses from a connected association is
 943 * optional functionality. Implementations that do not support this
 944 * functionality should return EOPNOTSUPP.
 945 *
 946 * Basically do nothing but copying the addresses from user to kernel
 947 * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
 948 * This is used for tunneling the sctp_bindx() request through sctp_setsockopt()
 949 * from userspace.
 950 *
 951 * We don't use copy_from_user() for optimization: we first do the
 952 * sanity checks (buffer size -fast- and access check-healthy
 953 * pointer); if all of those succeed, then we can alloc the memory
 954 * (expensive operation) needed to copy the data to kernel. Then we do
 955 * the copying without checking the user space area
 956 * (__copy_from_user()).
 957 *
 958 * On exit there is no need to do sockfd_put(), sys_setsockopt() does
 959 * it.
 960 *
 961 * sk        The sk of the socket
 962 * addrs     The pointer to the addresses in user land
 963 * addrssize Size of the addrs buffer
 964 * op        Operation to perform (add or remove, see the flags of
 965 *           sctp_bindx)
 966 *
 967 * Returns 0 if ok, <0 errno code on error.
 968 */
 969static int sctp_setsockopt_bindx(struct sock *sk,
 970                                 struct sockaddr __user *addrs,
 971                                 int addrs_size, int op)
 972{
 973        struct sockaddr *kaddrs;
 974        int err;
 975        int addrcnt = 0;
 976        int walk_size = 0;
 977        struct sockaddr *sa_addr;
 978        void *addr_buf;
 979        struct sctp_af *af;
 980
 981        pr_debug("%s: sk:%p addrs:%p addrs_size:%d opt:%d\n",
 982                 __func__, sk, addrs, addrs_size, op);
 983
 984        if (unlikely(addrs_size <= 0))
 985                return -EINVAL;
 986
 987        /* Check the user passed a healthy pointer.  */
 988        if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
 989                return -EFAULT;
 990
 991        /* Alloc space for the address array in kernel memory.  */
 992        kaddrs = kmalloc(addrs_size, GFP_USER | __GFP_NOWARN);
 993        if (unlikely(!kaddrs))
 994                return -ENOMEM;
 995
 996        if (__copy_from_user(kaddrs, addrs, addrs_size)) {
 997                kfree(kaddrs);
 998                return -EFAULT;
 999        }
1000
1001        /* Walk through the addrs buffer and count the number of addresses. */
1002        addr_buf = kaddrs;
1003        while (walk_size < addrs_size) {
1004                if (walk_size + sizeof(sa_family_t) > addrs_size) {
1005                        kfree(kaddrs);
1006                        return -EINVAL;
1007                }
1008
1009                sa_addr = addr_buf;
1010                af = sctp_get_af_specific(sa_addr->sa_family);
1011
1012                /* If the address family is not supported or if this address
1013                 * causes the address buffer to overflow return EINVAL.
1014                 */
1015                if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1016                        kfree(kaddrs);
1017                        return -EINVAL;
1018                }
1019                addrcnt++;
1020                addr_buf += af->sockaddr_len;
1021                walk_size += af->sockaddr_len;
1022        }
1023
1024        /* Do the work. */
1025        switch (op) {
1026        case SCTP_BINDX_ADD_ADDR:
1027                err = sctp_bindx_add(sk, kaddrs, addrcnt);
1028                if (err)
1029                        goto out;
1030                err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt);
1031                break;
1032
1033        case SCTP_BINDX_REM_ADDR:
1034                err = sctp_bindx_rem(sk, kaddrs, addrcnt);
1035                if (err)
1036                        goto out;
1037                err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt);
1038                break;
1039
1040        default:
1041                err = -EINVAL;
1042                break;
1043        }
1044
1045out:
1046        kfree(kaddrs);
1047
1048        return err;
1049}
1050
1051/* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size)
1052 *
1053 * Common routine for handling connect() and sctp_connectx().
1054 * Connect will come in with just a single address.
1055 */
1056static int __sctp_connect(struct sock *sk,
1057                          struct sockaddr *kaddrs,
1058                          int addrs_size,
1059                          sctp_assoc_t *assoc_id)
1060{
1061        struct net *net = sock_net(sk);
1062        struct sctp_sock *sp;
1063        struct sctp_endpoint *ep;
1064        struct sctp_association *asoc = NULL;
1065        struct sctp_association *asoc2;
1066        struct sctp_transport *transport;
1067        union sctp_addr to;
1068        sctp_scope_t scope;
1069        long timeo;
1070        int err = 0;
1071        int addrcnt = 0;
1072        int walk_size = 0;
1073        union sctp_addr *sa_addr = NULL;
1074        void *addr_buf;
1075        unsigned short port;
1076        unsigned int f_flags = 0;
1077
1078        sp = sctp_sk(sk);
1079        ep = sp->ep;
1080
1081        /* connect() cannot be done on a socket that is already in ESTABLISHED
1082         * state - UDP-style peeled off socket or a TCP-style socket that
1083         * is already connected.
1084         * It cannot be done even on a TCP-style listening socket.
1085         */
1086        if (sctp_sstate(sk, ESTABLISHED) || sctp_sstate(sk, CLOSING) ||
1087            (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {
1088                err = -EISCONN;
1089                goto out_free;
1090        }
1091
1092        /* Walk through the addrs buffer and count the number of addresses. */
1093        addr_buf = kaddrs;
1094        while (walk_size < addrs_size) {
1095                struct sctp_af *af;
1096
1097                if (walk_size + sizeof(sa_family_t) > addrs_size) {
1098                        err = -EINVAL;
1099                        goto out_free;
1100                }
1101
1102                sa_addr = addr_buf;
1103                af = sctp_get_af_specific(sa_addr->sa.sa_family);
1104
1105                /* If the address family is not supported or if this address
1106                 * causes the address buffer to overflow return EINVAL.
1107                 */
1108                if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1109                        err = -EINVAL;
1110                        goto out_free;
1111                }
1112
1113                port = ntohs(sa_addr->v4.sin_port);
1114
1115                /* Save current address so we can work with it */
1116                memcpy(&to, sa_addr, af->sockaddr_len);
1117
1118                err = sctp_verify_addr(sk, &to, af->sockaddr_len);
1119                if (err)
1120                        goto out_free;
1121
1122                /* Make sure the destination port is correctly set
1123                 * in all addresses.
1124                 */
1125                if (asoc && asoc->peer.port && asoc->peer.port != port) {
1126                        err = -EINVAL;
1127                        goto out_free;
1128                }
1129
1130                /* Check if there already is a matching association on the
1131                 * endpoint (other than the one created here).
1132                 */
1133                asoc2 = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1134                if (asoc2 && asoc2 != asoc) {
1135                        if (asoc2->state >= SCTP_STATE_ESTABLISHED)
1136                                err = -EISCONN;
1137                        else
1138                                err = -EALREADY;
1139                        goto out_free;
1140                }
1141
1142                /* If we could not find a matching association on the endpoint,
1143                 * make sure that there is no peeled-off association matching
1144                 * the peer address even on another socket.
1145                 */
1146                if (sctp_endpoint_is_peeled_off(ep, &to)) {
1147                        err = -EADDRNOTAVAIL;
1148                        goto out_free;
1149                }
1150
1151                if (!asoc) {
1152                        /* If a bind() or sctp_bindx() is not called prior to
1153                         * an sctp_connectx() call, the system picks an
1154                         * ephemeral port and will choose an address set
1155                         * equivalent to binding with a wildcard address.
1156                         */
1157                        if (!ep->base.bind_addr.port) {
1158                                if (sctp_autobind(sk)) {
1159                                        err = -EAGAIN;
1160                                        goto out_free;
1161                                }
1162                        } else {
1163                                /*
1164                                 * If an unprivileged user inherits a 1-many
1165                                 * style socket with open associations on a
1166                                 * privileged port, it MAY be permitted to
1167                                 * accept new associations, but it SHOULD NOT
1168                                 * be permitted to open new associations.
1169                                 */
1170                                if (ep->base.bind_addr.port < PROT_SOCK &&
1171                                    !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
1172                                        err = -EACCES;
1173                                        goto out_free;
1174                                }
1175                        }
1176
1177                        scope = sctp_scope(&to);
1178                        asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1179                        if (!asoc) {
1180                                err = -ENOMEM;
1181                                goto out_free;
1182                        }
1183
1184                        err = sctp_assoc_set_bind_addr_from_ep(asoc, scope,
1185                                                              GFP_KERNEL);
1186                        if (err < 0) {
1187                                goto out_free;
1188                        }
1189
1190                }
1191
1192                /* Prime the peer's transport structures.  */
1193                transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL,
1194                                                SCTP_UNKNOWN);
1195                if (!transport) {
1196                        err = -ENOMEM;
1197                        goto out_free;
1198                }
1199
1200                addrcnt++;
1201                addr_buf += af->sockaddr_len;
1202                walk_size += af->sockaddr_len;
1203        }
1204
1205        /* In case the user of sctp_connectx() wants an association
1206         * id back, assign one now.
1207         */
1208        if (assoc_id) {
1209                err = sctp_assoc_set_id(asoc, GFP_KERNEL);
1210                if (err < 0)
1211                        goto out_free;
1212        }
1213
1214        err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
1215        if (err < 0) {
1216                goto out_free;
1217        }
1218
1219        /* Initialize sk's dport and daddr for getpeername() */
1220        inet_sk(sk)->inet_dport = htons(asoc->peer.port);
1221        sp->pf->to_sk_daddr(sa_addr, sk);
1222        sk->sk_err = 0;
1223
1224        /* in-kernel sockets don't generally have a file allocated to them
1225         * if all they do is call sock_create_kern().
1226         */
1227        if (sk->sk_socket->file)
1228                f_flags = sk->sk_socket->file->f_flags;
1229
1230        timeo = sock_sndtimeo(sk, f_flags & O_NONBLOCK);
1231
1232        if (assoc_id)
1233                *assoc_id = asoc->assoc_id;
1234        err = sctp_wait_for_connect(asoc, &timeo);
1235        /* Note: the asoc may be freed after the return of
1236         * sctp_wait_for_connect.
1237         */
1238
1239        /* Don't free association on exit. */
1240        asoc = NULL;
1241
1242out_free:
1243        pr_debug("%s: took out_free path with asoc:%p kaddrs:%p err:%d\n",
1244                 __func__, asoc, kaddrs, err);
1245
1246        if (asoc) {
1247                /* sctp_primitive_ASSOCIATE may have added this association
1248                 * To the hash table, try to unhash it, just in case, its a noop
1249                 * if it wasn't hashed so we're safe
1250                 */
1251                sctp_association_free(asoc);
1252        }
1253        return err;
1254}
1255
1256/* Helper for tunneling sctp_connectx() requests through sctp_setsockopt()
1257 *
1258 * API 8.9
1259 * int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt,
1260 *                      sctp_assoc_t *asoc);
1261 *
1262 * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
1263 * If the sd is an IPv6 socket, the addresses passed can either be IPv4
1264 * or IPv6 addresses.
1265 *
1266 * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
1267 * Section 3.1.2 for this usage.
1268 *
1269 * addrs is a pointer to an array of one or more socket addresses. Each
1270 * address is contained in its appropriate structure (i.e. struct
1271 * sockaddr_in or struct sockaddr_in6) the family of the address type
1272 * must be used to distengish the address length (note that this
1273 * representation is termed a "packed array" of addresses). The caller
1274 * specifies the number of addresses in the array with addrcnt.
1275 *
1276 * On success, sctp_connectx() returns 0. It also sets the assoc_id to
1277 * the association id of the new association.  On failure, sctp_connectx()
1278 * returns -1, and sets errno to the appropriate error code.  The assoc_id
1279 * is not touched by the kernel.
1280 *
1281 * For SCTP, the port given in each socket address must be the same, or
1282 * sctp_connectx() will fail, setting errno to EINVAL.
1283 *
1284 * An application can use sctp_connectx to initiate an association with
1285 * an endpoint that is multi-homed.  Much like sctp_bindx() this call
1286 * allows a caller to specify multiple addresses at which a peer can be
1287 * reached.  The way the SCTP stack uses the list of addresses to set up
1288 * the association is implementation dependent.  This function only
1289 * specifies that the stack will try to make use of all the addresses in
1290 * the list when needed.
1291 *
1292 * Note that the list of addresses passed in is only used for setting up
1293 * the association.  It does not necessarily equal the set of addresses
1294 * the peer uses for the resulting association.  If the caller wants to
1295 * find out the set of peer addresses, it must use sctp_getpaddrs() to
1296 * retrieve them after the association has been set up.
1297 *
1298 * Basically do nothing but copying the addresses from user to kernel
1299 * land and invoking either sctp_connectx(). This is used for tunneling
1300 * the sctp_connectx() request through sctp_setsockopt() from userspace.
1301 *
1302 * We don't use copy_from_user() for optimization: we first do the
1303 * sanity checks (buffer size -fast- and access check-healthy
1304 * pointer); if all of those succeed, then we can alloc the memory
1305 * (expensive operation) needed to copy the data to kernel. Then we do
1306 * the copying without checking the user space area
1307 * (__copy_from_user()).
1308 *
1309 * On exit there is no need to do sockfd_put(), sys_setsockopt() does
1310 * it.
1311 *
1312 * sk        The sk of the socket
1313 * addrs     The pointer to the addresses in user land
1314 * addrssize Size of the addrs buffer
1315 *
1316 * Returns >=0 if ok, <0 errno code on error.
1317 */
1318static int __sctp_setsockopt_connectx(struct sock *sk,
1319                                      struct sockaddr __user *addrs,
1320                                      int addrs_size,
1321                                      sctp_assoc_t *assoc_id)
1322{
1323        struct sockaddr *kaddrs;
1324        gfp_t gfp = GFP_KERNEL;
1325        int err = 0;
1326
1327        pr_debug("%s: sk:%p addrs:%p addrs_size:%d\n",
1328                 __func__, sk, addrs, addrs_size);
1329
1330        if (unlikely(addrs_size <= 0))
1331                return -EINVAL;
1332
1333        /* Check the user passed a healthy pointer.  */
1334        if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
1335                return -EFAULT;
1336
1337        /* Alloc space for the address array in kernel memory.  */
1338        if (sk->sk_socket->file)
1339                gfp = GFP_USER | __GFP_NOWARN;
1340        kaddrs = kmalloc(addrs_size, gfp);
1341        if (unlikely(!kaddrs))
1342                return -ENOMEM;
1343
1344        if (__copy_from_user(kaddrs, addrs, addrs_size)) {
1345                err = -EFAULT;
1346        } else {
1347                err = __sctp_connect(sk, kaddrs, addrs_size, assoc_id);
1348        }
1349
1350        kfree(kaddrs);
1351
1352        return err;
1353}
1354
1355/*
1356 * This is an older interface.  It's kept for backward compatibility
1357 * to the option that doesn't provide association id.
1358 */
1359static int sctp_setsockopt_connectx_old(struct sock *sk,
1360                                        struct sockaddr __user *addrs,
1361                                        int addrs_size)
1362{
1363        return __sctp_setsockopt_connectx(sk, addrs, addrs_size, NULL);
1364}
1365
1366/*
1367 * New interface for the API.  The since the API is done with a socket
1368 * option, to make it simple we feed back the association id is as a return
1369 * indication to the call.  Error is always negative and association id is
1370 * always positive.
1371 */
1372static int sctp_setsockopt_connectx(struct sock *sk,
1373                                    struct sockaddr __user *addrs,
1374                                    int addrs_size)
1375{
1376        sctp_assoc_t assoc_id = 0;
1377        int err = 0;
1378
1379        err = __sctp_setsockopt_connectx(sk, addrs, addrs_size, &assoc_id);
1380
1381        if (err)
1382                return err;
1383        else
1384                return assoc_id;
1385}
1386
1387/*
1388 * New (hopefully final) interface for the API.
1389 * We use the sctp_getaddrs_old structure so that use-space library
1390 * can avoid any unnecessary allocations. The only different part
1391 * is that we store the actual length of the address buffer into the
1392 * addrs_num structure member. That way we can re-use the existing
1393 * code.
1394 */
1395#ifdef CONFIG_COMPAT
1396struct compat_sctp_getaddrs_old {
1397        sctp_assoc_t    assoc_id;
1398        s32             addr_num;
1399        compat_uptr_t   addrs;          /* struct sockaddr * */
1400};
1401#endif
1402
1403static int sctp_getsockopt_connectx3(struct sock *sk, int len,
1404                                     char __user *optval,
1405                                     int __user *optlen)
1406{
1407        struct sctp_getaddrs_old param;
1408        sctp_assoc_t assoc_id = 0;
1409        int err = 0;
1410
1411#ifdef CONFIG_COMPAT
1412        if (in_compat_syscall()) {
1413                struct compat_sctp_getaddrs_old param32;
1414
1415                if (len < sizeof(param32))
1416                        return -EINVAL;
1417                if (copy_from_user(&param32, optval, sizeof(param32)))
1418                        return -EFAULT;
1419
1420                param.assoc_id = param32.assoc_id;
1421                param.addr_num = param32.addr_num;
1422                param.addrs = compat_ptr(param32.addrs);
1423        } else
1424#endif
1425        {
1426                if (len < sizeof(param))
1427                        return -EINVAL;
1428                if (copy_from_user(&param, optval, sizeof(param)))
1429                        return -EFAULT;
1430        }
1431
1432        err = __sctp_setsockopt_connectx(sk, (struct sockaddr __user *)
1433                                         param.addrs, param.addr_num,
1434                                         &assoc_id);
1435        if (err == 0 || err == -EINPROGRESS) {
1436                if (copy_to_user(optval, &assoc_id, sizeof(assoc_id)))
1437                        return -EFAULT;
1438                if (put_user(sizeof(assoc_id), optlen))
1439                        return -EFAULT;
1440        }
1441
1442        return err;
1443}
1444
1445/* API 3.1.4 close() - UDP Style Syntax
1446 * Applications use close() to perform graceful shutdown (as described in
1447 * Section 10.1 of [SCTP]) on ALL the associations currently represented
1448 * by a UDP-style socket.
1449 *
1450 * The syntax is
1451 *
1452 *   ret = close(int sd);
1453 *
1454 *   sd      - the socket descriptor of the associations to be closed.
1455 *
1456 * To gracefully shutdown a specific association represented by the
1457 * UDP-style socket, an application should use the sendmsg() call,
1458 * passing no user data, but including the appropriate flag in the
1459 * ancillary data (see Section xxxx).
1460 *
1461 * If sd in the close() call is a branched-off socket representing only
1462 * one association, the shutdown is performed on that association only.
1463 *
1464 * 4.1.6 close() - TCP Style Syntax
1465 *
1466 * Applications use close() to gracefully close down an association.
1467 *
1468 * The syntax is:
1469 *
1470 *    int close(int sd);
1471 *
1472 *      sd      - the socket descriptor of the association to be closed.
1473 *
1474 * After an application calls close() on a socket descriptor, no further
1475 * socket operations will succeed on that descriptor.
1476 *
1477 * API 7.1.4 SO_LINGER
1478 *
1479 * An application using the TCP-style socket can use this option to
1480 * perform the SCTP ABORT primitive.  The linger option structure is:
1481 *
1482 *  struct  linger {
1483 *     int     l_onoff;                // option on/off
1484 *     int     l_linger;               // linger time
1485 * };
1486 *
1487 * To enable the option, set l_onoff to 1.  If the l_linger value is set
1488 * to 0, calling close() is the same as the ABORT primitive.  If the
1489 * value is set to a negative value, the setsockopt() call will return
1490 * an error.  If the value is set to a positive value linger_time, the
1491 * close() can be blocked for at most linger_time ms.  If the graceful
1492 * shutdown phase does not finish during this period, close() will
1493 * return but the graceful shutdown phase continues in the system.
1494 */
1495static void sctp_close(struct sock *sk, long timeout)
1496{
1497        struct net *net = sock_net(sk);
1498        struct sctp_endpoint *ep;
1499        struct sctp_association *asoc;
1500        struct list_head *pos, *temp;
1501        unsigned int data_was_unread;
1502
1503        pr_debug("%s: sk:%p, timeout:%ld\n", __func__, sk, timeout);
1504
1505        lock_sock(sk);
1506        sk->sk_shutdown = SHUTDOWN_MASK;
1507        sk->sk_state = SCTP_SS_CLOSING;
1508
1509        ep = sctp_sk(sk)->ep;
1510
1511        /* Clean up any skbs sitting on the receive queue.  */
1512        data_was_unread = sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
1513        data_was_unread += sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
1514
1515        /* Walk all associations on an endpoint.  */
1516        list_for_each_safe(pos, temp, &ep->asocs) {
1517                asoc = list_entry(pos, struct sctp_association, asocs);
1518
1519                if (sctp_style(sk, TCP)) {
1520                        /* A closed association can still be in the list if
1521                         * it belongs to a TCP-style listening socket that is
1522                         * not yet accepted. If so, free it. If not, send an
1523                         * ABORT or SHUTDOWN based on the linger options.
1524                         */
1525                        if (sctp_state(asoc, CLOSED)) {
1526                                sctp_association_free(asoc);
1527                                continue;
1528                        }
1529                }
1530
1531                if (data_was_unread || !skb_queue_empty(&asoc->ulpq.lobby) ||
1532                    !skb_queue_empty(&asoc->ulpq.reasm) ||
1533                    (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime)) {
1534                        struct sctp_chunk *chunk;
1535
1536                        chunk = sctp_make_abort_user(asoc, NULL, 0);
1537                        sctp_primitive_ABORT(net, asoc, chunk);
1538                } else
1539                        sctp_primitive_SHUTDOWN(net, asoc, NULL);
1540        }
1541
1542        /* On a TCP-style socket, block for at most linger_time if set. */
1543        if (sctp_style(sk, TCP) && timeout)
1544                sctp_wait_for_close(sk, timeout);
1545
1546        /* This will run the backlog queue.  */
1547        release_sock(sk);
1548
1549        /* Supposedly, no process has access to the socket, but
1550         * the net layers still may.
1551         * Also, sctp_destroy_sock() needs to be called with addr_wq_lock
1552         * held and that should be grabbed before socket lock.
1553         */
1554        spin_lock_bh(&net->sctp.addr_wq_lock);
1555        bh_lock_sock(sk);
1556
1557        /* Hold the sock, since sk_common_release() will put sock_put()
1558         * and we have just a little more cleanup.
1559         */
1560        sock_hold(sk);
1561        sk_common_release(sk);
1562
1563        bh_unlock_sock(sk);
1564        spin_unlock_bh(&net->sctp.addr_wq_lock);
1565
1566        sock_put(sk);
1567
1568        SCTP_DBG_OBJCNT_DEC(sock);
1569}
1570
1571/* Handle EPIPE error. */
1572static int sctp_error(struct sock *sk, int flags, int err)
1573{
1574        if (err == -EPIPE)
1575                err = sock_error(sk) ? : -EPIPE;
1576        if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
1577                send_sig(SIGPIPE, current, 0);
1578        return err;
1579}
1580
1581/* API 3.1.3 sendmsg() - UDP Style Syntax
1582 *
1583 * An application uses sendmsg() and recvmsg() calls to transmit data to
1584 * and receive data from its peer.
1585 *
1586 *  ssize_t sendmsg(int socket, const struct msghdr *message,
1587 *                  int flags);
1588 *
1589 *  socket  - the socket descriptor of the endpoint.
1590 *  message - pointer to the msghdr structure which contains a single
1591 *            user message and possibly some ancillary data.
1592 *
1593 *            See Section 5 for complete description of the data
1594 *            structures.
1595 *
1596 *  flags   - flags sent or received with the user message, see Section
1597 *            5 for complete description of the flags.
1598 *
1599 * Note:  This function could use a rewrite especially when explicit
1600 * connect support comes in.
1601 */
1602/* BUG:  We do not implement the equivalent of sk_stream_wait_memory(). */
1603
1604static int sctp_msghdr_parse(const struct msghdr *, sctp_cmsgs_t *);
1605
1606static int sctp_sendmsg(struct kiocb *iocb, struct sock *sk,
1607                        struct msghdr *msg, size_t msg_len)
1608{
1609        struct net *net = sock_net(sk);
1610        struct sctp_sock *sp;
1611        struct sctp_endpoint *ep;
1612        struct sctp_association *new_asoc = NULL, *asoc = NULL;
1613        struct sctp_transport *transport, *chunk_tp;
1614        struct sctp_chunk *chunk;
1615        union sctp_addr to;
1616        struct sockaddr *msg_name = NULL;
1617        struct sctp_sndrcvinfo default_sinfo;
1618        struct sctp_sndrcvinfo *sinfo;
1619        struct sctp_initmsg *sinit;
1620        sctp_assoc_t associd = 0;
1621        sctp_cmsgs_t cmsgs = { NULL };
1622        sctp_scope_t scope;
1623        bool fill_sinfo_ttl = false, wait_connect = false;
1624        struct sctp_datamsg *datamsg;
1625        int msg_flags = msg->msg_flags;
1626        __u16 sinfo_flags = 0;
1627        long timeo;
1628        int err;
1629
1630        err = 0;
1631        sp = sctp_sk(sk);
1632        ep = sp->ep;
1633
1634        pr_debug("%s: sk:%p, msg:%p, msg_len:%zu ep:%p\n", __func__, sk,
1635                 msg, msg_len, ep);
1636
1637        /* We cannot send a message over a TCP-style listening socket. */
1638        if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) {
1639                err = -EPIPE;
1640                goto out_nounlock;
1641        }
1642
1643        /* Parse out the SCTP CMSGs.  */
1644        err = sctp_msghdr_parse(msg, &cmsgs);
1645        if (err) {
1646                pr_debug("%s: msghdr parse err:%x\n", __func__, err);
1647                goto out_nounlock;
1648        }
1649
1650        /* Fetch the destination address for this packet.  This
1651         * address only selects the association--it is not necessarily
1652         * the address we will send to.
1653         * For a peeled-off socket, msg_name is ignored.
1654         */
1655        if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
1656                int msg_namelen = msg->msg_namelen;
1657
1658                err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name,
1659                                       msg_namelen);
1660                if (err)
1661                        return err;
1662
1663                if (msg_namelen > sizeof(to))
1664                        msg_namelen = sizeof(to);
1665                memcpy(&to, msg->msg_name, msg_namelen);
1666                msg_name = msg->msg_name;
1667        }
1668
1669        sinit = cmsgs.init;
1670        if (cmsgs.sinfo != NULL) {
1671                memset(&default_sinfo, 0, sizeof(default_sinfo));
1672                default_sinfo.sinfo_stream = cmsgs.sinfo->snd_sid;
1673                default_sinfo.sinfo_flags = cmsgs.sinfo->snd_flags;
1674                default_sinfo.sinfo_ppid = cmsgs.sinfo->snd_ppid;
1675                default_sinfo.sinfo_context = cmsgs.sinfo->snd_context;
1676                default_sinfo.sinfo_assoc_id = cmsgs.sinfo->snd_assoc_id;
1677
1678                sinfo = &default_sinfo;
1679                fill_sinfo_ttl = true;
1680        } else {
1681                sinfo = cmsgs.srinfo;
1682        }
1683        /* Did the user specify SNDINFO/SNDRCVINFO? */
1684        if (sinfo) {
1685                sinfo_flags = sinfo->sinfo_flags;
1686                associd = sinfo->sinfo_assoc_id;
1687        }
1688
1689        pr_debug("%s: msg_len:%zu, sinfo_flags:0x%x\n", __func__,
1690                 msg_len, sinfo_flags);
1691
1692        /* SCTP_EOF or SCTP_ABORT cannot be set on a TCP-style socket. */
1693        if (sctp_style(sk, TCP) && (sinfo_flags & (SCTP_EOF | SCTP_ABORT))) {
1694                err = -EINVAL;
1695                goto out_nounlock;
1696        }
1697
1698        /* If SCTP_EOF is set, no data can be sent. Disallow sending zero
1699         * length messages when SCTP_EOF|SCTP_ABORT is not set.
1700         * If SCTP_ABORT is set, the message length could be non zero with
1701         * the msg_iov set to the user abort reason.
1702         */
1703        if (((sinfo_flags & SCTP_EOF) && (msg_len > 0)) ||
1704            (!(sinfo_flags & (SCTP_EOF|SCTP_ABORT)) && (msg_len == 0))) {
1705                err = -EINVAL;
1706                goto out_nounlock;
1707        }
1708
1709        /* If SCTP_ADDR_OVER is set, there must be an address
1710         * specified in msg_name.
1711         */
1712        if ((sinfo_flags & SCTP_ADDR_OVER) && (!msg->msg_name)) {
1713                err = -EINVAL;
1714                goto out_nounlock;
1715        }
1716
1717        transport = NULL;
1718
1719        pr_debug("%s: about to look up association\n", __func__);
1720
1721        lock_sock(sk);
1722
1723        /* If a msg_name has been specified, assume this is to be used.  */
1724        if (msg_name) {
1725                /* Look for a matching association on the endpoint. */
1726                asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1727
1728                /* If we could not find a matching association on the
1729                 * endpoint, make sure that it is not a TCP-style
1730                 * socket that already has an association or there is
1731                 * no peeled-off association on another socket.
1732                 */
1733                if (!asoc &&
1734                    ((sctp_style(sk, TCP) &&
1735                      (sctp_sstate(sk, ESTABLISHED) ||
1736                       sctp_sstate(sk, CLOSING))) ||
1737                     sctp_endpoint_is_peeled_off(ep, &to))) {
1738                        err = -EADDRNOTAVAIL;
1739                        goto out_unlock;
1740                }
1741        } else {
1742                asoc = sctp_id2assoc(sk, associd);
1743                if (!asoc) {
1744                        err = -EPIPE;
1745                        goto out_unlock;
1746                }
1747        }
1748
1749        if (asoc) {
1750                pr_debug("%s: just looked up association:%p\n", __func__, asoc);
1751
1752                /* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED
1753                 * socket that has an association in CLOSED state. This can
1754                 * happen when an accepted socket has an association that is
1755                 * already CLOSED.
1756                 */
1757                if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) {
1758                        err = -EPIPE;
1759                        goto out_unlock;
1760                }
1761
1762                if (sinfo_flags & SCTP_EOF) {
1763                        pr_debug("%s: shutting down association:%p\n",
1764                                 __func__, asoc);
1765
1766                        sctp_primitive_SHUTDOWN(net, asoc, NULL);
1767                        err = 0;
1768                        goto out_unlock;
1769                }
1770                if (sinfo_flags & SCTP_ABORT) {
1771
1772                        chunk = sctp_make_abort_user(asoc, msg, msg_len);
1773                        if (!chunk) {
1774                                err = -ENOMEM;
1775                                goto out_unlock;
1776                        }
1777
1778                        pr_debug("%s: aborting association:%p\n",
1779                                 __func__, asoc);
1780
1781                        sctp_primitive_ABORT(net, asoc, chunk);
1782                        err = 0;
1783                        goto out_unlock;
1784                }
1785        }
1786
1787        /* Do we need to create the association?  */
1788        if (!asoc) {
1789                pr_debug("%s: there is no association yet\n", __func__);
1790
1791                if (sinfo_flags & (SCTP_EOF | SCTP_ABORT)) {
1792                        err = -EINVAL;
1793                        goto out_unlock;
1794                }
1795
1796                /* Check for invalid stream against the stream counts,
1797                 * either the default or the user specified stream counts.
1798                 */
1799                if (sinfo) {
1800                        if (!sinit || (sinit && !sinit->sinit_num_ostreams)) {
1801                                /* Check against the defaults. */
1802                                if (sinfo->sinfo_stream >=
1803                                    sp->initmsg.sinit_num_ostreams) {
1804                                        err = -EINVAL;
1805                                        goto out_unlock;
1806                                }
1807                        } else {
1808                                /* Check against the requested.  */
1809                                if (sinfo->sinfo_stream >=
1810                                    sinit->sinit_num_ostreams) {
1811                                        err = -EINVAL;
1812                                        goto out_unlock;
1813                                }
1814                        }
1815                }
1816
1817                /*
1818                 * API 3.1.2 bind() - UDP Style Syntax
1819                 * If a bind() or sctp_bindx() is not called prior to a
1820                 * sendmsg() call that initiates a new association, the
1821                 * system picks an ephemeral port and will choose an address
1822                 * set equivalent to binding with a wildcard address.
1823                 */
1824                if (!ep->base.bind_addr.port) {
1825                        if (sctp_autobind(sk)) {
1826                                err = -EAGAIN;
1827                                goto out_unlock;
1828                        }
1829                } else {
1830                        /*
1831                         * If an unprivileged user inherits a one-to-many
1832                         * style socket with open associations on a privileged
1833                         * port, it MAY be permitted to accept new associations,
1834                         * but it SHOULD NOT be permitted to open new
1835                         * associations.
1836                         */
1837                        if (ep->base.bind_addr.port < PROT_SOCK &&
1838                            !ns_capable(net->user_ns, CAP_NET_BIND_SERVICE)) {
1839                                err = -EACCES;
1840                                goto out_unlock;
1841                        }
1842                }
1843
1844                scope = sctp_scope(&to);
1845                new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1846                if (!new_asoc) {
1847                        err = -ENOMEM;
1848                        goto out_unlock;
1849                }
1850                asoc = new_asoc;
1851                err = sctp_assoc_set_bind_addr_from_ep(asoc, scope, GFP_KERNEL);
1852                if (err < 0) {
1853                        err = -ENOMEM;
1854                        goto out_free;
1855                }
1856
1857                /* If the SCTP_INIT ancillary data is specified, set all
1858                 * the association init values accordingly.
1859                 */
1860                if (sinit) {
1861                        if (sinit->sinit_num_ostreams) {
1862                                asoc->c.sinit_num_ostreams =
1863                                        sinit->sinit_num_ostreams;
1864                        }
1865                        if (sinit->sinit_max_instreams) {
1866                                asoc->c.sinit_max_instreams =
1867                                        sinit->sinit_max_instreams;
1868                        }
1869                        if (sinit->sinit_max_attempts) {
1870                                asoc->max_init_attempts
1871                                        = sinit->sinit_max_attempts;
1872                        }
1873                        if (sinit->sinit_max_init_timeo) {
1874                                asoc->max_init_timeo =
1875                                 msecs_to_jiffies(sinit->sinit_max_init_timeo);
1876                        }
1877                }
1878
1879                /* Prime the peer's transport structures.  */
1880                transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, SCTP_UNKNOWN);
1881                if (!transport) {
1882                        err = -ENOMEM;
1883                        goto out_free;
1884                }
1885        }
1886
1887        /* ASSERT: we have a valid association at this point.  */
1888        pr_debug("%s: we have a valid association\n", __func__);
1889
1890        if (!sinfo) {
1891                /* If the user didn't specify SNDINFO/SNDRCVINFO, make up
1892                 * one with some defaults.
1893                 */
1894                memset(&default_sinfo, 0, sizeof(default_sinfo));
1895                default_sinfo.sinfo_stream = asoc->default_stream;
1896                default_sinfo.sinfo_flags = asoc->default_flags;
1897                default_sinfo.sinfo_ppid = asoc->default_ppid;
1898                default_sinfo.sinfo_context = asoc->default_context;
1899                default_sinfo.sinfo_timetolive = asoc->default_timetolive;
1900                default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc);
1901
1902                sinfo = &default_sinfo;
1903        } else if (fill_sinfo_ttl) {
1904                /* In case SNDINFO was specified, we still need to fill
1905                 * it with a default ttl from the assoc here.
1906                 */
1907                sinfo->sinfo_timetolive = asoc->default_timetolive;
1908        }
1909
1910        /* API 7.1.7, the sndbuf size per association bounds the
1911         * maximum size of data that can be sent in a single send call.
1912         */
1913        if (msg_len > sk->sk_sndbuf) {
1914                err = -EMSGSIZE;
1915                goto out_free;
1916        }
1917
1918        if (asoc->pmtu_pending)
1919                sctp_assoc_pending_pmtu(asoc);
1920
1921        /* If fragmentation is disabled and the message length exceeds the
1922         * association fragmentation point, return EMSGSIZE.  The I-D
1923         * does not specify what this error is, but this looks like
1924         * a great fit.
1925         */
1926        if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) {
1927                err = -EMSGSIZE;
1928                goto out_free;
1929        }
1930
1931        /* Check for invalid stream. */
1932        if (sinfo->sinfo_stream >= asoc->c.sinit_num_ostreams) {
1933                err = -EINVAL;
1934                goto out_free;
1935        }
1936
1937        if (sctp_wspace(asoc) < msg_len)
1938                sctp_prsctp_prune(asoc, sinfo, msg_len - sctp_wspace(asoc));
1939
1940        timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1941        if (!sctp_wspace(asoc)) {
1942                err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len);
1943                if (err)
1944                        goto out_free;
1945        }
1946
1947        /* If an address is passed with the sendto/sendmsg call, it is used
1948         * to override the primary destination address in the TCP model, or
1949         * when SCTP_ADDR_OVER flag is set in the UDP model.
1950         */
1951        if ((sctp_style(sk, TCP) && msg_name) ||
1952            (sinfo_flags & SCTP_ADDR_OVER)) {
1953                chunk_tp = sctp_assoc_lookup_paddr(asoc, &to);
1954                if (!chunk_tp) {
1955                        err = -EINVAL;
1956                        goto out_free;
1957                }
1958        } else
1959                chunk_tp = NULL;
1960
1961        /* Auto-connect, if we aren't connected already. */
1962        if (sctp_state(asoc, CLOSED)) {
1963                err = sctp_primitive_ASSOCIATE(net, asoc, NULL);
1964                if (err < 0)
1965                        goto out_free;
1966                wait_connect = true;
1967                pr_debug("%s: we associated primitively\n", __func__);
1968        }
1969
1970        /* Break the message into multiple chunks of maximum size. */
1971        datamsg = sctp_datamsg_from_user(asoc, sinfo, msg, msg_len);
1972        if (IS_ERR(datamsg)) {
1973                err = PTR_ERR(datamsg);
1974                goto out_free;
1975        }
1976        asoc->force_delay = !!(msg->msg_flags & MSG_MORE);
1977
1978        /* Now send the (possibly) fragmented message. */
1979        list_for_each_entry(chunk, &datamsg->chunks, frag_list) {
1980                sctp_chunk_hold(chunk);
1981
1982                /* Do accounting for the write space.  */
1983                sctp_set_owner_w(chunk);
1984
1985                chunk->transport = chunk_tp;
1986        }
1987
1988        /* Send it to the lower layers.  Note:  all chunks
1989         * must either fail or succeed.   The lower layer
1990         * works that way today.  Keep it that way or this
1991         * breaks.
1992         */
1993        err = sctp_primitive_SEND(net, asoc, datamsg);
1994        /* Did the lower layer accept the chunk? */
1995        if (err) {
1996                sctp_datamsg_free(datamsg);
1997                goto out_free;
1998        }
1999
2000        pr_debug("%s: we sent primitively\n", __func__);
2001
2002        sctp_datamsg_put(datamsg);
2003        err = msg_len;
2004
2005        if (unlikely(wait_connect)) {
2006                timeo = sock_sndtimeo(sk, msg_flags & MSG_DONTWAIT);
2007                sctp_wait_for_connect(asoc, &timeo);
2008        }
2009
2010        /* If we are already past ASSOCIATE, the lower
2011         * layers are responsible for association cleanup.
2012         */
2013        goto out_unlock;
2014
2015out_free:
2016        if (new_asoc)
2017                sctp_association_free(asoc);
2018out_unlock:
2019        release_sock(sk);
2020
2021out_nounlock:
2022        return sctp_error(sk, msg_flags, err);
2023
2024#if 0
2025do_sock_err:
2026        if (msg_len)
2027                err = msg_len;
2028        else
2029                err = sock_error(sk);
2030        goto out;
2031
2032do_interrupted:
2033        if (msg_len)
2034                err = msg_len;
2035        goto out;
2036#endif /* 0 */
2037}
2038
2039/* This is an extended version of skb_pull() that removes the data from the
2040 * start of a skb even when data is spread across the list of skb's in the
2041 * frag_list. len specifies the total amount of data that needs to be removed.
2042 * when 'len' bytes could be removed from the skb, it returns 0.
2043 * If 'len' exceeds the total skb length,  it returns the no. of bytes that
2044 * could not be removed.
2045 */
2046static int sctp_skb_pull(struct sk_buff *skb, int len)
2047{
2048        struct sk_buff *list;
2049        int skb_len = skb_headlen(skb);
2050        int rlen;
2051
2052        if (len <= skb_len) {
2053                __skb_pull(skb, len);
2054                return 0;
2055        }
2056        len -= skb_len;
2057        __skb_pull(skb, skb_len);
2058
2059        skb_walk_frags(skb, list) {
2060                rlen = sctp_skb_pull(list, len);
2061                skb->len -= (len-rlen);
2062                skb->data_len -= (len-rlen);
2063
2064                if (!rlen)
2065                        return 0;
2066
2067                len = rlen;
2068        }
2069
2070        return len;
2071}
2072
2073/* API 3.1.3  recvmsg() - UDP Style Syntax
2074 *
2075 *  ssize_t recvmsg(int socket, struct msghdr *message,
2076 *                    int flags);
2077 *
2078 *  socket  - the socket descriptor of the endpoint.
2079 *  message - pointer to the msghdr structure which contains a single
2080 *            user message and possibly some ancillary data.
2081 *
2082 *            See Section 5 for complete description of the data
2083 *            structures.
2084 *
2085 *  flags   - flags sent or received with the user message, see Section
2086 *            5 for complete description of the flags.
2087 */
2088static int sctp_recvmsg(struct kiocb *iocb, struct sock *sk,
2089                        struct msghdr *msg, size_t len, int noblock,
2090                        int flags, int *addr_len)
2091{
2092        struct sctp_ulpevent *event = NULL;
2093        struct sctp_sock *sp = sctp_sk(sk);
2094        struct sk_buff *skb, *head_skb;
2095        int copied;
2096        int err = 0;
2097        int skb_len;
2098
2099        pr_debug("%s: sk:%p, msghdr:%p, len:%zd, noblock:%d, flags:0x%x, "
2100                 "addr_len:%p)\n", __func__, sk, msg, len, noblock, flags,
2101                 addr_len);
2102
2103        lock_sock(sk);
2104
2105        if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED) &&
2106            !sctp_sstate(sk, CLOSING) && !sctp_sstate(sk, CLOSED)) {
2107                err = -ENOTCONN;
2108                goto out;
2109        }
2110
2111        skb = sctp_skb_recv_datagram(sk, flags, noblock, &err);
2112        if (!skb)
2113                goto out;
2114
2115        /* Get the total length of the skb including any skb's in the
2116         * frag_list.
2117         */
2118        skb_len = skb->len;
2119
2120        copied = skb_len;
2121        if (copied > len)
2122                copied = len;
2123
2124        err = skb_copy_datagram_msg(skb, 0, msg, copied);
2125
2126        event = sctp_skb2event(skb);
2127
2128        if (err)
2129                goto out_free;
2130
2131        if (event->chunk && event->chunk->head_skb)
2132                head_skb = event->chunk->head_skb;
2133        else
2134                head_skb = skb;
2135        sock_recv_ts_and_drops(msg, sk, head_skb);
2136        if (sctp_ulpevent_is_notification(event)) {
2137                msg->msg_flags |= MSG_NOTIFICATION;
2138                sp->pf->event_msgname(event, msg->msg_name, addr_len);
2139        } else {
2140                sp->pf->skb_msgname(head_skb, msg->msg_name, addr_len);
2141        }
2142
2143        /* Check if we allow SCTP_NXTINFO. */
2144        if (sp->recvnxtinfo)
2145                sctp_ulpevent_read_nxtinfo(event, msg, sk);
2146        /* Check if we allow SCTP_RCVINFO. */
2147        if (sp->recvrcvinfo)
2148                sctp_ulpevent_read_rcvinfo(event, msg);
2149        /* Check if we allow SCTP_SNDRCVINFO. */
2150        if (sp->subscribe.sctp_data_io_event)
2151                sctp_ulpevent_read_sndrcvinfo(event, msg);
2152
2153#if 0
2154        /* FIXME: we should be calling IP/IPv6 layers.  */
2155        if (sk->sk_protinfo.af_inet.cmsg_flags)
2156                ip_cmsg_recv(msg, skb);
2157#endif
2158
2159        err = copied;
2160
2161        /* If skb's length exceeds the user's buffer, update the skb and
2162         * push it back to the receive_queue so that the next call to
2163         * recvmsg() will return the remaining data. Don't set MSG_EOR.
2164         */
2165        if (skb_len > copied) {
2166                msg->msg_flags &= ~MSG_EOR;
2167                if (flags & MSG_PEEK)
2168                        goto out_free;
2169                sctp_skb_pull(skb, copied);
2170                skb_queue_head(&sk->sk_receive_queue, skb);
2171
2172                /* When only partial message is copied to the user, increase
2173                 * rwnd by that amount. If all the data in the skb is read,
2174                 * rwnd is updated when the event is freed.
2175                 */
2176                if (!sctp_ulpevent_is_notification(event))
2177                        sctp_assoc_rwnd_increase(event->asoc, copied);
2178                goto out;
2179        } else if ((event->msg_flags & MSG_NOTIFICATION) ||
2180                   (event->msg_flags & MSG_EOR))
2181                msg->msg_flags |= MSG_EOR;
2182        else
2183                msg->msg_flags &= ~MSG_EOR;
2184
2185out_free:
2186        if (flags & MSG_PEEK) {
2187                /* Release the skb reference acquired after peeking the skb in
2188                 * sctp_skb_recv_datagram().
2189                 */
2190                kfree_skb(skb);
2191        } else {
2192                /* Free the event which includes releasing the reference to
2193                 * the owner of the skb, freeing the skb and updating the
2194                 * rwnd.
2195                 */
2196                sctp_ulpevent_free(event);
2197        }
2198out:
2199        release_sock(sk);
2200        return err;
2201}
2202
2203/* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
2204 *
2205 * This option is a on/off flag.  If enabled no SCTP message
2206 * fragmentation will be performed.  Instead if a message being sent
2207 * exceeds the current PMTU size, the message will NOT be sent and
2208 * instead a error will be indicated to the user.
2209 */
2210static int sctp_setsockopt_disable_fragments(struct sock *sk,
2211                                             char __user *optval,
2212                                             unsigned int optlen)
2213{
2214        int val;
2215
2216        if (optlen < sizeof(int))
2217                return -EINVAL;
2218
2219        if (get_user(val, (int __user *)optval))
2220                return -EFAULT;
2221
2222        sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1;
2223
2224        return 0;
2225}
2226
2227static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
2228                                  unsigned int optlen)
2229{
2230        struct sctp_association *asoc;
2231        struct sctp_ulpevent *event;
2232
2233        if (optlen > sizeof(struct sctp_event_subscribe))
2234                return -EINVAL;
2235        if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
2236                return -EFAULT;
2237
2238        /*
2239         * At the time when a user app subscribes to SCTP_SENDER_DRY_EVENT,
2240         * if there is no data to be sent or retransmit, the stack will
2241         * immediately send up this notification.
2242         */
2243        if (sctp_ulpevent_type_enabled(SCTP_SENDER_DRY_EVENT,
2244                                       &sctp_sk(sk)->subscribe)) {
2245                asoc = sctp_id2assoc(sk, 0);
2246
2247                if (asoc && sctp_outq_is_empty(&asoc->outqueue)) {
2248                        event = sctp_ulpevent_make_sender_dry_event(asoc,
2249                                        GFP_ATOMIC);
2250                        if (!event)
2251                                return -ENOMEM;
2252
2253                        sctp_ulpq_tail_event(&asoc->ulpq, event);
2254                }
2255        }
2256
2257        return 0;
2258}
2259
2260/* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
2261 *
2262 * This socket option is applicable to the UDP-style socket only.  When
2263 * set it will cause associations that are idle for more than the
2264 * specified number of seconds to automatically close.  An association
2265 * being idle is defined an association that has NOT sent or received
2266 * user data.  The special value of '0' indicates that no automatic
2267 * close of any associations should be performed.  The option expects an
2268 * integer defining the number of seconds of idle time before an
2269 * association is closed.
2270 */
2271static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval,
2272                                     unsigned int optlen)
2273{
2274        struct sctp_sock *sp = sctp_sk(sk);
2275        struct net *net = sock_net(sk);
2276
2277        /* Applicable to UDP-style socket only */
2278        if (sctp_style(sk, TCP))
2279                return -EOPNOTSUPP;
2280        if (optlen != sizeof(int))
2281                return -EINVAL;
2282        if (copy_from_user(&sp->autoclose, optval, optlen))
2283                return -EFAULT;
2284
2285        if (sp->autoclose > net->sctp.max_autoclose)
2286                sp->autoclose = net->sctp.max_autoclose;
2287
2288        return 0;
2289}
2290
2291/* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
2292 *
2293 * Applications can enable or disable heartbeats for any peer address of
2294 * an association, modify an address's heartbeat interval, force a
2295 * heartbeat to be sent immediately, and adjust the address's maximum
2296 * number of retransmissions sent before an address is considered
2297 * unreachable.  The following structure is used to access and modify an
2298 * address's parameters:
2299 *
2300 *  struct sctp_paddrparams {
2301 *     sctp_assoc_t            spp_assoc_id;
2302 *     struct sockaddr_storage spp_address;
2303 *     uint32_t                spp_hbinterval;
2304 *     uint16_t                spp_pathmaxrxt;
2305 *     uint32_t                spp_pathmtu;
2306 *     uint32_t                spp_sackdelay;
2307 *     uint32_t                spp_flags;
2308 * };
2309 *
2310 *   spp_assoc_id    - (one-to-many style socket) This is filled in the
2311 *                     application, and identifies the association for
2312 *                     this query.
2313 *   spp_address     - This specifies which address is of interest.
2314 *   spp_hbinterval  - This contains the value of the heartbeat interval,
2315 *                     in milliseconds.  If a  value of zero
2316 *                     is present in this field then no changes are to
2317 *                     be made to this parameter.
2318 *   spp_pathmaxrxt  - This contains the maximum number of
2319 *                     retransmissions before this address shall be
2320 *                     considered unreachable. If a  value of zero
2321 *                     is present in this field then no changes are to
2322 *                     be made to this parameter.
2323 *   spp_pathmtu     - When Path MTU discovery is disabled the value
2324 *                     specified here will be the "fixed" path mtu.
2325 *                     Note that if the spp_address field is empty
2326 *                     then all associations on this address will
2327 *                     have this fixed path mtu set upon them.
2328 *
2329 *   spp_sackdelay   - When delayed sack is enabled, this value specifies
2330 *                     the number of milliseconds that sacks will be delayed
2331 *                     for. This value will apply to all addresses of an
2332 *                     association if the spp_address field is empty. Note
2333 *                     also, that if delayed sack is enabled and this
2334 *                     value is set to 0, no change is made to the last
2335 *                     recorded delayed sack timer value.
2336 *
2337 *   spp_flags       - These flags are used to control various features
2338 *                     on an association. The flag field may contain
2339 *                     zero or more of the following options.
2340 *
2341 *                     SPP_HB_ENABLE  - Enable heartbeats on the
2342 *                     specified address. Note that if the address
2343 *                     field is empty all addresses for the association
2344 *                     have heartbeats enabled upon them.
2345 *
2346 *                     SPP_HB_DISABLE - Disable heartbeats on the
2347 *                     speicifed address. Note that if the address
2348 *                     field is empty all addresses for the association
2349 *                     will have their heartbeats disabled. Note also
2350 *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
2351 *                     mutually exclusive, only one of these two should
2352 *                     be specified. Enabling both fields will have
2353 *                     undetermined results.
2354 *
2355 *                     SPP_HB_DEMAND - Request a user initiated heartbeat
2356 *                     to be made immediately.
2357 *
2358 *                     SPP_HB_TIME_IS_ZERO - Specify's that the time for
2359 *                     heartbeat delayis to be set to the value of 0
2360 *                     milliseconds.
2361 *
2362 *                     SPP_PMTUD_ENABLE - This field will enable PMTU
2363 *                     discovery upon the specified address. Note that
2364 *                     if the address feild is empty then all addresses
2365 *                     on the association are effected.
2366 *
2367 *                     SPP_PMTUD_DISABLE - This field will disable PMTU
2368 *                     discovery upon the specified address. Note that
2369 *                     if the address feild is empty then all addresses
2370 *                     on the association are effected. Not also that
2371 *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
2372 *                     exclusive. Enabling both will have undetermined
2373 *                     results.
2374 *
2375 *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
2376 *                     on delayed sack. The time specified in spp_sackdelay
2377 *                     is used to specify the sack delay for this address. Note
2378 *                     that if spp_address is empty then all addresses will
2379 *                     enable delayed sack and take on the sack delay
2380 *                     value specified in spp_sackdelay.
2381 *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
2382 *                     off delayed sack. If the spp_address field is blank then
2383 *                     delayed sack is disabled for the entire association. Note
2384 *                     also that this field is mutually exclusive to
2385 *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
2386 *                     results.
2387 */
2388static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params,
2389                                       struct sctp_transport   *trans,
2390                                       struct sctp_association *asoc,
2391                                       struct sctp_sock        *sp,
2392                                       int                      hb_change,
2393                                       int                      pmtud_change,
2394                                       int                      sackdelay_change)
2395{
2396        int error;
2397
2398        if (params->spp_flags & SPP_HB_DEMAND && trans) {
2399                struct net *net = sock_net(trans->asoc->base.sk);
2400
2401                error = sctp_primitive_REQUESTHEARTBEAT(net, trans->asoc, trans);
2402                if (error)
2403                        return error;
2404        }
2405
2406        /* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of
2407         * this field is ignored.  Note also that a value of zero indicates
2408         * the current setting should be left unchanged.
2409         */
2410        if (params->spp_flags & SPP_HB_ENABLE) {
2411
2412                /* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is
2413                 * set.  This lets us use 0 value when this flag
2414                 * is set.
2415                 */
2416                if (params->spp_flags & SPP_HB_TIME_IS_ZERO)
2417                        params->spp_hbinterval = 0;
2418
2419                if (params->spp_hbinterval ||
2420                    (params->spp_flags & SPP_HB_TIME_IS_ZERO)) {
2421                        if (trans) {
2422                                trans->hbinterval =
2423                                    msecs_to_jiffies(params->spp_hbinterval);
2424                        } else if (asoc) {
2425                                asoc->hbinterval =
2426                                    msecs_to_jiffies(params->spp_hbinterval);
2427                        } else {
2428                                sp->hbinterval = params->spp_hbinterval;
2429                        }
2430                }
2431        }
2432
2433        if (hb_change) {
2434                if (trans) {
2435                        trans->param_flags =
2436                                (trans->param_flags & ~SPP_HB) | hb_change;
2437                } else if (asoc) {
2438                        asoc->param_flags =
2439                                (asoc->param_flags & ~SPP_HB) | hb_change;
2440                } else {
2441                        sp->param_flags =
2442                                (sp->param_flags & ~SPP_HB) | hb_change;
2443                }
2444        }
2445
2446        /* When Path MTU discovery is disabled the value specified here will
2447         * be the "fixed" path mtu (i.e. the value of the spp_flags field must
2448         * include the flag SPP_PMTUD_DISABLE for this field to have any
2449         * effect).
2450         */
2451        if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) {
2452                if (trans) {
2453                        trans->pathmtu = params->spp_pathmtu;
2454                        sctp_assoc_sync_pmtu(asoc);
2455                } else if (asoc) {
2456                        asoc->pathmtu = params->spp_pathmtu;
2457                        sctp_frag_point(asoc, params->spp_pathmtu);
2458                } else {
2459                        sp->pathmtu = params->spp_pathmtu;
2460                }
2461        }
2462
2463        if (pmtud_change) {
2464                if (trans) {
2465                        int update = (trans->param_flags & SPP_PMTUD_DISABLE) &&
2466                                (params->spp_flags & SPP_PMTUD_ENABLE);
2467                        trans->param_flags =
2468                                (trans->param_flags & ~SPP_PMTUD) | pmtud_change;
2469                        if (update) {
2470                                sctp_transport_pmtu(trans, sctp_opt2sk(sp));
2471                                sctp_assoc_sync_pmtu(asoc);
2472                        }
2473                } else if (asoc) {
2474                        asoc->param_flags =
2475                                (asoc->param_flags & ~SPP_PMTUD) | pmtud_change;
2476                } else {
2477                        sp->param_flags =
2478                                (sp->param_flags & ~SPP_PMTUD) | pmtud_change;
2479                }
2480        }
2481
2482        /* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the
2483         * value of this field is ignored.  Note also that a value of zero
2484         * indicates the current setting should be left unchanged.
2485         */
2486        if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) {
2487                if (trans) {
2488                        trans->sackdelay =
2489                                msecs_to_jiffies(params->spp_sackdelay);
2490                } else if (asoc) {
2491                        asoc->sackdelay =
2492                                msecs_to_jiffies(params->spp_sackdelay);
2493                } else {
2494                        sp->sackdelay = params->spp_sackdelay;
2495                }
2496        }
2497
2498        if (sackdelay_change) {
2499                if (trans) {
2500                        trans->param_flags =
2501                                (trans->param_flags & ~SPP_SACKDELAY) |
2502                                sackdelay_change;
2503                } else if (asoc) {
2504                        asoc->param_flags =
2505                                (asoc->param_flags & ~SPP_SACKDELAY) |
2506                                sackdelay_change;
2507                } else {
2508                        sp->param_flags =
2509                                (sp->param_flags & ~SPP_SACKDELAY) |
2510                                sackdelay_change;
2511                }
2512        }
2513
2514        /* Note that a value of zero indicates the current setting should be
2515           left unchanged.
2516         */
2517        if (params->spp_pathmaxrxt) {
2518                if (trans) {
2519                        trans->pathmaxrxt = params->spp_pathmaxrxt;
2520                } else if (asoc) {
2521                        asoc->pathmaxrxt = params->spp_pathmaxrxt;
2522                } else {
2523                        sp->pathmaxrxt = params->spp_pathmaxrxt;
2524                }
2525        }
2526
2527        return 0;
2528}
2529
2530static int sctp_setsockopt_peer_addr_params(struct sock *sk,
2531                                            char __user *optval,
2532                                            unsigned int optlen)
2533{
2534        struct sctp_paddrparams  params;
2535        struct sctp_transport   *trans = NULL;
2536        struct sctp_association *asoc = NULL;
2537        struct sctp_sock        *sp = sctp_sk(sk);
2538        int error;
2539        int hb_change, pmtud_change, sackdelay_change;
2540
2541        if (optlen != sizeof(struct sctp_paddrparams))
2542                return -EINVAL;
2543
2544        if (copy_from_user(&params, optval, optlen))
2545                return -EFAULT;
2546
2547        /* Validate flags and value parameters. */
2548        hb_change        = params.spp_flags & SPP_HB;
2549        pmtud_change     = params.spp_flags & SPP_PMTUD;
2550        sackdelay_change = params.spp_flags & SPP_SACKDELAY;
2551
2552        if (hb_change        == SPP_HB ||
2553            pmtud_change     == SPP_PMTUD ||
2554            sackdelay_change == SPP_SACKDELAY ||
2555            params.spp_sackdelay > 500 ||
2556            (params.spp_pathmtu &&
2557             params.spp_pathmtu < SCTP_DEFAULT_MINSEGMENT))
2558                return -EINVAL;
2559
2560        /* If an address other than INADDR_ANY is specified, and
2561         * no transport is found, then the request is invalid.
2562         */
2563        if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) {
2564                trans = sctp_addr_id2transport(sk, &params.spp_address,
2565                                               params.spp_assoc_id);
2566                if (!trans)
2567                        return -EINVAL;
2568        }
2569
2570        /* Get association, if assoc_id != 0 and the socket is a one
2571         * to many style socket, and an association was not found, then
2572         * the id was invalid.
2573         */
2574        asoc = sctp_id2assoc(sk, params.spp_assoc_id);
2575        if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP))
2576                return -EINVAL;
2577
2578        /* Heartbeat demand can only be sent on a transport or
2579         * association, but not a socket.
2580         */
2581        if (params.spp_flags & SPP_HB_DEMAND && !trans && !asoc)
2582                return -EINVAL;
2583
2584        /* Process parameters. */
2585        error = sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2586                                            hb_change, pmtud_change,
2587                                            sackdelay_change);
2588
2589        if (error)
2590                return error;
2591
2592        /* If changes are for association, also apply parameters to each
2593         * transport.
2594         */
2595        if (!trans && asoc) {
2596                list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2597                                transports) {
2598                        sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2599                                                    hb_change, pmtud_change,
2600                                                    sackdelay_change);
2601                }
2602        }
2603
2604        return 0;
2605}
2606
2607/*
2608 * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
2609 *
2610 * This option will effect the way delayed acks are performed.  This
2611 * option allows you to get or set the delayed ack time, in
2612 * milliseconds.  It also allows changing the delayed ack frequency.
2613 * Changing the frequency to 1 disables the delayed sack algorithm.  If
2614 * the assoc_id is 0, then this sets or gets the endpoints default
2615 * values.  If the assoc_id field is non-zero, then the set or get
2616 * effects the specified association for the one to many model (the
2617 * assoc_id field is ignored by the one to one model).  Note that if
2618 * sack_delay or sack_freq are 0 when setting this option, then the
2619 * current values will remain unchanged.
2620 *
2621 * struct sctp_sack_info {
2622 *     sctp_assoc_t            sack_assoc_id;
2623 *     uint32_t                sack_delay;
2624 *     uint32_t                sack_freq;
2625 * };
2626 *
2627 * sack_assoc_id -  This parameter, indicates which association the user
2628 *    is performing an action upon.  Note that if this field's value is
2629 *    zero then the endpoints default value is changed (effecting future
2630 *    associations only).
2631 *
2632 * sack_delay -  This parameter contains the number of milliseconds that
2633 *    the user is requesting the delayed ACK timer be set to.  Note that
2634 *    this value is defined in the standard to be between 200 and 500
2635 *    milliseconds.
2636 *
2637 * sack_freq -  This parameter contains the number of packets that must
2638 *    be received before a sack is sent without waiting for the delay
2639 *    timer to expire.  The default value for this is 2, setting this
2640 *    value to 1 will disable the delayed sack algorithm.
2641 */
2642
2643static int sctp_setsockopt_delayed_ack(struct sock *sk,
2644                                       char __user *optval, unsigned int optlen)
2645{
2646        struct sctp_sack_info    params;
2647        struct sctp_transport   *trans = NULL;
2648        struct sctp_association *asoc = NULL;
2649        struct sctp_sock        *sp = sctp_sk(sk);
2650
2651        if (optlen == sizeof(struct sctp_sack_info)) {
2652                if (copy_from_user(&params, optval, optlen))
2653                        return -EFAULT;
2654
2655                if (params.sack_delay == 0 && params.sack_freq == 0)
2656                        return 0;
2657        } else if (optlen == sizeof(struct sctp_assoc_value)) {
2658                pr_warn_ratelimited("%s (pid %d) "
2659                                    "Use of struct sctp_assoc_value in delayed_ack socket option deprecated\n"
2660                                    "Use struct sctp_sack_info instead\n",
2661                                    current->comm, task_pid_nr(current));
2662                if (copy_from_user(&params, optval, optlen))
2663                        return -EFAULT;
2664
2665                if (params.sack_delay == 0)
2666                        params.sack_freq = 1;
2667                else
2668                        params.sack_freq = 0;
2669        } else
2670                return -EINVAL;
2671
2672        /* Validate value parameter. */
2673        if (params.sack_delay > 500)
2674                return -EINVAL;
2675
2676        /* Get association, if sack_assoc_id != 0 and the socket is a one
2677         * to many style socket, and an association was not found, then
2678         * the id was invalid.
2679         */
2680        asoc = sctp_id2assoc(sk, params.sack_assoc_id);
2681        if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
2682                return -EINVAL;
2683
2684        if (params.sack_delay) {
2685                if (asoc) {
2686                        asoc->sackdelay =
2687                                msecs_to_jiffies(params.sack_delay);
2688                        asoc->param_flags =
2689                                (asoc->param_flags & ~SPP_SACKDELAY) |
2690                                SPP_SACKDELAY_ENABLE;
2691                } else {
2692                        sp->sackdelay = params.sack_delay;
2693                        sp->param_flags =
2694                                (sp->param_flags & ~SPP_SACKDELAY) |
2695                                SPP_SACKDELAY_ENABLE;
2696                }
2697        }
2698
2699        if (params.sack_freq == 1) {
2700                if (asoc) {
2701                        asoc->param_flags =
2702                                (asoc->param_flags & ~SPP_SACKDELAY) |
2703                                SPP_SACKDELAY_DISABLE;
2704                } else {
2705                        sp->param_flags =
2706                                (sp->param_flags & ~SPP_SACKDELAY) |
2707                                SPP_SACKDELAY_DISABLE;
2708                }
2709        } else if (params.sack_freq > 1) {
2710                if (asoc) {
2711                        asoc->sackfreq = params.sack_freq;
2712                        asoc->param_flags =
2713                                (asoc->param_flags & ~SPP_SACKDELAY) |
2714                                SPP_SACKDELAY_ENABLE;
2715                } else {
2716                        sp->sackfreq = params.sack_freq;
2717                        sp->param_flags =
2718                                (sp->param_flags & ~SPP_SACKDELAY) |
2719                                SPP_SACKDELAY_ENABLE;
2720                }
2721        }
2722
2723        /* If change is for association, also apply to each transport. */
2724        if (asoc) {
2725                list_for_each_entry(trans, &asoc->peer.transport_addr_list,
2726                                transports) {
2727                        if (params.sack_delay) {
2728                                trans->sackdelay =
2729                                        msecs_to_jiffies(params.sack_delay);
2730                                trans->param_flags =
2731                                        (trans->param_flags & ~SPP_SACKDELAY) |
2732                                        SPP_SACKDELAY_ENABLE;
2733                        }
2734                        if (params.sack_freq == 1) {
2735                                trans->param_flags =
2736                                        (trans->param_flags & ~SPP_SACKDELAY) |
2737                                        SPP_SACKDELAY_DISABLE;
2738                        } else if (params.sack_freq > 1) {
2739                                trans->sackfreq = params.sack_freq;
2740                                trans->param_flags =
2741                                        (trans->param_flags & ~SPP_SACKDELAY) |
2742                                        SPP_SACKDELAY_ENABLE;
2743                        }
2744                }
2745        }
2746
2747        return 0;
2748}
2749
2750/* 7.1.3 Initialization Parameters (SCTP_INITMSG)
2751 *
2752 * Applications can specify protocol parameters for the default association
2753 * initialization.  The option name argument to setsockopt() and getsockopt()
2754 * is SCTP_INITMSG.
2755 *
2756 * Setting initialization parameters is effective only on an unconnected
2757 * socket (for UDP-style sockets only future associations are effected
2758 * by the change).  With TCP-style sockets, this option is inherited by
2759 * sockets derived from a listener socket.
2760 */
2761static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, unsigned int optlen)
2762{
2763        struct sctp_initmsg sinit;
2764        struct sctp_sock *sp = sctp_sk(sk);
2765
2766        if (optlen != sizeof(struct sctp_initmsg))
2767                return -EINVAL;
2768        if (copy_from_user(&sinit, optval, optlen))
2769                return -EFAULT;
2770
2771        if (sinit.sinit_num_ostreams)
2772                sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams;
2773        if (sinit.sinit_max_instreams)
2774                sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams;
2775        if (sinit.sinit_max_attempts)
2776                sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts;
2777        if (sinit.sinit_max_init_timeo)
2778                sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo;
2779
2780        return 0;
2781}
2782
2783/*
2784 * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
2785 *
2786 *   Applications that wish to use the sendto() system call may wish to
2787 *   specify a default set of parameters that would normally be supplied
2788 *   through the inclusion of ancillary data.  This socket option allows
2789 *   such an application to set the default sctp_sndrcvinfo structure.
2790 *   The application that wishes to use this socket option simply passes
2791 *   in to this call the sctp_sndrcvinfo structure defined in Section
2792 *   5.2.2) The input parameters accepted by this call include
2793 *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
2794 *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
2795 *   to this call if the caller is using the UDP model.
2796 */
2797static int sctp_setsockopt_default_send_param(struct sock *sk,
2798                                              char __user *optval,
2799                                              unsigned int optlen)
2800{
2801        struct sctp_sock *sp = sctp_sk(sk);
2802        struct sctp_association *asoc;
2803        struct sctp_sndrcvinfo info;
2804
2805        if (optlen != sizeof(info))
2806                return -EINVAL;
2807        if (copy_from_user(&info, optval, optlen))
2808                return -EFAULT;
2809        if (info.sinfo_flags &
2810            ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
2811              SCTP_ABORT | SCTP_EOF))
2812                return -EINVAL;
2813
2814        asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
2815        if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
2816                return -EINVAL;
2817        if (asoc) {
2818                asoc->default_stream = info.sinfo_stream;
2819                asoc->default_flags = info.sinfo_flags;
2820                asoc->default_ppid = info.sinfo_ppid;
2821                asoc->default_context = info.sinfo_context;
2822                asoc->default_timetolive = info.sinfo_timetolive;
2823        } else {
2824                sp->default_stream = info.sinfo_stream;
2825                sp->default_flags = info.sinfo_flags;
2826                sp->default_ppid = info.sinfo_ppid;
2827                sp->default_context = info.sinfo_context;
2828                sp->default_timetolive = info.sinfo_timetolive;
2829        }
2830
2831        return 0;
2832}
2833
2834/* RFC6458, Section 8.1.31. Set/get Default Send Parameters
2835 * (SCTP_DEFAULT_SNDINFO)
2836 */
2837static int sctp_setsockopt_default_sndinfo(struct sock *sk,
2838                                           char __user *optval,
2839                                           unsigned int optlen)
2840{
2841        struct sctp_sock *sp = sctp_sk(sk);
2842        struct sctp_association *asoc;
2843        struct sctp_sndinfo info;
2844
2845        if (optlen != sizeof(info))
2846                return -EINVAL;
2847        if (copy_from_user(&info, optval, optlen))
2848                return -EFAULT;
2849        if (info.snd_flags &
2850            ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
2851              SCTP_ABORT | SCTP_EOF))
2852                return -EINVAL;
2853
2854        asoc = sctp_id2assoc(sk, info.snd_assoc_id);
2855        if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP))
2856                return -EINVAL;
2857        if (asoc) {
2858                asoc->default_stream = info.snd_sid;
2859                asoc->default_flags = info.snd_flags;
2860                asoc->default_ppid = info.snd_ppid;
2861                asoc->default_context = info.snd_context;
2862        } else {
2863                sp->default_stream = info.snd_sid;
2864                sp->default_flags = info.snd_flags;
2865                sp->default_ppid = info.snd_ppid;
2866                sp->default_context = info.snd_context;
2867        }
2868
2869        return 0;
2870}
2871
2872/* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
2873 *
2874 * Requests that the local SCTP stack use the enclosed peer address as
2875 * the association primary.  The enclosed address must be one of the
2876 * association peer's addresses.
2877 */
2878static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval,
2879                                        unsigned int optlen)
2880{
2881        struct sctp_prim prim;
2882        struct sctp_transport *trans;
2883
2884        if (optlen != sizeof(struct sctp_prim))
2885                return -EINVAL;
2886
2887        if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
2888                return -EFAULT;
2889
2890        trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id);
2891        if (!trans)
2892                return -EINVAL;
2893
2894        sctp_assoc_set_primary(trans->asoc, trans);
2895
2896        return 0;
2897}
2898
2899/*
2900 * 7.1.5 SCTP_NODELAY
2901 *
2902 * Turn on/off any Nagle-like algorithm.  This means that packets are
2903 * generally sent as soon as possible and no unnecessary delays are
2904 * introduced, at the cost of more packets in the network.  Expects an
2905 *  integer boolean flag.
2906 */
2907static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval,
2908                                   unsigned int optlen)
2909{
2910        int val;
2911
2912        if (optlen < sizeof(int))
2913                return -EINVAL;
2914        if (get_user(val, (int __user *)optval))
2915                return -EFAULT;
2916
2917        sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1;
2918        return 0;
2919}
2920
2921/*
2922 *
2923 * 7.1.1 SCTP_RTOINFO
2924 *
2925 * The protocol parameters used to initialize and bound retransmission
2926 * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
2927 * and modify these parameters.
2928 * All parameters are time values, in milliseconds.  A value of 0, when
2929 * modifying the parameters, indicates that the current value should not
2930 * be changed.
2931 *
2932 */
2933static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, unsigned int optlen)
2934{
2935        struct sctp_rtoinfo rtoinfo;
2936        struct sctp_association *asoc;
2937        unsigned long rto_min, rto_max;
2938        struct sctp_sock *sp = sctp_sk(sk);
2939
2940        if (optlen != sizeof (struct sctp_rtoinfo))
2941                return -EINVAL;
2942
2943        if (copy_from_user(&rtoinfo, optval, optlen))
2944                return -EFAULT;
2945
2946        asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
2947
2948        /* Set the values to the specific association */
2949        if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
2950                return -EINVAL;
2951
2952        rto_max = rtoinfo.srto_max;
2953        rto_min = rtoinfo.srto_min;
2954
2955        if (rto_max)
2956                rto_max = asoc ? msecs_to_jiffies(rto_max) : rto_max;
2957        else
2958                rto_max = asoc ? asoc->rto_max : sp->rtoinfo.srto_max;
2959
2960        if (rto_min)
2961                rto_min = asoc ? msecs_to_jiffies(rto_min) : rto_min;
2962        else
2963                rto_min = asoc ? asoc->rto_min : sp->rtoinfo.srto_min;
2964
2965        if (rto_min > rto_max)
2966                return -EINVAL;
2967
2968        if (asoc) {
2969                if (rtoinfo.srto_initial != 0)
2970                        asoc->rto_initial =
2971                                msecs_to_jiffies(rtoinfo.srto_initial);
2972                asoc->rto_max = rto_max;
2973                asoc->rto_min = rto_min;
2974        } else {
2975                /* If there is no association or the association-id = 0
2976                 * set the values to the endpoint.
2977                 */
2978                if (rtoinfo.srto_initial != 0)
2979                        sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
2980                sp->rtoinfo.srto_max = rto_max;
2981                sp->rtoinfo.srto_min = rto_min;
2982        }
2983
2984        return 0;
2985}
2986
2987/*
2988 *
2989 * 7.1.2 SCTP_ASSOCINFO
2990 *
2991 * This option is used to tune the maximum retransmission attempts
2992 * of the association.
2993 * Returns an error if the new association retransmission value is
2994 * greater than the sum of the retransmission value  of the peer.
2995 * See [SCTP] for more information.
2996 *
2997 */
2998static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, unsigned int optlen)
2999{
3000
3001        struct sctp_assocparams assocparams;
3002        struct sctp_association *asoc;
3003
3004        if (optlen != sizeof(struct sctp_assocparams))
3005                return -EINVAL;
3006        if (copy_from_user(&assocparams, optval, optlen))
3007                return -EFAULT;
3008
3009        asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
3010
3011        if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
3012                return -EINVAL;
3013
3014        /* Set the values to the specific association */
3015        if (asoc) {
3016                if (assocparams.sasoc_asocmaxrxt != 0) {
3017                        __u32 path_sum = 0;
3018                        int   paths = 0;
3019                        struct sctp_transport *peer_addr;
3020
3021                        list_for_each_entry(peer_addr, &asoc->peer.transport_addr_list,
3022                                        transports) {
3023                                path_sum += peer_addr->pathmaxrxt;
3024                                paths++;
3025                        }
3026
3027                        /* Only validate asocmaxrxt if we have more than
3028                         * one path/transport.  We do this because path
3029                         * retransmissions are only counted when we have more
3030                         * then one path.
3031                         */
3032                        if (paths > 1 &&
3033                            assocparams.sasoc_asocmaxrxt > path_sum)
3034                                return -EINVAL;
3035
3036                        asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
3037                }
3038
3039                if (assocparams.sasoc_cookie_life != 0)
3040                        asoc->cookie_life = ms_to_ktime(assocparams.sasoc_cookie_life);
3041        } else {
3042                /* Set the values to the endpoint */
3043                struct sctp_sock *sp = sctp_sk(sk);
3044
3045                if (assocparams.sasoc_asocmaxrxt != 0)
3046                        sp->assocparams.sasoc_asocmaxrxt =
3047                                                assocparams.sasoc_asocmaxrxt;
3048                if (assocparams.sasoc_cookie_life != 0)
3049                        sp->assocparams.sasoc_cookie_life =
3050                                                assocparams.sasoc_cookie_life;
3051        }
3052        return 0;
3053}
3054
3055/*
3056 * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
3057 *
3058 * This socket option is a boolean flag which turns on or off mapped V4
3059 * addresses.  If this option is turned on and the socket is type
3060 * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
3061 * If this option is turned off, then no mapping will be done of V4
3062 * addresses and a user will receive both PF_INET6 and PF_INET type
3063 * addresses on the socket.
3064 */
3065static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, unsigned int optlen)
3066{
3067        int val;
3068        struct sctp_sock *sp = sctp_sk(sk);
3069
3070        if (optlen < sizeof(int))
3071                return -EINVAL;
3072        if (get_user(val, (int __user *)optval))
3073                return -EFAULT;
3074        if (val)
3075                sp->v4mapped = 1;
3076        else
3077                sp->v4mapped = 0;
3078
3079        return 0;
3080}
3081
3082/*
3083 * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
3084 * This option will get or set the maximum size to put in any outgoing
3085 * SCTP DATA chunk.  If a message is larger than this size it will be
3086 * fragmented by SCTP into the specified size.  Note that the underlying
3087 * SCTP implementation may fragment into smaller sized chunks when the
3088 * PMTU of the underlying association is smaller than the value set by
3089 * the user.  The default value for this option is '0' which indicates
3090 * the user is NOT limiting fragmentation and only the PMTU will effect
3091 * SCTP's choice of DATA chunk size.  Note also that values set larger
3092 * than the maximum size of an IP datagram will effectively let SCTP
3093 * control fragmentation (i.e. the same as setting this option to 0).
3094 *
3095 * The following structure is used to access and modify this parameter:
3096 *
3097 * struct sctp_assoc_value {
3098 *   sctp_assoc_t assoc_id;
3099 *   uint32_t assoc_value;
3100 * };
3101 *
3102 * assoc_id:  This parameter is ignored for one-to-one style sockets.
3103 *    For one-to-many style sockets this parameter indicates which
3104 *    association the user is performing an action upon.  Note that if
3105 *    this field's value is zero then the endpoints default value is
3106 *    changed (effecting future associations only).
3107 * assoc_value:  This parameter specifies the maximum size in bytes.
3108 */
3109static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, unsigned int optlen)
3110{
3111        struct sctp_assoc_value params;
3112        struct sctp_association *asoc;
3113        struct sctp_sock *sp = sctp_sk(sk);
3114        int val;
3115
3116        if (optlen == sizeof(int)) {
3117                pr_warn_ratelimited("%s (pid %d) "
3118                                    "Use of int in maxseg socket option deprecated\n"
3119                                    "Use struct sctp_assoc_value instead\n",
3120                                    current->comm, task_pid_nr(current));
3121                if (copy_from_user(&val, optval, optlen))
3122                        return -EFAULT;
3123                params.assoc_id = 0;
3124        } else if (optlen == sizeof(struct sctp_assoc_value)) {
3125                if (copy_from_user(&params, optval, optlen))
3126                        return -EFAULT;
3127                val = params.assoc_value;
3128        } else
3129                return -EINVAL;
3130
3131        if ((val != 0) && ((val < 8) || (val > SCTP_MAX_CHUNK_LEN)))
3132                return -EINVAL;
3133
3134        asoc = sctp_id2assoc(sk, params.assoc_id);
3135        if (!asoc && params.assoc_id && sctp_style(sk, UDP))
3136                return -EINVAL;
3137
3138        if (asoc) {
3139                if (val == 0) {
3140                        val = asoc->pathmtu;
3141                        val -= sp->pf->af->net_header_len;
3142                        val -= sizeof(struct sctphdr) +
3143                                        sizeof(struct sctp_data_chunk);
3144                }
3145                asoc->user_frag = val;
3146                asoc->frag_point = sctp_frag_point(asoc, asoc->pathmtu);
3147        } else {
3148                sp->user_frag = val;
3149        }
3150
3151        return 0;
3152}
3153
3154
3155/*
3156 *  7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
3157 *
3158 *   Requests that the peer mark the enclosed address as the association
3159 *   primary. The enclosed address must be one of the association's
3160 *   locally bound addresses. The following structure is used to make a
3161 *   set primary request:
3162 */
3163static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval,
3164                                             unsigned int optlen)
3165{
3166        struct net *net = sock_net(sk);
3167        struct sctp_sock        *sp;
3168        struct sctp_association *asoc = NULL;
3169        struct sctp_setpeerprim prim;
3170        struct sctp_chunk       *chunk;
3171        struct sctp_af          *af;
3172        int                     err;
3173
3174        sp = sctp_sk(sk);
3175
3176        if (!net->sctp.addip_enable)
3177                return -EPERM;
3178
3179        if (optlen != sizeof(struct sctp_setpeerprim))
3180                return -EINVAL;
3181
3182        if (copy_from_user(&prim, optval, optlen))
3183                return -EFAULT;
3184
3185        asoc = sctp_id2assoc(sk, prim.sspp_assoc_id);
3186        if (!asoc)
3187                return -EINVAL;
3188
3189        if (!asoc->peer.asconf_capable)
3190                return -EPERM;
3191
3192        if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
3193                return -EPERM;
3194
3195        if (!sctp_state(asoc, ESTABLISHED))
3196                return -ENOTCONN;
3197
3198        af = sctp_get_af_specific(prim.sspp_addr.ss_family);
3199        if (!af)
3200                return -EINVAL;
3201
3202        if (!af->addr_valid((union sctp_addr *)&prim.sspp_addr, sp, NULL))
3203                return -EADDRNOTAVAIL;
3204
3205        if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr))
3206                return -EADDRNOTAVAIL;
3207
3208        /* Create an ASCONF chunk with SET_PRIMARY parameter    */
3209        chunk = sctp_make_asconf_set_prim(asoc,
3210                                          (union sctp_addr *)&prim.sspp_addr);
3211        if (!chunk)
3212                return -ENOMEM;
3213
3214        err = sctp_send_asconf(asoc, chunk);
3215
3216        pr_debug("%s: we set peer primary addr primitively\n", __func__);
3217
3218        return err;
3219}
3220
3221static int sctp_setsockopt_adaptation_layer(struct sock *sk, char __user *optval,
3222                                            unsigned int optlen)
3223{
3224        struct sctp_setadaptation adaptation;
3225
3226        if (optlen != sizeof(struct sctp_setadaptation))
3227                return -EINVAL;
3228        if (copy_from_user(&adaptation, optval, optlen))
3229                return -EFAULT;
3230
3231        sctp_sk(sk)->adaptation_ind = adaptation.ssb_adaptation_ind;
3232
3233        return 0;
3234}
3235
3236/*
3237 * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
3238 *
3239 * The context field in the sctp_sndrcvinfo structure is normally only
3240 * used when a failed message is retrieved holding the value that was
3241 * sent down on the actual send call.  This option allows the setting of
3242 * a default context on an association basis that will be received on
3243 * reading messages from the peer.  This is especially helpful in the
3244 * one-2-many model for an application to keep some reference to an
3245 * internal state machine that is processing messages on the
3246 * association.  Note that the setting of this value only effects
3247 * received messages from the peer and does not effect the value that is
3248 * saved with outbound messages.
3249 */
3250static int sctp_setsockopt_context(struct sock *sk, char __user *optval,
3251                                   unsigned int optlen)
3252{
3253        struct sctp_assoc_value params;
3254        struct sctp_sock *sp;
3255        struct sctp_association *asoc;
3256
3257        if (optlen != sizeof(struct sctp_assoc_value))
3258                return -EINVAL;
3259        if (copy_from_user(&params, optval, optlen))
3260                return -EFAULT;
3261
3262        sp = sctp_sk(sk);
3263
3264        if (params.assoc_id != 0) {
3265                asoc = sctp_id2assoc(sk, params.assoc_id);
3266                if (!asoc)
3267                        return -EINVAL;
3268                asoc->default_rcv_context = params.assoc_value;
3269        } else {
3270                sp->default_rcv_context = params.assoc_value;
3271        }
3272
3273        return 0;
3274}
3275
3276/*
3277 * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
3278 *
3279 * This options will at a minimum specify if the implementation is doing
3280 * fragmented interleave.  Fragmented interleave, for a one to many
3281 * socket, is when subsequent calls to receive a message may return
3282 * parts of messages from different associations.  Some implementations
3283 * may allow you to turn this value on or off.  If so, when turned off,
3284 * no fragment interleave will occur (which will cause a head of line
3285 * blocking amongst multiple associations sharing the same one to many
3286 * socket).  When this option is turned on, then each receive call may
3287 * come from a different association (thus the user must receive data
3288 * with the extended calls (e.g. sctp_recvmsg) to keep track of which
3289 * association each receive belongs to.
3290 *
3291 * This option takes a boolean value.  A non-zero value indicates that
3292 * fragmented interleave is on.  A value of zero indicates that
3293 * fragmented interleave is off.
3294 *
3295 * Note that it is important that an implementation that allows this
3296 * option to be turned on, have it off by default.  Otherwise an unaware
3297 * application using the one to many model may become confused and act
3298 * incorrectly.
3299 */
3300static int sctp_setsockopt_fragment_interleave(struct sock *sk,
3301                                               char __user *optval,
3302                                               unsigned int optlen)
3303{
3304        int val;
3305
3306        if (optlen != sizeof(int))
3307                return -EINVAL;
3308        if (get_user(val, (int __user *)optval))
3309                return -EFAULT;
3310
3311        sctp_sk(sk)->frag_interleave = (val == 0) ? 0 : 1;
3312
3313        return 0;
3314}
3315
3316/*
3317 * 8.1.21.  Set or Get the SCTP Partial Delivery Point
3318 *       (SCTP_PARTIAL_DELIVERY_POINT)
3319 *
3320 * This option will set or get the SCTP partial delivery point.  This
3321 * point is the size of a message where the partial delivery API will be
3322 * invoked to help free up rwnd space for the peer.  Setting this to a
3323 * lower value will cause partial deliveries to happen more often.  The
3324 * calls argument is an integer that sets or gets the partial delivery
3325 * point.  Note also that the call will fail if the user attempts to set
3326 * this value larger than the socket receive buffer size.
3327 *
3328 * Note that any single message having a length smaller than or equal to
3329 * the SCTP partial delivery point will be delivered in one single read
3330 * call as long as the user provided buffer is large enough to hold the
3331 * message.
3332 */
3333static int sctp_setsockopt_partial_delivery_point(struct sock *sk,
3334                                                  char __user *optval,
3335                                                  unsigned int optlen)
3336{
3337        u32 val;
3338
3339        if (optlen != sizeof(u32))
3340                return -EINVAL;
3341        if (get_user(val, (int __user *)optval))
3342                return -EFAULT;
3343
3344        /* Note: We double the receive buffer from what the user sets
3345         * it to be, also initial rwnd is based on rcvbuf/2.
3346         */
3347        if (val > (sk->sk_rcvbuf >> 1))
3348                return -EINVAL;
3349
3350        sctp_sk(sk)->pd_point = val;
3351
3352        return 0; /* is this the right error code? */
3353}
3354
3355/*
3356 * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
3357 *
3358 * This option will allow a user to change the maximum burst of packets
3359 * that can be emitted by this association.  Note that the default value
3360 * is 4, and some implementations may restrict this setting so that it
3361 * can only be lowered.
3362 *
3363 * NOTE: This text doesn't seem right.  Do this on a socket basis with
3364 * future associations inheriting the socket value.
3365 */
3366static int sctp_setsockopt_maxburst(struct sock *sk,
3367                                    char __user *optval,
3368                                    unsigned int optlen)
3369{
3370        struct sctp_assoc_value params;
3371        struct sctp_sock *sp;
3372        struct sctp_association *asoc;
3373        int val;
3374        int assoc_id = 0;
3375
3376        if (optlen == sizeof(int)) {
3377                pr_warn_ratelimited("%s (pid %d) "
3378                                    "Use of int in max_burst socket option deprecated\n"
3379                                    "Use struct sctp_assoc_value instead\n",
3380                                    current->comm, task_pid_nr(current));
3381                if (copy_from_user(&val, optval, optlen))
3382                        return -EFAULT;
3383        } else if (optlen == sizeof(struct sctp_assoc_value)) {
3384                if (copy_from_user(&params, optval, optlen))
3385                        return -EFAULT;
3386                val = params.assoc_value;
3387                assoc_id = params.assoc_id;
3388        } else
3389                return -EINVAL;
3390
3391        sp = sctp_sk(sk);
3392
3393        if (assoc_id != 0) {
3394                asoc = sctp_id2assoc(sk, assoc_id);
3395                if (!asoc)
3396                        return -EINVAL;
3397                asoc->max_burst = val;
3398        } else
3399                sp->max_burst = val;
3400
3401        return 0;
3402}
3403
3404/*
3405 * 7.1.18.  Add a chunk that must be authenticated (SCTP_AUTH_CHUNK)
3406 *
3407 * This set option adds a chunk type that the user is requesting to be
3408 * received only in an authenticated way.  Changes to the list of chunks
3409 * will only effect future associations on the socket.
3410 */
3411static int sctp_setsockopt_auth_chunk(struct sock *sk,
3412                                      char __user *optval,
3413                                      unsigned int optlen)
3414{
3415        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3416        struct sctp_authchunk val;
3417
3418        if (!ep->auth_enable)
3419                return -EACCES;
3420
3421        if (optlen != sizeof(struct sctp_authchunk))
3422                return -EINVAL;
3423        if (copy_from_user(&val, optval, optlen))
3424                return -EFAULT;
3425
3426        switch (val.sauth_chunk) {
3427        case SCTP_CID_INIT:
3428        case SCTP_CID_INIT_ACK:
3429        case SCTP_CID_SHUTDOWN_COMPLETE:
3430        case SCTP_CID_AUTH:
3431                return -EINVAL;
3432        }
3433
3434        /* add this chunk id to the endpoint */
3435        return sctp_auth_ep_add_chunkid(ep, val.sauth_chunk);
3436}
3437
3438/*
3439 * 7.1.19.  Get or set the list of supported HMAC Identifiers (SCTP_HMAC_IDENT)
3440 *
3441 * This option gets or sets the list of HMAC algorithms that the local
3442 * endpoint requires the peer to use.
3443 */
3444static int sctp_setsockopt_hmac_ident(struct sock *sk,
3445                                      char __user *optval,
3446                                      unsigned int optlen)
3447{
3448        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3449        struct sctp_hmacalgo *hmacs;
3450        u32 idents;
3451        int err;
3452
3453        if (!ep->auth_enable)
3454                return -EACCES;
3455
3456        if (optlen < sizeof(struct sctp_hmacalgo))
3457                return -EINVAL;
3458
3459        hmacs = memdup_user(optval, optlen);
3460        if (IS_ERR(hmacs))
3461                return PTR_ERR(hmacs);
3462
3463        idents = hmacs->shmac_num_idents;
3464        if (idents == 0 || idents > SCTP_AUTH_NUM_HMACS ||
3465            (idents * sizeof(u16)) > (optlen - sizeof(struct sctp_hmacalgo))) {
3466                err = -EINVAL;
3467                goto out;
3468        }
3469
3470        err = sctp_auth_ep_set_hmacs(ep, hmacs);
3471out:
3472        kfree(hmacs);
3473        return err;
3474}
3475
3476/*
3477 * 7.1.20.  Set a shared key (SCTP_AUTH_KEY)
3478 *
3479 * This option will set a shared secret key which is used to build an
3480 * association shared key.
3481 */
3482static int sctp_setsockopt_auth_key(struct sock *sk,
3483                                    char __user *optval,
3484                                    unsigned int optlen)
3485{
3486        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3487        struct sctp_authkey *authkey;
3488        struct sctp_association *asoc;
3489        int ret;
3490
3491        if (!ep->auth_enable)
3492                return -EACCES;
3493
3494        if (optlen <= sizeof(struct sctp_authkey))
3495                return -EINVAL;
3496
3497        authkey = memdup_user(optval, optlen);
3498        if (IS_ERR(authkey))
3499                return PTR_ERR(authkey);
3500
3501        if (authkey->sca_keylength > optlen - sizeof(struct sctp_authkey)) {
3502                ret = -EINVAL;
3503                goto out;
3504        }
3505
3506        asoc = sctp_id2assoc(sk, authkey->sca_assoc_id);
3507        if (!asoc && authkey->sca_assoc_id && sctp_style(sk, UDP)) {
3508                ret = -EINVAL;
3509                goto out;
3510        }
3511
3512        ret = sctp_auth_set_key(ep, asoc, authkey);
3513out:
3514        kzfree(authkey);
3515        return ret;
3516}
3517
3518/*
3519 * 7.1.21.  Get or set the active shared key (SCTP_AUTH_ACTIVE_KEY)
3520 *
3521 * This option will get or set the active shared key to be used to build
3522 * the association shared key.
3523 */
3524static int sctp_setsockopt_active_key(struct sock *sk,
3525                                      char __user *optval,
3526                                      unsigned int optlen)
3527{
3528        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3529        struct sctp_authkeyid val;
3530        struct sctp_association *asoc;
3531
3532        if (!ep->auth_enable)
3533                return -EACCES;
3534
3535        if (optlen != sizeof(struct sctp_authkeyid))
3536                return -EINVAL;
3537        if (copy_from_user(&val, optval, optlen))
3538                return -EFAULT;
3539
3540        asoc = sctp_id2assoc(sk, val.scact_assoc_id);
3541        if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
3542                return -EINVAL;
3543
3544        return sctp_auth_set_active_key(ep, asoc, val.scact_keynumber);
3545}
3546
3547/*
3548 * 7.1.22.  Delete a shared key (SCTP_AUTH_DELETE_KEY)
3549 *
3550 * This set option will delete a shared secret key from use.
3551 */
3552static int sctp_setsockopt_del_key(struct sock *sk,
3553                                   char __user *optval,
3554                                   unsigned int optlen)
3555{
3556        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
3557        struct sctp_authkeyid val;
3558        struct sctp_association *asoc;
3559
3560        if (!ep->auth_enable)
3561                return -EACCES;
3562
3563        if (optlen != sizeof(struct sctp_authkeyid))
3564                return -EINVAL;
3565        if (copy_from_user(&val, optval, optlen))
3566                return -EFAULT;
3567
3568        asoc = sctp_id2assoc(sk, val.scact_assoc_id);
3569        if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
3570                return -EINVAL;
3571
3572        return sctp_auth_del_key_id(ep, asoc, val.scact_keynumber);
3573
3574}
3575
3576/*
3577 * 8.1.23 SCTP_AUTO_ASCONF
3578 *
3579 * This option will enable or disable the use of the automatic generation of
3580 * ASCONF chunks to add and delete addresses to an existing association.  Note
3581 * that this option has two caveats namely: a) it only affects sockets that
3582 * are bound to all addresses available to the SCTP stack, and b) the system
3583 * administrator may have an overriding control that turns the ASCONF feature
3584 * off no matter what setting the socket option may have.
3585 * This option expects an integer boolean flag, where a non-zero value turns on
3586 * the option, and a zero value turns off the option.
3587 * Note. In this implementation, socket operation overrides default parameter
3588 * being set by sysctl as well as FreeBSD implementation
3589 */
3590static int sctp_setsockopt_auto_asconf(struct sock *sk, char __user *optval,
3591                                        unsigned int optlen)
3592{
3593        int val;
3594        struct sctp_sock *sp = sctp_sk(sk);
3595
3596        if (optlen < sizeof(int))
3597                return -EINVAL;
3598        if (get_user(val, (int __user *)optval))
3599                return -EFAULT;
3600        if (!sctp_is_ep_boundall(sk) && val)
3601                return -EINVAL;
3602        if ((val && sp->do_auto_asconf) || (!val && !sp->do_auto_asconf))
3603                return 0;
3604
3605        spin_lock_bh(&sock_net(sk)->sctp.addr_wq_lock);
3606        if (val == 0 && sp->do_auto_asconf) {
3607                list_del(&sp->auto_asconf_list);
3608                sp->do_auto_asconf = 0;
3609        } else if (val && !sp->do_auto_asconf) {
3610                list_add_tail(&sp->auto_asconf_list,
3611                    &sock_net(sk)->sctp.auto_asconf_splist);
3612                sp->do_auto_asconf = 1;
3613        }
3614        spin_unlock_bh(&sock_net(sk)->sctp.addr_wq_lock);
3615        return 0;
3616}
3617
3618/*
3619 * SCTP_PEER_ADDR_THLDS
3620 *
3621 * This option allows us to alter the partially failed threshold for one or all
3622 * transports in an association.  See Section 6.1 of:
3623 * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
3624 */
3625static int sctp_setsockopt_paddr_thresholds(struct sock *sk,
3626                                            char __user *optval,
3627                                            unsigned int optlen)
3628{
3629        struct sctp_paddrthlds val;
3630        struct sctp_transport *trans;
3631        struct sctp_association *asoc;
3632
3633        if (optlen < sizeof(struct sctp_paddrthlds))
3634                return -EINVAL;
3635        if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval,
3636                           sizeof(struct sctp_paddrthlds)))
3637                return -EFAULT;
3638
3639
3640        if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
3641                asoc = sctp_id2assoc(sk, val.spt_assoc_id);
3642                if (!asoc)
3643                        return -ENOENT;
3644                list_for_each_entry(trans, &asoc->peer.transport_addr_list,
3645                                    transports) {
3646                        if (val.spt_pathmaxrxt)
3647                                trans->pathmaxrxt = val.spt_pathmaxrxt;
3648                        trans->pf_retrans = val.spt_pathpfthld;
3649                }
3650
3651                if (val.spt_pathmaxrxt)
3652                        asoc->pathmaxrxt = val.spt_pathmaxrxt;
3653                asoc->pf_retrans = val.spt_pathpfthld;
3654        } else {
3655                trans = sctp_addr_id2transport(sk, &val.spt_address,
3656                                               val.spt_assoc_id);
3657                if (!trans)
3658                        return -ENOENT;
3659
3660                if (val.spt_pathmaxrxt)
3661                        trans->pathmaxrxt = val.spt_pathmaxrxt;
3662                trans->pf_retrans = val.spt_pathpfthld;
3663        }
3664
3665        return 0;
3666}
3667
3668static int sctp_setsockopt_recvrcvinfo(struct sock *sk,
3669                                       char __user *optval,
3670                                       unsigned int optlen)
3671{
3672        int val;
3673
3674        if (optlen < sizeof(int))
3675                return -EINVAL;
3676        if (get_user(val, (int __user *) optval))
3677                return -EFAULT;
3678
3679        sctp_sk(sk)->recvrcvinfo = (val == 0) ? 0 : 1;
3680
3681        return 0;
3682}
3683
3684static int sctp_setsockopt_recvnxtinfo(struct sock *sk,
3685                                       char __user *optval,
3686                                       unsigned int optlen)
3687{
3688        int val;
3689
3690        if (optlen < sizeof(int))
3691                return -EINVAL;
3692        if (get_user(val, (int __user *) optval))
3693                return -EFAULT;
3694
3695        sctp_sk(sk)->recvnxtinfo = (val == 0) ? 0 : 1;
3696
3697        return 0;
3698}
3699
3700static int sctp_setsockopt_pr_supported(struct sock *sk,
3701                                        char __user *optval,
3702                                        unsigned int optlen)
3703{
3704        struct sctp_assoc_value params;
3705        struct sctp_association *asoc;
3706        int retval = -EINVAL;
3707
3708        if (optlen != sizeof(params))
3709                goto out;
3710
3711        if (copy_from_user(&params, optval, optlen)) {
3712                retval = -EFAULT;
3713                goto out;
3714        }
3715
3716        asoc = sctp_id2assoc(sk, params.assoc_id);
3717        if (asoc) {
3718                asoc->prsctp_enable = !!params.assoc_value;
3719        } else if (!params.assoc_id) {
3720                struct sctp_sock *sp = sctp_sk(sk);
3721
3722                sp->ep->prsctp_enable = !!params.assoc_value;
3723        } else {
3724                goto out;
3725        }
3726
3727        retval = 0;
3728
3729out:
3730        return retval;
3731}
3732
3733static int sctp_setsockopt_default_prinfo(struct sock *sk,
3734                                          char __user *optval,
3735                                          unsigned int optlen)
3736{
3737        struct sctp_default_prinfo info;
3738        struct sctp_association *asoc;
3739        int retval = -EINVAL;
3740
3741        if (optlen != sizeof(info))
3742                goto out;
3743
3744        if (copy_from_user(&info, optval, sizeof(info))) {
3745                retval = -EFAULT;
3746                goto out;
3747        }
3748
3749        if (info.pr_policy & ~SCTP_PR_SCTP_MASK)
3750                goto out;
3751
3752        if (info.pr_policy == SCTP_PR_SCTP_NONE)
3753                info.pr_value = 0;
3754
3755        asoc = sctp_id2assoc(sk, info.pr_assoc_id);
3756        if (asoc) {
3757                SCTP_PR_SET_POLICY(asoc->default_flags, info.pr_policy);
3758                asoc->default_timetolive = info.pr_value;
3759        } else if (!info.pr_assoc_id) {
3760                struct sctp_sock *sp = sctp_sk(sk);
3761
3762                SCTP_PR_SET_POLICY(sp->default_flags, info.pr_policy);
3763                sp->default_timetolive = info.pr_value;
3764        } else {
3765                goto out;
3766        }
3767
3768        retval = 0;
3769
3770out:
3771        return retval;
3772}
3773
3774/* API 6.2 setsockopt(), getsockopt()
3775 *
3776 * Applications use setsockopt() and getsockopt() to set or retrieve
3777 * socket options.  Socket options are used to change the default
3778 * behavior of sockets calls.  They are described in Section 7.
3779 *
3780 * The syntax is:
3781 *
3782 *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
3783 *                    int __user *optlen);
3784 *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
3785 *                    int optlen);
3786 *
3787 *   sd      - the socket descript.
3788 *   level   - set to IPPROTO_SCTP for all SCTP options.
3789 *   optname - the option name.
3790 *   optval  - the buffer to store the value of the option.
3791 *   optlen  - the size of the buffer.
3792 */
3793static int sctp_setsockopt(struct sock *sk, int level, int optname,
3794                           char __user *optval, unsigned int optlen)
3795{
3796        int retval = 0;
3797
3798        pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
3799
3800        /* I can hardly begin to describe how wrong this is.  This is
3801         * so broken as to be worse than useless.  The API draft
3802         * REALLY is NOT helpful here...  I am not convinced that the
3803         * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
3804         * are at all well-founded.
3805         */
3806        if (level != SOL_SCTP) {
3807                struct sctp_af *af = sctp_sk(sk)->pf->af;
3808                retval = af->setsockopt(sk, level, optname, optval, optlen);
3809                goto out_nounlock;
3810        }
3811
3812        lock_sock(sk);
3813
3814        switch (optname) {
3815        case SCTP_SOCKOPT_BINDX_ADD:
3816                /* 'optlen' is the size of the addresses buffer. */
3817                retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
3818                                               optlen, SCTP_BINDX_ADD_ADDR);
3819                break;
3820
3821        case SCTP_SOCKOPT_BINDX_REM:
3822                /* 'optlen' is the size of the addresses buffer. */
3823                retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
3824                                               optlen, SCTP_BINDX_REM_ADDR);
3825                break;
3826
3827        case SCTP_SOCKOPT_CONNECTX_OLD:
3828                /* 'optlen' is the size of the addresses buffer. */
3829                retval = sctp_setsockopt_connectx_old(sk,
3830                                            (struct sockaddr __user *)optval,
3831                                            optlen);
3832                break;
3833
3834        case SCTP_SOCKOPT_CONNECTX:
3835                /* 'optlen' is the size of the addresses buffer. */
3836                retval = sctp_setsockopt_connectx(sk,
3837                                            (struct sockaddr __user *)optval,
3838                                            optlen);
3839                break;
3840
3841        case SCTP_DISABLE_FRAGMENTS:
3842                retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
3843                break;
3844
3845        case SCTP_EVENTS:
3846                retval = sctp_setsockopt_events(sk, optval, optlen);
3847                break;
3848
3849        case SCTP_AUTOCLOSE:
3850                retval = sctp_setsockopt_autoclose(sk, optval, optlen);
3851                break;
3852
3853        case SCTP_PEER_ADDR_PARAMS:
3854                retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
3855                break;
3856
3857        case SCTP_DELAYED_SACK:
3858                retval = sctp_setsockopt_delayed_ack(sk, optval, optlen);
3859                break;
3860        case SCTP_PARTIAL_DELIVERY_POINT:
3861                retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen);
3862                break;
3863
3864        case SCTP_INITMSG:
3865                retval = sctp_setsockopt_initmsg(sk, optval, optlen);
3866                break;
3867        case SCTP_DEFAULT_SEND_PARAM:
3868                retval = sctp_setsockopt_default_send_param(sk, optval,
3869                                                            optlen);
3870                break;
3871        case SCTP_DEFAULT_SNDINFO:
3872                retval = sctp_setsockopt_default_sndinfo(sk, optval, optlen);
3873                break;
3874        case SCTP_PRIMARY_ADDR:
3875                retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
3876                break;
3877        case SCTP_SET_PEER_PRIMARY_ADDR:
3878                retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
3879                break;
3880        case SCTP_NODELAY:
3881                retval = sctp_setsockopt_nodelay(sk, optval, optlen);
3882                break;
3883        case SCTP_RTOINFO:
3884                retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
3885                break;
3886        case SCTP_ASSOCINFO:
3887                retval = sctp_setsockopt_associnfo(sk, optval, optlen);
3888                break;
3889        case SCTP_I_WANT_MAPPED_V4_ADDR:
3890                retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
3891                break;
3892        case SCTP_MAXSEG:
3893                retval = sctp_setsockopt_maxseg(sk, optval, optlen);
3894                break;
3895        case SCTP_ADAPTATION_LAYER:
3896                retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen);
3897                break;
3898        case SCTP_CONTEXT:
3899                retval = sctp_setsockopt_context(sk, optval, optlen);
3900                break;
3901        case SCTP_FRAGMENT_INTERLEAVE:
3902                retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen);
3903                break;
3904        case SCTP_MAX_BURST:
3905                retval = sctp_setsockopt_maxburst(sk, optval, optlen);
3906                break;
3907        case SCTP_AUTH_CHUNK:
3908                retval = sctp_setsockopt_auth_chunk(sk, optval, optlen);
3909                break;
3910        case SCTP_HMAC_IDENT:
3911                retval = sctp_setsockopt_hmac_ident(sk, optval, optlen);
3912                break;
3913        case SCTP_AUTH_KEY:
3914                retval = sctp_setsockopt_auth_key(sk, optval, optlen);
3915                break;
3916        case SCTP_AUTH_ACTIVE_KEY:
3917                retval = sctp_setsockopt_active_key(sk, optval, optlen);
3918                break;
3919        case SCTP_AUTH_DELETE_KEY:
3920                retval = sctp_setsockopt_del_key(sk, optval, optlen);
3921                break;
3922        case SCTP_AUTO_ASCONF:
3923                retval = sctp_setsockopt_auto_asconf(sk, optval, optlen);
3924                break;
3925        case SCTP_PEER_ADDR_THLDS:
3926                retval = sctp_setsockopt_paddr_thresholds(sk, optval, optlen);
3927                break;
3928        case SCTP_RECVRCVINFO:
3929                retval = sctp_setsockopt_recvrcvinfo(sk, optval, optlen);
3930                break;
3931        case SCTP_RECVNXTINFO:
3932                retval = sctp_setsockopt_recvnxtinfo(sk, optval, optlen);
3933                break;
3934        case SCTP_PR_SUPPORTED:
3935                retval = sctp_setsockopt_pr_supported(sk, optval, optlen);
3936                break;
3937        case SCTP_DEFAULT_PRINFO:
3938                retval = sctp_setsockopt_default_prinfo(sk, optval, optlen);
3939                break;
3940        default:
3941                retval = -ENOPROTOOPT;
3942                break;
3943        }
3944
3945        release_sock(sk);
3946
3947out_nounlock:
3948        return retval;
3949}
3950
3951/* API 3.1.6 connect() - UDP Style Syntax
3952 *
3953 * An application may use the connect() call in the UDP model to initiate an
3954 * association without sending data.
3955 *
3956 * The syntax is:
3957 *
3958 * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
3959 *
3960 * sd: the socket descriptor to have a new association added to.
3961 *
3962 * nam: the address structure (either struct sockaddr_in or struct
3963 *    sockaddr_in6 defined in RFC2553 [7]).
3964 *
3965 * len: the size of the address.
3966 */
3967static int sctp_connect(struct sock *sk, struct sockaddr *addr,
3968                        int addr_len)
3969{
3970        int err = 0;
3971        struct sctp_af *af;
3972
3973        lock_sock(sk);
3974
3975        pr_debug("%s: sk:%p, sockaddr:%p, addr_len:%d\n", __func__, sk,
3976                 addr, addr_len);
3977
3978        /* Validate addr_len before calling common connect/connectx routine. */
3979        af = sctp_get_af_specific(addr->sa_family);
3980        if (!af || addr_len < af->sockaddr_len) {
3981                err = -EINVAL;
3982        } else {
3983                /* Pass correct addr len to common routine (so it knows there
3984                 * is only one address being passed.
3985                 */
3986                err = __sctp_connect(sk, addr, af->sockaddr_len, NULL);
3987        }
3988
3989        release_sock(sk);
3990        return err;
3991}
3992
3993/* FIXME: Write comments. */
3994static int sctp_disconnect(struct sock *sk, int flags)
3995{
3996        return -EOPNOTSUPP; /* STUB */
3997}
3998
3999/* 4.1.4 accept() - TCP Style Syntax
4000 *
4001 * Applications use accept() call to remove an established SCTP
4002 * association from the accept queue of the endpoint.  A new socket
4003 * descriptor will be returned from accept() to represent the newly
4004 * formed association.
4005 */
4006static struct sock *sctp_accept(struct sock *sk, int flags, int *err)
4007{
4008        struct sctp_sock *sp;
4009        struct sctp_endpoint *ep;
4010        struct sock *newsk = NULL;
4011        struct sctp_association *asoc;
4012        long timeo;
4013        int error = 0;
4014
4015        lock_sock(sk);
4016
4017        sp = sctp_sk(sk);
4018        ep = sp->ep;
4019
4020        if (!sctp_style(sk, TCP)) {
4021                error = -EOPNOTSUPP;
4022                goto out;
4023        }
4024
4025        if (!sctp_sstate(sk, LISTENING)) {
4026                error = -EINVAL;
4027                goto out;
4028        }
4029
4030        timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
4031
4032        error = sctp_wait_for_accept(sk, timeo);
4033        if (error)
4034                goto out;
4035
4036        /* We treat the list of associations on the endpoint as the accept
4037         * queue and pick the first association on the list.
4038         */
4039        asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
4040
4041        newsk = sp->pf->create_accept_sk(sk, asoc);
4042        if (!newsk) {
4043                error = -ENOMEM;
4044                goto out;
4045        }
4046
4047        /* Populate the fields of the newsk from the oldsk and migrate the
4048         * asoc to the newsk.
4049         */
4050        sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
4051
4052out:
4053        release_sock(sk);
4054        *err = error;
4055        return newsk;
4056}
4057
4058/* The SCTP ioctl handler. */
4059static int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
4060{
4061        int rc = -ENOTCONN;
4062
4063        lock_sock(sk);
4064
4065        /*
4066         * SEQPACKET-style sockets in LISTENING state are valid, for
4067         * SCTP, so only discard TCP-style sockets in LISTENING state.
4068         */
4069        if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
4070                goto out;
4071
4072        switch (cmd) {
4073        case SIOCINQ: {
4074                struct sk_buff *skb;
4075                unsigned int amount = 0;
4076
4077                skb = skb_peek(&sk->sk_receive_queue);
4078                if (skb != NULL) {
4079                        /*
4080                         * We will only return the amount of this packet since
4081                         * that is all that will be read.
4082                         */
4083                        amount = skb->len;
4084                }
4085                rc = put_user(amount, (int __user *)arg);
4086                break;
4087        }
4088        default:
4089                rc = -ENOIOCTLCMD;
4090                break;
4091        }
4092out:
4093        release_sock(sk);
4094        return rc;
4095}
4096
4097/* This is the function which gets called during socket creation to
4098 * initialized the SCTP-specific portion of the sock.
4099 * The sock structure should already be zero-filled memory.
4100 */
4101static int sctp_init_sock(struct sock *sk)
4102{
4103        struct net *net = sock_net(sk);
4104        struct sctp_endpoint *ep;
4105        struct sctp_sock *sp;
4106
4107        pr_debug("%s: sk:%p\n", __func__, sk);
4108
4109        sp = sctp_sk(sk);
4110
4111        /* Initialize the SCTP per socket area.  */
4112        switch (sk->sk_type) {
4113        case SOCK_SEQPACKET:
4114                sp->type = SCTP_SOCKET_UDP;
4115                break;
4116        case SOCK_STREAM:
4117                sp->type = SCTP_SOCKET_TCP;
4118                break;
4119        default:
4120                return -ESOCKTNOSUPPORT;
4121        }
4122
4123        sk->sk_gso_type = SKB_GSO_SCTP;
4124
4125        /* Initialize default send parameters. These parameters can be
4126         * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
4127         */
4128        sp->default_stream = 0;
4129        sp->default_ppid = 0;
4130        sp->default_flags = 0;
4131        sp->default_context = 0;
4132        sp->default_timetolive = 0;
4133
4134        sp->default_rcv_context = 0;
4135        sp->max_burst = net->sctp.max_burst;
4136
4137        sp->sctp_hmac_alg = net->sctp.sctp_hmac_alg;
4138
4139        /* Initialize default setup parameters. These parameters
4140         * can be modified with the SCTP_INITMSG socket option or
4141         * overridden by the SCTP_INIT CMSG.
4142         */
4143        sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
4144        sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
4145        sp->initmsg.sinit_max_attempts   = net->sctp.max_retrans_init;
4146        sp->initmsg.sinit_max_init_timeo = net->sctp.rto_max;
4147
4148        /* Initialize default RTO related parameters.  These parameters can
4149         * be modified for with the SCTP_RTOINFO socket option.
4150         */
4151        sp->rtoinfo.srto_initial = net->sctp.rto_initial;
4152        sp->rtoinfo.srto_max     = net->sctp.rto_max;
4153        sp->rtoinfo.srto_min     = net->sctp.rto_min;
4154
4155        /* Initialize default association related parameters. These parameters
4156         * can be modified with the SCTP_ASSOCINFO socket option.
4157         */
4158        sp->assocparams.sasoc_asocmaxrxt = net->sctp.max_retrans_association;
4159        sp->assocparams.sasoc_number_peer_destinations = 0;
4160        sp->assocparams.sasoc_peer_rwnd = 0;
4161        sp->assocparams.sasoc_local_rwnd = 0;
4162        sp->assocparams.sasoc_cookie_life = net->sctp.valid_cookie_life;
4163
4164        /* Initialize default event subscriptions. By default, all the
4165         * options are off.
4166         */
4167        memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
4168
4169        /* Default Peer Address Parameters.  These defaults can
4170         * be modified via SCTP_PEER_ADDR_PARAMS
4171         */
4172        sp->hbinterval  = net->sctp.hb_interval;
4173        sp->pathmaxrxt  = net->sctp.max_retrans_path;
4174        sp->pathmtu     = 0; // allow default discovery
4175        sp->sackdelay   = net->sctp.sack_timeout;
4176        sp->sackfreq    = 2;
4177        sp->param_flags = SPP_HB_ENABLE |
4178                          SPP_PMTUD_ENABLE |
4179                          SPP_SACKDELAY_ENABLE;
4180
4181        /* If enabled no SCTP message fragmentation will be performed.
4182         * Configure through SCTP_DISABLE_FRAGMENTS socket option.
4183         */
4184        sp->disable_fragments = 0;
4185
4186        /* Enable Nagle algorithm by default.  */
4187        sp->nodelay           = 0;
4188
4189        sp->recvrcvinfo = 0;
4190        sp->recvnxtinfo = 0;
4191
4192        /* Enable by default. */
4193        sp->v4mapped          = 1;
4194
4195        /* Auto-close idle associations after the configured
4196         * number of seconds.  A value of 0 disables this
4197         * feature.  Configure through the SCTP_AUTOCLOSE socket option,
4198         * for UDP-style sockets only.
4199         */
4200        sp->autoclose         = 0;
4201
4202        /* User specified fragmentation limit. */
4203        sp->user_frag         = 0;
4204
4205        sp->adaptation_ind = 0;
4206
4207        sp->pf = sctp_get_pf_specific(sk->sk_family);
4208
4209        /* Control variables for partial data delivery. */
4210        atomic_set(&sp->pd_mode, 0);
4211        skb_queue_head_init(&sp->pd_lobby);
4212        sp->frag_interleave = 0;
4213
4214        /* Create a per socket endpoint structure.  Even if we
4215         * change the data structure relationships, this may still
4216         * be useful for storing pre-connect address information.
4217         */
4218        ep = sctp_endpoint_new(sk, GFP_KERNEL);
4219        if (!ep)
4220                return -ENOMEM;
4221
4222        sp->ep = ep;
4223        sp->hmac = NULL;
4224
4225        sk->sk_destruct = sctp_destruct_sock;
4226
4227        SCTP_DBG_OBJCNT_INC(sock);
4228
4229        local_bh_disable();
4230        percpu_counter_inc(&sctp_sockets_allocated);
4231        sock_prot_inuse_add(net, sk->sk_prot, 1);
4232
4233        /* Nothing can fail after this block, otherwise
4234         * sctp_destroy_sock() will be called without addr_wq_lock held
4235         */
4236        if (net->sctp.default_auto_asconf) {
4237                spin_lock(&sock_net(sk)->sctp.addr_wq_lock);
4238                list_add_tail(&sp->auto_asconf_list,
4239                    &net->sctp.auto_asconf_splist);
4240                sp->do_auto_asconf = 1;
4241                spin_unlock(&sock_net(sk)->sctp.addr_wq_lock);
4242        } else {
4243                sp->do_auto_asconf = 0;
4244        }
4245
4246        local_bh_enable();
4247
4248        return 0;
4249}
4250
4251/* Cleanup any SCTP per socket resources. Must be called with
4252 * sock_net(sk)->sctp.addr_wq_lock held if sp->do_auto_asconf is true
4253 */
4254static void sctp_destroy_sock(struct sock *sk)
4255{
4256        struct sctp_sock *sp;
4257
4258        pr_debug("%s: sk:%p\n", __func__, sk);
4259
4260        /* Release our hold on the endpoint. */
4261        sp = sctp_sk(sk);
4262        /* This could happen during socket init, thus we bail out
4263         * early, since the rest of the below is not setup either.
4264         */
4265        if (sp->ep == NULL)
4266                return;
4267
4268        if (sp->do_auto_asconf) {
4269                sp->do_auto_asconf = 0;
4270                list_del(&sp->auto_asconf_list);
4271        }
4272        sctp_endpoint_free(sp->ep);
4273        local_bh_disable();
4274        percpu_counter_dec(&sctp_sockets_allocated);
4275        sock_prot_inuse_add(sock_net(sk), sk->sk_prot, -1);
4276        local_bh_enable();
4277}
4278
4279/* Triggered when there are no references on the socket anymore */
4280static void sctp_destruct_sock(struct sock *sk)
4281{
4282        struct sctp_sock *sp = sctp_sk(sk);
4283
4284        /* Free up the HMAC transform. */
4285        crypto_free_hash(sp->hmac);
4286
4287        inet_sock_destruct(sk);
4288}
4289
4290/* API 4.1.7 shutdown() - TCP Style Syntax
4291 *     int shutdown(int socket, int how);
4292 *
4293 *     sd      - the socket descriptor of the association to be closed.
4294 *     how     - Specifies the type of shutdown.  The  values  are
4295 *               as follows:
4296 *               SHUT_RD
4297 *                     Disables further receive operations. No SCTP
4298 *                     protocol action is taken.
4299 *               SHUT_WR
4300 *                     Disables further send operations, and initiates
4301 *                     the SCTP shutdown sequence.
4302 *               SHUT_RDWR
4303 *                     Disables further send  and  receive  operations
4304 *                     and initiates the SCTP shutdown sequence.
4305 */
4306static void sctp_shutdown(struct sock *sk, int how)
4307{
4308        struct net *net = sock_net(sk);
4309        struct sctp_endpoint *ep;
4310
4311        if (!sctp_style(sk, TCP))
4312                return;
4313
4314        ep = sctp_sk(sk)->ep;
4315        if (how & SEND_SHUTDOWN && !list_empty(&ep->asocs)) {
4316                struct sctp_association *asoc;
4317
4318                sk->sk_state = SCTP_SS_CLOSING;
4319                asoc = list_entry(ep->asocs.next,
4320                                  struct sctp_association, asocs);
4321                sctp_primitive_SHUTDOWN(net, asoc, NULL);
4322        }
4323}
4324
4325int sctp_get_sctp_info(struct sock *sk, struct sctp_association *asoc,
4326                       struct sctp_info *info)
4327{
4328        struct sctp_transport *prim;
4329        struct list_head *pos;
4330        int mask;
4331
4332        memset(info, 0, sizeof(*info));
4333        if (!asoc) {
4334                struct sctp_sock *sp = sctp_sk(sk);
4335
4336                info->sctpi_s_autoclose = sp->autoclose;
4337                info->sctpi_s_adaptation_ind = sp->adaptation_ind;
4338                info->sctpi_s_pd_point = sp->pd_point;
4339                info->sctpi_s_nodelay = sp->nodelay;
4340                info->sctpi_s_disable_fragments = sp->disable_fragments;
4341                info->sctpi_s_v4mapped = sp->v4mapped;
4342                info->sctpi_s_frag_interleave = sp->frag_interleave;
4343                info->sctpi_s_type = sp->type;
4344
4345                return 0;
4346        }
4347
4348        info->sctpi_tag = asoc->c.my_vtag;
4349        info->sctpi_state = asoc->state;
4350        info->sctpi_rwnd = asoc->a_rwnd;
4351        info->sctpi_unackdata = asoc->unack_data;
4352        info->sctpi_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
4353        info->sctpi_instrms = asoc->c.sinit_max_instreams;
4354        info->sctpi_outstrms = asoc->c.sinit_num_ostreams;
4355        list_for_each(pos, &asoc->base.inqueue.in_chunk_list)
4356                info->sctpi_inqueue++;
4357        list_for_each(pos, &asoc->outqueue.out_chunk_list)
4358                info->sctpi_outqueue++;
4359        info->sctpi_overall_error = asoc->overall_error_count;
4360        info->sctpi_max_burst = asoc->max_burst;
4361        info->sctpi_maxseg = asoc->frag_point;
4362        info->sctpi_peer_rwnd = asoc->peer.rwnd;
4363        info->sctpi_peer_tag = asoc->c.peer_vtag;
4364
4365        mask = asoc->peer.ecn_capable << 1;
4366        mask = (mask | asoc->peer.ipv4_address) << 1;
4367        mask = (mask | asoc->peer.ipv6_address) << 1;
4368        mask = (mask | asoc->peer.hostname_address) << 1;
4369        mask = (mask | asoc->peer.asconf_capable) << 1;
4370        mask = (mask | asoc->peer.prsctp_capable) << 1;
4371        mask = (mask | asoc->peer.auth_capable);
4372        info->sctpi_peer_capable = mask;
4373        mask = asoc->peer.sack_needed << 1;
4374        mask = (mask | asoc->peer.sack_generation) << 1;
4375        mask = (mask | asoc->peer.zero_window_announced);
4376        info->sctpi_peer_sack = mask;
4377
4378        info->sctpi_isacks = asoc->stats.isacks;
4379        info->sctpi_osacks = asoc->stats.osacks;
4380        info->sctpi_opackets = asoc->stats.opackets;
4381        info->sctpi_ipackets = asoc->stats.ipackets;
4382        info->sctpi_rtxchunks = asoc->stats.rtxchunks;
4383        info->sctpi_outofseqtsns = asoc->stats.outofseqtsns;
4384        info->sctpi_idupchunks = asoc->stats.idupchunks;
4385        info->sctpi_gapcnt = asoc->stats.gapcnt;
4386        info->sctpi_ouodchunks = asoc->stats.ouodchunks;
4387        info->sctpi_iuodchunks = asoc->stats.iuodchunks;
4388        info->sctpi_oodchunks = asoc->stats.oodchunks;
4389        info->sctpi_iodchunks = asoc->stats.iodchunks;
4390        info->sctpi_octrlchunks = asoc->stats.octrlchunks;
4391        info->sctpi_ictrlchunks = asoc->stats.ictrlchunks;
4392
4393        prim = asoc->peer.primary_path;
4394        memcpy(&info->sctpi_p_address, &prim->ipaddr, sizeof(prim->ipaddr));
4395        info->sctpi_p_state = prim->state;
4396        info->sctpi_p_cwnd = prim->cwnd;
4397        info->sctpi_p_srtt = prim->srtt;
4398        info->sctpi_p_rto = jiffies_to_msecs(prim->rto);
4399        info->sctpi_p_hbinterval = prim->hbinterval;
4400        info->sctpi_p_pathmaxrxt = prim->pathmaxrxt;
4401        info->sctpi_p_sackdelay = jiffies_to_msecs(prim->sackdelay);
4402        info->sctpi_p_ssthresh = prim->ssthresh;
4403        info->sctpi_p_partial_bytes_acked = prim->partial_bytes_acked;
4404        info->sctpi_p_flight_size = prim->flight_size;
4405        info->sctpi_p_error = prim->error_count;
4406
4407        return 0;
4408}
4409EXPORT_SYMBOL_GPL(sctp_get_sctp_info);
4410
4411/* use callback to avoid exporting the core structure */
4412int sctp_transport_walk_start(struct rhashtable_iter *iter)
4413{
4414        int err;
4415
4416        rhltable_walk_enter(&sctp_transport_hashtable, iter);
4417
4418        err = rhashtable_walk_start(iter);
4419        if (err && err != -EAGAIN) {
4420                rhashtable_walk_stop(iter);
4421                rhashtable_walk_exit(iter);
4422                return err;
4423        }
4424
4425        return 0;
4426}
4427
4428void sctp_transport_walk_stop(struct rhashtable_iter *iter)
4429{
4430        rhashtable_walk_stop(iter);
4431        rhashtable_walk_exit(iter);
4432}
4433
4434struct sctp_transport *sctp_transport_get_next(struct net *net,
4435                                               struct rhashtable_iter *iter)
4436{
4437        struct sctp_transport *t;
4438
4439        t = rhashtable_walk_next(iter);
4440        for (; t; t = rhashtable_walk_next(iter)) {
4441                if (IS_ERR(t)) {
4442                        if (PTR_ERR(t) == -EAGAIN)
4443                                continue;
4444                        break;
4445                }
4446
4447                if (net_eq(sock_net(t->asoc->base.sk), net) &&
4448                    t->asoc->peer.primary_path == t)
4449                        break;
4450        }
4451
4452        return t;
4453}
4454
4455struct sctp_transport *sctp_transport_get_idx(struct net *net,
4456                                              struct rhashtable_iter *iter,
4457                                              int pos)
4458{
4459        void *obj = SEQ_START_TOKEN;
4460
4461        while (pos && (obj = sctp_transport_get_next(net, iter)) &&
4462               !IS_ERR(obj))
4463                pos--;
4464
4465        return obj;
4466}
4467
4468int sctp_for_each_endpoint(int (*cb)(struct sctp_endpoint *, void *),
4469                           void *p) {
4470        int err = 0;
4471        int hash = 0;
4472        struct sctp_ep_common *epb;
4473        struct sctp_hashbucket *head;
4474
4475        for (head = sctp_ep_hashtable; hash < sctp_ep_hashsize;
4476             hash++, head++) {
4477                read_lock_bh(&head->lock);
4478                sctp_for_each_hentry(epb, &head->chain) {
4479                        err = cb(sctp_ep(epb), p);
4480                        if (err)
4481                                break;
4482                }
4483                read_unlock_bh(&head->lock);
4484        }
4485
4486        return err;
4487}
4488EXPORT_SYMBOL_GPL(sctp_for_each_endpoint);
4489
4490int sctp_transport_lookup_process(int (*cb)(struct sctp_transport *, void *),
4491                                  struct net *net,
4492                                  const union sctp_addr *laddr,
4493                                  const union sctp_addr *paddr, void *p)
4494{
4495        struct sctp_transport *transport;
4496        int err;
4497
4498        rcu_read_lock();
4499        transport = sctp_addrs_lookup_transport(net, laddr, paddr);
4500        rcu_read_unlock();
4501        if (!transport)
4502                return -ENOENT;
4503
4504        err = cb(transport, p);
4505        sctp_transport_put(transport);
4506
4507        return err;
4508}
4509EXPORT_SYMBOL_GPL(sctp_transport_lookup_process);
4510
4511int sctp_for_each_transport(int (*cb)(struct sctp_transport *, void *),
4512                            struct net *net, int pos, void *p) {
4513        struct rhashtable_iter hti;
4514        void *obj;
4515        int err;
4516
4517        err = sctp_transport_walk_start(&hti);
4518        if (err)
4519                return err;
4520
4521        obj = sctp_transport_get_idx(net, &hti, pos + 1);
4522        for (; !IS_ERR_OR_NULL(obj); obj = sctp_transport_get_next(net, &hti)) {
4523                struct sctp_transport *transport = obj;
4524
4525                if (!sctp_transport_hold(transport))
4526                        continue;
4527                err = cb(transport, p);
4528                sctp_transport_put(transport);
4529                if (err)
4530                        break;
4531        }
4532        sctp_transport_walk_stop(&hti);
4533
4534        return err;
4535}
4536EXPORT_SYMBOL_GPL(sctp_for_each_transport);
4537
4538/* 7.2.1 Association Status (SCTP_STATUS)
4539
4540 * Applications can retrieve current status information about an
4541 * association, including association state, peer receiver window size,
4542 * number of unacked data chunks, and number of data chunks pending
4543 * receipt.  This information is read-only.
4544 */
4545static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
4546                                       char __user *optval,
4547                                       int __user *optlen)
4548{
4549        struct sctp_status status;
4550        struct sctp_association *asoc = NULL;
4551        struct sctp_transport *transport;
4552        sctp_assoc_t associd;
4553        int retval = 0;
4554
4555        if (len < sizeof(status)) {
4556                retval = -EINVAL;
4557                goto out;
4558        }
4559
4560        len = sizeof(status);
4561        if (copy_from_user(&status, optval, len)) {
4562                retval = -EFAULT;
4563                goto out;
4564        }
4565
4566        associd = status.sstat_assoc_id;
4567        asoc = sctp_id2assoc(sk, associd);
4568        if (!asoc) {
4569                retval = -EINVAL;
4570                goto out;
4571        }
4572
4573        transport = asoc->peer.primary_path;
4574
4575        status.sstat_assoc_id = sctp_assoc2id(asoc);
4576        status.sstat_state = sctp_assoc_to_state(asoc);
4577        status.sstat_rwnd =  asoc->peer.rwnd;
4578        status.sstat_unackdata = asoc->unack_data;
4579
4580        status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
4581        status.sstat_instrms = asoc->c.sinit_max_instreams;
4582        status.sstat_outstrms = asoc->c.sinit_num_ostreams;
4583        status.sstat_fragmentation_point = asoc->frag_point;
4584        status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4585        memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
4586                        transport->af_specific->sockaddr_len);
4587        /* Map ipv4 address into v4-mapped-on-v6 address.  */
4588        sctp_get_pf_specific(sk->sk_family)->addr_to_user(sctp_sk(sk),
4589                (union sctp_addr *)&status.sstat_primary.spinfo_address);
4590        status.sstat_primary.spinfo_state = transport->state;
4591        status.sstat_primary.spinfo_cwnd = transport->cwnd;
4592        status.sstat_primary.spinfo_srtt = transport->srtt;
4593        status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
4594        status.sstat_primary.spinfo_mtu = transport->pathmtu;
4595
4596        if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
4597                status.sstat_primary.spinfo_state = SCTP_ACTIVE;
4598
4599        if (put_user(len, optlen)) {
4600                retval = -EFAULT;
4601                goto out;
4602        }
4603
4604        pr_debug("%s: len:%d, state:%d, rwnd:%d, assoc_id:%d\n",
4605                 __func__, len, status.sstat_state, status.sstat_rwnd,
4606                 status.sstat_assoc_id);
4607
4608        if (copy_to_user(optval, &status, len)) {
4609                retval = -EFAULT;
4610                goto out;
4611        }
4612
4613out:
4614        return retval;
4615}
4616
4617
4618/* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
4619 *
4620 * Applications can retrieve information about a specific peer address
4621 * of an association, including its reachability state, congestion
4622 * window, and retransmission timer values.  This information is
4623 * read-only.
4624 */
4625static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
4626                                          char __user *optval,
4627                                          int __user *optlen)
4628{
4629        struct sctp_paddrinfo pinfo;
4630        struct sctp_transport *transport;
4631        int retval = 0;
4632
4633        if (len < sizeof(pinfo)) {
4634                retval = -EINVAL;
4635                goto out;
4636        }
4637
4638        len = sizeof(pinfo);
4639        if (copy_from_user(&pinfo, optval, len)) {
4640                retval = -EFAULT;
4641                goto out;
4642        }
4643
4644        transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
4645                                           pinfo.spinfo_assoc_id);
4646        if (!transport)
4647                return -EINVAL;
4648
4649        pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
4650        pinfo.spinfo_state = transport->state;
4651        pinfo.spinfo_cwnd = transport->cwnd;
4652        pinfo.spinfo_srtt = transport->srtt;
4653        pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
4654        pinfo.spinfo_mtu = transport->pathmtu;
4655
4656        if (pinfo.spinfo_state == SCTP_UNKNOWN)
4657                pinfo.spinfo_state = SCTP_ACTIVE;
4658
4659        if (put_user(len, optlen)) {
4660                retval = -EFAULT;
4661                goto out;
4662        }
4663
4664        if (copy_to_user(optval, &pinfo, len)) {
4665                retval = -EFAULT;
4666                goto out;
4667        }
4668
4669out:
4670        return retval;
4671}
4672
4673/* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
4674 *
4675 * This option is a on/off flag.  If enabled no SCTP message
4676 * fragmentation will be performed.  Instead if a message being sent
4677 * exceeds the current PMTU size, the message will NOT be sent and
4678 * instead a error will be indicated to the user.
4679 */
4680static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
4681                                        char __user *optval, int __user *optlen)
4682{
4683        int val;
4684
4685        if (len < sizeof(int))
4686                return -EINVAL;
4687
4688        len = sizeof(int);
4689        val = (sctp_sk(sk)->disable_fragments == 1);
4690        if (put_user(len, optlen))
4691                return -EFAULT;
4692        if (copy_to_user(optval, &val, len))
4693                return -EFAULT;
4694        return 0;
4695}
4696
4697/* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
4698 *
4699 * This socket option is used to specify various notifications and
4700 * ancillary data the user wishes to receive.
4701 */
4702static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
4703                                  int __user *optlen)
4704{
4705        if (len == 0)
4706                return -EINVAL;
4707        if (len > sizeof(struct sctp_event_subscribe))
4708                len = sizeof(struct sctp_event_subscribe);
4709        if (put_user(len, optlen))
4710                return -EFAULT;
4711        if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
4712                return -EFAULT;
4713        return 0;
4714}
4715
4716/* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
4717 *
4718 * This socket option is applicable to the UDP-style socket only.  When
4719 * set it will cause associations that are idle for more than the
4720 * specified number of seconds to automatically close.  An association
4721 * being idle is defined an association that has NOT sent or received
4722 * user data.  The special value of '0' indicates that no automatic
4723 * close of any associations should be performed.  The option expects an
4724 * integer defining the number of seconds of idle time before an
4725 * association is closed.
4726 */
4727static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
4728{
4729        /* Applicable to UDP-style socket only */
4730        if (sctp_style(sk, TCP))
4731                return -EOPNOTSUPP;
4732        if (len < sizeof(int))
4733                return -EINVAL;
4734        len = sizeof(int);
4735        if (put_user(len, optlen))
4736                return -EFAULT;
4737        if (copy_to_user(optval, &sctp_sk(sk)->autoclose, sizeof(int)))
4738                return -EFAULT;
4739        return 0;
4740}
4741
4742/* Helper routine to branch off an association to a new socket.  */
4743int sctp_do_peeloff(struct sock *sk, sctp_assoc_t id, struct socket **sockp)
4744{
4745        struct sctp_association *asoc = sctp_id2assoc(sk, id);
4746        struct sctp_sock *sp = sctp_sk(sk);
4747        struct socket *sock;
4748        int err = 0;
4749
4750        if (!asoc)
4751                return -EINVAL;
4752
4753        /* If there is a thread waiting on more sndbuf space for
4754         * sending on this asoc, it cannot be peeled.
4755         */
4756        if (waitqueue_active(&asoc->wait))
4757                return -EBUSY;
4758
4759        /* An association cannot be branched off from an already peeled-off
4760         * socket, nor is this supported for tcp style sockets.
4761         */
4762        if (!sctp_style(sk, UDP))
4763                return -EINVAL;
4764
4765        /* Create a new socket.  */
4766        err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
4767        if (err < 0)
4768                return err;
4769
4770        sctp_copy_sock(sock->sk, sk, asoc);
4771
4772        /* Make peeled-off sockets more like 1-1 accepted sockets.
4773         * Set the daddr and initialize id to something more random
4774         */
4775        sp->pf->to_sk_daddr(&asoc->peer.primary_addr, sk);
4776
4777        /* Populate the fields of the newsk from the oldsk and migrate the
4778         * asoc to the newsk.
4779         */
4780        sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
4781
4782        *sockp = sock;
4783
4784        return err;
4785}
4786EXPORT_SYMBOL(sctp_do_peeloff);
4787
4788static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
4789{
4790        sctp_peeloff_arg_t peeloff;
4791        struct socket *newsock;
4792        struct file *newfile;
4793        int retval = 0;
4794
4795        if (len < sizeof(sctp_peeloff_arg_t))
4796                return -EINVAL;
4797        len = sizeof(sctp_peeloff_arg_t);
4798        if (copy_from_user(&peeloff, optval, len))
4799                return -EFAULT;
4800
4801        retval = sctp_do_peeloff(sk, peeloff.associd, &newsock);
4802        if (retval < 0)
4803                goto out;
4804
4805        /* Map the socket to an unused fd that can be returned to the user.  */
4806        retval = get_unused_fd();
4807        if (retval < 0) {
4808                sock_release(newsock);
4809                goto out;
4810        }
4811
4812        newfile = sock_alloc_file(newsock, 0, NULL);
4813        if (IS_ERR(newfile)) {
4814                put_unused_fd(retval);
4815                sock_release(newsock);
4816                return PTR_ERR(newfile);
4817        }
4818
4819        pr_debug("%s: sk:%p, newsk:%p, sd:%d\n", __func__, sk, newsock->sk,
4820                 retval);
4821
4822        /* Return the fd mapped to the new socket.  */
4823        if (put_user(len, optlen)) {
4824                fput(newfile);
4825                put_unused_fd(retval);
4826                return -EFAULT;
4827        }
4828        peeloff.sd = retval;
4829        if (copy_to_user(optval, &peeloff, len)) {
4830                fput(newfile);
4831                put_unused_fd(retval);
4832                return -EFAULT;
4833        }
4834        fd_install(retval, newfile);
4835out:
4836        return retval;
4837}
4838
4839/* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
4840 *
4841 * Applications can enable or disable heartbeats for any peer address of
4842 * an association, modify an address's heartbeat interval, force a
4843 * heartbeat to be sent immediately, and adjust the address's maximum
4844 * number of retransmissions sent before an address is considered
4845 * unreachable.  The following structure is used to access and modify an
4846 * address's parameters:
4847 *
4848 *  struct sctp_paddrparams {
4849 *     sctp_assoc_t            spp_assoc_id;
4850 *     struct sockaddr_storage spp_address;
4851 *     uint32_t                spp_hbinterval;
4852 *     uint16_t                spp_pathmaxrxt;
4853 *     uint32_t                spp_pathmtu;
4854 *     uint32_t                spp_sackdelay;
4855 *     uint32_t                spp_flags;
4856 * };
4857 *
4858 *   spp_assoc_id    - (one-to-many style socket) This is filled in the
4859 *                     application, and identifies the association for
4860 *                     this query.
4861 *   spp_address     - This specifies which address is of interest.
4862 *   spp_hbinterval  - This contains the value of the heartbeat interval,
4863 *                     in milliseconds.  If a  value of zero
4864 *                     is present in this field then no changes are to
4865 *                     be made to this parameter.
4866 *   spp_pathmaxrxt  - This contains the maximum number of
4867 *                     retransmissions before this address shall be
4868 *                     considered unreachable. If a  value of zero
4869 *                     is present in this field then no changes are to
4870 *                     be made to this parameter.
4871 *   spp_pathmtu     - When Path MTU discovery is disabled the value
4872 *                     specified here will be the "fixed" path mtu.
4873 *                     Note that if the spp_address field is empty
4874 *                     then all associations on this address will
4875 *                     have this fixed path mtu set upon them.
4876 *
4877 *   spp_sackdelay   - When delayed sack is enabled, this value specifies
4878 *                     the number of milliseconds that sacks will be delayed
4879 *                     for. This value will apply to all addresses of an
4880 *                     association if the spp_address field is empty. Note
4881 *                     also, that if delayed sack is enabled and this
4882 *                     value is set to 0, no change is made to the last
4883 *                     recorded delayed sack timer value.
4884 *
4885 *   spp_flags       - These flags are used to control various features
4886 *                     on an association. The flag field may contain
4887 *                     zero or more of the following options.
4888 *
4889 *                     SPP_HB_ENABLE  - Enable heartbeats on the
4890 *                     specified address. Note that if the address
4891 *                     field is empty all addresses for the association
4892 *                     have heartbeats enabled upon them.
4893 *
4894 *                     SPP_HB_DISABLE - Disable heartbeats on the
4895 *                     speicifed address. Note that if the address
4896 *                     field is empty all addresses for the association
4897 *                     will have their heartbeats disabled. Note also
4898 *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
4899 *                     mutually exclusive, only one of these two should
4900 *                     be specified. Enabling both fields will have
4901 *                     undetermined results.
4902 *
4903 *                     SPP_HB_DEMAND - Request a user initiated heartbeat
4904 *                     to be made immediately.
4905 *
4906 *                     SPP_PMTUD_ENABLE - This field will enable PMTU
4907 *                     discovery upon the specified address. Note that
4908 *                     if the address feild is empty then all addresses
4909 *                     on the association are effected.
4910 *
4911 *                     SPP_PMTUD_DISABLE - This field will disable PMTU
4912 *                     discovery upon the specified address. Note that
4913 *                     if the address feild is empty then all addresses
4914 *                     on the association are effected. Not also that
4915 *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
4916 *                     exclusive. Enabling both will have undetermined
4917 *                     results.
4918 *
4919 *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
4920 *                     on delayed sack. The time specified in spp_sackdelay
4921 *                     is used to specify the sack delay for this address. Note
4922 *                     that if spp_address is empty then all addresses will
4923 *                     enable delayed sack and take on the sack delay
4924 *                     value specified in spp_sackdelay.
4925 *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
4926 *                     off delayed sack. If the spp_address field is blank then
4927 *                     delayed sack is disabled for the entire association. Note
4928 *                     also that this field is mutually exclusive to
4929 *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
4930 *                     results.
4931 */
4932static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
4933                                            char __user *optval, int __user *optlen)
4934{
4935        struct sctp_paddrparams  params;
4936        struct sctp_transport   *trans = NULL;
4937        struct sctp_association *asoc = NULL;
4938        struct sctp_sock        *sp = sctp_sk(sk);
4939
4940        if (len < sizeof(struct sctp_paddrparams))
4941                return -EINVAL;
4942        len = sizeof(struct sctp_paddrparams);
4943        if (copy_from_user(&params, optval, len))
4944                return -EFAULT;
4945
4946        /* If an address other than INADDR_ANY is specified, and
4947         * no transport is found, then the request is invalid.
4948         */
4949        if (!sctp_is_any(sk, (union sctp_addr *)&params.spp_address)) {
4950                trans = sctp_addr_id2transport(sk, &params.spp_address,
4951                                               params.spp_assoc_id);
4952                if (!trans) {
4953                        pr_debug("%s: failed no transport\n", __func__);
4954                        return -EINVAL;
4955                }
4956        }
4957
4958        /* Get association, if assoc_id != 0 and the socket is a one
4959         * to many style socket, and an association was not found, then
4960         * the id was invalid.
4961         */
4962        asoc = sctp_id2assoc(sk, params.spp_assoc_id);
4963        if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) {
4964                pr_debug("%s: failed no association\n", __func__);
4965                return -EINVAL;
4966        }
4967
4968        if (trans) {
4969                /* Fetch transport values. */
4970                params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
4971                params.spp_pathmtu    = trans->pathmtu;
4972                params.spp_pathmaxrxt = trans->pathmaxrxt;
4973                params.spp_sackdelay  = jiffies_to_msecs(trans->sackdelay);
4974
4975                /*draft-11 doesn't say what to return in spp_flags*/
4976                params.spp_flags      = trans->param_flags;
4977        } else if (asoc) {
4978                /* Fetch association values. */
4979                params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
4980                params.spp_pathmtu    = asoc->pathmtu;
4981                params.spp_pathmaxrxt = asoc->pathmaxrxt;
4982                params.spp_sackdelay  = jiffies_to_msecs(asoc->sackdelay);
4983
4984                /*draft-11 doesn't say what to return in spp_flags*/
4985                params.spp_flags      = asoc->param_flags;
4986        } else {
4987                /* Fetch socket values. */
4988                params.spp_hbinterval = sp->hbinterval;
4989                params.spp_pathmtu    = sp->pathmtu;
4990                params.spp_sackdelay  = sp->sackdelay;
4991                params.spp_pathmaxrxt = sp->pathmaxrxt;
4992
4993                /*draft-11 doesn't say what to return in spp_flags*/
4994                params.spp_flags      = sp->param_flags;
4995        }
4996
4997        if (copy_to_user(optval, &params, len))
4998                return -EFAULT;
4999
5000        if (put_user(len, optlen))
5001                return -EFAULT;
5002
5003        return 0;
5004}
5005
5006/*
5007 * 7.1.23.  Get or set delayed ack timer (SCTP_DELAYED_SACK)
5008 *
5009 * This option will effect the way delayed acks are performed.  This
5010 * option allows you to get or set the delayed ack time, in
5011 * milliseconds.  It also allows changing the delayed ack frequency.
5012 * Changing the frequency to 1 disables the delayed sack algorithm.  If
5013 * the assoc_id is 0, then this sets or gets the endpoints default
5014 * values.  If the assoc_id field is non-zero, then the set or get
5015 * effects the specified association for the one to many model (the
5016 * assoc_id field is ignored by the one to one model).  Note that if
5017 * sack_delay or sack_freq are 0 when setting this option, then the
5018 * current values will remain unchanged.
5019 *
5020 * struct sctp_sack_info {
5021 *     sctp_assoc_t            sack_assoc_id;
5022 *     uint32_t                sack_delay;
5023 *     uint32_t                sack_freq;
5024 * };
5025 *
5026 * sack_assoc_id -  This parameter, indicates which association the user
5027 *    is performing an action upon.  Note that if this field's value is
5028 *    zero then the endpoints default value is changed (effecting future
5029 *    associations only).
5030 *
5031 * sack_delay -  This parameter contains the number of milliseconds that
5032 *    the user is requesting the delayed ACK timer be set to.  Note that
5033 *    this value is defined in the standard to be between 200 and 500
5034 *    milliseconds.
5035 *
5036 * sack_freq -  This parameter contains the number of packets that must
5037 *    be received before a sack is sent without waiting for the delay
5038 *    timer to expire.  The default value for this is 2, setting this
5039 *    value to 1 will disable the delayed sack algorithm.
5040 */
5041static int sctp_getsockopt_delayed_ack(struct sock *sk, int len,
5042                                            char __user *optval,
5043                                            int __user *optlen)
5044{
5045        struct sctp_sack_info    params;
5046        struct sctp_association *asoc = NULL;
5047        struct sctp_sock        *sp = sctp_sk(sk);
5048
5049        if (len >= sizeof(struct sctp_sack_info)) {
5050                len = sizeof(struct sctp_sack_info);
5051
5052                if (copy_from_user(&params, optval, len))
5053                        return -EFAULT;
5054        } else if (len == sizeof(struct sctp_assoc_value)) {
5055                pr_warn_ratelimited("%s (pid %d) "
5056                                    "Use of struct sctp_assoc_value in delayed_ack socket option deprecated\n"
5057                                    "Use struct sctp_sack_info instead\n",
5058                                    current->comm, task_pid_nr(current));
5059                if (copy_from_user(&params, optval, len))
5060                        return -EFAULT;
5061        } else
5062                return -EINVAL;
5063
5064        /* Get association, if sack_assoc_id != 0 and the socket is a one
5065         * to many style socket, and an association was not found, then
5066         * the id was invalid.
5067         */
5068        asoc = sctp_id2assoc(sk, params.sack_assoc_id);
5069        if (!asoc && params.sack_assoc_id && sctp_style(sk, UDP))
5070                return -EINVAL;
5071
5072        if (asoc) {
5073                /* Fetch association values. */
5074                if (asoc->param_flags & SPP_SACKDELAY_ENABLE) {
5075                        params.sack_delay = jiffies_to_msecs(
5076                                asoc->sackdelay);
5077                        params.sack_freq = asoc->sackfreq;
5078
5079                } else {
5080                        params.sack_delay = 0;
5081                        params.sack_freq = 1;
5082                }
5083        } else {
5084                /* Fetch socket values. */
5085                if (sp->param_flags & SPP_SACKDELAY_ENABLE) {
5086                        params.sack_delay  = sp->sackdelay;
5087                        params.sack_freq = sp->sackfreq;
5088                } else {
5089                        params.sack_delay  = 0;
5090                        params.sack_freq = 1;
5091                }
5092        }
5093
5094        if (copy_to_user(optval, &params, len))
5095                return -EFAULT;
5096
5097        if (put_user(len, optlen))
5098                return -EFAULT;
5099
5100        return 0;
5101}
5102
5103/* 7.1.3 Initialization Parameters (SCTP_INITMSG)
5104 *
5105 * Applications can specify protocol parameters for the default association
5106 * initialization.  The option name argument to setsockopt() and getsockopt()
5107 * is SCTP_INITMSG.
5108 *
5109 * Setting initialization parameters is effective only on an unconnected
5110 * socket (for UDP-style sockets only future associations are effected
5111 * by the change).  With TCP-style sockets, this option is inherited by
5112 * sockets derived from a listener socket.
5113 */
5114static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
5115{
5116        if (len < sizeof(struct sctp_initmsg))
5117                return -EINVAL;
5118        len = sizeof(struct sctp_initmsg);
5119        if (put_user(len, optlen))
5120                return -EFAULT;
5121        if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
5122                return -EFAULT;
5123        return 0;
5124}
5125
5126
5127static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
5128                                      char __user *optval, int __user *optlen)
5129{
5130        struct sctp_association *asoc;
5131        int cnt = 0;
5132        struct sctp_getaddrs getaddrs;
5133        struct sctp_transport *from;
5134        void __user *to;
5135        union sctp_addr temp;
5136        struct sctp_sock *sp = sctp_sk(sk);
5137        int addrlen;
5138        size_t space_left;
5139        int bytes_copied;
5140
5141        if (len < sizeof(struct sctp_getaddrs))
5142                return -EINVAL;
5143
5144        if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
5145                return -EFAULT;
5146
5147        /* For UDP-style sockets, id specifies the association to query.  */
5148        asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
5149        if (!asoc)
5150                return -EINVAL;
5151
5152        to = optval + offsetof(struct sctp_getaddrs, addrs);
5153        space_left = len - offsetof(struct sctp_getaddrs, addrs);
5154
5155        list_for_each_entry(from, &asoc->peer.transport_addr_list,
5156                                transports) {
5157                memcpy(&temp, &from->ipaddr, sizeof(temp));
5158                addrlen = sctp_get_pf_specific(sk->sk_family)
5159                              ->addr_to_user(sp, &temp);
5160                if (space_left < addrlen)
5161                        return -ENOMEM;
5162                if (copy_to_user(to, &temp, addrlen))
5163                        return -EFAULT;
5164                to += addrlen;
5165                cnt++;
5166                space_left -= addrlen;
5167        }
5168
5169        if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
5170                return -EFAULT;
5171        bytes_copied = ((char __user *)to) - optval;
5172        if (put_user(bytes_copied, optlen))
5173                return -EFAULT;
5174
5175        return 0;
5176}
5177
5178static int sctp_copy_laddrs(struct sock *sk, __u16 port, void *to,
5179                            size_t space_left, int *bytes_copied)
5180{
5181        struct sctp_sockaddr_entry *addr;
5182        union sctp_addr temp;
5183        int cnt = 0;
5184        int addrlen;
5185        struct net *net = sock_net(sk);
5186
5187        rcu_read_lock();
5188        list_for_each_entry_rcu(addr, &net->sctp.local_addr_list, list) {
5189                if (!addr->valid)
5190                        continue;
5191
5192                if ((PF_INET == sk->sk_family) &&
5193                    (AF_INET6 == addr->a.sa.sa_family))
5194                        continue;
5195                if ((PF_INET6 == sk->sk_family) &&
5196                    inet_v6_ipv6only(sk) &&
5197                    (AF_INET == addr->a.sa.sa_family))
5198                        continue;
5199                memcpy(&temp, &addr->a, sizeof(temp));
5200                if (!temp.v4.sin_port)
5201                        temp.v4.sin_port = htons(port);
5202
5203                addrlen = sctp_get_pf_specific(sk->sk_family)
5204                              ->addr_to_user(sctp_sk(sk), &temp);
5205
5206                if (space_left < addrlen) {
5207                        cnt =  -ENOMEM;
5208                        break;
5209                }
5210                memcpy(to, &temp, addrlen);
5211
5212                to += addrlen;
5213                cnt++;
5214                space_left -= addrlen;
5215                *bytes_copied += addrlen;
5216        }
5217        rcu_read_unlock();
5218
5219        return cnt;
5220}
5221
5222
5223static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
5224                                       char __user *optval, int __user *optlen)
5225{
5226        struct sctp_bind_addr *bp;
5227        struct sctp_association *asoc;
5228        int cnt = 0;
5229        struct sctp_getaddrs getaddrs;
5230        struct sctp_sockaddr_entry *addr;
5231        void __user *to;
5232        union sctp_addr temp;
5233        struct sctp_sock *sp = sctp_sk(sk);
5234        int addrlen;
5235        int err = 0;
5236        size_t space_left;
5237        int bytes_copied = 0;
5238        void *addrs;
5239        void *buf;
5240
5241        if (len < sizeof(struct sctp_getaddrs))
5242                return -EINVAL;
5243
5244        if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
5245                return -EFAULT;
5246
5247        /*
5248         *  For UDP-style sockets, id specifies the association to query.
5249         *  If the id field is set to the value '0' then the locally bound
5250         *  addresses are returned without regard to any particular
5251         *  association.
5252         */
5253        if (0 == getaddrs.assoc_id) {
5254                bp = &sctp_sk(sk)->ep->base.bind_addr;
5255        } else {
5256                asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
5257                if (!asoc)
5258                        return -EINVAL;
5259                bp = &asoc->base.bind_addr;
5260        }
5261
5262        to = optval + offsetof(struct sctp_getaddrs, addrs);
5263        space_left = len - offsetof(struct sctp_getaddrs, addrs);
5264
5265        addrs = kmalloc(space_left, GFP_USER | __GFP_NOWARN);
5266        if (!addrs)
5267                return -ENOMEM;
5268
5269        /* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
5270         * addresses from the global local address list.
5271         */
5272        if (sctp_list_single_entry(&bp->address_list)) {
5273                addr = list_entry(bp->address_list.next,
5274                                  struct sctp_sockaddr_entry, list);
5275                if (sctp_is_any(sk, &addr->a)) {
5276                        cnt = sctp_copy_laddrs(sk, bp->port, addrs,
5277                                                space_left, &bytes_copied);
5278                        if (cnt < 0) {
5279                                err = cnt;
5280                                goto out;
5281                        }
5282                        goto copy_getaddrs;
5283                }
5284        }
5285
5286        buf = addrs;
5287        /* Protection on the bound address list is not needed since
5288         * in the socket option context we hold a socket lock and
5289         * thus the bound address list can't change.
5290         */
5291        list_for_each_entry(addr, &bp->address_list, list) {
5292                memcpy(&temp, &addr->a, sizeof(temp));
5293                addrlen = sctp_get_pf_specific(sk->sk_family)
5294                              ->addr_to_user(sp, &temp);
5295                if (space_left < addrlen) {
5296                        err =  -ENOMEM; /*fixme: right error?*/
5297                        goto out;
5298                }
5299                memcpy(buf, &temp, addrlen);
5300                buf += addrlen;
5301                bytes_copied += addrlen;
5302                cnt++;
5303                space_left -= addrlen;
5304        }
5305
5306copy_getaddrs:
5307        if (copy_to_user(to, addrs, bytes_copied)) {
5308                err = -EFAULT;
5309                goto out;
5310        }
5311        if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num)) {
5312                err = -EFAULT;
5313                goto out;
5314        }
5315        if (put_user(bytes_copied, optlen))
5316                err = -EFAULT;
5317out:
5318        kfree(addrs);
5319        return err;
5320}
5321
5322/* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
5323 *
5324 * Requests that the local SCTP stack use the enclosed peer address as
5325 * the association primary.  The enclosed address must be one of the
5326 * association peer's addresses.
5327 */
5328static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
5329                                        char __user *optval, int __user *optlen)
5330{
5331        struct sctp_prim prim;
5332        struct sctp_association *asoc;
5333        struct sctp_sock *sp = sctp_sk(sk);
5334
5335        if (len < sizeof(struct sctp_prim))
5336                return -EINVAL;
5337
5338        len = sizeof(struct sctp_prim);
5339
5340        if (copy_from_user(&prim, optval, len))
5341                return -EFAULT;
5342
5343        asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
5344        if (!asoc)
5345                return -EINVAL;
5346
5347        if (!asoc->peer.primary_path)
5348                return -ENOTCONN;
5349
5350        memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
5351                asoc->peer.primary_path->af_specific->sockaddr_len);
5352
5353        sctp_get_pf_specific(sk->sk_family)->addr_to_user(sp,
5354                        (union sctp_addr *)&prim.ssp_addr);
5355
5356        if (put_user(len, optlen))
5357                return -EFAULT;
5358        if (copy_to_user(optval, &prim, len))
5359                return -EFAULT;
5360
5361        return 0;
5362}
5363
5364/*
5365 * 7.1.11  Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
5366 *
5367 * Requests that the local endpoint set the specified Adaptation Layer
5368 * Indication parameter for all future INIT and INIT-ACK exchanges.
5369 */
5370static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
5371                                  char __user *optval, int __user *optlen)
5372{
5373        struct sctp_setadaptation adaptation;
5374
5375        if (len < sizeof(struct sctp_setadaptation))
5376                return -EINVAL;
5377
5378        len = sizeof(struct sctp_setadaptation);
5379
5380        adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
5381
5382        if (put_user(len, optlen))
5383                return -EFAULT;
5384        if (copy_to_user(optval, &adaptation, len))
5385                return -EFAULT;
5386
5387        return 0;
5388}
5389
5390/*
5391 *
5392 * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
5393 *
5394 *   Applications that wish to use the sendto() system call may wish to
5395 *   specify a default set of parameters that would normally be supplied
5396 *   through the inclusion of ancillary data.  This socket option allows
5397 *   such an application to set the default sctp_sndrcvinfo structure.
5398
5399
5400 *   The application that wishes to use this socket option simply passes
5401 *   in to this call the sctp_sndrcvinfo structure defined in Section
5402 *   5.2.2) The input parameters accepted by this call include
5403 *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
5404 *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
5405 *   to this call if the caller is using the UDP model.
5406 *
5407 *   For getsockopt, it get the default sctp_sndrcvinfo structure.
5408 */
5409static int sctp_getsockopt_default_send_param(struct sock *sk,
5410                                        int len, char __user *optval,
5411                                        int __user *optlen)
5412{
5413        struct sctp_sock *sp = sctp_sk(sk);
5414        struct sctp_association *asoc;
5415        struct sctp_sndrcvinfo info;
5416
5417        if (len < sizeof(info))
5418                return -EINVAL;
5419
5420        len = sizeof(info);
5421
5422        if (copy_from_user(&info, optval, len))
5423                return -EFAULT;
5424
5425        asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
5426        if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
5427                return -EINVAL;
5428        if (asoc) {
5429                info.sinfo_stream = asoc->default_stream;
5430                info.sinfo_flags = asoc->default_flags;
5431                info.sinfo_ppid = asoc->default_ppid;
5432                info.sinfo_context = asoc->default_context;
5433                info.sinfo_timetolive = asoc->default_timetolive;
5434        } else {
5435                info.sinfo_stream = sp->default_stream;
5436                info.sinfo_flags = sp->default_flags;
5437                info.sinfo_ppid = sp->default_ppid;
5438                info.sinfo_context = sp->default_context;
5439                info.sinfo_timetolive = sp->default_timetolive;
5440        }
5441
5442        if (put_user(len, optlen))
5443                return -EFAULT;
5444        if (copy_to_user(optval, &info, len))
5445                return -EFAULT;
5446
5447        return 0;
5448}
5449
5450/* RFC6458, Section 8.1.31. Set/get Default Send Parameters
5451 * (SCTP_DEFAULT_SNDINFO)
5452 */
5453static int sctp_getsockopt_default_sndinfo(struct sock *sk, int len,
5454                                           char __user *optval,
5455                                           int __user *optlen)
5456{
5457        struct sctp_sock *sp = sctp_sk(sk);
5458        struct sctp_association *asoc;
5459        struct sctp_sndinfo info;
5460
5461        if (len < sizeof(info))
5462                return -EINVAL;
5463
5464        len = sizeof(info);
5465
5466        if (copy_from_user(&info, optval, len))
5467                return -EFAULT;
5468
5469        asoc = sctp_id2assoc(sk, info.snd_assoc_id);
5470        if (!asoc && info.snd_assoc_id && sctp_style(sk, UDP))
5471                return -EINVAL;
5472        if (asoc) {
5473                info.snd_sid = asoc->default_stream;
5474                info.snd_flags = asoc->default_flags;
5475                info.snd_ppid = asoc->default_ppid;
5476                info.snd_context = asoc->default_context;
5477        } else {
5478                info.snd_sid = sp->default_stream;
5479                info.snd_flags = sp->default_flags;
5480                info.snd_ppid = sp->default_ppid;
5481                info.snd_context = sp->default_context;
5482        }
5483
5484        if (put_user(len, optlen))
5485                return -EFAULT;
5486        if (copy_to_user(optval, &info, len))
5487                return -EFAULT;
5488
5489        return 0;
5490}
5491
5492/*
5493 *
5494 * 7.1.5 SCTP_NODELAY
5495 *
5496 * Turn on/off any Nagle-like algorithm.  This means that packets are
5497 * generally sent as soon as possible and no unnecessary delays are
5498 * introduced, at the cost of more packets in the network.  Expects an
5499 * integer boolean flag.
5500 */
5501
5502static int sctp_getsockopt_nodelay(struct sock *sk, int len,
5503                                   char __user *optval, int __user *optlen)
5504{
5505        int val;
5506
5507        if (len < sizeof(int))
5508                return -EINVAL;
5509
5510        len = sizeof(int);
5511        val = (sctp_sk(sk)->nodelay == 1);
5512        if (put_user(len, optlen))
5513                return -EFAULT;
5514        if (copy_to_user(optval, &val, len))
5515                return -EFAULT;
5516        return 0;
5517}
5518
5519/*
5520 *
5521 * 7.1.1 SCTP_RTOINFO
5522 *
5523 * The protocol parameters used to initialize and bound retransmission
5524 * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
5525 * and modify these parameters.
5526 * All parameters are time values, in milliseconds.  A value of 0, when
5527 * modifying the parameters, indicates that the current value should not
5528 * be changed.
5529 *
5530 */
5531static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
5532                                char __user *optval,
5533                                int __user *optlen) {
5534        struct sctp_rtoinfo rtoinfo;
5535        struct sctp_association *asoc;
5536
5537        if (len < sizeof (struct sctp_rtoinfo))
5538                return -EINVAL;
5539
5540        len = sizeof(struct sctp_rtoinfo);
5541
5542        if (copy_from_user(&rtoinfo, optval, len))
5543                return -EFAULT;
5544
5545        asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
5546
5547        if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
5548                return -EINVAL;
5549
5550        /* Values corresponding to the specific association. */
5551        if (asoc) {
5552                rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
5553                rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
5554                rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
5555        } else {
5556                /* Values corresponding to the endpoint. */
5557                struct sctp_sock *sp = sctp_sk(sk);
5558
5559                rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
5560                rtoinfo.srto_max = sp->rtoinfo.srto_max;
5561                rtoinfo.srto_min = sp->rtoinfo.srto_min;
5562        }
5563
5564        if (put_user(len, optlen))
5565                return -EFAULT;
5566
5567        if (copy_to_user(optval, &rtoinfo, len))
5568                return -EFAULT;
5569
5570        return 0;
5571}
5572
5573/*
5574 *
5575 * 7.1.2 SCTP_ASSOCINFO
5576 *
5577 * This option is used to tune the maximum retransmission attempts
5578 * of the association.
5579 * Returns an error if the new association retransmission value is
5580 * greater than the sum of the retransmission value  of the peer.
5581 * See [SCTP] for more information.
5582 *
5583 */
5584static int sctp_getsockopt_associnfo(struct sock *sk, int len,
5585                                     char __user *optval,
5586                                     int __user *optlen)
5587{
5588
5589        struct sctp_assocparams assocparams;
5590        struct sctp_association *asoc;
5591        struct list_head *pos;
5592        int cnt = 0;
5593
5594        if (len < sizeof (struct sctp_assocparams))
5595                return -EINVAL;
5596
5597        len = sizeof(struct sctp_assocparams);
5598
5599        if (copy_from_user(&assocparams, optval, len))
5600                return -EFAULT;
5601
5602        asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
5603
5604        if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
5605                return -EINVAL;
5606
5607        /* Values correspoinding to the specific association */
5608        if (asoc) {
5609                assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
5610                assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
5611                assocparams.sasoc_local_rwnd = asoc->a_rwnd;
5612                assocparams.sasoc_cookie_life = ktime_to_ms(asoc->cookie_life);
5613
5614                list_for_each(pos, &asoc->peer.transport_addr_list) {
5615                        cnt++;
5616                }
5617
5618                assocparams.sasoc_number_peer_destinations = cnt;
5619        } else {
5620                /* Values corresponding to the endpoint */
5621                struct sctp_sock *sp = sctp_sk(sk);
5622
5623                assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
5624                assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
5625                assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
5626                assocparams.sasoc_cookie_life =
5627                                        sp->assocparams.sasoc_cookie_life;
5628                assocparams.sasoc_number_peer_destinations =
5629                                        sp->assocparams.
5630                                        sasoc_number_peer_destinations;
5631        }
5632
5633        if (put_user(len, optlen))
5634                return -EFAULT;
5635
5636        if (copy_to_user(optval, &assocparams, len))
5637                return -EFAULT;
5638
5639        return 0;
5640}
5641
5642/*
5643 * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
5644 *
5645 * This socket option is a boolean flag which turns on or off mapped V4
5646 * addresses.  If this option is turned on and the socket is type
5647 * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
5648 * If this option is turned off, then no mapping will be done of V4
5649 * addresses and a user will receive both PF_INET6 and PF_INET type
5650 * addresses on the socket.
5651 */
5652static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
5653                                    char __user *optval, int __user *optlen)
5654{
5655        int val;
5656        struct sctp_sock *sp = sctp_sk(sk);
5657
5658        if (len < sizeof(int))
5659                return -EINVAL;
5660
5661        len = sizeof(int);
5662        val = sp->v4mapped;
5663        if (put_user(len, optlen))
5664                return -EFAULT;
5665        if (copy_to_user(optval, &val, len))
5666                return -EFAULT;
5667
5668        return 0;
5669}
5670
5671/*
5672 * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
5673 * (chapter and verse is quoted at sctp_setsockopt_context())
5674 */
5675static int sctp_getsockopt_context(struct sock *sk, int len,
5676                                   char __user *optval, int __user *optlen)
5677{
5678        struct sctp_assoc_value params;
5679        struct sctp_sock *sp;
5680        struct sctp_association *asoc;
5681
5682        if (len < sizeof(struct sctp_assoc_value))
5683                return -EINVAL;
5684
5685        len = sizeof(struct sctp_assoc_value);
5686
5687        if (copy_from_user(&params, optval, len))
5688                return -EFAULT;
5689
5690        sp = sctp_sk(sk);
5691
5692        if (params.assoc_id != 0) {
5693                asoc = sctp_id2assoc(sk, params.assoc_id);
5694                if (!asoc)
5695                        return -EINVAL;
5696                params.assoc_value = asoc->default_rcv_context;
5697        } else {
5698                params.assoc_value = sp->default_rcv_context;
5699        }
5700
5701        if (put_user(len, optlen))
5702                return -EFAULT;
5703        if (copy_to_user(optval, &params, len))
5704                return -EFAULT;
5705
5706        return 0;
5707}
5708
5709/*
5710 * 8.1.16.  Get or Set the Maximum Fragmentation Size (SCTP_MAXSEG)
5711 * This option will get or set the maximum size to put in any outgoing
5712 * SCTP DATA chunk.  If a message is larger than this size it will be
5713 * fragmented by SCTP into the specified size.  Note that the underlying
5714 * SCTP implementation may fragment into smaller sized chunks when the
5715 * PMTU of the underlying association is smaller than the value set by
5716 * the user.  The default value for this option is '0' which indicates
5717 * the user is NOT limiting fragmentation and only the PMTU will effect
5718 * SCTP's choice of DATA chunk size.  Note also that values set larger
5719 * than the maximum size of an IP datagram will effectively let SCTP
5720 * control fragmentation (i.e. the same as setting this option to 0).
5721 *
5722 * The following structure is used to access and modify this parameter:
5723 *
5724 * struct sctp_assoc_value {
5725 *   sctp_assoc_t assoc_id;
5726 *   uint32_t assoc_value;
5727 * };
5728 *
5729 * assoc_id:  This parameter is ignored for one-to-one style sockets.
5730 *    For one-to-many style sockets this parameter indicates which
5731 *    association the user is performing an action upon.  Note that if
5732 *    this field's value is zero then the endpoints default value is
5733 *    changed (effecting future associations only).
5734 * assoc_value:  This parameter specifies the maximum size in bytes.
5735 */
5736static int sctp_getsockopt_maxseg(struct sock *sk, int len,
5737                                  char __user *optval, int __user *optlen)
5738{
5739        struct sctp_assoc_value params;
5740        struct sctp_association *asoc;
5741
5742        if (len == sizeof(int)) {
5743                pr_warn_ratelimited("%s (pid %d) "
5744                                    "Use of int in maxseg socket option deprecated\n"
5745                                    "Use struct sctp_assoc_value instead\n",
5746                                    current->comm, task_pid_nr(current));
5747                params.assoc_id = 0;
5748        } else if (len >= sizeof(struct sctp_assoc_value)) {
5749                len = sizeof(struct sctp_assoc_value);
5750                if (copy_from_user(&params, optval, sizeof(params)))
5751                        return -EFAULT;
5752        } else
5753                return -EINVAL;
5754
5755        asoc = sctp_id2assoc(sk, params.assoc_id);
5756        if (!asoc && params.assoc_id && sctp_style(sk, UDP))
5757                return -EINVAL;
5758
5759        if (asoc)
5760                params.assoc_value = asoc->frag_point;
5761        else
5762                params.assoc_value = sctp_sk(sk)->user_frag;
5763
5764        if (put_user(len, optlen))
5765                return -EFAULT;
5766        if (len == sizeof(int)) {
5767                if (copy_to_user(optval, &params.assoc_value, len))
5768                        return -EFAULT;
5769        } else {
5770                if (copy_to_user(optval, &params, len))
5771                        return -EFAULT;
5772        }
5773
5774        return 0;
5775}
5776
5777/*
5778 * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
5779 * (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
5780 */
5781static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
5782                                               char __user *optval, int __user *optlen)
5783{
5784        int val;
5785
5786        if (len < sizeof(int))
5787                return -EINVAL;
5788
5789        len = sizeof(int);
5790
5791        val = sctp_sk(sk)->frag_interleave;
5792        if (put_user(len, optlen))
5793                return -EFAULT;
5794        if (copy_to_user(optval, &val, len))
5795                return -EFAULT;
5796
5797        return 0;
5798}
5799
5800/*
5801 * 7.1.25.  Set or Get the sctp partial delivery point
5802 * (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
5803 */
5804static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
5805                                                  char __user *optval,
5806                                                  int __user *optlen)
5807{
5808        u32 val;
5809
5810        if (len < sizeof(u32))
5811                return -EINVAL;
5812
5813        len = sizeof(u32);
5814
5815        val = sctp_sk(sk)->pd_point;
5816        if (put_user(len, optlen))
5817                return -EFAULT;
5818        if (copy_to_user(optval, &val, len))
5819                return -EFAULT;
5820
5821        return 0;
5822}
5823
5824/*
5825 * 7.1.28.  Set or Get the maximum burst (SCTP_MAX_BURST)
5826 * (chapter and verse is quoted at sctp_setsockopt_maxburst())
5827 */
5828static int sctp_getsockopt_maxburst(struct sock *sk, int len,
5829                                    char __user *optval,
5830                                    int __user *optlen)
5831{
5832        struct sctp_assoc_value params;
5833        struct sctp_sock *sp;
5834        struct sctp_association *asoc;
5835
5836        if (len == sizeof(int)) {
5837                pr_warn_ratelimited("%s (pid %d) "
5838                                    "Use of int in max_burst socket option deprecated\n"
5839                                    "Use struct sctp_assoc_value instead\n",
5840                                    current->comm, task_pid_nr(current));
5841                params.assoc_id = 0;
5842        } else if (len >= sizeof(struct sctp_assoc_value)) {
5843                len = sizeof(struct sctp_assoc_value);
5844                if (copy_from_user(&params, optval, len))
5845                        return -EFAULT;
5846        } else
5847                return -EINVAL;
5848
5849        sp = sctp_sk(sk);
5850
5851        if (params.assoc_id != 0) {
5852                asoc = sctp_id2assoc(sk, params.assoc_id);
5853                if (!asoc)
5854                        return -EINVAL;
5855                params.assoc_value = asoc->max_burst;
5856        } else
5857                params.assoc_value = sp->max_burst;
5858
5859        if (len == sizeof(int)) {
5860                if (copy_to_user(optval, &params.assoc_value, len))
5861                        return -EFAULT;
5862        } else {
5863                if (copy_to_user(optval, &params, len))
5864                        return -EFAULT;
5865        }
5866
5867        return 0;
5868
5869}
5870
5871static int sctp_getsockopt_hmac_ident(struct sock *sk, int len,
5872                                    char __user *optval, int __user *optlen)
5873{
5874        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
5875        struct sctp_hmacalgo  __user *p = (void __user *)optval;
5876        struct sctp_hmac_algo_param *hmacs;
5877        __u16 data_len = 0;
5878        u32 num_idents;
5879        int i;
5880
5881        if (!ep->auth_enable)
5882                return -EACCES;
5883
5884        hmacs = ep->auth_hmacs_list;
5885        data_len = ntohs(hmacs->param_hdr.length) - sizeof(sctp_paramhdr_t);
5886
5887        if (len < sizeof(struct sctp_hmacalgo) + data_len)
5888                return -EINVAL;
5889
5890        len = sizeof(struct sctp_hmacalgo) + data_len;
5891        num_idents = data_len / sizeof(u16);
5892
5893        if (put_user(len, optlen))
5894                return -EFAULT;
5895        if (put_user(num_idents, &p->shmac_num_idents))
5896                return -EFAULT;
5897        for (i = 0; i < num_idents; i++) {
5898                __u16 hmacid = ntohs(hmacs->hmac_ids[i]);
5899
5900                if (copy_to_user(&p->shmac_idents[i], &hmacid, sizeof(__u16)))
5901                        return -EFAULT;
5902        }
5903        return 0;
5904}
5905
5906static int sctp_getsockopt_active_key(struct sock *sk, int len,
5907                                    char __user *optval, int __user *optlen)
5908{
5909        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
5910        struct sctp_authkeyid val;
5911        struct sctp_association *asoc;
5912
5913        if (!ep->auth_enable)
5914                return -EACCES;
5915
5916        if (len < sizeof(struct sctp_authkeyid))
5917                return -EINVAL;
5918        if (copy_from_user(&val, optval, sizeof(struct sctp_authkeyid)))
5919                return -EFAULT;
5920
5921        asoc = sctp_id2assoc(sk, val.scact_assoc_id);
5922        if (!asoc && val.scact_assoc_id && sctp_style(sk, UDP))
5923                return -EINVAL;
5924
5925        if (asoc)
5926                val.scact_keynumber = asoc->active_key_id;
5927        else
5928                val.scact_keynumber = ep->active_key_id;
5929
5930        len = sizeof(struct sctp_authkeyid);
5931        if (put_user(len, optlen))
5932                return -EFAULT;
5933        if (copy_to_user(optval, &val, len))
5934                return -EFAULT;
5935
5936        return 0;
5937}
5938
5939static int sctp_getsockopt_peer_auth_chunks(struct sock *sk, int len,
5940                                    char __user *optval, int __user *optlen)
5941{
5942        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
5943        struct sctp_authchunks __user *p = (void __user *)optval;
5944        struct sctp_authchunks val;
5945        struct sctp_association *asoc;
5946        struct sctp_chunks_param *ch;
5947        u32    num_chunks = 0;
5948        char __user *to;
5949
5950        if (!ep->auth_enable)
5951                return -EACCES;
5952
5953        if (len < sizeof(struct sctp_authchunks))
5954                return -EINVAL;
5955
5956        if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
5957                return -EFAULT;
5958
5959        to = p->gauth_chunks;
5960        asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
5961        if (!asoc)
5962                return -EINVAL;
5963
5964        ch = asoc->peer.peer_chunks;
5965        if (!ch)
5966                goto num;
5967
5968        /* See if the user provided enough room for all the data */
5969        num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t);
5970        if (len < num_chunks)
5971                return -EINVAL;
5972
5973        if (copy_to_user(to, ch->chunks, num_chunks))
5974                return -EFAULT;
5975num:
5976        len = sizeof(struct sctp_authchunks) + num_chunks;
5977        if (put_user(len, optlen))
5978                return -EFAULT;
5979        if (put_user(num_chunks, &p->gauth_number_of_chunks))
5980                return -EFAULT;
5981        return 0;
5982}
5983
5984static int sctp_getsockopt_local_auth_chunks(struct sock *sk, int len,
5985                                    char __user *optval, int __user *optlen)
5986{
5987        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
5988        struct sctp_authchunks __user *p = (void __user *)optval;
5989        struct sctp_authchunks val;
5990        struct sctp_association *asoc;
5991        struct sctp_chunks_param *ch;
5992        u32    num_chunks = 0;
5993        char __user *to;
5994
5995        if (!ep->auth_enable)
5996                return -EACCES;
5997
5998        if (len < sizeof(struct sctp_authchunks))
5999                return -EINVAL;
6000
6001        if (copy_from_user(&val, optval, sizeof(struct sctp_authchunks)))
6002                return -EFAULT;
6003
6004        to = p->gauth_chunks;
6005        asoc = sctp_id2assoc(sk, val.gauth_assoc_id);
6006        if (!asoc && val.gauth_assoc_id && sctp_style(sk, UDP))
6007                return -EINVAL;
6008
6009        if (asoc)
6010                ch = (struct sctp_chunks_param *)asoc->c.auth_chunks;
6011        else
6012                ch = ep->auth_chunk_list;
6013
6014        if (!ch)
6015                goto num;
6016
6017        num_chunks = ntohs(ch->param_hdr.length) - sizeof(sctp_paramhdr_t);
6018        if (len < sizeof(struct sctp_authchunks) + num_chunks)
6019                return -EINVAL;
6020
6021        if (copy_to_user(to, ch->chunks, num_chunks))
6022                return -EFAULT;
6023num:
6024        len = sizeof(struct sctp_authchunks) + num_chunks;
6025        if (put_user(len, optlen))
6026                return -EFAULT;
6027        if (put_user(num_chunks, &p->gauth_number_of_chunks))
6028                return -EFAULT;
6029
6030        return 0;
6031}
6032
6033/*
6034 * 8.2.5.  Get the Current Number of Associations (SCTP_GET_ASSOC_NUMBER)
6035 * This option gets the current number of associations that are attached
6036 * to a one-to-many style socket.  The option value is an uint32_t.
6037 */
6038static int sctp_getsockopt_assoc_number(struct sock *sk, int len,
6039                                    char __user *optval, int __user *optlen)
6040{
6041        struct sctp_sock *sp = sctp_sk(sk);
6042        struct sctp_association *asoc;
6043        u32 val = 0;
6044
6045        if (sctp_style(sk, TCP))
6046                return -EOPNOTSUPP;
6047
6048        if (len < sizeof(u32))
6049                return -EINVAL;
6050
6051        len = sizeof(u32);
6052
6053        list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6054                val++;
6055        }
6056
6057        if (put_user(len, optlen))
6058                return -EFAULT;
6059        if (copy_to_user(optval, &val, len))
6060                return -EFAULT;
6061
6062        return 0;
6063}
6064
6065/*
6066 * 8.1.23 SCTP_AUTO_ASCONF
6067 * See the corresponding setsockopt entry as description
6068 */
6069static int sctp_getsockopt_auto_asconf(struct sock *sk, int len,
6070                                   char __user *optval, int __user *optlen)
6071{
6072        int val = 0;
6073
6074        if (len < sizeof(int))
6075                return -EINVAL;
6076
6077        len = sizeof(int);
6078        if (sctp_sk(sk)->do_auto_asconf && sctp_is_ep_boundall(sk))
6079                val = 1;
6080        if (put_user(len, optlen))
6081                return -EFAULT;
6082        if (copy_to_user(optval, &val, len))
6083                return -EFAULT;
6084        return 0;
6085}
6086
6087/*
6088 * 8.2.6. Get the Current Identifiers of Associations
6089 *        (SCTP_GET_ASSOC_ID_LIST)
6090 *
6091 * This option gets the current list of SCTP association identifiers of
6092 * the SCTP associations handled by a one-to-many style socket.
6093 */
6094static int sctp_getsockopt_assoc_ids(struct sock *sk, int len,
6095                                    char __user *optval, int __user *optlen)
6096{
6097        struct sctp_sock *sp = sctp_sk(sk);
6098        struct sctp_association *asoc;
6099        struct sctp_assoc_ids *ids;
6100        u32 num = 0;
6101
6102        if (sctp_style(sk, TCP))
6103                return -EOPNOTSUPP;
6104
6105        if (len < sizeof(struct sctp_assoc_ids))
6106                return -EINVAL;
6107
6108        list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6109                num++;
6110        }
6111
6112        if (len < sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num)
6113                return -EINVAL;
6114
6115        len = sizeof(struct sctp_assoc_ids) + sizeof(sctp_assoc_t) * num;
6116
6117        ids = kmalloc(len, GFP_USER | __GFP_NOWARN);
6118        if (unlikely(!ids))
6119                return -ENOMEM;
6120
6121        ids->gaids_number_of_ids = num;
6122        num = 0;
6123        list_for_each_entry(asoc, &(sp->ep->asocs), asocs) {
6124                ids->gaids_assoc_id[num++] = asoc->assoc_id;
6125        }
6126
6127        if (put_user(len, optlen) || copy_to_user(optval, ids, len)) {
6128                kfree(ids);
6129                return -EFAULT;
6130        }
6131
6132        kfree(ids);
6133        return 0;
6134}
6135
6136/*
6137 * SCTP_PEER_ADDR_THLDS
6138 *
6139 * This option allows us to fetch the partially failed threshold for one or all
6140 * transports in an association.  See Section 6.1 of:
6141 * http://www.ietf.org/id/draft-nishida-tsvwg-sctp-failover-05.txt
6142 */
6143static int sctp_getsockopt_paddr_thresholds(struct sock *sk,
6144                                            char __user *optval,
6145                                            int len,
6146                                            int __user *optlen)
6147{
6148        struct sctp_paddrthlds val;
6149        struct sctp_transport *trans;
6150        struct sctp_association *asoc;
6151
6152        if (len < sizeof(struct sctp_paddrthlds))
6153                return -EINVAL;
6154        len = sizeof(struct sctp_paddrthlds);
6155        if (copy_from_user(&val, (struct sctp_paddrthlds __user *)optval, len))
6156                return -EFAULT;
6157
6158        if (sctp_is_any(sk, (const union sctp_addr *)&val.spt_address)) {
6159                asoc = sctp_id2assoc(sk, val.spt_assoc_id);
6160                if (!asoc)
6161                        return -ENOENT;
6162
6163                val.spt_pathpfthld = asoc->pf_retrans;
6164                val.spt_pathmaxrxt = asoc->pathmaxrxt;
6165        } else {
6166                trans = sctp_addr_id2transport(sk, &val.spt_address,
6167                                               val.spt_assoc_id);
6168                if (!trans)
6169                        return -ENOENT;
6170
6171                val.spt_pathmaxrxt = trans->pathmaxrxt;
6172                val.spt_pathpfthld = trans->pf_retrans;
6173        }
6174
6175        if (put_user(len, optlen) || copy_to_user(optval, &val, len))
6176                return -EFAULT;
6177
6178        return 0;
6179}
6180
6181/*
6182 * SCTP_GET_ASSOC_STATS
6183 *
6184 * This option retrieves local per endpoint statistics. It is modeled
6185 * after OpenSolaris' implementation
6186 */
6187static int sctp_getsockopt_assoc_stats(struct sock *sk, int len,
6188                                       char __user *optval,
6189                                       int __user *optlen)
6190{
6191        struct sctp_assoc_stats sas;
6192        struct sctp_association *asoc = NULL;
6193
6194        /* User must provide at least the assoc id */
6195        if (len < sizeof(sctp_assoc_t))
6196                return -EINVAL;
6197
6198        /* Allow the struct to grow and fill in as much as possible */
6199        len = min_t(size_t, len, sizeof(sas));
6200
6201        if (copy_from_user(&sas, optval, len))
6202                return -EFAULT;
6203
6204        asoc = sctp_id2assoc(sk, sas.sas_assoc_id);
6205        if (!asoc)
6206                return -EINVAL;
6207
6208        sas.sas_rtxchunks = asoc->stats.rtxchunks;
6209        sas.sas_gapcnt = asoc->stats.gapcnt;
6210        sas.sas_outofseqtsns = asoc->stats.outofseqtsns;
6211        sas.sas_osacks = asoc->stats.osacks;
6212        sas.sas_isacks = asoc->stats.isacks;
6213        sas.sas_octrlchunks = asoc->stats.octrlchunks;
6214        sas.sas_ictrlchunks = asoc->stats.ictrlchunks;
6215        sas.sas_oodchunks = asoc->stats.oodchunks;
6216        sas.sas_iodchunks = asoc->stats.iodchunks;
6217        sas.sas_ouodchunks = asoc->stats.ouodchunks;
6218        sas.sas_iuodchunks = asoc->stats.iuodchunks;
6219        sas.sas_idupchunks = asoc->stats.idupchunks;
6220        sas.sas_opackets = asoc->stats.opackets;
6221        sas.sas_ipackets = asoc->stats.ipackets;
6222
6223        /* New high max rto observed, will return 0 if not a single
6224         * RTO update took place. obs_rto_ipaddr will be bogus
6225         * in such a case
6226         */
6227        sas.sas_maxrto = asoc->stats.max_obs_rto;
6228        memcpy(&sas.sas_obs_rto_ipaddr, &asoc->stats.obs_rto_ipaddr,
6229                sizeof(struct sockaddr_storage));
6230
6231        /* Mark beginning of a new observation period */
6232        asoc->stats.max_obs_rto = asoc->rto_min;
6233
6234        if (put_user(len, optlen))
6235                return -EFAULT;
6236
6237        pr_debug("%s: len:%d, assoc_id:%d\n", __func__, len, sas.sas_assoc_id);
6238
6239        if (copy_to_user(optval, &sas, len))
6240                return -EFAULT;
6241
6242        return 0;
6243}
6244
6245static int sctp_getsockopt_recvrcvinfo(struct sock *sk, int len,
6246                                       char __user *optval,
6247                                       int __user *optlen)
6248{
6249        int val = 0;
6250
6251        if (len < sizeof(int))
6252                return -EINVAL;
6253
6254        len = sizeof(int);
6255        if (sctp_sk(sk)->recvrcvinfo)
6256                val = 1;
6257        if (put_user(len, optlen))
6258                return -EFAULT;
6259        if (copy_to_user(optval, &val, len))
6260                return -EFAULT;
6261
6262        return 0;
6263}
6264
6265static int sctp_getsockopt_recvnxtinfo(struct sock *sk, int len,
6266                                       char __user *optval,
6267                                       int __user *optlen)
6268{
6269        int val = 0;
6270
6271        if (len < sizeof(int))
6272                return -EINVAL;
6273
6274        len = sizeof(int);
6275        if (sctp_sk(sk)->recvnxtinfo)
6276                val = 1;
6277        if (put_user(len, optlen))
6278                return -EFAULT;
6279        if (copy_to_user(optval, &val, len))
6280                return -EFAULT;
6281
6282        return 0;
6283}
6284
6285static int sctp_getsockopt_pr_supported(struct sock *sk, int len,
6286                                        char __user *optval,
6287                                        int __user *optlen)
6288{
6289        struct sctp_assoc_value params;
6290        struct sctp_association *asoc;
6291        int retval = -EFAULT;
6292
6293        if (len < sizeof(params)) {
6294                retval = -EINVAL;
6295                goto out;
6296        }
6297
6298        len = sizeof(params);
6299        if (copy_from_user(&params, optval, len))
6300                goto out;
6301
6302        asoc = sctp_id2assoc(sk, params.assoc_id);
6303        if (asoc) {
6304                params.assoc_value = asoc->prsctp_enable;
6305        } else if (!params.assoc_id) {
6306                struct sctp_sock *sp = sctp_sk(sk);
6307
6308                params.assoc_value = sp->ep->prsctp_enable;
6309        } else {
6310                retval = -EINVAL;
6311                goto out;
6312        }
6313
6314        if (put_user(len, optlen))
6315                goto out;
6316
6317        if (copy_to_user(optval, &params, len))
6318                goto out;
6319
6320        retval = 0;
6321
6322out:
6323        return retval;
6324}
6325
6326static int sctp_getsockopt_default_prinfo(struct sock *sk, int len,
6327                                          char __user *optval,
6328                                          int __user *optlen)
6329{
6330        struct sctp_default_prinfo info;
6331        struct sctp_association *asoc;
6332        int retval = -EFAULT;
6333
6334        if (len < sizeof(info)) {
6335                retval = -EINVAL;
6336                goto out;
6337        }
6338
6339        len = sizeof(info);
6340        if (copy_from_user(&info, optval, len))
6341                goto out;
6342
6343        asoc = sctp_id2assoc(sk, info.pr_assoc_id);
6344        if (asoc) {
6345                info.pr_policy = SCTP_PR_POLICY(asoc->default_flags);
6346                info.pr_value = asoc->default_timetolive;
6347        } else if (!info.pr_assoc_id) {
6348                struct sctp_sock *sp = sctp_sk(sk);
6349
6350                info.pr_policy = SCTP_PR_POLICY(sp->default_flags);
6351                info.pr_value = sp->default_timetolive;
6352        } else {
6353                retval = -EINVAL;
6354                goto out;
6355        }
6356
6357        if (put_user(len, optlen))
6358                goto out;
6359
6360        if (copy_to_user(optval, &info, len))
6361                goto out;
6362
6363        retval = 0;
6364
6365out:
6366        return retval;
6367}
6368
6369static int sctp_getsockopt_pr_assocstatus(struct sock *sk, int len,
6370                                          char __user *optval,
6371                                          int __user *optlen)
6372{
6373        struct sctp_prstatus params;
6374        struct sctp_association *asoc;
6375        int policy;
6376        int retval = -EINVAL;
6377
6378        if (len < sizeof(params))
6379                goto out;
6380
6381        len = sizeof(params);
6382        if (copy_from_user(&params, optval, len)) {
6383                retval = -EFAULT;
6384                goto out;
6385        }
6386
6387        policy = params.sprstat_policy;
6388        if (policy & ~SCTP_PR_SCTP_MASK)
6389                goto out;
6390
6391        asoc = sctp_id2assoc(sk, params.sprstat_assoc_id);
6392        if (!asoc)
6393                goto out;
6394
6395        if (policy == SCTP_PR_SCTP_NONE) {
6396                params.sprstat_abandoned_unsent = 0;
6397                params.sprstat_abandoned_sent = 0;
6398                for (policy = 0; policy <= SCTP_PR_INDEX(MAX); policy++) {
6399                        params.sprstat_abandoned_unsent +=
6400                                asoc->abandoned_unsent[policy];
6401                        params.sprstat_abandoned_sent +=
6402                                asoc->abandoned_sent[policy];
6403                }
6404        } else {
6405                params.sprstat_abandoned_unsent =
6406                        asoc->abandoned_unsent[__SCTP_PR_INDEX(policy)];
6407                params.sprstat_abandoned_sent =
6408                        asoc->abandoned_sent[__SCTP_PR_INDEX(policy)];
6409        }
6410
6411        if (put_user(len, optlen)) {
6412                retval = -EFAULT;
6413                goto out;
6414        }
6415
6416        if (copy_to_user(optval, &params, len)) {
6417                retval = -EFAULT;
6418                goto out;
6419        }
6420
6421        retval = 0;
6422
6423out:
6424        return retval;
6425}
6426
6427static int sctp_getsockopt(struct sock *sk, int level, int optname,
6428                           char __user *optval, int __user *optlen)
6429{
6430        int retval = 0;
6431        int len;
6432
6433        pr_debug("%s: sk:%p, optname:%d\n", __func__, sk, optname);
6434
6435        /* I can hardly begin to describe how wrong this is.  This is
6436         * so broken as to be worse than useless.  The API draft
6437         * REALLY is NOT helpful here...  I am not convinced that the
6438         * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
6439         * are at all well-founded.
6440         */
6441        if (level != SOL_SCTP) {
6442                struct sctp_af *af = sctp_sk(sk)->pf->af;
6443
6444                retval = af->getsockopt(sk, level, optname, optval, optlen);
6445                return retval;
6446        }
6447
6448        if (get_user(len, optlen))
6449                return -EFAULT;
6450
6451        if (len < 0)
6452                return -EINVAL;
6453
6454        lock_sock(sk);
6455
6456        switch (optname) {
6457        case SCTP_STATUS:
6458                retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
6459                break;
6460        case SCTP_DISABLE_FRAGMENTS:
6461                retval = sctp_getsockopt_disable_fragments(sk, len, optval,
6462                                                           optlen);
6463                break;
6464        case SCTP_EVENTS:
6465                retval = sctp_getsockopt_events(sk, len, optval, optlen);
6466                break;
6467        case SCTP_AUTOCLOSE:
6468                retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
6469                break;
6470        case SCTP_SOCKOPT_PEELOFF:
6471                retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
6472                break;
6473        case SCTP_PEER_ADDR_PARAMS:
6474                retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
6475                                                          optlen);
6476                break;
6477        case SCTP_DELAYED_SACK:
6478                retval = sctp_getsockopt_delayed_ack(sk, len, optval,
6479                                                          optlen);
6480                break;
6481        case SCTP_INITMSG:
6482                retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
6483                break;
6484        case SCTP_GET_PEER_ADDRS:
6485                retval = sctp_getsockopt_peer_addrs(sk, len, optval,
6486                                                    optlen);
6487                break;
6488        case SCTP_GET_LOCAL_ADDRS:
6489                retval = sctp_getsockopt_local_addrs(sk, len, optval,
6490                                                     optlen);
6491                break;
6492        case SCTP_SOCKOPT_CONNECTX3:
6493                retval = sctp_getsockopt_connectx3(sk, len, optval, optlen);
6494                break;
6495        case SCTP_DEFAULT_SEND_PARAM:
6496                retval = sctp_getsockopt_default_send_param(sk, len,
6497                                                            optval, optlen);
6498                break;
6499        case SCTP_DEFAULT_SNDINFO:
6500                retval = sctp_getsockopt_default_sndinfo(sk, len,
6501                                                         optval, optlen);
6502                break;
6503        case SCTP_PRIMARY_ADDR:
6504                retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
6505                break;
6506        case SCTP_NODELAY:
6507                retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
6508                break;
6509        case SCTP_RTOINFO:
6510                retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
6511                break;
6512        case SCTP_ASSOCINFO:
6513                retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
6514                break;
6515        case SCTP_I_WANT_MAPPED_V4_ADDR:
6516                retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
6517                break;
6518        case SCTP_MAXSEG:
6519                retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
6520                break;
6521        case SCTP_GET_PEER_ADDR_INFO:
6522                retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
6523                                                        optlen);
6524                break;
6525        case SCTP_ADAPTATION_LAYER:
6526                retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
6527                                                        optlen);
6528                break;
6529        case SCTP_CONTEXT:
6530                retval = sctp_getsockopt_context(sk, len, optval, optlen);
6531                break;
6532        case SCTP_FRAGMENT_INTERLEAVE:
6533                retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
6534                                                             optlen);
6535                break;
6536        case SCTP_PARTIAL_DELIVERY_POINT:
6537                retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
6538                                                                optlen);
6539                break;
6540        case SCTP_MAX_BURST:
6541                retval = sctp_getsockopt_maxburst(sk, len, optval, optlen);
6542                break;
6543        case SCTP_AUTH_KEY:
6544        case SCTP_AUTH_CHUNK:
6545        case SCTP_AUTH_DELETE_KEY:
6546                retval = -EOPNOTSUPP;
6547                break;
6548        case SCTP_HMAC_IDENT:
6549                retval = sctp_getsockopt_hmac_ident(sk, len, optval, optlen);
6550                break;
6551        case SCTP_AUTH_ACTIVE_KEY:
6552                retval = sctp_getsockopt_active_key(sk, len, optval, optlen);
6553                break;
6554        case SCTP_PEER_AUTH_CHUNKS:
6555                retval = sctp_getsockopt_peer_auth_chunks(sk, len, optval,
6556                                                        optlen);
6557                break;
6558        case SCTP_LOCAL_AUTH_CHUNKS:
6559                retval = sctp_getsockopt_local_auth_chunks(sk, len, optval,
6560                                                        optlen);
6561                break;
6562        case SCTP_GET_ASSOC_NUMBER:
6563                retval = sctp_getsockopt_assoc_number(sk, len, optval, optlen);
6564                break;
6565        case SCTP_GET_ASSOC_ID_LIST:
6566                retval = sctp_getsockopt_assoc_ids(sk, len, optval, optlen);
6567                break;
6568        case SCTP_AUTO_ASCONF:
6569                retval = sctp_getsockopt_auto_asconf(sk, len, optval, optlen);
6570                break;
6571        case SCTP_PEER_ADDR_THLDS:
6572                retval = sctp_getsockopt_paddr_thresholds(sk, optval, len, optlen);
6573                break;
6574        case SCTP_GET_ASSOC_STATS:
6575                retval = sctp_getsockopt_assoc_stats(sk, len, optval, optlen);
6576                break;
6577        case SCTP_RECVRCVINFO:
6578                retval = sctp_getsockopt_recvrcvinfo(sk, len, optval, optlen);
6579                break;
6580        case SCTP_RECVNXTINFO:
6581                retval = sctp_getsockopt_recvnxtinfo(sk, len, optval, optlen);
6582                break;
6583        case SCTP_PR_SUPPORTED:
6584                retval = sctp_getsockopt_pr_supported(sk, len, optval, optlen);
6585                break;
6586        case SCTP_DEFAULT_PRINFO:
6587                retval = sctp_getsockopt_default_prinfo(sk, len, optval,
6588                                                        optlen);
6589                break;
6590        case SCTP_PR_ASSOC_STATUS:
6591                retval = sctp_getsockopt_pr_assocstatus(sk, len, optval,
6592                                                        optlen);
6593                break;
6594        default:
6595                retval = -ENOPROTOOPT;
6596                break;
6597        }
6598
6599        release_sock(sk);
6600        return retval;
6601}
6602
6603static void sctp_hash(struct sock *sk)
6604{
6605        /* STUB */
6606}
6607
6608static void sctp_unhash(struct sock *sk)
6609{
6610        /* STUB */
6611}
6612
6613/* Check if port is acceptable.  Possibly find first available port.
6614 *
6615 * The port hash table (contained in the 'global' SCTP protocol storage
6616 * returned by struct sctp_protocol *sctp_get_protocol()). The hash
6617 * table is an array of 4096 lists (sctp_bind_hashbucket). Each
6618 * list (the list number is the port number hashed out, so as you
6619 * would expect from a hash function, all the ports in a given list have
6620 * such a number that hashes out to the same list number; you were
6621 * expecting that, right?); so each list has a set of ports, with a
6622 * link to the socket (struct sock) that uses it, the port number and
6623 * a fastreuse flag (FIXME: NPI ipg).
6624 */
6625static struct sctp_bind_bucket *sctp_bucket_create(
6626        struct sctp_bind_hashbucket *head, struct net *, unsigned short snum);
6627
6628static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
6629{
6630        struct sctp_bind_hashbucket *head; /* hash list */
6631        struct sctp_bind_bucket *pp;
6632        unsigned short snum;
6633        int ret;
6634
6635        snum = ntohs(addr->v4.sin_port);
6636
6637        pr_debug("%s: begins, snum:%d\n", __func__, snum);
6638
6639        local_bh_disable();
6640
6641        if (snum == 0) {
6642                /* Search for an available port. */
6643                int low, high, remaining, index;
6644                unsigned int rover;
6645
6646                inet_get_local_port_range(sock_net(sk), &low, &high);
6647                remaining = (high - low) + 1;
6648                rover = prandom_u32() % remaining + low;
6649
6650                do {
6651                        rover++;
6652                        if ((rover < low) || (rover > high))
6653                                rover = low;
6654                        if (inet_is_reserved_local_port(rover))
6655                                continue;
6656                        index = sctp_phashfn(sock_net(sk), rover);
6657                        head = &sctp_port_hashtable[index];
6658                        spin_lock(&head->lock);
6659                        sctp_for_each_hentry(pp, &head->chain)
6660                                if ((pp->port == rover) &&
6661                                    net_eq(sock_net(sk), pp->net))
6662                                        goto next;
6663                        break;
6664                next:
6665                        spin_unlock(&head->lock);
6666                } while (--remaining > 0);
6667
6668                /* Exhausted local port range during search? */
6669                ret = 1;
6670                if (remaining <= 0)
6671                        goto fail;
6672
6673                /* OK, here is the one we will use.  HEAD (the port
6674                 * hash table list entry) is non-NULL and we hold it's
6675                 * mutex.
6676                 */
6677                snum = rover;
6678        } else {
6679                /* We are given an specific port number; we verify
6680                 * that it is not being used. If it is used, we will
6681                 * exahust the search in the hash list corresponding
6682                 * to the port number (snum) - we detect that with the
6683                 * port iterator, pp being NULL.
6684                 */
6685                head = &sctp_port_hashtable[sctp_phashfn(sock_net(sk), snum)];
6686                spin_lock(&head->lock);
6687                sctp_for_each_hentry(pp, &head->chain) {
6688                        if ((pp->port == snum) && net_eq(pp->net, sock_net(sk)))
6689                                goto pp_found;
6690                }
6691        }
6692        pp = NULL;
6693        goto pp_not_found;
6694pp_found:
6695        if (!hlist_empty(&pp->owner)) {
6696                /* We had a port hash table hit - there is an
6697                 * available port (pp != NULL) and it is being
6698                 * used by other socket (pp->owner not empty); that other
6699                 * socket is going to be sk2.
6700                 */
6701                int reuse = sk->sk_reuse;
6702                struct sock *sk2;
6703
6704                pr_debug("%s: found a possible match\n", __func__);
6705
6706                if (pp->fastreuse && sk->sk_reuse &&
6707                        sk->sk_state != SCTP_SS_LISTENING)
6708                        goto success;
6709
6710                /* Run through the list of sockets bound to the port
6711                 * (pp->port) [via the pointers bind_next and
6712                 * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
6713                 * we get the endpoint they describe and run through
6714                 * the endpoint's list of IP (v4 or v6) addresses,
6715                 * comparing each of the addresses with the address of
6716                 * the socket sk. If we find a match, then that means
6717                 * that this port/socket (sk) combination are already
6718                 * in an endpoint.
6719                 */
6720                sk_for_each_bound(sk2, &pp->owner) {
6721                        struct sctp_endpoint *ep2;
6722                        ep2 = sctp_sk(sk2)->ep;
6723
6724                        if (sk == sk2 ||
6725                            (reuse && sk2->sk_reuse &&
6726                             sk2->sk_state != SCTP_SS_LISTENING))
6727                                continue;
6728
6729                        if (sctp_bind_addr_conflict(&ep2->base.bind_addr, addr,
6730                                                 sctp_sk(sk2), sctp_sk(sk))) {
6731                                ret = (long)sk2;
6732                                goto fail_unlock;
6733                        }
6734                }
6735
6736                pr_debug("%s: found a match\n", __func__);
6737        }
6738pp_not_found:
6739        /* If there was a hash table miss, create a new port.  */
6740        ret = 1;
6741        if (!pp && !(pp = sctp_bucket_create(head, sock_net(sk), snum)))
6742                goto fail_unlock;
6743
6744        /* In either case (hit or miss), make sure fastreuse is 1 only
6745         * if sk->sk_reuse is too (that is, if the caller requested
6746         * SO_REUSEADDR on this socket -sk-).
6747         */
6748        if (hlist_empty(&pp->owner)) {
6749                if (sk->sk_reuse && sk->sk_state != SCTP_SS_LISTENING)
6750                        pp->fastreuse = 1;
6751                else
6752                        pp->fastreuse = 0;
6753        } else if (pp->fastreuse &&
6754                (!sk->sk_reuse || sk->sk_state == SCTP_SS_LISTENING))
6755                pp->fastreuse = 0;
6756
6757        /* We are set, so fill up all the data in the hash table
6758         * entry, tie the socket list information with the rest of the
6759         * sockets FIXME: Blurry, NPI (ipg).
6760         */
6761success:
6762        if (!sctp_sk(sk)->bind_hash) {
6763                inet_sk(sk)->inet_num = snum;
6764                sk_add_bind_node(sk, &pp->owner);
6765                sctp_sk(sk)->bind_hash = pp;
6766        }
6767        ret = 0;
6768
6769fail_unlock:
6770        spin_unlock(&head->lock);
6771
6772fail:
6773        local_bh_enable();
6774        return ret;
6775}
6776
6777/* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
6778 * port is requested.
6779 */
6780static int sctp_get_port(struct sock *sk, unsigned short snum)
6781{
6782        long ret;
6783        union sctp_addr addr;
6784        struct sctp_af *af = sctp_sk(sk)->pf->af;
6785
6786        /* Set up a dummy address struct from the sk. */
6787        af->from_sk(&addr, sk);
6788        addr.v4.sin_port = htons(snum);
6789
6790        /* Note: sk->sk_num gets filled in if ephemeral port request. */
6791        ret = sctp_get_port_local(sk, &addr);
6792
6793        return ret ? 1 : 0;
6794}
6795
6796/*
6797 *  Move a socket to LISTENING state.
6798 */
6799static int sctp_listen_start(struct sock *sk, int backlog)
6800{
6801        struct sctp_sock *sp = sctp_sk(sk);
6802        struct sctp_endpoint *ep = sp->ep;
6803        struct crypto_hash *tfm = NULL;
6804        char alg[32];
6805
6806        /* Allocate HMAC for generating cookie. */
6807        if (!sp->hmac && sp->sctp_hmac_alg) {
6808                sprintf(alg, "hmac(%s)", sp->sctp_hmac_alg);
6809                tfm = crypto_alloc_hash(alg, 0, CRYPTO_ALG_ASYNC);
6810                if (IS_ERR(tfm)) {
6811                        net_info_ratelimited("failed to load transform for %s: %ld\n",
6812                                             sp->sctp_hmac_alg, PTR_ERR(tfm));
6813                        return -ENOSYS;
6814                }
6815                sctp_sk(sk)->hmac = tfm;
6816        }
6817
6818        /*
6819         * If a bind() or sctp_bindx() is not called prior to a listen()
6820         * call that allows new associations to be accepted, the system
6821         * picks an ephemeral port and will choose an address set equivalent
6822         * to binding with a wildcard address.
6823         *
6824         * This is not currently spelled out in the SCTP sockets
6825         * extensions draft, but follows the practice as seen in TCP
6826         * sockets.
6827         *
6828         */
6829        sk->sk_state = SCTP_SS_LISTENING;
6830        if (!ep->base.bind_addr.port) {
6831                if (sctp_autobind(sk))
6832                        return -EAGAIN;
6833        } else {
6834                if (sctp_get_port(sk, inet_sk(sk)->inet_num)) {
6835                        sk->sk_state = SCTP_SS_CLOSED;
6836                        return -EADDRINUSE;
6837                }
6838        }
6839
6840        sk->sk_max_ack_backlog = backlog;
6841        sctp_hash_endpoint(ep);
6842        return 0;
6843}
6844
6845/*
6846 * 4.1.3 / 5.1.3 listen()
6847 *
6848 *   By default, new associations are not accepted for UDP style sockets.
6849 *   An application uses listen() to mark a socket as being able to
6850 *   accept new associations.
6851 *
6852 *   On TCP style sockets, applications use listen() to ready the SCTP
6853 *   endpoint for accepting inbound associations.
6854 *
6855 *   On both types of endpoints a backlog of '0' disables listening.
6856 *
6857 *  Move a socket to LISTENING state.
6858 */
6859int sctp_inet_listen(struct socket *sock, int backlog)
6860{
6861        struct sock *sk = sock->sk;
6862        struct sctp_endpoint *ep = sctp_sk(sk)->ep;
6863        int err = -EINVAL;
6864
6865        if (unlikely(backlog < 0))
6866                return err;
6867
6868        lock_sock(sk);
6869
6870        /* Peeled-off sockets are not allowed to listen().  */
6871        if (sctp_style(sk, UDP_HIGH_BANDWIDTH))
6872                goto out;
6873
6874        if (sock->state != SS_UNCONNECTED)
6875                goto out;
6876
6877        /* If backlog is zero, disable listening. */
6878        if (!backlog) {
6879                if (sctp_sstate(sk, CLOSED))
6880                        goto out;
6881
6882                err = 0;
6883                sctp_unhash_endpoint(ep);
6884                sk->sk_state = SCTP_SS_CLOSED;
6885                if (sk->sk_reuse)
6886                        sctp_sk(sk)->bind_hash->fastreuse = 1;
6887                goto out;
6888        }
6889
6890        /* If we are already listening, just update the backlog */
6891        if (sctp_sstate(sk, LISTENING))
6892                sk->sk_max_ack_backlog = backlog;
6893        else {
6894                err = sctp_listen_start(sk, backlog);
6895                if (err)
6896                        goto out;
6897        }
6898
6899        err = 0;
6900out:
6901        release_sock(sk);
6902        return err;
6903}
6904
6905/*
6906 * This function is done by modeling the current datagram_poll() and the
6907 * tcp_poll().  Note that, based on these implementations, we don't
6908 * lock the socket in this function, even though it seems that,
6909 * ideally, locking or some other mechanisms can be used to ensure
6910 * the integrity of the counters (sndbuf and wmem_alloc) used
6911 * in this place.  We assume that we don't need locks either until proven
6912 * otherwise.
6913 *
6914 * Another thing to note is that we include the Async I/O support
6915 * here, again, by modeling the current TCP/UDP code.  We don't have
6916 * a good way to test with it yet.
6917 */
6918unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
6919{
6920        struct sock *sk = sock->sk;
6921        struct sctp_sock *sp = sctp_sk(sk);
6922        unsigned int mask;
6923
6924        poll_wait(file, sk_sleep(sk), wait);
6925
6926        sock_rps_record_flow(sk);
6927
6928        /* A TCP-style listening socket becomes readable when the accept queue
6929         * is not empty.
6930         */
6931        if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
6932                return (!list_empty(&sp->ep->asocs)) ?
6933                        (POLLIN | POLLRDNORM) : 0;
6934
6935        mask = 0;
6936
6937        /* Is there any exceptional events?  */
6938        if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
6939                mask |= POLLERR |
6940                        (sock_flag(sk, SOCK_SELECT_ERR_QUEUE) ? POLLPRI : 0);
6941        if (sk->sk_shutdown & RCV_SHUTDOWN)
6942                mask |= POLLRDHUP | POLLIN | POLLRDNORM;
6943        if (sk->sk_shutdown == SHUTDOWN_MASK)
6944                mask |= POLLHUP;
6945
6946        /* Is it readable?  Reconsider this code with TCP-style support.  */
6947        if (!skb_queue_empty(&sk->sk_receive_queue))
6948                mask |= POLLIN | POLLRDNORM;
6949
6950        /* The association is either gone or not ready.  */
6951        if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
6952                return mask;
6953
6954        /* Is it writable?  */
6955        if (sctp_writeable(sk)) {
6956                mask |= POLLOUT | POLLWRNORM;
6957        } else {
6958                set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
6959                /*
6960                 * Since the socket is not locked, the buffer
6961                 * might be made available after the writeable check and
6962                 * before the bit is set.  This could cause a lost I/O
6963                 * signal.  tcp_poll() has a race breaker for this race
6964                 * condition.  Based on their implementation, we put
6965                 * in the following code to cover it as well.
6966                 */
6967                if (sctp_writeable(sk))
6968                        mask |= POLLOUT | POLLWRNORM;
6969        }
6970        return mask;
6971}
6972
6973/********************************************************************
6974 * 2nd Level Abstractions
6975 ********************************************************************/
6976
6977static struct sctp_bind_bucket *sctp_bucket_create(
6978        struct sctp_bind_hashbucket *head, struct net *net, unsigned short snum)
6979{
6980        struct sctp_bind_bucket *pp;
6981
6982        pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
6983        if (pp) {
6984                SCTP_DBG_OBJCNT_INC(bind_bucket);
6985                pp->port = snum;
6986                pp->fastreuse = 0;
6987                INIT_HLIST_HEAD(&pp->owner);
6988                pp->net = net;
6989                hlist_add_head(&pp->node, &head->chain);
6990        }
6991        return pp;
6992}
6993
6994/* Caller must hold hashbucket lock for this tb with local BH disabled */
6995static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
6996{
6997        if (pp && hlist_empty(&pp->owner)) {
6998                __hlist_del(&pp->node);
6999                kmem_cache_free(sctp_bucket_cachep, pp);
7000                SCTP_DBG_OBJCNT_DEC(bind_bucket);
7001        }
7002}
7003
7004/* Release this socket's reference to a local port.  */
7005static inline void __sctp_put_port(struct sock *sk)
7006{
7007        struct sctp_bind_hashbucket *head =
7008                &sctp_port_hashtable[sctp_phashfn(sock_net(sk),
7009                                                  inet_sk(sk)->inet_num)];
7010        struct sctp_bind_bucket *pp;
7011
7012        spin_lock(&head->lock);
7013        pp = sctp_sk(sk)->bind_hash;
7014        __sk_del_bind_node(sk);
7015        sctp_sk(sk)->bind_hash = NULL;
7016        inet_sk(sk)->inet_num = 0;
7017        sctp_bucket_destroy(pp);
7018        spin_unlock(&head->lock);
7019}
7020
7021void sctp_put_port(struct sock *sk)
7022{
7023        local_bh_disable();
7024        __sctp_put_port(sk);
7025        local_bh_enable();
7026}
7027
7028/*
7029 * The system picks an ephemeral port and choose an address set equivalent
7030 * to binding with a wildcard address.
7031 * One of those addresses will be the primary address for the association.
7032 * This automatically enables the multihoming capability of SCTP.
7033 */
7034static int sctp_autobind(struct sock *sk)
7035{
7036        union sctp_addr autoaddr;
7037        struct sctp_af *af;
7038        __be16 port;
7039
7040        /* Initialize a local sockaddr structure to INADDR_ANY. */
7041        af = sctp_sk(sk)->pf->af;
7042
7043        port = htons(inet_sk(sk)->inet_num);
7044        af->inaddr_any(&autoaddr, port);
7045
7046        return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
7047}
7048
7049/* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
7050 *
7051 * From RFC 2292
7052 * 4.2 The cmsghdr Structure *
7053 *
7054 * When ancillary data is sent or received, any number of ancillary data
7055 * objects can be specified by the msg_control and msg_controllen members of
7056 * the msghdr structure, because each object is preceded by
7057 * a cmsghdr structure defining the object's length (the cmsg_len member).
7058 * Historically Berkeley-derived implementations have passed only one object
7059 * at a time, but this API allows multiple objects to be
7060 * passed in a single call to sendmsg() or recvmsg(). The following example
7061 * shows two ancillary data objects in a control buffer.
7062 *
7063 *   |<--------------------------- msg_controllen -------------------------->|
7064 *   |                                                                       |
7065 *
7066 *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
7067 *
7068 *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
7069 *   |                                   |                                   |
7070 *
7071 *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
7072 *
7073 *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
7074 *   |                                |  |                                |  |
7075 *
7076 *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
7077 *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
7078 *
7079 *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
7080 *
7081 *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
7082 *    ^
7083 *    |
7084 *
7085 * msg_control
7086 * points here
7087 */
7088static int sctp_msghdr_parse(const struct msghdr *msg, sctp_cmsgs_t *cmsgs)
7089{
7090        struct cmsghdr *cmsg;
7091        struct msghdr *my_msg = (struct msghdr *)msg;
7092
7093        for (cmsg = CMSG_FIRSTHDR(msg); cmsg != NULL;
7094             cmsg = CMSG_NXTHDR(my_msg, cmsg)) {
7095                if (!CMSG_OK(my_msg, cmsg))
7096                        return -EINVAL;
7097
7098                /* Should we parse this header or ignore?  */
7099                if (cmsg->cmsg_level != IPPROTO_SCTP)
7100                        continue;
7101
7102                /* Strictly check lengths following example in SCM code.  */
7103                switch (cmsg->cmsg_type) {
7104                case SCTP_INIT:
7105                        /* SCTP Socket API Extension
7106                         * 5.3.1 SCTP Initiation Structure (SCTP_INIT)
7107                         *
7108                         * This cmsghdr structure provides information for
7109                         * initializing new SCTP associations with sendmsg().
7110                         * The SCTP_INITMSG socket option uses this same data
7111                         * structure.  This structure is not used for
7112                         * recvmsg().
7113                         *
7114                         * cmsg_level    cmsg_type      cmsg_data[]
7115                         * ------------  ------------   ----------------------
7116                         * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
7117                         */
7118                        if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_initmsg)))
7119                                return -EINVAL;
7120
7121                        cmsgs->init = CMSG_DATA(cmsg);
7122                        break;
7123
7124                case SCTP_SNDRCV:
7125                        /* SCTP Socket API Extension
7126                         * 5.3.2 SCTP Header Information Structure(SCTP_SNDRCV)
7127                         *
7128                         * This cmsghdr structure specifies SCTP options for
7129                         * sendmsg() and describes SCTP header information
7130                         * about a received message through recvmsg().
7131                         *
7132                         * cmsg_level    cmsg_type      cmsg_data[]
7133                         * ------------  ------------   ----------------------
7134                         * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
7135                         */
7136                        if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
7137                                return -EINVAL;
7138
7139                        cmsgs->srinfo = CMSG_DATA(cmsg);
7140
7141                        if (cmsgs->srinfo->sinfo_flags &
7142                            ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
7143                              SCTP_SACK_IMMEDIATELY | SCTP_PR_SCTP_MASK |
7144                              SCTP_ABORT | SCTP_EOF))
7145                                return -EINVAL;
7146                        break;
7147
7148                case SCTP_SNDINFO:
7149                        /* SCTP Socket API Extension
7150                         * 5.3.4 SCTP Send Information Structure (SCTP_SNDINFO)
7151                         *
7152                         * This cmsghdr structure specifies SCTP options for
7153                         * sendmsg(). This structure and SCTP_RCVINFO replaces
7154                         * SCTP_SNDRCV which has been deprecated.
7155                         *
7156                         * cmsg_level    cmsg_type      cmsg_data[]
7157                         * ------------  ------------   ---------------------
7158                         * IPPROTO_SCTP  SCTP_SNDINFO    struct sctp_sndinfo
7159                         */
7160                        if (cmsg->cmsg_len != CMSG_LEN(sizeof(struct sctp_sndinfo)))
7161                                return -EINVAL;
7162
7163                        cmsgs->sinfo = CMSG_DATA(cmsg);
7164
7165                        if (cmsgs->sinfo->snd_flags &
7166                            ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
7167                              SCTP_SACK_IMMEDIATELY | SCTP_PR_SCTP_MASK |
7168                              SCTP_ABORT | SCTP_EOF))
7169                                return -EINVAL;
7170                        break;
7171                default:
7172                        return -EINVAL;
7173                }
7174        }
7175
7176        return 0;
7177}
7178
7179/*
7180 * Wait for a packet..
7181 * Note: This function is the same function as in core/datagram.c
7182 * with a few modifications to make lksctp work.
7183 */
7184static int sctp_wait_for_packet(struct sock *sk, int *err, long *timeo_p)
7185{
7186        int error;
7187        DEFINE_WAIT(wait);
7188
7189        prepare_to_wait_exclusive(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
7190
7191        /* Socket errors? */
7192        error = sock_error(sk);
7193        if (error)
7194                goto out;
7195
7196        if (!skb_queue_empty(&sk->sk_receive_queue))
7197                goto ready;
7198
7199        /* Socket shut down?  */
7200        if (sk->sk_shutdown & RCV_SHUTDOWN)
7201                goto out;
7202
7203        /* Sequenced packets can come disconnected.  If so we report the
7204         * problem.
7205         */
7206        error = -ENOTCONN;
7207
7208        /* Is there a good reason to think that we may receive some data?  */
7209        if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
7210                goto out;
7211
7212        /* Handle signals.  */
7213        if (signal_pending(current))
7214                goto interrupted;
7215
7216        /* Let another process have a go.  Since we are going to sleep
7217         * anyway.  Note: This may cause odd behaviors if the message
7218         * does not fit in the user's buffer, but this seems to be the
7219         * only way to honor MSG_DONTWAIT realistically.
7220         */
7221        release_sock(sk);
7222        *timeo_p = schedule_timeout(*timeo_p);
7223        lock_sock(sk);
7224
7225ready:
7226        finish_wait(sk_sleep(sk), &wait);
7227        return 0;
7228
7229interrupted:
7230        error = sock_intr_errno(*timeo_p);
7231
7232out:
7233        finish_wait(sk_sleep(sk), &wait);
7234        *err = error;
7235        return error;
7236}
7237
7238/* Receive a datagram.
7239 * Note: This is pretty much the same routine as in core/datagram.c
7240 * with a few changes to make lksctp work.
7241 */
7242struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
7243                                       int noblock, int *err)
7244{
7245        int error;
7246        struct sk_buff *skb;
7247        long timeo;
7248
7249        timeo = sock_rcvtimeo(sk, noblock);
7250
7251        pr_debug("%s: timeo:%ld, max:%ld\n", __func__, timeo,
7252                 MAX_SCHEDULE_TIMEOUT);
7253
7254        do {
7255                /* Again only user level code calls this function,
7256                 * so nothing interrupt level
7257                 * will suddenly eat the receive_queue.
7258                 *
7259                 *  Look at current nfs client by the way...
7260                 *  However, this function was correct in any case. 8)
7261                 */
7262                if (flags & MSG_PEEK) {
7263                        skb = skb_peek(&sk->sk_receive_queue);
7264                        if (skb)
7265                                atomic_inc(&skb->users);
7266                } else {
7267                        skb = __skb_dequeue(&sk->sk_receive_queue);
7268                }
7269
7270                if (skb)
7271                        return skb;
7272
7273                /* Caller is allowed not to check sk->sk_err before calling. */
7274                error = sock_error(sk);
7275                if (error)
7276                        goto no_packet;
7277
7278                if (sk->sk_shutdown & RCV_SHUTDOWN)
7279                        break;
7280
7281                /* User doesn't want to wait.  */
7282                error = -EAGAIN;
7283                if (!timeo)
7284                        goto no_packet;
7285        } while (sctp_wait_for_packet(sk, err, &timeo) == 0);
7286
7287        return NULL;
7288
7289no_packet:
7290        *err = error;
7291        return NULL;
7292}
7293
7294/* If sndbuf has changed, wake up per association sndbuf waiters.  */
7295static void __sctp_write_space(struct sctp_association *asoc)
7296{
7297        struct sock *sk = asoc->base.sk;
7298        struct socket *sock = sk->sk_socket;
7299
7300        if ((sctp_wspace(asoc) > 0) && sock) {
7301                if (waitqueue_active(&asoc->wait))
7302                        wake_up_interruptible(&asoc->wait);
7303
7304                if (sctp_writeable(sk)) {
7305                        wait_queue_head_t *wq = sk_sleep(sk);
7306
7307                        if (wq && waitqueue_active(wq))
7308                                wake_up_interruptible(wq);
7309
7310                        /* Note that we try to include the Async I/O support
7311                         * here by modeling from the current TCP/UDP code.
7312                         * We have not tested with it yet.
7313                         */
7314                        if (!(sk->sk_shutdown & SEND_SHUTDOWN))
7315                                sock_wake_async(sock,
7316                                                SOCK_WAKE_SPACE, POLL_OUT);
7317                }
7318        }
7319}
7320
7321static void sctp_wake_up_waiters(struct sock *sk,
7322                                 struct sctp_association *asoc)
7323{
7324        struct sctp_association *tmp = asoc;
7325
7326        /* We do accounting for the sndbuf space per association,
7327         * so we only need to wake our own association.
7328         */
7329        if (asoc->ep->sndbuf_policy)
7330                return __sctp_write_space(asoc);
7331
7332        /* If association goes down and is just flushing its
7333         * outq, then just normally notify others.
7334         */
7335        if (asoc->base.dead)
7336                return sctp_write_space(sk);
7337
7338        /* Accounting for the sndbuf space is per socket, so we
7339         * need to wake up others, try to be fair and in case of
7340         * other associations, let them have a go first instead
7341         * of just doing a sctp_write_space() call.
7342         *
7343         * Note that we reach sctp_wake_up_waiters() only when
7344         * associations free up queued chunks, thus we are under
7345         * lock and the list of associations on a socket is
7346         * guaranteed not to change.
7347         */
7348        for (tmp = list_next_entry(tmp, asocs); 1;
7349             tmp = list_next_entry(tmp, asocs)) {
7350                /* Manually skip the head element. */
7351                if (&tmp->asocs == &((sctp_sk(sk))->ep->asocs))
7352                        continue;
7353                /* Wake up association. */
7354                __sctp_write_space(tmp);
7355                /* We've reached the end. */
7356                if (tmp == asoc)
7357                        break;
7358        }
7359}
7360
7361/* Do accounting for the sndbuf space.
7362 * Decrement the used sndbuf space of the corresponding association by the
7363 * data size which was just transmitted(freed).
7364 */
7365static void sctp_wfree(struct sk_buff *skb)
7366{
7367        struct sctp_chunk *chunk = skb_shinfo(skb)->destructor_arg;
7368        struct sctp_association *asoc = chunk->asoc;
7369        struct sock *sk = asoc->base.sk;
7370
7371        asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk) +
7372                                sizeof(struct sk_buff) +
7373                                sizeof(struct sctp_chunk);
7374
7375        atomic_sub(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
7376
7377        /*
7378         * This undoes what is done via sctp_set_owner_w and sk_mem_charge
7379         */
7380        sk->sk_wmem_queued   -= skb->truesize;
7381        sk_mem_uncharge(sk, skb->truesize);
7382
7383        sock_wfree(skb);
7384        sctp_wake_up_waiters(sk, asoc);
7385
7386        sctp_association_put(asoc);
7387}
7388
7389/* Do accounting for the receive space on the socket.
7390 * Accounting for the association is done in ulpevent.c
7391 * We set this as a destructor for the cloned data skbs so that
7392 * accounting is done at the correct time.
7393 */
7394void sctp_sock_rfree(struct sk_buff *skb)
7395{
7396        struct sock *sk = skb->sk;
7397        struct sctp_ulpevent *event = sctp_skb2event(skb);
7398
7399        atomic_sub(event->rmem_len, &sk->sk_rmem_alloc);
7400
7401        /*
7402         * Mimic the behavior of sock_rfree
7403         */
7404        sk_mem_uncharge(sk, event->rmem_len);
7405}
7406
7407
7408/* Helper function to wait for space in the sndbuf.  */
7409static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
7410                                size_t msg_len)
7411{
7412        struct sock *sk = asoc->base.sk;
7413        int err = 0;
7414        long current_timeo = *timeo_p;
7415        DEFINE_WAIT(wait);
7416
7417        pr_debug("%s: asoc:%p, timeo:%ld, msg_len:%zu\n", __func__, asoc,
7418                 *timeo_p, msg_len);
7419
7420        /* Increment the association's refcnt.  */
7421        sctp_association_hold(asoc);
7422
7423        /* Wait on the association specific sndbuf space. */
7424        for (;;) {
7425                prepare_to_wait_exclusive(&asoc->wait, &wait,
7426                                          TASK_INTERRUPTIBLE);
7427                if (!*timeo_p)
7428                        goto do_nonblock;
7429                if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
7430                    asoc->base.dead)
7431                        goto do_error;
7432                if (signal_pending(current))
7433                        goto do_interrupted;
7434                if (msg_len <= sctp_wspace(asoc))
7435                        break;
7436
7437                /* Let another process have a go.  Since we are going
7438                 * to sleep anyway.
7439                 */
7440                release_sock(sk);
7441                current_timeo = schedule_timeout(current_timeo);
7442                lock_sock(sk);
7443
7444                *timeo_p = current_timeo;
7445        }
7446
7447out:
7448        finish_wait(&asoc->wait, &wait);
7449
7450        /* Release the association's refcnt.  */
7451        sctp_association_put(asoc);
7452
7453        return err;
7454
7455do_error:
7456        err = -EPIPE;
7457        goto out;
7458
7459do_interrupted:
7460        err = sock_intr_errno(*timeo_p);
7461        goto out;
7462
7463do_nonblock:
7464        err = -EAGAIN;
7465        goto out;
7466}
7467
7468void sctp_data_ready(struct sock *sk, int len)
7469{
7470        struct socket_wq *wq;
7471
7472        rcu_read_lock();
7473        wq = rcu_dereference(sk->sk_wq);
7474        if (wq_has_sleeper(wq))
7475                wake_up_interruptible_sync_poll(&wq->wait, POLLIN |
7476                                                POLLRDNORM | POLLRDBAND);
7477        sk_wake_async(sk, SOCK_WAKE_WAITD, POLL_IN);
7478        rcu_read_unlock();
7479}
7480
7481/* If socket sndbuf has changed, wake up all per association waiters.  */
7482void sctp_write_space(struct sock *sk)
7483{
7484        struct sctp_association *asoc;
7485
7486        /* Wake up the tasks in each wait queue.  */
7487        list_for_each_entry(asoc, &((sctp_sk(sk))->ep->asocs), asocs) {
7488                __sctp_write_space(asoc);
7489        }
7490}
7491
7492/* Is there any sndbuf space available on the socket?
7493 *
7494 * Note that sk_wmem_alloc is the sum of the send buffers on all of the
7495 * associations on the same socket.  For a UDP-style socket with
7496 * multiple associations, it is possible for it to be "unwriteable"
7497 * prematurely.  I assume that this is acceptable because
7498 * a premature "unwriteable" is better than an accidental "writeable" which
7499 * would cause an unwanted block under certain circumstances.  For the 1-1
7500 * UDP-style sockets or TCP-style sockets, this code should work.
7501 *  - Daisy
7502 */
7503static int sctp_writeable(struct sock *sk)
7504{
7505        int amt = 0;
7506
7507        amt = sk->sk_sndbuf - sk_wmem_alloc_get(sk);
7508        if (amt < 0)
7509                amt = 0;
7510        return amt;
7511}
7512
7513/* Wait for an association to go into ESTABLISHED state. If timeout is 0,
7514 * returns immediately with EINPROGRESS.
7515 */
7516static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
7517{
7518        struct sock *sk = asoc->base.sk;
7519        int err = 0;
7520        long current_timeo = *timeo_p;
7521        DEFINE_WAIT(wait);
7522
7523        pr_debug("%s: asoc:%p, timeo:%ld\n", __func__, asoc, *timeo_p);
7524
7525        /* Increment the association's refcnt.  */
7526        sctp_association_hold(asoc);
7527
7528        for (;;) {
7529                prepare_to_wait_exclusive(&asoc->wait, &wait,
7530                                          TASK_INTERRUPTIBLE);
7531                if (!*timeo_p)
7532                        goto do_nonblock;
7533                if (sk->sk_shutdown & RCV_SHUTDOWN)
7534                        break;
7535                if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
7536                    asoc->base.dead)
7537                        goto do_error;
7538                if (signal_pending(current))
7539                        goto do_interrupted;
7540
7541                if (sctp_state(asoc, ESTABLISHED))
7542                        break;
7543
7544                /* Let another process have a go.  Since we are going
7545                 * to sleep anyway.
7546                 */
7547                release_sock(sk);
7548                current_timeo = schedule_timeout(current_timeo);
7549                lock_sock(sk);
7550
7551                *timeo_p = current_timeo;
7552        }
7553
7554out:
7555        finish_wait(&asoc->wait, &wait);
7556
7557        /* Release the association's refcnt.  */
7558        sctp_association_put(asoc);
7559
7560        return err;
7561
7562do_error:
7563        if (asoc->init_err_counter + 1 > asoc->max_init_attempts)
7564                err = -ETIMEDOUT;
7565        else
7566                err = -ECONNREFUSED;
7567        goto out;
7568
7569do_interrupted:
7570        err = sock_intr_errno(*timeo_p);
7571        goto out;
7572
7573do_nonblock:
7574        err = -EINPROGRESS;
7575        goto out;
7576}
7577
7578static int sctp_wait_for_accept(struct sock *sk, long timeo)
7579{
7580        struct sctp_endpoint *ep;
7581        int err = 0;
7582        DEFINE_WAIT(wait);
7583
7584        ep = sctp_sk(sk)->ep;
7585
7586
7587        for (;;) {
7588                prepare_to_wait_exclusive(sk_sleep(sk), &wait,
7589                                          TASK_INTERRUPTIBLE);
7590
7591                if (list_empty(&ep->asocs)) {
7592                        release_sock(sk);
7593                        timeo = schedule_timeout(timeo);
7594                        lock_sock(sk);
7595                }
7596
7597                err = -EINVAL;
7598                if (!sctp_sstate(sk, LISTENING))
7599                        break;
7600
7601                err = 0;
7602                if (!list_empty(&ep->asocs))
7603                        break;
7604
7605                err = sock_intr_errno(timeo);
7606                if (signal_pending(current))
7607                        break;
7608
7609                err = -EAGAIN;
7610                if (!timeo)
7611                        break;
7612        }
7613
7614        finish_wait(sk_sleep(sk), &wait);
7615
7616        return err;
7617}
7618
7619static void sctp_wait_for_close(struct sock *sk, long timeout)
7620{
7621        DEFINE_WAIT(wait);
7622
7623        do {
7624                prepare_to_wait(sk_sleep(sk), &wait, TASK_INTERRUPTIBLE);
7625                if (list_empty(&sctp_sk(sk)->ep->asocs))
7626                        break;
7627                release_sock(sk);
7628                timeout = schedule_timeout(timeout);
7629                lock_sock(sk);
7630        } while (!signal_pending(current) && timeout);
7631
7632        finish_wait(sk_sleep(sk), &wait);
7633}
7634
7635static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk)
7636{
7637        struct sk_buff *frag;
7638
7639        if (!skb->data_len)
7640                goto done;
7641
7642        /* Don't forget the fragments. */
7643        skb_walk_frags(skb, frag)
7644                sctp_skb_set_owner_r_frag(frag, sk);
7645
7646done:
7647        sctp_skb_set_owner_r(skb, sk);
7648}
7649
7650void sctp_copy_sock(struct sock *newsk, struct sock *sk,
7651                    struct sctp_association *asoc)
7652{
7653        struct inet_sock *inet = inet_sk(sk);
7654        struct inet_sock *newinet;
7655
7656        newsk->sk_type = sk->sk_type;
7657        newsk->sk_bound_dev_if = sk->sk_bound_dev_if;
7658        newsk->sk_flags = sk->sk_flags;
7659        newsk->sk_tsflags = sk->sk_tsflags;
7660        newsk->sk_no_check_tx = sk->sk_no_check_tx;
7661        newsk->sk_no_check_rx = sk->sk_no_check_rx;
7662        newsk->sk_reuse = sk->sk_reuse;
7663
7664        newsk->sk_shutdown = sk->sk_shutdown;
7665        newsk->sk_destruct = sctp_destruct_sock;
7666        newsk->sk_family = sk->sk_family;
7667        newsk->sk_protocol = IPPROTO_SCTP;
7668        newsk->sk_backlog_rcv = sk->sk_prot->backlog_rcv;
7669        newsk->sk_sndbuf = sk->sk_sndbuf;
7670        newsk->sk_rcvbuf = sk->sk_rcvbuf;
7671        newsk->sk_lingertime = sk->sk_lingertime;
7672        newsk->sk_rcvtimeo = sk->sk_rcvtimeo;
7673        newsk->sk_sndtimeo = sk->sk_sndtimeo;
7674        newsk->sk_rxhash = sk->sk_rxhash;
7675
7676        newinet = inet_sk(newsk);
7677
7678        /* Initialize sk's sport, dport, rcv_saddr and daddr for
7679         * getsockname() and getpeername()
7680         */
7681        newinet->inet_sport = inet->inet_sport;
7682        newinet->inet_saddr = inet->inet_saddr;
7683        newinet->inet_rcv_saddr = inet->inet_rcv_saddr;
7684        newinet->inet_dport = htons(asoc->peer.port);
7685        newinet->pmtudisc = inet->pmtudisc;
7686        newinet->inet_id = asoc->next_tsn ^ jiffies;
7687
7688        newinet->uc_ttl = inet->uc_ttl;
7689        newinet->mc_loop = 1;
7690        newinet->mc_ttl = 1;
7691        newinet->mc_index = 0;
7692        newinet->mc_list = NULL;
7693
7694        if (newsk->sk_flags & SK_FLAGS_TIMESTAMP)
7695                net_enable_timestamp();
7696
7697        security_sk_clone(sk, newsk);
7698}
7699
7700static inline void sctp_copy_descendant(struct sock *sk_to,
7701                                        const struct sock *sk_from)
7702{
7703        int ancestor_size = sizeof(struct inet_sock) +
7704                            sizeof(struct sctp_sock) -
7705                            offsetof(struct sctp_sock, auto_asconf_list);
7706
7707        if (sk_from->sk_family == PF_INET6)
7708                ancestor_size += sizeof(struct ipv6_pinfo);
7709
7710        __inet_sk_copy_descendant(sk_to, sk_from, ancestor_size);
7711}
7712
7713/* Populate the fields of the newsk from the oldsk and migrate the assoc
7714 * and its messages to the newsk.
7715 */
7716static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
7717                              struct sctp_association *assoc,
7718                              sctp_socket_type_t type)
7719{
7720        struct sctp_sock *oldsp = sctp_sk(oldsk);
7721        struct sctp_sock *newsp = sctp_sk(newsk);
7722        struct sctp_bind_bucket *pp; /* hash list port iterator */
7723        struct sctp_endpoint *newep = newsp->ep;
7724        struct sk_buff *skb, *tmp;
7725        struct sctp_ulpevent *event;
7726        struct sctp_bind_hashbucket *head;
7727
7728        /* Migrate socket buffer sizes and all the socket level options to the
7729         * new socket.
7730         */
7731        newsk->sk_sndbuf = oldsk->sk_sndbuf;
7732        newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
7733        /* Brute force copy old sctp opt. */
7734        sctp_copy_descendant(newsk, oldsk);
7735
7736        /* Restore the ep value that was overwritten with the above structure
7737         * copy.
7738         */
7739        newsp->ep = newep;
7740        newsp->hmac = NULL;
7741
7742        /* Hook this new socket in to the bind_hash list. */
7743        head = &sctp_port_hashtable[sctp_phashfn(sock_net(oldsk),
7744                                                 inet_sk(oldsk)->inet_num)];
7745        spin_lock_bh(&head->lock);
7746        pp = sctp_sk(oldsk)->bind_hash;
7747        sk_add_bind_node(newsk, &pp->owner);
7748        sctp_sk(newsk)->bind_hash = pp;
7749        inet_sk(newsk)->inet_num = inet_sk(oldsk)->inet_num;
7750        spin_unlock_bh(&head->lock);
7751
7752        /* Copy the bind_addr list from the original endpoint to the new
7753         * endpoint so that we can handle restarts properly
7754         */
7755        sctp_bind_addr_dup(&newsp->ep->base.bind_addr,
7756                                &oldsp->ep->base.bind_addr, GFP_KERNEL);
7757
7758        /* Move any messages in the old socket's receive queue that are for the
7759         * peeled off association to the new socket's receive queue.
7760         */
7761        sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
7762                event = sctp_skb2event(skb);
7763                if (event->asoc == assoc) {
7764                        __skb_unlink(skb, &oldsk->sk_receive_queue);
7765                        __skb_queue_tail(&newsk->sk_receive_queue, skb);
7766                        sctp_skb_set_owner_r_frag(skb, newsk);
7767                }
7768        }
7769
7770        /* Clean up any messages pending delivery due to partial
7771         * delivery.   Three cases:
7772         * 1) No partial deliver;  no work.
7773         * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
7774         * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
7775         */
7776        skb_queue_head_init(&newsp->pd_lobby);
7777        atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
7778
7779        if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
7780                struct sk_buff_head *queue;
7781
7782                /* Decide which queue to move pd_lobby skbs to. */
7783                if (assoc->ulpq.pd_mode) {
7784                        queue = &newsp->pd_lobby;
7785                } else
7786                        queue = &newsk->sk_receive_queue;
7787
7788                /* Walk through the pd_lobby, looking for skbs that
7789                 * need moved to the new socket.
7790                 */
7791                sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
7792                        event = sctp_skb2event(skb);
7793                        if (event->asoc == assoc) {
7794                                __skb_unlink(skb, &oldsp->pd_lobby);
7795                                __skb_queue_tail(queue, skb);
7796                                sctp_skb_set_owner_r_frag(skb, newsk);
7797                        }
7798                }
7799
7800                /* Clear up any skbs waiting for the partial
7801                 * delivery to finish.
7802                 */
7803                if (assoc->ulpq.pd_mode)
7804                        sctp_clear_pd(oldsk, NULL);
7805
7806        }
7807
7808        sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp)
7809                sctp_skb_set_owner_r_frag(skb, newsk);
7810
7811        sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp)
7812                sctp_skb_set_owner_r_frag(skb, newsk);
7813
7814        /* Set the type of socket to indicate that it is peeled off from the
7815         * original UDP-style socket or created with the accept() call on a
7816         * TCP-style socket..
7817         */
7818        newsp->type = type;
7819
7820        /* Mark the new socket "in-use" by the user so that any packets
7821         * that may arrive on the association after we've moved it are
7822         * queued to the backlog.  This prevents a potential race between
7823         * backlog processing on the old socket and new-packet processing
7824         * on the new socket.
7825         *
7826         * The caller has just allocated newsk so we can guarantee that other
7827         * paths won't try to lock it and then oldsk.
7828         */
7829        lock_sock_nested(newsk, SINGLE_DEPTH_NESTING);
7830        sctp_assoc_migrate(assoc, newsk);
7831
7832        /* If the association on the newsk is already closed before accept()
7833         * is called, set RCV_SHUTDOWN flag.
7834         */
7835        if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP)) {
7836                newsk->sk_state = SCTP_SS_CLOSED;
7837                newsk->sk_shutdown |= RCV_SHUTDOWN;
7838        } else {
7839                newsk->sk_state = SCTP_SS_ESTABLISHED;
7840        }
7841
7842        release_sock(newsk);
7843}
7844
7845
7846/* This proto struct describes the ULP interface for SCTP.  */
7847struct proto sctp_prot = {
7848        .name        =  "SCTP",
7849        .owner       =  THIS_MODULE,
7850        .close       =  sctp_close,
7851        .connect     =  sctp_connect,
7852        .disconnect  =  sctp_disconnect,
7853        .accept      =  sctp_accept,
7854        .ioctl       =  sctp_ioctl,
7855        .init        =  sctp_init_sock,
7856        .destroy     =  sctp_destroy_sock,
7857        .shutdown    =  sctp_shutdown,
7858        .setsockopt  =  sctp_setsockopt,
7859        .getsockopt  =  sctp_getsockopt,
7860        .sendmsg     =  sctp_sendmsg,
7861        .recvmsg     =  sctp_recvmsg,
7862        .bind        =  sctp_bind,
7863        .backlog_rcv =  sctp_backlog_rcv,
7864        .hash        =  sctp_hash,
7865        .unhash      =  sctp_unhash,
7866        .get_port    =  sctp_get_port,
7867        .obj_size    =  sizeof(struct sctp_sock),
7868        .sysctl_mem  =  sysctl_sctp_mem,
7869        .sysctl_rmem =  sysctl_sctp_rmem,
7870        .sysctl_wmem =  sysctl_sctp_wmem,
7871        .memory_pressure = &sctp_memory_pressure,
7872        .enter_memory_pressure = sctp_enter_memory_pressure,
7873        .memory_allocated = &sctp_memory_allocated,
7874        .sockets_allocated = &sctp_sockets_allocated,
7875};
7876
7877#if IS_ENABLED(CONFIG_IPV6)
7878
7879#include <net/transp_v6.h>
7880static void sctp_v6_destroy_sock(struct sock *sk)
7881{
7882        sctp_destroy_sock(sk);
7883        inet6_destroy_sock(sk);
7884}
7885
7886struct proto sctpv6_prot = {
7887        .name           = "SCTPv6",
7888        .owner          = THIS_MODULE,
7889        .close          = sctp_close,
7890        .connect        = sctp_connect,
7891        .disconnect     = sctp_disconnect,
7892        .accept         = sctp_accept,
7893        .ioctl          = sctp_ioctl,
7894        .init           = sctp_init_sock,
7895        .destroy        = sctp_v6_destroy_sock,
7896        .shutdown       = sctp_shutdown,
7897        .setsockopt     = sctp_setsockopt,
7898        .getsockopt     = sctp_getsockopt,
7899        .sendmsg        = sctp_sendmsg,
7900        .recvmsg        = sctp_recvmsg,
7901        .bind           = sctp_bind,
7902        .backlog_rcv    = sctp_backlog_rcv,
7903        .hash           = sctp_hash,
7904        .unhash         = sctp_unhash,
7905        .get_port       = sctp_get_port,
7906        .obj_size       = sizeof(struct sctp6_sock),
7907        .sysctl_mem     = sysctl_sctp_mem,
7908        .sysctl_rmem    = sysctl_sctp_rmem,
7909        .sysctl_wmem    = sysctl_sctp_wmem,
7910        .memory_pressure = &sctp_memory_pressure,
7911        .enter_memory_pressure = sctp_enter_memory_pressure,
7912        .memory_allocated = &sctp_memory_allocated,
7913        .sockets_allocated = &sctp_sockets_allocated,
7914};
7915#endif /* IS_ENABLED(CONFIG_IPV6) */
7916