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