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