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