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