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