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