[SCTP]: Honor flags when setting peer address parameters
[safe/jmp/linux-2.6] / net / sctp / socket.c
1 /* SCTP kernel reference 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 reference 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  * The SCTP reference 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  * The SCTP reference 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, write to
32  * the Free Software Foundation, 59 Temple Place - Suite 330,
33  * Boston, MA 02111-1307, USA.
34  *
35  * Please send any bug reports or fixes you make to the
36  * email address(es):
37  *    lksctp developers <lksctp-developers@lists.sourceforge.net>
38  *
39  * Or submit a bug report through the following website:
40  *    http://www.sf.net/projects/lksctp
41  *
42  * Written or modified by:
43  *    La Monte H.P. Yarroll <piggy@acm.org>
44  *    Narasimha Budihal     <narsi@refcode.org>
45  *    Karl Knutson          <karl@athena.chicago.il.us>
46  *    Jon Grimm             <jgrimm@us.ibm.com>
47  *    Xingang Guo           <xingang.guo@intel.com>
48  *    Daisy Chang           <daisyc@us.ibm.com>
49  *    Sridhar Samudrala     <samudrala@us.ibm.com>
50  *    Inaky Perez-Gonzalez  <inaky.gonzalez@intel.com>
51  *    Ardelle Fan           <ardelle.fan@intel.com>
52  *    Ryan Layer            <rmlayer@us.ibm.com>
53  *    Anup Pemmaiah         <pemmaiah@cc.usu.edu>
54  *    Kevin Gao             <kevin.gao@intel.com>
55  *
56  * Any bugs reported given to us we will try to fix... any fixes shared will
57  * be incorporated into the next SCTP release.
58  */
59
60 #include <linux/types.h>
61 #include <linux/kernel.h>
62 #include <linux/wait.h>
63 #include <linux/time.h>
64 #include <linux/ip.h>
65 #include <linux/capability.h>
66 #include <linux/fcntl.h>
67 #include <linux/poll.h>
68 #include <linux/init.h>
69 #include <linux/crypto.h>
70
71 #include <net/ip.h>
72 #include <net/icmp.h>
73 #include <net/route.h>
74 #include <net/ipv6.h>
75 #include <net/inet_common.h>
76
77 #include <linux/socket.h> /* for sa_family_t */
78 #include <net/sock.h>
79 #include <net/sctp/sctp.h>
80 #include <net/sctp/sm.h>
81
82 /* WARNING:  Please do not remove the SCTP_STATIC attribute to
83  * any of the functions below as they are used to export functions
84  * used by a project regression testsuite.
85  */
86
87 /* Forward declarations for internal helper functions. */
88 static int sctp_writeable(struct sock *sk);
89 static void sctp_wfree(struct sk_buff *skb);
90 static int sctp_wait_for_sndbuf(struct sctp_association *, long *timeo_p,
91                                 size_t msg_len);
92 static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p);
93 static int sctp_wait_for_connect(struct sctp_association *, long *timeo_p);
94 static int sctp_wait_for_accept(struct sock *sk, long timeo);
95 static void sctp_wait_for_close(struct sock *sk, long timeo);
96 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
97                                         union sctp_addr *addr, int len);
98 static int sctp_bindx_add(struct sock *, struct sockaddr *, int);
99 static int sctp_bindx_rem(struct sock *, struct sockaddr *, int);
100 static int sctp_send_asconf_add_ip(struct sock *, struct sockaddr *, int);
101 static int sctp_send_asconf_del_ip(struct sock *, struct sockaddr *, int);
102 static int sctp_send_asconf(struct sctp_association *asoc,
103                             struct sctp_chunk *chunk);
104 static int sctp_do_bind(struct sock *, union sctp_addr *, int);
105 static int sctp_autobind(struct sock *sk);
106 static void sctp_sock_migrate(struct sock *, struct sock *,
107                               struct sctp_association *, sctp_socket_type_t);
108 static char *sctp_hmac_alg = SCTP_COOKIE_HMAC_ALG;
109
110 extern struct kmem_cache *sctp_bucket_cachep;
111
112 /* Get the sndbuf space available at the time on the association.  */
113 static inline int sctp_wspace(struct sctp_association *asoc)
114 {
115         struct sock *sk = asoc->base.sk;
116         int amt = 0;
117
118         if (asoc->ep->sndbuf_policy) {
119                 /* make sure that no association uses more than sk_sndbuf */
120                 amt = sk->sk_sndbuf - asoc->sndbuf_used;
121         } else {
122                 /* do socket level accounting */
123                 amt = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
124         }
125
126         if (amt < 0)
127                 amt = 0;
128
129         return amt;
130 }
131
132 /* Increment the used sndbuf space count of the corresponding association by
133  * the size of the outgoing data chunk.
134  * Also, set the skb destructor for sndbuf accounting later.
135  *
136  * Since it is always 1-1 between chunk and skb, and also a new skb is always
137  * allocated for chunk bundling in sctp_packet_transmit(), we can use the
138  * destructor in the data chunk skb for the purpose of the sndbuf space
139  * tracking.
140  */
141 static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
142 {
143         struct sctp_association *asoc = chunk->asoc;
144         struct sock *sk = asoc->base.sk;
145
146         /* The sndbuf space is tracked per association.  */
147         sctp_association_hold(asoc);
148
149         skb_set_owner_w(chunk->skb, sk);
150
151         chunk->skb->destructor = sctp_wfree;
152         /* Save the chunk pointer in skb for sctp_wfree to use later.  */
153         *((struct sctp_chunk **)(chunk->skb->cb)) = chunk;
154
155         asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk) +
156                                 sizeof(struct sk_buff) +
157                                 sizeof(struct sctp_chunk);
158
159         atomic_add(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
160 }
161
162 /* Verify that this is a valid address. */
163 static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
164                                    int len)
165 {
166         struct sctp_af *af;
167
168         /* Verify basic sockaddr. */
169         af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
170         if (!af)
171                 return -EINVAL;
172
173         /* Is this a valid SCTP address?  */
174         if (!af->addr_valid(addr, sctp_sk(sk), NULL))
175                 return -EINVAL;
176
177         if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
178                 return -EINVAL;
179
180         return 0;
181 }
182
183 /* Look up the association by its id.  If this is not a UDP-style
184  * socket, the ID field is always ignored.
185  */
186 struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
187 {
188         struct sctp_association *asoc = NULL;
189
190         /* If this is not a UDP-style socket, assoc id should be ignored. */
191         if (!sctp_style(sk, UDP)) {
192                 /* Return NULL if the socket state is not ESTABLISHED. It
193                  * could be a TCP-style listening socket or a socket which
194                  * hasn't yet called connect() to establish an association.
195                  */
196                 if (!sctp_sstate(sk, ESTABLISHED))
197                         return NULL;
198
199                 /* Get the first and the only association from the list. */
200                 if (!list_empty(&sctp_sk(sk)->ep->asocs))
201                         asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
202                                           struct sctp_association, asocs);
203                 return asoc;
204         }
205
206         /* Otherwise this is a UDP-style socket. */
207         if (!id || (id == (sctp_assoc_t)-1))
208                 return NULL;
209
210         spin_lock_bh(&sctp_assocs_id_lock);
211         asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
212         spin_unlock_bh(&sctp_assocs_id_lock);
213
214         if (!asoc || (asoc->base.sk != sk) || asoc->base.dead)
215                 return NULL;
216
217         return asoc;
218 }
219
220 /* Look up the transport from an address and an assoc id. If both address and
221  * id are specified, the associations matching the address and the id should be
222  * the same.
223  */
224 static struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
225                                               struct sockaddr_storage *addr,
226                                               sctp_assoc_t id)
227 {
228         struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
229         struct sctp_transport *transport;
230         union sctp_addr *laddr = (union sctp_addr *)addr;
231
232         addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
233                                                laddr,
234                                                &transport);
235
236         if (!addr_asoc)
237                 return NULL;
238
239         id_asoc = sctp_id2assoc(sk, id);
240         if (id_asoc && (id_asoc != addr_asoc))
241                 return NULL;
242
243         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
244                                                 (union sctp_addr *)addr);
245
246         return transport;
247 }
248
249 /* API 3.1.2 bind() - UDP Style Syntax
250  * The syntax of bind() is,
251  *
252  *   ret = bind(int sd, struct sockaddr *addr, int addrlen);
253  *
254  *   sd      - the socket descriptor returned by socket().
255  *   addr    - the address structure (struct sockaddr_in or struct
256  *             sockaddr_in6 [RFC 2553]),
257  *   addr_len - the size of the address structure.
258  */
259 SCTP_STATIC int sctp_bind(struct sock *sk, struct sockaddr *addr, int addr_len)
260 {
261         int retval = 0;
262
263         sctp_lock_sock(sk);
264
265         SCTP_DEBUG_PRINTK("sctp_bind(sk: %p, addr: %p, addr_len: %d)\n",
266                           sk, addr, addr_len);
267
268         /* Disallow binding twice. */
269         if (!sctp_sk(sk)->ep->base.bind_addr.port)
270                 retval = sctp_do_bind(sk, (union sctp_addr *)addr,
271                                       addr_len);
272         else
273                 retval = -EINVAL;
274
275         sctp_release_sock(sk);
276
277         return retval;
278 }
279
280 static long sctp_get_port_local(struct sock *, union sctp_addr *);
281
282 /* Verify this is a valid sockaddr. */
283 static struct sctp_af *sctp_sockaddr_af(struct sctp_sock *opt,
284                                         union sctp_addr *addr, int len)
285 {
286         struct sctp_af *af;
287
288         /* Check minimum size.  */
289         if (len < sizeof (struct sockaddr))
290                 return NULL;
291
292         /* Does this PF support this AF? */
293         if (!opt->pf->af_supported(addr->sa.sa_family, opt))
294                 return NULL;
295
296         /* If we get this far, af is valid. */
297         af = sctp_get_af_specific(addr->sa.sa_family);
298
299         if (len < af->sockaddr_len)
300                 return NULL;
301
302         return af;
303 }
304
305 /* Bind a local address either to an endpoint or to an association.  */
306 SCTP_STATIC int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
307 {
308         struct sctp_sock *sp = sctp_sk(sk);
309         struct sctp_endpoint *ep = sp->ep;
310         struct sctp_bind_addr *bp = &ep->base.bind_addr;
311         struct sctp_af *af;
312         unsigned short snum;
313         int ret = 0;
314
315         /* Common sockaddr verification. */
316         af = sctp_sockaddr_af(sp, addr, len);
317         if (!af) {
318                 SCTP_DEBUG_PRINTK("sctp_do_bind(sk: %p, newaddr: %p, len: %d) EINVAL\n",
319                                   sk, addr, len);
320                 return -EINVAL;
321         }
322
323         snum = ntohs(addr->v4.sin_port);
324
325         SCTP_DEBUG_PRINTK_IPADDR("sctp_do_bind(sk: %p, new addr: ",
326                                  ", port: %d, new port: %d, len: %d)\n",
327                                  sk,
328                                  addr,
329                                  bp->port, snum,
330                                  len);
331
332         /* PF specific bind() address verification. */
333         if (!sp->pf->bind_verify(sp, addr))
334                 return -EADDRNOTAVAIL;
335
336         /* We must either be unbound, or bind to the same port.  */
337         if (bp->port && (snum != bp->port)) {
338                 SCTP_DEBUG_PRINTK("sctp_do_bind:"
339                                   " New port %d does not match existing port "
340                                   "%d.\n", snum, bp->port);
341                 return -EINVAL;
342         }
343
344         if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE))
345                 return -EACCES;
346
347         /* Make sure we are allowed to bind here.
348          * The function sctp_get_port_local() does duplicate address
349          * detection.
350          */
351         if ((ret = sctp_get_port_local(sk, addr))) {
352                 if (ret == (long) sk) {
353                         /* This endpoint has a conflicting address. */
354                         return -EINVAL;
355                 } else {
356                         return -EADDRINUSE;
357                 }
358         }
359
360         /* Refresh ephemeral port.  */
361         if (!bp->port)
362                 bp->port = inet_sk(sk)->num;
363
364         /* Add the address to the bind address list.  */
365         sctp_local_bh_disable();
366         sctp_write_lock(&ep->base.addr_lock);
367
368         /* Use GFP_ATOMIC since BHs are disabled.  */
369         ret = sctp_add_bind_addr(bp, addr, 1, GFP_ATOMIC);
370         sctp_write_unlock(&ep->base.addr_lock);
371         sctp_local_bh_enable();
372
373         /* Copy back into socket for getsockname() use. */
374         if (!ret) {
375                 inet_sk(sk)->sport = htons(inet_sk(sk)->num);
376                 af->to_sk_saddr(addr, sk);
377         }
378
379         return ret;
380 }
381
382  /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
383  *
384  * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged
385  * at any one time.  If a sender, after sending an ASCONF chunk, decides
386  * it needs to transfer another ASCONF Chunk, it MUST wait until the
387  * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
388  * subsequent ASCONF. Note this restriction binds each side, so at any
389  * time two ASCONF may be in-transit on any given association (one sent
390  * from each endpoint).
391  */
392 static int sctp_send_asconf(struct sctp_association *asoc,
393                             struct sctp_chunk *chunk)
394 {
395         int             retval = 0;
396
397         /* If there is an outstanding ASCONF chunk, queue it for later
398          * transmission.
399          */
400         if (asoc->addip_last_asconf) {
401                 list_add_tail(&chunk->list, &asoc->addip_chunk_list);
402                 goto out;
403         }
404
405         /* Hold the chunk until an ASCONF_ACK is received. */
406         sctp_chunk_hold(chunk);
407         retval = sctp_primitive_ASCONF(asoc, chunk);
408         if (retval)
409                 sctp_chunk_free(chunk);
410         else
411                 asoc->addip_last_asconf = chunk;
412
413 out:
414         return retval;
415 }
416
417 /* Add a list of addresses as bind addresses to local endpoint or
418  * association.
419  *
420  * Basically run through each address specified in the addrs/addrcnt
421  * array/length pair, determine if it is IPv6 or IPv4 and call
422  * sctp_do_bind() on it.
423  *
424  * If any of them fails, then the operation will be reversed and the
425  * ones that were added will be removed.
426  *
427  * Only sctp_setsockopt_bindx() is supposed to call this function.
428  */
429 int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
430 {
431         int cnt;
432         int retval = 0;
433         void *addr_buf;
434         struct sockaddr *sa_addr;
435         struct sctp_af *af;
436
437         SCTP_DEBUG_PRINTK("sctp_bindx_add (sk: %p, addrs: %p, addrcnt: %d)\n",
438                           sk, addrs, addrcnt);
439
440         addr_buf = addrs;
441         for (cnt = 0; cnt < addrcnt; cnt++) {
442                 /* The list may contain either IPv4 or IPv6 address;
443                  * determine the address length for walking thru the list.
444                  */
445                 sa_addr = (struct sockaddr *)addr_buf;
446                 af = sctp_get_af_specific(sa_addr->sa_family);
447                 if (!af) {
448                         retval = -EINVAL;
449                         goto err_bindx_add;
450                 }
451
452                 retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr,
453                                       af->sockaddr_len);
454
455                 addr_buf += af->sockaddr_len;
456
457 err_bindx_add:
458                 if (retval < 0) {
459                         /* Failed. Cleanup the ones that have been added */
460                         if (cnt > 0)
461                                 sctp_bindx_rem(sk, addrs, cnt);
462                         return retval;
463                 }
464         }
465
466         return retval;
467 }
468
469 /* Send an ASCONF chunk with Add IP address parameters to all the peers of the
470  * associations that are part of the endpoint indicating that a list of local
471  * addresses are added to the endpoint.
472  *
473  * If any of the addresses is already in the bind address list of the
474  * association, we do not send the chunk for that association.  But it will not
475  * affect other associations.
476  *
477  * Only sctp_setsockopt_bindx() is supposed to call this function.
478  */
479 static int sctp_send_asconf_add_ip(struct sock          *sk,
480                                    struct sockaddr      *addrs,
481                                    int                  addrcnt)
482 {
483         struct sctp_sock                *sp;
484         struct sctp_endpoint            *ep;
485         struct sctp_association         *asoc;
486         struct sctp_bind_addr           *bp;
487         struct sctp_chunk               *chunk;
488         struct sctp_sockaddr_entry      *laddr;
489         union sctp_addr                 *addr;
490         union sctp_addr                 saveaddr;
491         void                            *addr_buf;
492         struct sctp_af                  *af;
493         struct list_head                *pos;
494         struct list_head                *p;
495         int                             i;
496         int                             retval = 0;
497
498         if (!sctp_addip_enable)
499                 return retval;
500
501         sp = sctp_sk(sk);
502         ep = sp->ep;
503
504         SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n",
505                           __FUNCTION__, sk, addrs, addrcnt);
506
507         list_for_each(pos, &ep->asocs) {
508                 asoc = list_entry(pos, struct sctp_association, asocs);
509
510                 if (!asoc->peer.asconf_capable)
511                         continue;
512
513                 if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
514                         continue;
515
516                 if (!sctp_state(asoc, ESTABLISHED))
517                         continue;
518
519                 /* Check if any address in the packed array of addresses is
520                  * in the bind address list of the association. If so,
521                  * do not send the asconf chunk to its peer, but continue with
522                  * other associations.
523                  */
524                 addr_buf = addrs;
525                 for (i = 0; i < addrcnt; i++) {
526                         addr = (union sctp_addr *)addr_buf;
527                         af = sctp_get_af_specific(addr->v4.sin_family);
528                         if (!af) {
529                                 retval = -EINVAL;
530                                 goto out;
531                         }
532
533                         if (sctp_assoc_lookup_laddr(asoc, addr))
534                                 break;
535
536                         addr_buf += af->sockaddr_len;
537                 }
538                 if (i < addrcnt)
539                         continue;
540
541                 /* Use the first address in bind addr list of association as
542                  * Address Parameter of ASCONF CHUNK.
543                  */
544                 sctp_read_lock(&asoc->base.addr_lock);
545                 bp = &asoc->base.bind_addr;
546                 p = bp->address_list.next;
547                 laddr = list_entry(p, struct sctp_sockaddr_entry, list);
548                 sctp_read_unlock(&asoc->base.addr_lock);
549
550                 chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
551                                                    addrcnt, SCTP_PARAM_ADD_IP);
552                 if (!chunk) {
553                         retval = -ENOMEM;
554                         goto out;
555                 }
556
557                 retval = sctp_send_asconf(asoc, chunk);
558                 if (retval)
559                         goto out;
560
561                 /* Add the new addresses to the bind address list with
562                  * use_as_src set to 0.
563                  */
564                 sctp_local_bh_disable();
565                 sctp_write_lock(&asoc->base.addr_lock);
566                 addr_buf = addrs;
567                 for (i = 0; i < addrcnt; i++) {
568                         addr = (union sctp_addr *)addr_buf;
569                         af = sctp_get_af_specific(addr->v4.sin_family);
570                         memcpy(&saveaddr, addr, af->sockaddr_len);
571                         retval = sctp_add_bind_addr(bp, &saveaddr, 0,
572                                                     GFP_ATOMIC);
573                         addr_buf += af->sockaddr_len;
574                 }
575                 sctp_write_unlock(&asoc->base.addr_lock);
576                 sctp_local_bh_enable();
577         }
578
579 out:
580         return retval;
581 }
582
583 /* Remove a list of addresses from bind addresses list.  Do not remove the
584  * last address.
585  *
586  * Basically run through each address specified in the addrs/addrcnt
587  * array/length pair, determine if it is IPv6 or IPv4 and call
588  * sctp_del_bind() on it.
589  *
590  * If any of them fails, then the operation will be reversed and the
591  * ones that were removed will be added back.
592  *
593  * At least one address has to be left; if only one address is
594  * available, the operation will return -EBUSY.
595  *
596  * Only sctp_setsockopt_bindx() is supposed to call this function.
597  */
598 int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
599 {
600         struct sctp_sock *sp = sctp_sk(sk);
601         struct sctp_endpoint *ep = sp->ep;
602         int cnt;
603         struct sctp_bind_addr *bp = &ep->base.bind_addr;
604         int retval = 0;
605         void *addr_buf;
606         union sctp_addr *sa_addr;
607         struct sctp_af *af;
608
609         SCTP_DEBUG_PRINTK("sctp_bindx_rem (sk: %p, addrs: %p, addrcnt: %d)\n",
610                           sk, addrs, addrcnt);
611
612         addr_buf = addrs;
613         for (cnt = 0; cnt < addrcnt; cnt++) {
614                 /* If the bind address list is empty or if there is only one
615                  * bind address, there is nothing more to be removed (we need
616                  * at least one address here).
617                  */
618                 if (list_empty(&bp->address_list) ||
619                     (sctp_list_single_entry(&bp->address_list))) {
620                         retval = -EBUSY;
621                         goto err_bindx_rem;
622                 }
623
624                 sa_addr = (union sctp_addr *)addr_buf;
625                 af = sctp_get_af_specific(sa_addr->sa.sa_family);
626                 if (!af) {
627                         retval = -EINVAL;
628                         goto err_bindx_rem;
629                 }
630
631                 if (!af->addr_valid(sa_addr, sp, NULL)) {
632                         retval = -EADDRNOTAVAIL;
633                         goto err_bindx_rem;
634                 }
635
636                 if (sa_addr->v4.sin_port != htons(bp->port)) {
637                         retval = -EINVAL;
638                         goto err_bindx_rem;
639                 }
640
641                 /* FIXME - There is probably a need to check if sk->sk_saddr and
642                  * sk->sk_rcv_addr are currently set to one of the addresses to
643                  * be removed. This is something which needs to be looked into
644                  * when we are fixing the outstanding issues with multi-homing
645                  * socket routing and failover schemes. Refer to comments in
646                  * sctp_do_bind(). -daisy
647                  */
648                 sctp_local_bh_disable();
649                 sctp_write_lock(&ep->base.addr_lock);
650
651                 retval = sctp_del_bind_addr(bp, sa_addr);
652
653                 sctp_write_unlock(&ep->base.addr_lock);
654                 sctp_local_bh_enable();
655
656                 addr_buf += af->sockaddr_len;
657 err_bindx_rem:
658                 if (retval < 0) {
659                         /* Failed. Add the ones that has been removed back */
660                         if (cnt > 0)
661                                 sctp_bindx_add(sk, addrs, cnt);
662                         return retval;
663                 }
664         }
665
666         return retval;
667 }
668
669 /* Send an ASCONF chunk with Delete IP address parameters to all the peers of
670  * the associations that are part of the endpoint indicating that a list of
671  * local addresses are removed from the endpoint.
672  *
673  * If any of the addresses is already in the bind address list of the
674  * association, we do not send the chunk for that association.  But it will not
675  * affect other associations.
676  *
677  * Only sctp_setsockopt_bindx() is supposed to call this function.
678  */
679 static int sctp_send_asconf_del_ip(struct sock          *sk,
680                                    struct sockaddr      *addrs,
681                                    int                  addrcnt)
682 {
683         struct sctp_sock        *sp;
684         struct sctp_endpoint    *ep;
685         struct sctp_association *asoc;
686         struct sctp_transport   *transport;
687         struct sctp_bind_addr   *bp;
688         struct sctp_chunk       *chunk;
689         union sctp_addr         *laddr;
690         void                    *addr_buf;
691         struct sctp_af          *af;
692         struct list_head        *pos, *pos1;
693         struct sctp_sockaddr_entry *saddr;
694         int                     i;
695         int                     retval = 0;
696
697         if (!sctp_addip_enable)
698                 return retval;
699
700         sp = sctp_sk(sk);
701         ep = sp->ep;
702
703         SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n",
704                           __FUNCTION__, sk, addrs, addrcnt);
705
706         list_for_each(pos, &ep->asocs) {
707                 asoc = list_entry(pos, struct sctp_association, asocs);
708
709                 if (!asoc->peer.asconf_capable)
710                         continue;
711
712                 if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
713                         continue;
714
715                 if (!sctp_state(asoc, ESTABLISHED))
716                         continue;
717
718                 /* Check if any address in the packed array of addresses is
719                  * not present in the bind address list of the association.
720                  * If so, do not send the asconf chunk to its peer, but
721                  * continue with other associations.
722                  */
723                 addr_buf = addrs;
724                 for (i = 0; i < addrcnt; i++) {
725                         laddr = (union sctp_addr *)addr_buf;
726                         af = sctp_get_af_specific(laddr->v4.sin_family);
727                         if (!af) {
728                                 retval = -EINVAL;
729                                 goto out;
730                         }
731
732                         if (!sctp_assoc_lookup_laddr(asoc, laddr))
733                                 break;
734
735                         addr_buf += af->sockaddr_len;
736                 }
737                 if (i < addrcnt)
738                         continue;
739
740                 /* Find one address in the association's bind address list
741                  * that is not in the packed array of addresses. This is to
742                  * make sure that we do not delete all the addresses in the
743                  * association.
744                  */
745                 sctp_read_lock(&asoc->base.addr_lock);
746                 bp = &asoc->base.bind_addr;
747                 laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
748                                                addrcnt, sp);
749                 sctp_read_unlock(&asoc->base.addr_lock);
750                 if (!laddr)
751                         continue;
752
753                 chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
754                                                    SCTP_PARAM_DEL_IP);
755                 if (!chunk) {
756                         retval = -ENOMEM;
757                         goto out;
758                 }
759
760                 /* Reset use_as_src flag for the addresses in the bind address
761                  * list that are to be deleted.
762                  */
763                 sctp_local_bh_disable();
764                 sctp_write_lock(&asoc->base.addr_lock);
765                 addr_buf = addrs;
766                 for (i = 0; i < addrcnt; i++) {
767                         laddr = (union sctp_addr *)addr_buf;
768                         af = sctp_get_af_specific(laddr->v4.sin_family);
769                         list_for_each(pos1, &bp->address_list) {
770                                 saddr = list_entry(pos1,
771                                                    struct sctp_sockaddr_entry,
772                                                    list);
773                                 if (sctp_cmp_addr_exact(&saddr->a, laddr))
774                                         saddr->use_as_src = 0;
775                         }
776                         addr_buf += af->sockaddr_len;
777                 }
778                 sctp_write_unlock(&asoc->base.addr_lock);
779                 sctp_local_bh_enable();
780
781                 /* Update the route and saddr entries for all the transports
782                  * as some of the addresses in the bind address list are
783                  * about to be deleted and cannot be used as source addresses.
784                  */
785                 list_for_each(pos1, &asoc->peer.transport_addr_list) {
786                         transport = list_entry(pos1, struct sctp_transport,
787                                                transports);
788                         dst_release(transport->dst);
789                         sctp_transport_route(transport, NULL,
790                                              sctp_sk(asoc->base.sk));
791                 }
792
793                 retval = sctp_send_asconf(asoc, chunk);
794         }
795 out:
796         return retval;
797 }
798
799 /* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
800  *
801  * API 8.1
802  * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
803  *                int flags);
804  *
805  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
806  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
807  * or IPv6 addresses.
808  *
809  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
810  * Section 3.1.2 for this usage.
811  *
812  * addrs is a pointer to an array of one or more socket addresses. Each
813  * address is contained in its appropriate structure (i.e. struct
814  * sockaddr_in or struct sockaddr_in6) the family of the address type
815  * must be used to distinguish the address length (note that this
816  * representation is termed a "packed array" of addresses). The caller
817  * specifies the number of addresses in the array with addrcnt.
818  *
819  * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
820  * -1, and sets errno to the appropriate error code.
821  *
822  * For SCTP, the port given in each socket address must be the same, or
823  * sctp_bindx() will fail, setting errno to EINVAL.
824  *
825  * The flags parameter is formed from the bitwise OR of zero or more of
826  * the following currently defined flags:
827  *
828  * SCTP_BINDX_ADD_ADDR
829  *
830  * SCTP_BINDX_REM_ADDR
831  *
832  * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
833  * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
834  * addresses from the association. The two flags are mutually exclusive;
835  * if both are given, sctp_bindx() will fail with EINVAL. A caller may
836  * not remove all addresses from an association; sctp_bindx() will
837  * reject such an attempt with EINVAL.
838  *
839  * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
840  * additional addresses with an endpoint after calling bind().  Or use
841  * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
842  * socket is associated with so that no new association accepted will be
843  * associated with those addresses. If the endpoint supports dynamic
844  * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
845  * endpoint to send the appropriate message to the peer to change the
846  * peers address lists.
847  *
848  * Adding and removing addresses from a connected association is
849  * optional functionality. Implementations that do not support this
850  * functionality should return EOPNOTSUPP.
851  *
852  * Basically do nothing but copying the addresses from user to kernel
853  * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
854  * This is used for tunneling the sctp_bindx() request through sctp_setsockopt()
855  * from userspace.
856  *
857  * We don't use copy_from_user() for optimization: we first do the
858  * sanity checks (buffer size -fast- and access check-healthy
859  * pointer); if all of those succeed, then we can alloc the memory
860  * (expensive operation) needed to copy the data to kernel. Then we do
861  * the copying without checking the user space area
862  * (__copy_from_user()).
863  *
864  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
865  * it.
866  *
867  * sk        The sk of the socket
868  * addrs     The pointer to the addresses in user land
869  * addrssize Size of the addrs buffer
870  * op        Operation to perform (add or remove, see the flags of
871  *           sctp_bindx)
872  *
873  * Returns 0 if ok, <0 errno code on error.
874  */
875 SCTP_STATIC int sctp_setsockopt_bindx(struct sock* sk,
876                                       struct sockaddr __user *addrs,
877                                       int addrs_size, int op)
878 {
879         struct sockaddr *kaddrs;
880         int err;
881         int addrcnt = 0;
882         int walk_size = 0;
883         struct sockaddr *sa_addr;
884         void *addr_buf;
885         struct sctp_af *af;
886
887         SCTP_DEBUG_PRINTK("sctp_setsocktopt_bindx: sk %p addrs %p"
888                           " addrs_size %d opt %d\n", sk, addrs, addrs_size, op);
889
890         if (unlikely(addrs_size <= 0))
891                 return -EINVAL;
892
893         /* Check the user passed a healthy pointer.  */
894         if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
895                 return -EFAULT;
896
897         /* Alloc space for the address array in kernel memory.  */
898         kaddrs = kmalloc(addrs_size, GFP_KERNEL);
899         if (unlikely(!kaddrs))
900                 return -ENOMEM;
901
902         if (__copy_from_user(kaddrs, addrs, addrs_size)) {
903                 kfree(kaddrs);
904                 return -EFAULT;
905         }
906
907         /* Walk through the addrs buffer and count the number of addresses. */
908         addr_buf = kaddrs;
909         while (walk_size < addrs_size) {
910                 sa_addr = (struct sockaddr *)addr_buf;
911                 af = sctp_get_af_specific(sa_addr->sa_family);
912
913                 /* If the address family is not supported or if this address
914                  * causes the address buffer to overflow return EINVAL.
915                  */
916                 if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
917                         kfree(kaddrs);
918                         return -EINVAL;
919                 }
920                 addrcnt++;
921                 addr_buf += af->sockaddr_len;
922                 walk_size += af->sockaddr_len;
923         }
924
925         /* Do the work. */
926         switch (op) {
927         case SCTP_BINDX_ADD_ADDR:
928                 err = sctp_bindx_add(sk, kaddrs, addrcnt);
929                 if (err)
930                         goto out;
931                 err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt);
932                 break;
933
934         case SCTP_BINDX_REM_ADDR:
935                 err = sctp_bindx_rem(sk, kaddrs, addrcnt);
936                 if (err)
937                         goto out;
938                 err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt);
939                 break;
940
941         default:
942                 err = -EINVAL;
943                 break;
944         };
945
946 out:
947         kfree(kaddrs);
948
949         return err;
950 }
951
952 /* __sctp_connect(struct sock* sk, struct sockaddr *kaddrs, int addrs_size)
953  *
954  * Common routine for handling connect() and sctp_connectx().
955  * Connect will come in with just a single address.
956  */
957 static int __sctp_connect(struct sock* sk,
958                           struct sockaddr *kaddrs,
959                           int addrs_size)
960 {
961         struct sctp_sock *sp;
962         struct sctp_endpoint *ep;
963         struct sctp_association *asoc = NULL;
964         struct sctp_association *asoc2;
965         struct sctp_transport *transport;
966         union sctp_addr to;
967         struct sctp_af *af;
968         sctp_scope_t scope;
969         long timeo;
970         int err = 0;
971         int addrcnt = 0;
972         int walk_size = 0;
973         union sctp_addr *sa_addr;
974         void *addr_buf;
975
976         sp = sctp_sk(sk);
977         ep = sp->ep;
978
979         /* connect() cannot be done on a socket that is already in ESTABLISHED
980          * state - UDP-style peeled off socket or a TCP-style socket that
981          * is already connected.
982          * It cannot be done even on a TCP-style listening socket.
983          */
984         if (sctp_sstate(sk, ESTABLISHED) ||
985             (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {
986                 err = -EISCONN;
987                 goto out_free;
988         }
989
990         /* Walk through the addrs buffer and count the number of addresses. */
991         addr_buf = kaddrs;
992         while (walk_size < addrs_size) {
993                 sa_addr = (union sctp_addr *)addr_buf;
994                 af = sctp_get_af_specific(sa_addr->sa.sa_family);
995
996                 /* If the address family is not supported or if this address
997                  * causes the address buffer to overflow return EINVAL.
998                  */
999                 if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
1000                         err = -EINVAL;
1001                         goto out_free;
1002                 }
1003
1004                 err = sctp_verify_addr(sk, sa_addr, af->sockaddr_len);
1005                 if (err)
1006                         goto out_free;
1007
1008                 memcpy(&to, sa_addr, af->sockaddr_len);
1009
1010                 /* Check if there already is a matching association on the
1011                  * endpoint (other than the one created here).
1012                  */
1013                 asoc2 = sctp_endpoint_lookup_assoc(ep, sa_addr, &transport);
1014                 if (asoc2 && asoc2 != asoc) {
1015                         if (asoc2->state >= SCTP_STATE_ESTABLISHED)
1016                                 err = -EISCONN;
1017                         else
1018                                 err = -EALREADY;
1019                         goto out_free;
1020                 }
1021
1022                 /* If we could not find a matching association on the endpoint,
1023                  * make sure that there is no peeled-off association matching
1024                  * the peer address even on another socket.
1025                  */
1026                 if (sctp_endpoint_is_peeled_off(ep, sa_addr)) {
1027                         err = -EADDRNOTAVAIL;
1028                         goto out_free;
1029                 }
1030
1031                 if (!asoc) {
1032                         /* If a bind() or sctp_bindx() is not called prior to
1033                          * an sctp_connectx() call, the system picks an
1034                          * ephemeral port and will choose an address set
1035                          * equivalent to binding with a wildcard address.
1036                          */
1037                         if (!ep->base.bind_addr.port) {
1038                                 if (sctp_autobind(sk)) {
1039                                         err = -EAGAIN;
1040                                         goto out_free;
1041                                 }
1042                         } else {
1043                                 /*
1044                                  * If an unprivileged user inherits a 1-many
1045                                  * style socket with open associations on a
1046                                  * privileged port, it MAY be permitted to
1047                                  * accept new associations, but it SHOULD NOT
1048                                  * be permitted to open new associations.
1049                                  */
1050                                 if (ep->base.bind_addr.port < PROT_SOCK &&
1051                                     !capable(CAP_NET_BIND_SERVICE)) {
1052                                         err = -EACCES;
1053                                         goto out_free;
1054                                 }
1055                         }
1056
1057                         scope = sctp_scope(sa_addr);
1058                         asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1059                         if (!asoc) {
1060                                 err = -ENOMEM;
1061                                 goto out_free;
1062                         }
1063                 }
1064
1065                 /* Prime the peer's transport structures.  */
1066                 transport = sctp_assoc_add_peer(asoc, sa_addr, GFP_KERNEL,
1067                                                 SCTP_UNKNOWN);
1068                 if (!transport) {
1069                         err = -ENOMEM;
1070                         goto out_free;
1071                 }
1072
1073                 addrcnt++;
1074                 addr_buf += af->sockaddr_len;
1075                 walk_size += af->sockaddr_len;
1076         }
1077
1078         err = sctp_assoc_set_bind_addr_from_ep(asoc, GFP_KERNEL);
1079         if (err < 0) {
1080                 goto out_free;
1081         }
1082
1083         err = sctp_primitive_ASSOCIATE(asoc, NULL);
1084         if (err < 0) {
1085                 goto out_free;
1086         }
1087
1088         /* Initialize sk's dport and daddr for getpeername() */
1089         inet_sk(sk)->dport = htons(asoc->peer.port);
1090         af = sctp_get_af_specific(to.sa.sa_family);
1091         af->to_sk_daddr(&to, sk);
1092         sk->sk_err = 0;
1093
1094         timeo = sock_sndtimeo(sk, sk->sk_socket->file->f_flags & O_NONBLOCK);
1095         err = sctp_wait_for_connect(asoc, &timeo);
1096
1097         /* Don't free association on exit. */
1098         asoc = NULL;
1099
1100 out_free:
1101
1102         SCTP_DEBUG_PRINTK("About to exit __sctp_connect() free asoc: %p"
1103                           " kaddrs: %p err: %d\n",
1104                           asoc, kaddrs, err);
1105         if (asoc)
1106                 sctp_association_free(asoc);
1107         return err;
1108 }
1109
1110 /* Helper for tunneling sctp_connectx() requests through sctp_setsockopt()
1111  *
1112  * API 8.9
1113  * int sctp_connectx(int sd, struct sockaddr *addrs, int addrcnt);
1114  *
1115  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
1116  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
1117  * or IPv6 addresses.
1118  *
1119  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
1120  * Section 3.1.2 for this usage.
1121  *
1122  * addrs is a pointer to an array of one or more socket addresses. Each
1123  * address is contained in its appropriate structure (i.e. struct
1124  * sockaddr_in or struct sockaddr_in6) the family of the address type
1125  * must be used to distengish the address length (note that this
1126  * representation is termed a "packed array" of addresses). The caller
1127  * specifies the number of addresses in the array with addrcnt.
1128  *
1129  * On success, sctp_connectx() returns 0. On failure, sctp_connectx() returns
1130  * -1, and sets errno to the appropriate error code.
1131  *
1132  * For SCTP, the port given in each socket address must be the same, or
1133  * sctp_connectx() will fail, setting errno to EINVAL.
1134  *
1135  * An application can use sctp_connectx to initiate an association with
1136  * an endpoint that is multi-homed.  Much like sctp_bindx() this call
1137  * allows a caller to specify multiple addresses at which a peer can be
1138  * reached.  The way the SCTP stack uses the list of addresses to set up
1139  * the association is implementation dependant.  This function only
1140  * specifies that the stack will try to make use of all the addresses in
1141  * the list when needed.
1142  *
1143  * Note that the list of addresses passed in is only used for setting up
1144  * the association.  It does not necessarily equal the set of addresses
1145  * the peer uses for the resulting association.  If the caller wants to
1146  * find out the set of peer addresses, it must use sctp_getpaddrs() to
1147  * retrieve them after the association has been set up.
1148  *
1149  * Basically do nothing but copying the addresses from user to kernel
1150  * land and invoking either sctp_connectx(). This is used for tunneling
1151  * the sctp_connectx() request through sctp_setsockopt() from userspace.
1152  *
1153  * We don't use copy_from_user() for optimization: we first do the
1154  * sanity checks (buffer size -fast- and access check-healthy
1155  * pointer); if all of those succeed, then we can alloc the memory
1156  * (expensive operation) needed to copy the data to kernel. Then we do
1157  * the copying without checking the user space area
1158  * (__copy_from_user()).
1159  *
1160  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
1161  * it.
1162  *
1163  * sk        The sk of the socket
1164  * addrs     The pointer to the addresses in user land
1165  * addrssize Size of the addrs buffer
1166  *
1167  * Returns 0 if ok, <0 errno code on error.
1168  */
1169 SCTP_STATIC int sctp_setsockopt_connectx(struct sock* sk,
1170                                       struct sockaddr __user *addrs,
1171                                       int addrs_size)
1172 {
1173         int err = 0;
1174         struct sockaddr *kaddrs;
1175
1176         SCTP_DEBUG_PRINTK("%s - sk %p addrs %p addrs_size %d\n",
1177                           __FUNCTION__, sk, addrs, addrs_size);
1178
1179         if (unlikely(addrs_size <= 0))
1180                 return -EINVAL;
1181
1182         /* Check the user passed a healthy pointer.  */
1183         if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
1184                 return -EFAULT;
1185
1186         /* Alloc space for the address array in kernel memory.  */
1187         kaddrs = kmalloc(addrs_size, GFP_KERNEL);
1188         if (unlikely(!kaddrs))
1189                 return -ENOMEM;
1190
1191         if (__copy_from_user(kaddrs, addrs, addrs_size)) {
1192                 err = -EFAULT;
1193         } else {
1194                 err = __sctp_connect(sk, kaddrs, addrs_size);
1195         }
1196
1197         kfree(kaddrs);
1198         return err;
1199 }
1200
1201 /* API 3.1.4 close() - UDP Style Syntax
1202  * Applications use close() to perform graceful shutdown (as described in
1203  * Section 10.1 of [SCTP]) on ALL the associations currently represented
1204  * by a UDP-style socket.
1205  *
1206  * The syntax is
1207  *
1208  *   ret = close(int sd);
1209  *
1210  *   sd      - the socket descriptor of the associations to be closed.
1211  *
1212  * To gracefully shutdown a specific association represented by the
1213  * UDP-style socket, an application should use the sendmsg() call,
1214  * passing no user data, but including the appropriate flag in the
1215  * ancillary data (see Section xxxx).
1216  *
1217  * If sd in the close() call is a branched-off socket representing only
1218  * one association, the shutdown is performed on that association only.
1219  *
1220  * 4.1.6 close() - TCP Style Syntax
1221  *
1222  * Applications use close() to gracefully close down an association.
1223  *
1224  * The syntax is:
1225  *
1226  *    int close(int sd);
1227  *
1228  *      sd      - the socket descriptor of the association to be closed.
1229  *
1230  * After an application calls close() on a socket descriptor, no further
1231  * socket operations will succeed on that descriptor.
1232  *
1233  * API 7.1.4 SO_LINGER
1234  *
1235  * An application using the TCP-style socket can use this option to
1236  * perform the SCTP ABORT primitive.  The linger option structure is:
1237  *
1238  *  struct  linger {
1239  *     int     l_onoff;                // option on/off
1240  *     int     l_linger;               // linger time
1241  * };
1242  *
1243  * To enable the option, set l_onoff to 1.  If the l_linger value is set
1244  * to 0, calling close() is the same as the ABORT primitive.  If the
1245  * value is set to a negative value, the setsockopt() call will return
1246  * an error.  If the value is set to a positive value linger_time, the
1247  * close() can be blocked for at most linger_time ms.  If the graceful
1248  * shutdown phase does not finish during this period, close() will
1249  * return but the graceful shutdown phase continues in the system.
1250  */
1251 SCTP_STATIC void sctp_close(struct sock *sk, long timeout)
1252 {
1253         struct sctp_endpoint *ep;
1254         struct sctp_association *asoc;
1255         struct list_head *pos, *temp;
1256
1257         SCTP_DEBUG_PRINTK("sctp_close(sk: 0x%p, timeout:%ld)\n", sk, timeout);
1258
1259         sctp_lock_sock(sk);
1260         sk->sk_shutdown = SHUTDOWN_MASK;
1261
1262         ep = sctp_sk(sk)->ep;
1263
1264         /* Walk all associations on an endpoint.  */
1265         list_for_each_safe(pos, temp, &ep->asocs) {
1266                 asoc = list_entry(pos, struct sctp_association, asocs);
1267
1268                 if (sctp_style(sk, TCP)) {
1269                         /* A closed association can still be in the list if
1270                          * it belongs to a TCP-style listening socket that is
1271                          * not yet accepted. If so, free it. If not, send an
1272                          * ABORT or SHUTDOWN based on the linger options.
1273                          */
1274                         if (sctp_state(asoc, CLOSED)) {
1275                                 sctp_unhash_established(asoc);
1276                                 sctp_association_free(asoc);
1277                                 continue;
1278                         }
1279                 }
1280
1281                 if (sock_flag(sk, SOCK_LINGER) && !sk->sk_lingertime) {
1282                         struct sctp_chunk *chunk;
1283
1284                         chunk = sctp_make_abort_user(asoc, NULL, 0);
1285                         if (chunk)
1286                                 sctp_primitive_ABORT(asoc, chunk);
1287                 } else
1288                         sctp_primitive_SHUTDOWN(asoc, NULL);
1289         }
1290
1291         /* Clean up any skbs sitting on the receive queue.  */
1292         sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
1293         sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
1294
1295         /* On a TCP-style socket, block for at most linger_time if set. */
1296         if (sctp_style(sk, TCP) && timeout)
1297                 sctp_wait_for_close(sk, timeout);
1298
1299         /* This will run the backlog queue.  */
1300         sctp_release_sock(sk);
1301
1302         /* Supposedly, no process has access to the socket, but
1303          * the net layers still may.
1304          */
1305         sctp_local_bh_disable();
1306         sctp_bh_lock_sock(sk);
1307
1308         /* Hold the sock, since sk_common_release() will put sock_put()
1309          * and we have just a little more cleanup.
1310          */
1311         sock_hold(sk);
1312         sk_common_release(sk);
1313
1314         sctp_bh_unlock_sock(sk);
1315         sctp_local_bh_enable();
1316
1317         sock_put(sk);
1318
1319         SCTP_DBG_OBJCNT_DEC(sock);
1320 }
1321
1322 /* Handle EPIPE error. */
1323 static int sctp_error(struct sock *sk, int flags, int err)
1324 {
1325         if (err == -EPIPE)
1326                 err = sock_error(sk) ? : -EPIPE;
1327         if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
1328                 send_sig(SIGPIPE, current, 0);
1329         return err;
1330 }
1331
1332 /* API 3.1.3 sendmsg() - UDP Style Syntax
1333  *
1334  * An application uses sendmsg() and recvmsg() calls to transmit data to
1335  * and receive data from its peer.
1336  *
1337  *  ssize_t sendmsg(int socket, const struct msghdr *message,
1338  *                  int flags);
1339  *
1340  *  socket  - the socket descriptor of the endpoint.
1341  *  message - pointer to the msghdr structure which contains a single
1342  *            user message and possibly some ancillary data.
1343  *
1344  *            See Section 5 for complete description of the data
1345  *            structures.
1346  *
1347  *  flags   - flags sent or received with the user message, see Section
1348  *            5 for complete description of the flags.
1349  *
1350  * Note:  This function could use a rewrite especially when explicit
1351  * connect support comes in.
1352  */
1353 /* BUG:  We do not implement the equivalent of sk_stream_wait_memory(). */
1354
1355 SCTP_STATIC int sctp_msghdr_parse(const struct msghdr *, sctp_cmsgs_t *);
1356
1357 SCTP_STATIC int sctp_sendmsg(struct kiocb *iocb, struct sock *sk,
1358                              struct msghdr *msg, size_t msg_len)
1359 {
1360         struct sctp_sock *sp;
1361         struct sctp_endpoint *ep;
1362         struct sctp_association *new_asoc=NULL, *asoc=NULL;
1363         struct sctp_transport *transport, *chunk_tp;
1364         struct sctp_chunk *chunk;
1365         union sctp_addr to;
1366         struct sockaddr *msg_name = NULL;
1367         struct sctp_sndrcvinfo default_sinfo = { 0 };
1368         struct sctp_sndrcvinfo *sinfo;
1369         struct sctp_initmsg *sinit;
1370         sctp_assoc_t associd = 0;
1371         sctp_cmsgs_t cmsgs = { NULL };
1372         int err;
1373         sctp_scope_t scope;
1374         long timeo;
1375         __u16 sinfo_flags = 0;
1376         struct sctp_datamsg *datamsg;
1377         struct list_head *pos;
1378         int msg_flags = msg->msg_flags;
1379
1380         SCTP_DEBUG_PRINTK("sctp_sendmsg(sk: %p, msg: %p, msg_len: %zu)\n",
1381                           sk, msg, msg_len);
1382
1383         err = 0;
1384         sp = sctp_sk(sk);
1385         ep = sp->ep;
1386
1387         SCTP_DEBUG_PRINTK("Using endpoint: %p.\n", ep);
1388
1389         /* We cannot send a message over a TCP-style listening socket. */
1390         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) {
1391                 err = -EPIPE;
1392                 goto out_nounlock;
1393         }
1394
1395         /* Parse out the SCTP CMSGs.  */
1396         err = sctp_msghdr_parse(msg, &cmsgs);
1397
1398         if (err) {
1399                 SCTP_DEBUG_PRINTK("msghdr parse err = %x\n", err);
1400                 goto out_nounlock;
1401         }
1402
1403         /* Fetch the destination address for this packet.  This
1404          * address only selects the association--it is not necessarily
1405          * the address we will send to.
1406          * For a peeled-off socket, msg_name is ignored.
1407          */
1408         if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
1409                 int msg_namelen = msg->msg_namelen;
1410
1411                 err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name,
1412                                        msg_namelen);
1413                 if (err)
1414                         return err;
1415
1416                 if (msg_namelen > sizeof(to))
1417                         msg_namelen = sizeof(to);
1418                 memcpy(&to, msg->msg_name, msg_namelen);
1419                 msg_name = msg->msg_name;
1420         }
1421
1422         sinfo = cmsgs.info;
1423         sinit = cmsgs.init;
1424
1425         /* Did the user specify SNDRCVINFO?  */
1426         if (sinfo) {
1427                 sinfo_flags = sinfo->sinfo_flags;
1428                 associd = sinfo->sinfo_assoc_id;
1429         }
1430
1431         SCTP_DEBUG_PRINTK("msg_len: %zu, sinfo_flags: 0x%x\n",
1432                           msg_len, sinfo_flags);
1433
1434         /* SCTP_EOF or SCTP_ABORT cannot be set on a TCP-style socket. */
1435         if (sctp_style(sk, TCP) && (sinfo_flags & (SCTP_EOF | SCTP_ABORT))) {
1436                 err = -EINVAL;
1437                 goto out_nounlock;
1438         }
1439
1440         /* If SCTP_EOF is set, no data can be sent. Disallow sending zero
1441          * length messages when SCTP_EOF|SCTP_ABORT is not set.
1442          * If SCTP_ABORT is set, the message length could be non zero with
1443          * the msg_iov set to the user abort reason.
1444          */
1445         if (((sinfo_flags & SCTP_EOF) && (msg_len > 0)) ||
1446             (!(sinfo_flags & (SCTP_EOF|SCTP_ABORT)) && (msg_len == 0))) {
1447                 err = -EINVAL;
1448                 goto out_nounlock;
1449         }
1450
1451         /* If SCTP_ADDR_OVER is set, there must be an address
1452          * specified in msg_name.
1453          */
1454         if ((sinfo_flags & SCTP_ADDR_OVER) && (!msg->msg_name)) {
1455                 err = -EINVAL;
1456                 goto out_nounlock;
1457         }
1458
1459         transport = NULL;
1460
1461         SCTP_DEBUG_PRINTK("About to look up association.\n");
1462
1463         sctp_lock_sock(sk);
1464
1465         /* If a msg_name has been specified, assume this is to be used.  */
1466         if (msg_name) {
1467                 /* Look for a matching association on the endpoint. */
1468                 asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1469                 if (!asoc) {
1470                         /* If we could not find a matching association on the
1471                          * endpoint, make sure that it is not a TCP-style
1472                          * socket that already has an association or there is
1473                          * no peeled-off association on another socket.
1474                          */
1475                         if ((sctp_style(sk, TCP) &&
1476                              sctp_sstate(sk, ESTABLISHED)) ||
1477                             sctp_endpoint_is_peeled_off(ep, &to)) {
1478                                 err = -EADDRNOTAVAIL;
1479                                 goto out_unlock;
1480                         }
1481                 }
1482         } else {
1483                 asoc = sctp_id2assoc(sk, associd);
1484                 if (!asoc) {
1485                         err = -EPIPE;
1486                         goto out_unlock;
1487                 }
1488         }
1489
1490         if (asoc) {
1491                 SCTP_DEBUG_PRINTK("Just looked up association: %p.\n", asoc);
1492
1493                 /* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED
1494                  * socket that has an association in CLOSED state. This can
1495                  * happen when an accepted socket has an association that is
1496                  * already CLOSED.
1497                  */
1498                 if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) {
1499                         err = -EPIPE;
1500                         goto out_unlock;
1501                 }
1502
1503                 if (sinfo_flags & SCTP_EOF) {
1504                         SCTP_DEBUG_PRINTK("Shutting down association: %p\n",
1505                                           asoc);
1506                         sctp_primitive_SHUTDOWN(asoc, NULL);
1507                         err = 0;
1508                         goto out_unlock;
1509                 }
1510                 if (sinfo_flags & SCTP_ABORT) {
1511                         struct sctp_chunk *chunk;
1512
1513                         chunk = sctp_make_abort_user(asoc, msg, msg_len);
1514                         if (!chunk) {
1515                                 err = -ENOMEM;
1516                                 goto out_unlock;
1517                         }
1518
1519                         SCTP_DEBUG_PRINTK("Aborting association: %p\n", asoc);
1520                         sctp_primitive_ABORT(asoc, chunk);
1521                         err = 0;
1522                         goto out_unlock;
1523                 }
1524         }
1525
1526         /* Do we need to create the association?  */
1527         if (!asoc) {
1528                 SCTP_DEBUG_PRINTK("There is no association yet.\n");
1529
1530                 if (sinfo_flags & (SCTP_EOF | SCTP_ABORT)) {
1531                         err = -EINVAL;
1532                         goto out_unlock;
1533                 }
1534
1535                 /* Check for invalid stream against the stream counts,
1536                  * either the default or the user specified stream counts.
1537                  */
1538                 if (sinfo) {
1539                         if (!sinit || (sinit && !sinit->sinit_num_ostreams)) {
1540                                 /* Check against the defaults. */
1541                                 if (sinfo->sinfo_stream >=
1542                                     sp->initmsg.sinit_num_ostreams) {
1543                                         err = -EINVAL;
1544                                         goto out_unlock;
1545                                 }
1546                         } else {
1547                                 /* Check against the requested.  */
1548                                 if (sinfo->sinfo_stream >=
1549                                     sinit->sinit_num_ostreams) {
1550                                         err = -EINVAL;
1551                                         goto out_unlock;
1552                                 }
1553                         }
1554                 }
1555
1556                 /*
1557                  * API 3.1.2 bind() - UDP Style Syntax
1558                  * If a bind() or sctp_bindx() is not called prior to a
1559                  * sendmsg() call that initiates a new association, the
1560                  * system picks an ephemeral port and will choose an address
1561                  * set equivalent to binding with a wildcard address.
1562                  */
1563                 if (!ep->base.bind_addr.port) {
1564                         if (sctp_autobind(sk)) {
1565                                 err = -EAGAIN;
1566                                 goto out_unlock;
1567                         }
1568                 } else {
1569                         /*
1570                          * If an unprivileged user inherits a one-to-many
1571                          * style socket with open associations on a privileged
1572                          * port, it MAY be permitted to accept new associations,
1573                          * but it SHOULD NOT be permitted to open new
1574                          * associations.
1575                          */
1576                         if (ep->base.bind_addr.port < PROT_SOCK &&
1577                             !capable(CAP_NET_BIND_SERVICE)) {
1578                                 err = -EACCES;
1579                                 goto out_unlock;
1580                         }
1581                 }
1582
1583                 scope = sctp_scope(&to);
1584                 new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1585                 if (!new_asoc) {
1586                         err = -ENOMEM;
1587                         goto out_unlock;
1588                 }
1589                 asoc = new_asoc;
1590
1591                 /* If the SCTP_INIT ancillary data is specified, set all
1592                  * the association init values accordingly.
1593                  */
1594                 if (sinit) {
1595                         if (sinit->sinit_num_ostreams) {
1596                                 asoc->c.sinit_num_ostreams =
1597                                         sinit->sinit_num_ostreams;
1598                         }
1599                         if (sinit->sinit_max_instreams) {
1600                                 asoc->c.sinit_max_instreams =
1601                                         sinit->sinit_max_instreams;
1602                         }
1603                         if (sinit->sinit_max_attempts) {
1604                                 asoc->max_init_attempts
1605                                         = sinit->sinit_max_attempts;
1606                         }
1607                         if (sinit->sinit_max_init_timeo) {
1608                                 asoc->max_init_timeo =
1609                                  msecs_to_jiffies(sinit->sinit_max_init_timeo);
1610                         }
1611                 }
1612
1613                 /* Prime the peer's transport structures.  */
1614                 transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL, SCTP_UNKNOWN);
1615                 if (!transport) {
1616                         err = -ENOMEM;
1617                         goto out_free;
1618                 }
1619                 err = sctp_assoc_set_bind_addr_from_ep(asoc, GFP_KERNEL);
1620                 if (err < 0) {
1621                         err = -ENOMEM;
1622                         goto out_free;
1623                 }
1624         }
1625
1626         /* ASSERT: we have a valid association at this point.  */
1627         SCTP_DEBUG_PRINTK("We have a valid association.\n");
1628
1629         if (!sinfo) {
1630                 /* If the user didn't specify SNDRCVINFO, make up one with
1631                  * some defaults.
1632                  */
1633                 default_sinfo.sinfo_stream = asoc->default_stream;
1634                 default_sinfo.sinfo_flags = asoc->default_flags;
1635                 default_sinfo.sinfo_ppid = asoc->default_ppid;
1636                 default_sinfo.sinfo_context = asoc->default_context;
1637                 default_sinfo.sinfo_timetolive = asoc->default_timetolive;
1638                 default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc);
1639                 sinfo = &default_sinfo;
1640         }
1641
1642         /* API 7.1.7, the sndbuf size per association bounds the
1643          * maximum size of data that can be sent in a single send call.
1644          */
1645         if (msg_len > sk->sk_sndbuf) {
1646                 err = -EMSGSIZE;
1647                 goto out_free;
1648         }
1649
1650         /* If fragmentation is disabled and the message length exceeds the
1651          * association fragmentation point, return EMSGSIZE.  The I-D
1652          * does not specify what this error is, but this looks like
1653          * a great fit.
1654          */
1655         if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) {
1656                 err = -EMSGSIZE;
1657                 goto out_free;
1658         }
1659
1660         if (sinfo) {
1661                 /* Check for invalid stream. */
1662                 if (sinfo->sinfo_stream >= asoc->c.sinit_num_ostreams) {
1663                         err = -EINVAL;
1664                         goto out_free;
1665                 }
1666         }
1667
1668         timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1669         if (!sctp_wspace(asoc)) {
1670                 err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len);
1671                 if (err)
1672                         goto out_free;
1673         }
1674
1675         /* If an address is passed with the sendto/sendmsg call, it is used
1676          * to override the primary destination address in the TCP model, or
1677          * when SCTP_ADDR_OVER flag is set in the UDP model.
1678          */
1679         if ((sctp_style(sk, TCP) && msg_name) ||
1680             (sinfo_flags & SCTP_ADDR_OVER)) {
1681                 chunk_tp = sctp_assoc_lookup_paddr(asoc, &to);
1682                 if (!chunk_tp) {
1683                         err = -EINVAL;
1684                         goto out_free;
1685                 }
1686         } else
1687                 chunk_tp = NULL;
1688
1689         /* Auto-connect, if we aren't connected already. */
1690         if (sctp_state(asoc, CLOSED)) {
1691                 err = sctp_primitive_ASSOCIATE(asoc, NULL);
1692                 if (err < 0)
1693                         goto out_free;
1694                 SCTP_DEBUG_PRINTK("We associated primitively.\n");
1695         }
1696
1697         /* Break the message into multiple chunks of maximum size. */
1698         datamsg = sctp_datamsg_from_user(asoc, sinfo, msg, msg_len);
1699         if (!datamsg) {
1700                 err = -ENOMEM;
1701                 goto out_free;
1702         }
1703
1704         /* Now send the (possibly) fragmented message. */
1705         list_for_each(pos, &datamsg->chunks) {
1706                 chunk = list_entry(pos, struct sctp_chunk, frag_list);
1707                 sctp_datamsg_track(chunk);
1708
1709                 /* Do accounting for the write space.  */
1710                 sctp_set_owner_w(chunk);
1711
1712                 chunk->transport = chunk_tp;
1713
1714                 /* Send it to the lower layers.  Note:  all chunks
1715                  * must either fail or succeed.   The lower layer
1716                  * works that way today.  Keep it that way or this
1717                  * breaks.
1718                  */
1719                 err = sctp_primitive_SEND(asoc, chunk);
1720                 /* Did the lower layer accept the chunk? */
1721                 if (err)
1722                         sctp_chunk_free(chunk);
1723                 SCTP_DEBUG_PRINTK("We sent primitively.\n");
1724         }
1725
1726         sctp_datamsg_free(datamsg);
1727         if (err)
1728                 goto out_free;
1729         else
1730                 err = msg_len;
1731
1732         /* If we are already past ASSOCIATE, the lower
1733          * layers are responsible for association cleanup.
1734          */
1735         goto out_unlock;
1736
1737 out_free:
1738         if (new_asoc)
1739                 sctp_association_free(asoc);
1740 out_unlock:
1741         sctp_release_sock(sk);
1742
1743 out_nounlock:
1744         return sctp_error(sk, msg_flags, err);
1745
1746 #if 0
1747 do_sock_err:
1748         if (msg_len)
1749                 err = msg_len;
1750         else
1751                 err = sock_error(sk);
1752         goto out;
1753
1754 do_interrupted:
1755         if (msg_len)
1756                 err = msg_len;
1757         goto out;
1758 #endif /* 0 */
1759 }
1760
1761 /* This is an extended version of skb_pull() that removes the data from the
1762  * start of a skb even when data is spread across the list of skb's in the
1763  * frag_list. len specifies the total amount of data that needs to be removed.
1764  * when 'len' bytes could be removed from the skb, it returns 0.
1765  * If 'len' exceeds the total skb length,  it returns the no. of bytes that
1766  * could not be removed.
1767  */
1768 static int sctp_skb_pull(struct sk_buff *skb, int len)
1769 {
1770         struct sk_buff *list;
1771         int skb_len = skb_headlen(skb);
1772         int rlen;
1773
1774         if (len <= skb_len) {
1775                 __skb_pull(skb, len);
1776                 return 0;
1777         }
1778         len -= skb_len;
1779         __skb_pull(skb, skb_len);
1780
1781         for (list = skb_shinfo(skb)->frag_list; list; list = list->next) {
1782                 rlen = sctp_skb_pull(list, len);
1783                 skb->len -= (len-rlen);
1784                 skb->data_len -= (len-rlen);
1785
1786                 if (!rlen)
1787                         return 0;
1788
1789                 len = rlen;
1790         }
1791
1792         return len;
1793 }
1794
1795 /* API 3.1.3  recvmsg() - UDP Style Syntax
1796  *
1797  *  ssize_t recvmsg(int socket, struct msghdr *message,
1798  *                    int flags);
1799  *
1800  *  socket  - the socket descriptor of the endpoint.
1801  *  message - pointer to the msghdr structure which contains a single
1802  *            user message and possibly some ancillary data.
1803  *
1804  *            See Section 5 for complete description of the data
1805  *            structures.
1806  *
1807  *  flags   - flags sent or received with the user message, see Section
1808  *            5 for complete description of the flags.
1809  */
1810 static struct sk_buff *sctp_skb_recv_datagram(struct sock *, int, int, int *);
1811
1812 SCTP_STATIC int sctp_recvmsg(struct kiocb *iocb, struct sock *sk,
1813                              struct msghdr *msg, size_t len, int noblock,
1814                              int flags, int *addr_len)
1815 {
1816         struct sctp_ulpevent *event = NULL;
1817         struct sctp_sock *sp = sctp_sk(sk);
1818         struct sk_buff *skb;
1819         int copied;
1820         int err = 0;
1821         int skb_len;
1822
1823         SCTP_DEBUG_PRINTK("sctp_recvmsg(%s: %p, %s: %p, %s: %zd, %s: %d, %s: "
1824                           "0x%x, %s: %p)\n", "sk", sk, "msghdr", msg,
1825                           "len", len, "knoblauch", noblock,
1826                           "flags", flags, "addr_len", addr_len);
1827
1828         sctp_lock_sock(sk);
1829
1830         if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED)) {
1831                 err = -ENOTCONN;
1832                 goto out;
1833         }
1834
1835         skb = sctp_skb_recv_datagram(sk, flags, noblock, &err);
1836         if (!skb)
1837                 goto out;
1838
1839         /* Get the total length of the skb including any skb's in the
1840          * frag_list.
1841          */
1842         skb_len = skb->len;
1843
1844         copied = skb_len;
1845         if (copied > len)
1846                 copied = len;
1847
1848         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1849
1850         event = sctp_skb2event(skb);
1851
1852         if (err)
1853                 goto out_free;
1854
1855         sock_recv_timestamp(msg, sk, skb);
1856         if (sctp_ulpevent_is_notification(event)) {
1857                 msg->msg_flags |= MSG_NOTIFICATION;
1858                 sp->pf->event_msgname(event, msg->msg_name, addr_len);
1859         } else {
1860                 sp->pf->skb_msgname(skb, msg->msg_name, addr_len);
1861         }
1862
1863         /* Check if we allow SCTP_SNDRCVINFO. */
1864         if (sp->subscribe.sctp_data_io_event)
1865                 sctp_ulpevent_read_sndrcvinfo(event, msg);
1866 #if 0
1867         /* FIXME: we should be calling IP/IPv6 layers.  */
1868         if (sk->sk_protinfo.af_inet.cmsg_flags)
1869                 ip_cmsg_recv(msg, skb);
1870 #endif
1871
1872         err = copied;
1873
1874         /* If skb's length exceeds the user's buffer, update the skb and
1875          * push it back to the receive_queue so that the next call to
1876          * recvmsg() will return the remaining data. Don't set MSG_EOR.
1877          */
1878         if (skb_len > copied) {
1879                 msg->msg_flags &= ~MSG_EOR;
1880                 if (flags & MSG_PEEK)
1881                         goto out_free;
1882                 sctp_skb_pull(skb, copied);
1883                 skb_queue_head(&sk->sk_receive_queue, skb);
1884
1885                 /* When only partial message is copied to the user, increase
1886                  * rwnd by that amount. If all the data in the skb is read,
1887                  * rwnd is updated when the event is freed.
1888                  */
1889                 sctp_assoc_rwnd_increase(event->asoc, copied);
1890                 goto out;
1891         } else if ((event->msg_flags & MSG_NOTIFICATION) ||
1892                    (event->msg_flags & MSG_EOR))
1893                 msg->msg_flags |= MSG_EOR;
1894         else
1895                 msg->msg_flags &= ~MSG_EOR;
1896
1897 out_free:
1898         if (flags & MSG_PEEK) {
1899                 /* Release the skb reference acquired after peeking the skb in
1900                  * sctp_skb_recv_datagram().
1901                  */
1902                 kfree_skb(skb);
1903         } else {
1904                 /* Free the event which includes releasing the reference to
1905                  * the owner of the skb, freeing the skb and updating the
1906                  * rwnd.
1907                  */
1908                 sctp_ulpevent_free(event);
1909         }
1910 out:
1911         sctp_release_sock(sk);
1912         return err;
1913 }
1914
1915 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
1916  *
1917  * This option is a on/off flag.  If enabled no SCTP message
1918  * fragmentation will be performed.  Instead if a message being sent
1919  * exceeds the current PMTU size, the message will NOT be sent and
1920  * instead a error will be indicated to the user.
1921  */
1922 static int sctp_setsockopt_disable_fragments(struct sock *sk,
1923                                             char __user *optval, int optlen)
1924 {
1925         int val;
1926
1927         if (optlen < sizeof(int))
1928                 return -EINVAL;
1929
1930         if (get_user(val, (int __user *)optval))
1931                 return -EFAULT;
1932
1933         sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1;
1934
1935         return 0;
1936 }
1937
1938 static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
1939                                         int optlen)
1940 {
1941         if (optlen != sizeof(struct sctp_event_subscribe))
1942                 return -EINVAL;
1943         if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
1944                 return -EFAULT;
1945         return 0;
1946 }
1947
1948 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
1949  *
1950  * This socket option is applicable to the UDP-style socket only.  When
1951  * set it will cause associations that are idle for more than the
1952  * specified number of seconds to automatically close.  An association
1953  * being idle is defined an association that has NOT sent or received
1954  * user data.  The special value of '0' indicates that no automatic
1955  * close of any associations should be performed.  The option expects an
1956  * integer defining the number of seconds of idle time before an
1957  * association is closed.
1958  */
1959 static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval,
1960                                             int optlen)
1961 {
1962         struct sctp_sock *sp = sctp_sk(sk);
1963
1964         /* Applicable to UDP-style socket only */
1965         if (sctp_style(sk, TCP))
1966                 return -EOPNOTSUPP;
1967         if (optlen != sizeof(int))
1968                 return -EINVAL;
1969         if (copy_from_user(&sp->autoclose, optval, optlen))
1970                 return -EFAULT;
1971
1972         return 0;
1973 }
1974
1975 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
1976  *
1977  * Applications can enable or disable heartbeats for any peer address of
1978  * an association, modify an address's heartbeat interval, force a
1979  * heartbeat to be sent immediately, and adjust the address's maximum
1980  * number of retransmissions sent before an address is considered
1981  * unreachable.  The following structure is used to access and modify an
1982  * address's parameters:
1983  *
1984  *  struct sctp_paddrparams {
1985  *     sctp_assoc_t            spp_assoc_id;
1986  *     struct sockaddr_storage spp_address;
1987  *     uint32_t                spp_hbinterval;
1988  *     uint16_t                spp_pathmaxrxt;
1989  *     uint32_t                spp_pathmtu;
1990  *     uint32_t                spp_sackdelay;
1991  *     uint32_t                spp_flags;
1992  * };
1993  *
1994  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
1995  *                     application, and identifies the association for
1996  *                     this query.
1997  *   spp_address     - This specifies which address is of interest.
1998  *   spp_hbinterval  - This contains the value of the heartbeat interval,
1999  *                     in milliseconds.  If a  value of zero
2000  *                     is present in this field then no changes are to
2001  *                     be made to this parameter.
2002  *   spp_pathmaxrxt  - This contains the maximum number of
2003  *                     retransmissions before this address shall be
2004  *                     considered unreachable. If a  value of zero
2005  *                     is present in this field then no changes are to
2006  *                     be made to this parameter.
2007  *   spp_pathmtu     - When Path MTU discovery is disabled the value
2008  *                     specified here will be the "fixed" path mtu.
2009  *                     Note that if the spp_address field is empty
2010  *                     then all associations on this address will
2011  *                     have this fixed path mtu set upon them.
2012  *
2013  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
2014  *                     the number of milliseconds that sacks will be delayed
2015  *                     for. This value will apply to all addresses of an
2016  *                     association if the spp_address field is empty. Note
2017  *                     also, that if delayed sack is enabled and this
2018  *                     value is set to 0, no change is made to the last
2019  *                     recorded delayed sack timer value.
2020  *
2021  *   spp_flags       - These flags are used to control various features
2022  *                     on an association. The flag field may contain
2023  *                     zero or more of the following options.
2024  *
2025  *                     SPP_HB_ENABLE  - Enable heartbeats on the
2026  *                     specified address. Note that if the address
2027  *                     field is empty all addresses for the association
2028  *                     have heartbeats enabled upon them.
2029  *
2030  *                     SPP_HB_DISABLE - Disable heartbeats on the
2031  *                     speicifed address. Note that if the address
2032  *                     field is empty all addresses for the association
2033  *                     will have their heartbeats disabled. Note also
2034  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
2035  *                     mutually exclusive, only one of these two should
2036  *                     be specified. Enabling both fields will have
2037  *                     undetermined results.
2038  *
2039  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
2040  *                     to be made immediately.
2041  *
2042  *                     SPP_HB_TIME_IS_ZERO - Specify's that the time for
2043  *                     heartbeat delayis to be set to the value of 0
2044  *                     milliseconds.
2045  *
2046  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
2047  *                     discovery upon the specified address. Note that
2048  *                     if the address feild is empty then all addresses
2049  *                     on the association are effected.
2050  *
2051  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
2052  *                     discovery upon the specified address. Note that
2053  *                     if the address feild is empty then all addresses
2054  *                     on the association are effected. Not also that
2055  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
2056  *                     exclusive. Enabling both will have undetermined
2057  *                     results.
2058  *
2059  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
2060  *                     on delayed sack. The time specified in spp_sackdelay
2061  *                     is used to specify the sack delay for this address. Note
2062  *                     that if spp_address is empty then all addresses will
2063  *                     enable delayed sack and take on the sack delay
2064  *                     value specified in spp_sackdelay.
2065  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
2066  *                     off delayed sack. If the spp_address field is blank then
2067  *                     delayed sack is disabled for the entire association. Note
2068  *                     also that this field is mutually exclusive to
2069  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
2070  *                     results.
2071  */
2072 static int sctp_apply_peer_addr_params(struct sctp_paddrparams *params,
2073                                        struct sctp_transport   *trans,
2074                                        struct sctp_association *asoc,
2075                                        struct sctp_sock        *sp,
2076                                        int                      hb_change,
2077                                        int                      pmtud_change,
2078                                        int                      sackdelay_change)
2079 {
2080         int error;
2081
2082         if (params->spp_flags & SPP_HB_DEMAND && trans) {
2083                 error = sctp_primitive_REQUESTHEARTBEAT (trans->asoc, trans);
2084                 if (error)
2085                         return error;
2086         }
2087
2088         /* Note that unless the spp_flag is set to SPP_HB_ENABLE the value of
2089          * this field is ignored.  Note also that a value of zero indicates
2090          * the current setting should be left unchanged.
2091          */
2092         if (params->spp_flags & SPP_HB_ENABLE) {
2093
2094                 /* Re-zero the interval if the SPP_HB_TIME_IS_ZERO is
2095                  * set.  This lets us use 0 value when this flag
2096                  * is set.
2097                  */
2098                 if (params->spp_flags & SPP_HB_TIME_IS_ZERO)
2099                         params->spp_hbinterval = 0;
2100
2101                 if (params->spp_hbinterval ||
2102                     (params->spp_flags & SPP_HB_TIME_IS_ZERO)) {
2103                         if (trans) {
2104                                 trans->hbinterval =
2105                                     msecs_to_jiffies(params->spp_hbinterval);
2106                         } else if (asoc) {
2107                                 asoc->hbinterval =
2108                                     msecs_to_jiffies(params->spp_hbinterval);
2109                         } else {
2110                                 sp->hbinterval = params->spp_hbinterval;
2111                         }
2112                 }
2113         }
2114
2115         if (hb_change) {
2116                 if (trans) {
2117                         trans->param_flags =
2118                                 (trans->param_flags & ~SPP_HB) | hb_change;
2119                 } else if (asoc) {
2120                         asoc->param_flags =
2121                                 (asoc->param_flags & ~SPP_HB) | hb_change;
2122                 } else {
2123                         sp->param_flags =
2124                                 (sp->param_flags & ~SPP_HB) | hb_change;
2125                 }
2126         }
2127
2128         /* When Path MTU discovery is disabled the value specified here will
2129          * be the "fixed" path mtu (i.e. the value of the spp_flags field must
2130          * include the flag SPP_PMTUD_DISABLE for this field to have any
2131          * effect).
2132          */
2133         if ((params->spp_flags & SPP_PMTUD_DISABLE) && params->spp_pathmtu) {
2134                 if (trans) {
2135                         trans->pathmtu = params->spp_pathmtu;
2136                         sctp_assoc_sync_pmtu(asoc);
2137                 } else if (asoc) {
2138                         asoc->pathmtu = params->spp_pathmtu;
2139                         sctp_frag_point(sp, params->spp_pathmtu);
2140                 } else {
2141                         sp->pathmtu = params->spp_pathmtu;
2142                 }
2143         }
2144
2145         if (pmtud_change) {
2146                 if (trans) {
2147                         int update = (trans->param_flags & SPP_PMTUD_DISABLE) &&
2148                                 (params->spp_flags & SPP_PMTUD_ENABLE);
2149                         trans->param_flags =
2150                                 (trans->param_flags & ~SPP_PMTUD) | pmtud_change;
2151                         if (update) {
2152                                 sctp_transport_pmtu(trans);
2153                                 sctp_assoc_sync_pmtu(asoc);
2154                         }
2155                 } else if (asoc) {
2156                         asoc->param_flags =
2157                                 (asoc->param_flags & ~SPP_PMTUD) | pmtud_change;
2158                 } else {
2159                         sp->param_flags =
2160                                 (sp->param_flags & ~SPP_PMTUD) | pmtud_change;
2161                 }
2162         }
2163
2164         /* Note that unless the spp_flag is set to SPP_SACKDELAY_ENABLE the
2165          * value of this field is ignored.  Note also that a value of zero
2166          * indicates the current setting should be left unchanged.
2167          */
2168         if ((params->spp_flags & SPP_SACKDELAY_ENABLE) && params->spp_sackdelay) {
2169                 if (trans) {
2170                         trans->sackdelay =
2171                                 msecs_to_jiffies(params->spp_sackdelay);
2172                 } else if (asoc) {
2173                         asoc->sackdelay =
2174                                 msecs_to_jiffies(params->spp_sackdelay);
2175                 } else {
2176                         sp->sackdelay = params->spp_sackdelay;
2177                 }
2178         }
2179
2180         if (sackdelay_change) {
2181                 if (trans) {
2182                         trans->param_flags =
2183                                 (trans->param_flags & ~SPP_SACKDELAY) |
2184                                 sackdelay_change;
2185                 } else if (asoc) {
2186                         asoc->param_flags =
2187                                 (asoc->param_flags & ~SPP_SACKDELAY) |
2188                                 sackdelay_change;
2189                 } else {
2190                         sp->param_flags =
2191                                 (sp->param_flags & ~SPP_SACKDELAY) |
2192                                 sackdelay_change;
2193                 }
2194         }
2195
2196         /* Note that unless the spp_flag is set to SPP_PMTUD_ENABLE the value
2197          * of this field is ignored.  Note also that a value of zero
2198          * indicates the current setting should be left unchanged.
2199          */
2200         if ((params->spp_flags & SPP_PMTUD_ENABLE) && params->spp_pathmaxrxt) {
2201                 if (trans) {
2202                         trans->pathmaxrxt = params->spp_pathmaxrxt;
2203                 } else if (asoc) {
2204                         asoc->pathmaxrxt = params->spp_pathmaxrxt;
2205                 } else {
2206                         sp->pathmaxrxt = params->spp_pathmaxrxt;
2207                 }
2208         }
2209
2210         return 0;
2211 }
2212
2213 static int sctp_setsockopt_peer_addr_params(struct sock *sk,
2214                                             char __user *optval, int optlen)
2215 {
2216         struct sctp_paddrparams  params;
2217         struct sctp_transport   *trans = NULL;
2218         struct sctp_association *asoc = NULL;
2219         struct sctp_sock        *sp = sctp_sk(sk);
2220         int error;
2221         int hb_change, pmtud_change, sackdelay_change;
2222
2223         if (optlen != sizeof(struct sctp_paddrparams))
2224                 return - EINVAL;
2225
2226         if (copy_from_user(&params, optval, optlen))
2227                 return -EFAULT;
2228
2229         /* Validate flags and value parameters. */
2230         hb_change        = params.spp_flags & SPP_HB;
2231         pmtud_change     = params.spp_flags & SPP_PMTUD;
2232         sackdelay_change = params.spp_flags & SPP_SACKDELAY;
2233
2234         if (hb_change        == SPP_HB ||
2235             pmtud_change     == SPP_PMTUD ||
2236             sackdelay_change == SPP_SACKDELAY ||
2237             params.spp_sackdelay > 500 ||
2238             (params.spp_pathmtu
2239             && params.spp_pathmtu < SCTP_DEFAULT_MINSEGMENT))
2240                 return -EINVAL;
2241
2242         /* If an address other than INADDR_ANY is specified, and
2243          * no transport is found, then the request is invalid.
2244          */
2245         if (!sctp_is_any(( union sctp_addr *)&params.spp_address)) {
2246                 trans = sctp_addr_id2transport(sk, &params.spp_address,
2247                                                params.spp_assoc_id);
2248                 if (!trans)
2249                         return -EINVAL;
2250         }
2251
2252         /* Get association, if assoc_id != 0 and the socket is a one
2253          * to many style socket, and an association was not found, then
2254          * the id was invalid.
2255          */
2256         asoc = sctp_id2assoc(sk, params.spp_assoc_id);
2257         if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP))
2258                 return -EINVAL;
2259
2260         /* Heartbeat demand can only be sent on a transport or
2261          * association, but not a socket.
2262          */
2263         if (params.spp_flags & SPP_HB_DEMAND && !trans && !asoc)
2264                 return -EINVAL;
2265
2266         /* Process parameters. */
2267         error = sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2268                                             hb_change, pmtud_change,
2269                                             sackdelay_change);
2270
2271         if (error)
2272                 return error;
2273
2274         /* If changes are for association, also apply parameters to each
2275          * transport.
2276          */
2277         if (!trans && asoc) {
2278                 struct list_head *pos;
2279
2280                 list_for_each(pos, &asoc->peer.transport_addr_list) {
2281                         trans = list_entry(pos, struct sctp_transport,
2282                                            transports);
2283                         sctp_apply_peer_addr_params(&params, trans, asoc, sp,
2284                                                     hb_change, pmtud_change,
2285                                                     sackdelay_change);
2286                 }
2287         }
2288
2289         return 0;
2290 }
2291
2292 /* 7.1.23. Delayed Ack Timer (SCTP_DELAYED_ACK_TIME)
2293  *
2294  *   This options will get or set the delayed ack timer.  The time is set
2295  *   in milliseconds.  If the assoc_id is 0, then this sets or gets the
2296  *   endpoints default delayed ack timer value.  If the assoc_id field is
2297  *   non-zero, then the set or get effects the specified association.
2298  *
2299  *   struct sctp_assoc_value {
2300  *       sctp_assoc_t            assoc_id;
2301  *       uint32_t                assoc_value;
2302  *   };
2303  *
2304  *     assoc_id    - This parameter, indicates which association the
2305  *                   user is preforming an action upon. Note that if
2306  *                   this field's value is zero then the endpoints
2307  *                   default value is changed (effecting future
2308  *                   associations only).
2309  *
2310  *     assoc_value - This parameter contains the number of milliseconds
2311  *                   that the user is requesting the delayed ACK timer
2312  *                   be set to. Note that this value is defined in
2313  *                   the standard to be between 200 and 500 milliseconds.
2314  *
2315  *                   Note: a value of zero will leave the value alone,
2316  *                   but disable SACK delay. A non-zero value will also
2317  *                   enable SACK delay.
2318  */
2319
2320 static int sctp_setsockopt_delayed_ack_time(struct sock *sk,
2321                                             char __user *optval, int optlen)
2322 {
2323         struct sctp_assoc_value  params;
2324         struct sctp_transport   *trans = NULL;
2325         struct sctp_association *asoc = NULL;
2326         struct sctp_sock        *sp = sctp_sk(sk);
2327
2328         if (optlen != sizeof(struct sctp_assoc_value))
2329                 return - EINVAL;
2330
2331         if (copy_from_user(&params, optval, optlen))
2332                 return -EFAULT;
2333
2334         /* Validate value parameter. */
2335         if (params.assoc_value > 500)
2336                 return -EINVAL;
2337
2338         /* Get association, if assoc_id != 0 and the socket is a one
2339          * to many style socket, and an association was not found, then
2340          * the id was invalid.
2341          */
2342         asoc = sctp_id2assoc(sk, params.assoc_id);
2343         if (!asoc && params.assoc_id && sctp_style(sk, UDP))
2344                 return -EINVAL;
2345
2346         if (params.assoc_value) {
2347                 if (asoc) {
2348                         asoc->sackdelay =
2349                                 msecs_to_jiffies(params.assoc_value);
2350                         asoc->param_flags =
2351                                 (asoc->param_flags & ~SPP_SACKDELAY) |
2352                                 SPP_SACKDELAY_ENABLE;
2353                 } else {
2354                         sp->sackdelay = params.assoc_value;
2355                         sp->param_flags =
2356                                 (sp->param_flags & ~SPP_SACKDELAY) |
2357                                 SPP_SACKDELAY_ENABLE;
2358                 }
2359         } else {
2360                 if (asoc) {
2361                         asoc->param_flags =
2362                                 (asoc->param_flags & ~SPP_SACKDELAY) |
2363                                 SPP_SACKDELAY_DISABLE;
2364                 } else {
2365                         sp->param_flags =
2366                                 (sp->param_flags & ~SPP_SACKDELAY) |
2367                                 SPP_SACKDELAY_DISABLE;
2368                 }
2369         }
2370
2371         /* If change is for association, also apply to each transport. */
2372         if (asoc) {
2373                 struct list_head *pos;
2374
2375                 list_for_each(pos, &asoc->peer.transport_addr_list) {
2376                         trans = list_entry(pos, struct sctp_transport,
2377                                            transports);
2378                         if (params.assoc_value) {
2379                                 trans->sackdelay =
2380                                         msecs_to_jiffies(params.assoc_value);
2381                                 trans->param_flags =
2382                                         (trans->param_flags & ~SPP_SACKDELAY) |
2383                                         SPP_SACKDELAY_ENABLE;
2384                         } else {
2385                                 trans->param_flags =
2386                                         (trans->param_flags & ~SPP_SACKDELAY) |
2387                                         SPP_SACKDELAY_DISABLE;
2388                         }
2389                 }
2390         }
2391
2392         return 0;
2393 }
2394
2395 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
2396  *
2397  * Applications can specify protocol parameters for the default association
2398  * initialization.  The option name argument to setsockopt() and getsockopt()
2399  * is SCTP_INITMSG.
2400  *
2401  * Setting initialization parameters is effective only on an unconnected
2402  * socket (for UDP-style sockets only future associations are effected
2403  * by the change).  With TCP-style sockets, this option is inherited by
2404  * sockets derived from a listener socket.
2405  */
2406 static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, int optlen)
2407 {
2408         struct sctp_initmsg sinit;
2409         struct sctp_sock *sp = sctp_sk(sk);
2410
2411         if (optlen != sizeof(struct sctp_initmsg))
2412                 return -EINVAL;
2413         if (copy_from_user(&sinit, optval, optlen))
2414                 return -EFAULT;
2415
2416         if (sinit.sinit_num_ostreams)
2417                 sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams;
2418         if (sinit.sinit_max_instreams)
2419                 sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams;
2420         if (sinit.sinit_max_attempts)
2421                 sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts;
2422         if (sinit.sinit_max_init_timeo)
2423                 sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo;
2424
2425         return 0;
2426 }
2427
2428 /*
2429  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
2430  *
2431  *   Applications that wish to use the sendto() system call may wish to
2432  *   specify a default set of parameters that would normally be supplied
2433  *   through the inclusion of ancillary data.  This socket option allows
2434  *   such an application to set the default sctp_sndrcvinfo structure.
2435  *   The application that wishes to use this socket option simply passes
2436  *   in to this call the sctp_sndrcvinfo structure defined in Section
2437  *   5.2.2) The input parameters accepted by this call include
2438  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
2439  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
2440  *   to this call if the caller is using the UDP model.
2441  */
2442 static int sctp_setsockopt_default_send_param(struct sock *sk,
2443                                                 char __user *optval, int optlen)
2444 {
2445         struct sctp_sndrcvinfo info;
2446         struct sctp_association *asoc;
2447         struct sctp_sock *sp = sctp_sk(sk);
2448
2449         if (optlen != sizeof(struct sctp_sndrcvinfo))
2450                 return -EINVAL;
2451         if (copy_from_user(&info, optval, optlen))
2452                 return -EFAULT;
2453
2454         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
2455         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
2456                 return -EINVAL;
2457
2458         if (asoc) {
2459                 asoc->default_stream = info.sinfo_stream;
2460                 asoc->default_flags = info.sinfo_flags;
2461                 asoc->default_ppid = info.sinfo_ppid;
2462                 asoc->default_context = info.sinfo_context;
2463                 asoc->default_timetolive = info.sinfo_timetolive;
2464         } else {
2465                 sp->default_stream = info.sinfo_stream;
2466                 sp->default_flags = info.sinfo_flags;
2467                 sp->default_ppid = info.sinfo_ppid;
2468                 sp->default_context = info.sinfo_context;
2469                 sp->default_timetolive = info.sinfo_timetolive;
2470         }
2471
2472         return 0;
2473 }
2474
2475 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
2476  *
2477  * Requests that the local SCTP stack use the enclosed peer address as
2478  * the association primary.  The enclosed address must be one of the
2479  * association peer's addresses.
2480  */
2481 static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval,
2482                                         int optlen)
2483 {
2484         struct sctp_prim prim;
2485         struct sctp_transport *trans;
2486
2487         if (optlen != sizeof(struct sctp_prim))
2488                 return -EINVAL;
2489
2490         if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
2491                 return -EFAULT;
2492
2493         trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id);
2494         if (!trans)
2495                 return -EINVAL;
2496
2497         sctp_assoc_set_primary(trans->asoc, trans);
2498
2499         return 0;
2500 }
2501
2502 /*
2503  * 7.1.5 SCTP_NODELAY
2504  *
2505  * Turn on/off any Nagle-like algorithm.  This means that packets are
2506  * generally sent as soon as possible and no unnecessary delays are
2507  * introduced, at the cost of more packets in the network.  Expects an
2508  *  integer boolean flag.
2509  */
2510 static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval,
2511                                         int optlen)
2512 {
2513         int val;
2514
2515         if (optlen < sizeof(int))
2516                 return -EINVAL;
2517         if (get_user(val, (int __user *)optval))
2518                 return -EFAULT;
2519
2520         sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1;
2521         return 0;
2522 }
2523
2524 /*
2525  *
2526  * 7.1.1 SCTP_RTOINFO
2527  *
2528  * The protocol parameters used to initialize and bound retransmission
2529  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
2530  * and modify these parameters.
2531  * All parameters are time values, in milliseconds.  A value of 0, when
2532  * modifying the parameters, indicates that the current value should not
2533  * be changed.
2534  *
2535  */
2536 static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, int optlen) {
2537         struct sctp_rtoinfo rtoinfo;
2538         struct sctp_association *asoc;
2539
2540         if (optlen != sizeof (struct sctp_rtoinfo))
2541                 return -EINVAL;
2542
2543         if (copy_from_user(&rtoinfo, optval, optlen))
2544                 return -EFAULT;
2545
2546         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
2547
2548         /* Set the values to the specific association */
2549         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
2550                 return -EINVAL;
2551
2552         if (asoc) {
2553                 if (rtoinfo.srto_initial != 0)
2554                         asoc->rto_initial =
2555                                 msecs_to_jiffies(rtoinfo.srto_initial);
2556                 if (rtoinfo.srto_max != 0)
2557                         asoc->rto_max = msecs_to_jiffies(rtoinfo.srto_max);
2558                 if (rtoinfo.srto_min != 0)
2559                         asoc->rto_min = msecs_to_jiffies(rtoinfo.srto_min);
2560         } else {
2561                 /* If there is no association or the association-id = 0
2562                  * set the values to the endpoint.
2563                  */
2564                 struct sctp_sock *sp = sctp_sk(sk);
2565
2566                 if (rtoinfo.srto_initial != 0)
2567                         sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
2568                 if (rtoinfo.srto_max != 0)
2569                         sp->rtoinfo.srto_max = rtoinfo.srto_max;
2570                 if (rtoinfo.srto_min != 0)
2571                         sp->rtoinfo.srto_min = rtoinfo.srto_min;
2572         }
2573
2574         return 0;
2575 }
2576
2577 /*
2578  *
2579  * 7.1.2 SCTP_ASSOCINFO
2580  *
2581  * This option is used to tune the the maximum retransmission attempts
2582  * of the association.
2583  * Returns an error if the new association retransmission value is
2584  * greater than the sum of the retransmission value  of the peer.
2585  * See [SCTP] for more information.
2586  *
2587  */
2588 static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, int optlen)
2589 {
2590
2591         struct sctp_assocparams assocparams;
2592         struct sctp_association *asoc;
2593
2594         if (optlen != sizeof(struct sctp_assocparams))
2595                 return -EINVAL;
2596         if (copy_from_user(&assocparams, optval, optlen))
2597                 return -EFAULT;
2598
2599         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
2600
2601         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
2602                 return -EINVAL;
2603
2604         /* Set the values to the specific association */
2605         if (asoc) {
2606                 if (assocparams.sasoc_asocmaxrxt != 0) {
2607                         __u32 path_sum = 0;
2608                         int   paths = 0;
2609                         struct list_head *pos;
2610                         struct sctp_transport *peer_addr;
2611
2612                         list_for_each(pos, &asoc->peer.transport_addr_list) {
2613                                 peer_addr = list_entry(pos,
2614                                                 struct sctp_transport,
2615                                                 transports);
2616                                 path_sum += peer_addr->pathmaxrxt;
2617                                 paths++;
2618                         }
2619
2620                         /* Only validate asocmaxrxt if we have more then
2621                          * one path/transport.  We do this because path
2622                          * retransmissions are only counted when we have more
2623                          * then one path.
2624                          */
2625                         if (paths > 1 &&
2626                             assocparams.sasoc_asocmaxrxt > path_sum)
2627                                 return -EINVAL;
2628
2629                         asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
2630                 }
2631
2632                 if (assocparams.sasoc_cookie_life != 0) {
2633                         asoc->cookie_life.tv_sec =
2634                                         assocparams.sasoc_cookie_life / 1000;
2635                         asoc->cookie_life.tv_usec =
2636                                         (assocparams.sasoc_cookie_life % 1000)
2637                                         * 1000;
2638                 }
2639         } else {
2640                 /* Set the values to the endpoint */
2641                 struct sctp_sock *sp = sctp_sk(sk);
2642
2643                 if (assocparams.sasoc_asocmaxrxt != 0)
2644                         sp->assocparams.sasoc_asocmaxrxt =
2645                                                 assocparams.sasoc_asocmaxrxt;
2646                 if (assocparams.sasoc_cookie_life != 0)
2647                         sp->assocparams.sasoc_cookie_life =
2648                                                 assocparams.sasoc_cookie_life;
2649         }
2650         return 0;
2651 }
2652
2653 /*
2654  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
2655  *
2656  * This socket option is a boolean flag which turns on or off mapped V4
2657  * addresses.  If this option is turned on and the socket is type
2658  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
2659  * If this option is turned off, then no mapping will be done of V4
2660  * addresses and a user will receive both PF_INET6 and PF_INET type
2661  * addresses on the socket.
2662  */
2663 static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, int optlen)
2664 {
2665         int val;
2666         struct sctp_sock *sp = sctp_sk(sk);
2667
2668         if (optlen < sizeof(int))
2669                 return -EINVAL;
2670         if (get_user(val, (int __user *)optval))
2671                 return -EFAULT;
2672         if (val)
2673                 sp->v4mapped = 1;
2674         else
2675                 sp->v4mapped = 0;
2676
2677         return 0;
2678 }
2679
2680 /*
2681  * 7.1.17 Set the maximum fragrmentation size (SCTP_MAXSEG)
2682  *
2683  * This socket option specifies the maximum size to put in any outgoing
2684  * SCTP chunk.  If a message is larger than this size it will be
2685  * fragmented by SCTP into the specified size.  Note that the underlying
2686  * SCTP implementation may fragment into smaller sized chunks when the
2687  * PMTU of the underlying association is smaller than the value set by
2688  * the user.
2689  */
2690 static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, int optlen)
2691 {
2692         struct sctp_association *asoc;
2693         struct list_head *pos;
2694         struct sctp_sock *sp = sctp_sk(sk);
2695         int val;
2696
2697         if (optlen < sizeof(int))
2698                 return -EINVAL;
2699         if (get_user(val, (int __user *)optval))
2700                 return -EFAULT;
2701         if ((val != 0) && ((val < 8) || (val > SCTP_MAX_CHUNK_LEN)))
2702                 return -EINVAL;
2703         sp->user_frag = val;
2704
2705         /* Update the frag_point of the existing associations. */
2706         list_for_each(pos, &(sp->ep->asocs)) {
2707                 asoc = list_entry(pos, struct sctp_association, asocs);
2708                 asoc->frag_point = sctp_frag_point(sp, asoc->pathmtu);
2709         }
2710
2711         return 0;
2712 }
2713
2714
2715 /*
2716  *  7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
2717  *
2718  *   Requests that the peer mark the enclosed address as the association
2719  *   primary. The enclosed address must be one of the association's
2720  *   locally bound addresses. The following structure is used to make a
2721  *   set primary request:
2722  */
2723 static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval,
2724                                              int optlen)
2725 {
2726         struct sctp_sock        *sp;
2727         struct sctp_endpoint    *ep;
2728         struct sctp_association *asoc = NULL;
2729         struct sctp_setpeerprim prim;
2730         struct sctp_chunk       *chunk;
2731         int                     err;
2732
2733         sp = sctp_sk(sk);
2734         ep = sp->ep;
2735
2736         if (!sctp_addip_enable)
2737                 return -EPERM;
2738
2739         if (optlen != sizeof(struct sctp_setpeerprim))
2740                 return -EINVAL;
2741
2742         if (copy_from_user(&prim, optval, optlen))
2743                 return -EFAULT;
2744
2745         asoc = sctp_id2assoc(sk, prim.sspp_assoc_id);
2746         if (!asoc)
2747                 return -EINVAL;
2748
2749         if (!asoc->peer.asconf_capable)
2750                 return -EPERM;
2751
2752         if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
2753                 return -EPERM;
2754
2755         if (!sctp_state(asoc, ESTABLISHED))
2756                 return -ENOTCONN;
2757
2758         if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr))
2759                 return -EADDRNOTAVAIL;
2760
2761         /* Create an ASCONF chunk with SET_PRIMARY parameter    */
2762         chunk = sctp_make_asconf_set_prim(asoc,
2763                                           (union sctp_addr *)&prim.sspp_addr);
2764         if (!chunk)
2765                 return -ENOMEM;
2766
2767         err = sctp_send_asconf(asoc, chunk);
2768
2769         SCTP_DEBUG_PRINTK("We set peer primary addr primitively.\n");
2770
2771         return err;
2772 }
2773
2774 static int sctp_setsockopt_adaptation_layer(struct sock *sk, char __user *optval,
2775                                           int optlen)
2776 {
2777         struct sctp_setadaptation adaptation;
2778
2779         if (optlen != sizeof(struct sctp_setadaptation))
2780                 return -EINVAL;
2781         if (copy_from_user(&adaptation, optval, optlen))
2782                 return -EFAULT;
2783
2784         sctp_sk(sk)->adaptation_ind = adaptation.ssb_adaptation_ind;
2785
2786         return 0;
2787 }
2788
2789 /*
2790  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
2791  *
2792  * The context field in the sctp_sndrcvinfo structure is normally only
2793  * used when a failed message is retrieved holding the value that was
2794  * sent down on the actual send call.  This option allows the setting of
2795  * a default context on an association basis that will be received on
2796  * reading messages from the peer.  This is especially helpful in the
2797  * one-2-many model for an application to keep some reference to an
2798  * internal state machine that is processing messages on the
2799  * association.  Note that the setting of this value only effects
2800  * received messages from the peer and does not effect the value that is
2801  * saved with outbound messages.
2802  */
2803 static int sctp_setsockopt_context(struct sock *sk, char __user *optval,
2804                                    int optlen)
2805 {
2806         struct sctp_assoc_value params;
2807         struct sctp_sock *sp;
2808         struct sctp_association *asoc;
2809
2810         if (optlen != sizeof(struct sctp_assoc_value))
2811                 return -EINVAL;
2812         if (copy_from_user(&params, optval, optlen))
2813                 return -EFAULT;
2814
2815         sp = sctp_sk(sk);
2816
2817         if (params.assoc_id != 0) {
2818                 asoc = sctp_id2assoc(sk, params.assoc_id);
2819                 if (!asoc)
2820                         return -EINVAL;
2821                 asoc->default_rcv_context = params.assoc_value;
2822         } else {
2823                 sp->default_rcv_context = params.assoc_value;
2824         }
2825
2826         return 0;
2827 }
2828
2829 /*
2830  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
2831  *
2832  * This options will at a minimum specify if the implementation is doing
2833  * fragmented interleave.  Fragmented interleave, for a one to many
2834  * socket, is when subsequent calls to receive a message may return
2835  * parts of messages from different associations.  Some implementations
2836  * may allow you to turn this value on or off.  If so, when turned off,
2837  * no fragment interleave will occur (which will cause a head of line
2838  * blocking amongst multiple associations sharing the same one to many
2839  * socket).  When this option is turned on, then each receive call may
2840  * come from a different association (thus the user must receive data
2841  * with the extended calls (e.g. sctp_recvmsg) to keep track of which
2842  * association each receive belongs to.
2843  *
2844  * This option takes a boolean value.  A non-zero value indicates that
2845  * fragmented interleave is on.  A value of zero indicates that
2846  * fragmented interleave is off.
2847  *
2848  * Note that it is important that an implementation that allows this
2849  * option to be turned on, have it off by default.  Otherwise an unaware
2850  * application using the one to many model may become confused and act
2851  * incorrectly.
2852  */
2853 static int sctp_setsockopt_fragment_interleave(struct sock *sk,
2854                                                char __user *optval,
2855                                                int optlen)
2856 {
2857         int val;
2858
2859         if (optlen != sizeof(int))
2860                 return -EINVAL;
2861         if (get_user(val, (int __user *)optval))
2862                 return -EFAULT;
2863
2864         sctp_sk(sk)->frag_interleave = (val == 0) ? 0 : 1;
2865
2866         return 0;
2867 }
2868
2869 /*
2870  * 7.1.25.  Set or Get the sctp partial delivery point
2871  *       (SCTP_PARTIAL_DELIVERY_POINT)
2872  * This option will set or get the SCTP partial delivery point.  This
2873  * point is the size of a message where the partial delivery API will be
2874  * invoked to help free up rwnd space for the peer.  Setting this to a
2875  * lower value will cause partial delivery's to happen more often.  The
2876  * calls argument is an integer that sets or gets the partial delivery
2877  * point.
2878  */
2879 static int sctp_setsockopt_partial_delivery_point(struct sock *sk,
2880                                                   char __user *optval,
2881                                                   int optlen)
2882 {
2883         u32 val;
2884
2885         if (optlen != sizeof(u32))
2886                 return -EINVAL;
2887         if (get_user(val, (int __user *)optval))
2888                 return -EFAULT;
2889
2890         sctp_sk(sk)->pd_point = val;
2891
2892         return 0; /* is this the right error code? */
2893 }
2894
2895 /* API 6.2 setsockopt(), getsockopt()
2896  *
2897  * Applications use setsockopt() and getsockopt() to set or retrieve
2898  * socket options.  Socket options are used to change the default
2899  * behavior of sockets calls.  They are described in Section 7.
2900  *
2901  * The syntax is:
2902  *
2903  *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
2904  *                    int __user *optlen);
2905  *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
2906  *                    int optlen);
2907  *
2908  *   sd      - the socket descript.
2909  *   level   - set to IPPROTO_SCTP for all SCTP options.
2910  *   optname - the option name.
2911  *   optval  - the buffer to store the value of the option.
2912  *   optlen  - the size of the buffer.
2913  */
2914 SCTP_STATIC int sctp_setsockopt(struct sock *sk, int level, int optname,
2915                                 char __user *optval, int optlen)
2916 {
2917         int retval = 0;
2918
2919         SCTP_DEBUG_PRINTK("sctp_setsockopt(sk: %p... optname: %d)\n",
2920                           sk, optname);
2921
2922         /* I can hardly begin to describe how wrong this is.  This is
2923          * so broken as to be worse than useless.  The API draft
2924          * REALLY is NOT helpful here...  I am not convinced that the
2925          * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
2926          * are at all well-founded.
2927          */
2928         if (level != SOL_SCTP) {
2929                 struct sctp_af *af = sctp_sk(sk)->pf->af;
2930                 retval = af->setsockopt(sk, level, optname, optval, optlen);
2931                 goto out_nounlock;
2932         }
2933
2934         sctp_lock_sock(sk);
2935
2936         switch (optname) {
2937         case SCTP_SOCKOPT_BINDX_ADD:
2938                 /* 'optlen' is the size of the addresses buffer. */
2939                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
2940                                                optlen, SCTP_BINDX_ADD_ADDR);
2941                 break;
2942
2943         case SCTP_SOCKOPT_BINDX_REM:
2944                 /* 'optlen' is the size of the addresses buffer. */
2945                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
2946                                                optlen, SCTP_BINDX_REM_ADDR);
2947                 break;
2948
2949         case SCTP_SOCKOPT_CONNECTX:
2950                 /* 'optlen' is the size of the addresses buffer. */
2951                 retval = sctp_setsockopt_connectx(sk, (struct sockaddr __user *)optval,
2952                                                optlen);
2953                 break;
2954
2955         case SCTP_DISABLE_FRAGMENTS:
2956                 retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
2957                 break;
2958
2959         case SCTP_EVENTS:
2960                 retval = sctp_setsockopt_events(sk, optval, optlen);
2961                 break;
2962
2963         case SCTP_AUTOCLOSE:
2964                 retval = sctp_setsockopt_autoclose(sk, optval, optlen);
2965                 break;
2966
2967         case SCTP_PEER_ADDR_PARAMS:
2968                 retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
2969                 break;
2970
2971         case SCTP_DELAYED_ACK_TIME:
2972                 retval = sctp_setsockopt_delayed_ack_time(sk, optval, optlen);
2973                 break;
2974         case SCTP_PARTIAL_DELIVERY_POINT:
2975                 retval = sctp_setsockopt_partial_delivery_point(sk, optval, optlen);
2976                 break;
2977
2978         case SCTP_INITMSG:
2979                 retval = sctp_setsockopt_initmsg(sk, optval, optlen);
2980                 break;
2981         case SCTP_DEFAULT_SEND_PARAM:
2982                 retval = sctp_setsockopt_default_send_param(sk, optval,
2983                                                             optlen);
2984                 break;
2985         case SCTP_PRIMARY_ADDR:
2986                 retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
2987                 break;
2988         case SCTP_SET_PEER_PRIMARY_ADDR:
2989                 retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
2990                 break;
2991         case SCTP_NODELAY:
2992                 retval = sctp_setsockopt_nodelay(sk, optval, optlen);
2993                 break;
2994         case SCTP_RTOINFO:
2995                 retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
2996                 break;
2997         case SCTP_ASSOCINFO:
2998                 retval = sctp_setsockopt_associnfo(sk, optval, optlen);
2999                 break;
3000         case SCTP_I_WANT_MAPPED_V4_ADDR:
3001                 retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
3002                 break;
3003         case SCTP_MAXSEG:
3004                 retval = sctp_setsockopt_maxseg(sk, optval, optlen);
3005                 break;
3006         case SCTP_ADAPTATION_LAYER:
3007                 retval = sctp_setsockopt_adaptation_layer(sk, optval, optlen);
3008                 break;
3009         case SCTP_CONTEXT:
3010                 retval = sctp_setsockopt_context(sk, optval, optlen);
3011                 break;
3012         case SCTP_FRAGMENT_INTERLEAVE:
3013                 retval = sctp_setsockopt_fragment_interleave(sk, optval, optlen);
3014                 break;
3015         default:
3016                 retval = -ENOPROTOOPT;
3017                 break;
3018         };
3019
3020         sctp_release_sock(sk);
3021
3022 out_nounlock:
3023         return retval;
3024 }
3025
3026 /* API 3.1.6 connect() - UDP Style Syntax
3027  *
3028  * An application may use the connect() call in the UDP model to initiate an
3029  * association without sending data.
3030  *
3031  * The syntax is:
3032  *
3033  * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
3034  *
3035  * sd: the socket descriptor to have a new association added to.
3036  *
3037  * nam: the address structure (either struct sockaddr_in or struct
3038  *    sockaddr_in6 defined in RFC2553 [7]).
3039  *
3040  * len: the size of the address.
3041  */
3042 SCTP_STATIC int sctp_connect(struct sock *sk, struct sockaddr *addr,
3043                              int addr_len)
3044 {
3045         int err = 0;
3046         struct sctp_af *af;
3047
3048         sctp_lock_sock(sk);
3049
3050         SCTP_DEBUG_PRINTK("%s - sk: %p, sockaddr: %p, addr_len: %d\n",
3051                           __FUNCTION__, sk, addr, addr_len);
3052
3053         /* Validate addr_len before calling common connect/connectx routine. */
3054         af = sctp_get_af_specific(addr->sa_family);
3055         if (!af || addr_len < af->sockaddr_len) {
3056                 err = -EINVAL;
3057         } else {
3058                 /* Pass correct addr len to common routine (so it knows there
3059                  * is only one address being passed.
3060                  */
3061                 err = __sctp_connect(sk, addr, af->sockaddr_len);
3062         }
3063
3064         sctp_release_sock(sk);
3065         return err;
3066 }
3067
3068 /* FIXME: Write comments. */
3069 SCTP_STATIC int sctp_disconnect(struct sock *sk, int flags)
3070 {
3071         return -EOPNOTSUPP; /* STUB */
3072 }
3073
3074 /* 4.1.4 accept() - TCP Style Syntax
3075  *
3076  * Applications use accept() call to remove an established SCTP
3077  * association from the accept queue of the endpoint.  A new socket
3078  * descriptor will be returned from accept() to represent the newly
3079  * formed association.
3080  */
3081 SCTP_STATIC struct sock *sctp_accept(struct sock *sk, int flags, int *err)
3082 {
3083         struct sctp_sock *sp;
3084         struct sctp_endpoint *ep;
3085         struct sock *newsk = NULL;
3086         struct sctp_association *asoc;
3087         long timeo;
3088         int error = 0;
3089
3090         sctp_lock_sock(sk);
3091
3092         sp = sctp_sk(sk);
3093         ep = sp->ep;
3094
3095         if (!sctp_style(sk, TCP)) {
3096                 error = -EOPNOTSUPP;
3097                 goto out;
3098         }
3099
3100         if (!sctp_sstate(sk, LISTENING)) {
3101                 error = -EINVAL;
3102                 goto out;
3103         }
3104
3105         timeo = sock_rcvtimeo(sk, flags & O_NONBLOCK);
3106
3107         error = sctp_wait_for_accept(sk, timeo);
3108         if (error)
3109                 goto out;
3110
3111         /* We treat the list of associations on the endpoint as the accept
3112          * queue and pick the first association on the list.
3113          */
3114         asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
3115
3116         newsk = sp->pf->create_accept_sk(sk, asoc);
3117         if (!newsk) {
3118                 error = -ENOMEM;
3119                 goto out;
3120         }
3121
3122         /* Populate the fields of the newsk from the oldsk and migrate the
3123          * asoc to the newsk.
3124          */
3125         sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
3126
3127 out:
3128         sctp_release_sock(sk);
3129         *err = error;
3130         return newsk;
3131 }
3132
3133 /* The SCTP ioctl handler. */
3134 SCTP_STATIC int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
3135 {
3136         return -ENOIOCTLCMD;
3137 }
3138
3139 /* This is the function which gets called during socket creation to
3140  * initialized the SCTP-specific portion of the sock.
3141  * The sock structure should already be zero-filled memory.
3142  */
3143 SCTP_STATIC int sctp_init_sock(struct sock *sk)
3144 {
3145         struct sctp_endpoint *ep;
3146         struct sctp_sock *sp;
3147
3148         SCTP_DEBUG_PRINTK("sctp_init_sock(sk: %p)\n", sk);
3149
3150         sp = sctp_sk(sk);
3151
3152         /* Initialize the SCTP per socket area.  */
3153         switch (sk->sk_type) {
3154         case SOCK_SEQPACKET:
3155                 sp->type = SCTP_SOCKET_UDP;
3156                 break;
3157         case SOCK_STREAM:
3158                 sp->type = SCTP_SOCKET_TCP;
3159                 break;
3160         default:
3161                 return -ESOCKTNOSUPPORT;
3162         }
3163
3164         /* Initialize default send parameters. These parameters can be
3165          * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
3166          */
3167         sp->default_stream = 0;
3168         sp->default_ppid = 0;
3169         sp->default_flags = 0;
3170         sp->default_context = 0;
3171         sp->default_timetolive = 0;
3172
3173         sp->default_rcv_context = 0;
3174
3175         /* Initialize default setup parameters. These parameters
3176          * can be modified with the SCTP_INITMSG socket option or
3177          * overridden by the SCTP_INIT CMSG.
3178          */
3179         sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
3180         sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
3181         sp->initmsg.sinit_max_attempts   = sctp_max_retrans_init;
3182         sp->initmsg.sinit_max_init_timeo = sctp_rto_max;
3183
3184         /* Initialize default RTO related parameters.  These parameters can
3185          * be modified for with the SCTP_RTOINFO socket option.
3186          */
3187         sp->rtoinfo.srto_initial = sctp_rto_initial;
3188         sp->rtoinfo.srto_max     = sctp_rto_max;
3189         sp->rtoinfo.srto_min     = sctp_rto_min;
3190
3191         /* Initialize default association related parameters. These parameters
3192          * can be modified with the SCTP_ASSOCINFO socket option.
3193          */
3194         sp->assocparams.sasoc_asocmaxrxt = sctp_max_retrans_association;
3195         sp->assocparams.sasoc_number_peer_destinations = 0;
3196         sp->assocparams.sasoc_peer_rwnd = 0;
3197         sp->assocparams.sasoc_local_rwnd = 0;
3198         sp->assocparams.sasoc_cookie_life = sctp_valid_cookie_life;
3199
3200         /* Initialize default event subscriptions. By default, all the
3201          * options are off.
3202          */
3203         memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
3204
3205         /* Default Peer Address Parameters.  These defaults can
3206          * be modified via SCTP_PEER_ADDR_PARAMS
3207          */
3208         sp->hbinterval  = sctp_hb_interval;
3209         sp->pathmaxrxt  = sctp_max_retrans_path;
3210         sp->pathmtu     = 0; // allow default discovery
3211         sp->sackdelay   = sctp_sack_timeout;
3212         sp->param_flags = SPP_HB_ENABLE |
3213                           SPP_PMTUD_ENABLE |
3214                           SPP_SACKDELAY_ENABLE;
3215
3216         /* If enabled no SCTP message fragmentation will be performed.
3217          * Configure through SCTP_DISABLE_FRAGMENTS socket option.
3218          */
3219         sp->disable_fragments = 0;
3220
3221         /* Enable Nagle algorithm by default.  */
3222         sp->nodelay           = 0;
3223
3224         /* Enable by default. */
3225         sp->v4mapped          = 1;
3226
3227         /* Auto-close idle associations after the configured
3228          * number of seconds.  A value of 0 disables this
3229          * feature.  Configure through the SCTP_AUTOCLOSE socket option,
3230          * for UDP-style sockets only.
3231          */
3232         sp->autoclose         = 0;
3233
3234         /* User specified fragmentation limit. */
3235         sp->user_frag         = 0;
3236
3237         sp->adaptation_ind = 0;
3238
3239         sp->pf = sctp_get_pf_specific(sk->sk_family);
3240
3241         /* Control variables for partial data delivery. */
3242         atomic_set(&sp->pd_mode, 0);
3243         skb_queue_head_init(&sp->pd_lobby);
3244         sp->frag_interleave = 0;
3245
3246         /* Create a per socket endpoint structure.  Even if we
3247          * change the data structure relationships, this may still
3248          * be useful for storing pre-connect address information.
3249          */
3250         ep = sctp_endpoint_new(sk, GFP_KERNEL);
3251         if (!ep)
3252                 return -ENOMEM;
3253
3254         sp->ep = ep;
3255         sp->hmac = NULL;
3256
3257         SCTP_DBG_OBJCNT_INC(sock);
3258         return 0;
3259 }
3260
3261 /* Cleanup any SCTP per socket resources.  */
3262 SCTP_STATIC int sctp_destroy_sock(struct sock *sk)
3263 {
3264         struct sctp_endpoint *ep;
3265
3266         SCTP_DEBUG_PRINTK("sctp_destroy_sock(sk: %p)\n", sk);
3267
3268         /* Release our hold on the endpoint. */
3269         ep = sctp_sk(sk)->ep;
3270         sctp_endpoint_free(ep);
3271
3272         return 0;
3273 }
3274
3275 /* API 4.1.7 shutdown() - TCP Style Syntax
3276  *     int shutdown(int socket, int how);
3277  *
3278  *     sd      - the socket descriptor of the association to be closed.
3279  *     how     - Specifies the type of shutdown.  The  values  are
3280  *               as follows:
3281  *               SHUT_RD
3282  *                     Disables further receive operations. No SCTP
3283  *                     protocol action is taken.
3284  *               SHUT_WR
3285  *                     Disables further send operations, and initiates
3286  *                     the SCTP shutdown sequence.
3287  *               SHUT_RDWR
3288  *                     Disables further send  and  receive  operations
3289  *                     and initiates the SCTP shutdown sequence.
3290  */
3291 SCTP_STATIC void sctp_shutdown(struct sock *sk, int how)
3292 {
3293         struct sctp_endpoint *ep;
3294         struct sctp_association *asoc;
3295
3296         if (!sctp_style(sk, TCP))
3297                 return;
3298
3299         if (how & SEND_SHUTDOWN) {
3300                 ep = sctp_sk(sk)->ep;
3301                 if (!list_empty(&ep->asocs)) {
3302                         asoc = list_entry(ep->asocs.next,
3303                                           struct sctp_association, asocs);
3304                         sctp_primitive_SHUTDOWN(asoc, NULL);
3305                 }
3306         }
3307 }
3308
3309 /* 7.2.1 Association Status (SCTP_STATUS)
3310
3311  * Applications can retrieve current status information about an
3312  * association, including association state, peer receiver window size,
3313  * number of unacked data chunks, and number of data chunks pending
3314  * receipt.  This information is read-only.
3315  */
3316 static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
3317                                        char __user *optval,
3318                                        int __user *optlen)
3319 {
3320         struct sctp_status status;
3321         struct sctp_association *asoc = NULL;
3322         struct sctp_transport *transport;
3323         sctp_assoc_t associd;
3324         int retval = 0;
3325
3326         if (len != sizeof(status)) {
3327                 retval = -EINVAL;
3328                 goto out;
3329         }
3330
3331         if (copy_from_user(&status, optval, sizeof(status))) {
3332                 retval = -EFAULT;
3333                 goto out;
3334         }
3335
3336         associd = status.sstat_assoc_id;
3337         asoc = sctp_id2assoc(sk, associd);
3338         if (!asoc) {
3339                 retval = -EINVAL;
3340                 goto out;
3341         }
3342
3343         transport = asoc->peer.primary_path;
3344
3345         status.sstat_assoc_id = sctp_assoc2id(asoc);
3346         status.sstat_state = asoc->state;
3347         status.sstat_rwnd =  asoc->peer.rwnd;
3348         status.sstat_unackdata = asoc->unack_data;
3349
3350         status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
3351         status.sstat_instrms = asoc->c.sinit_max_instreams;
3352         status.sstat_outstrms = asoc->c.sinit_num_ostreams;
3353         status.sstat_fragmentation_point = asoc->frag_point;
3354         status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
3355         memcpy(&status.sstat_primary.spinfo_address, &transport->ipaddr,
3356                         transport->af_specific->sockaddr_len);
3357         /* Map ipv4 address into v4-mapped-on-v6 address.  */
3358         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
3359                 (union sctp_addr *)&status.sstat_primary.spinfo_address);
3360         status.sstat_primary.spinfo_state = transport->state;
3361         status.sstat_primary.spinfo_cwnd = transport->cwnd;
3362         status.sstat_primary.spinfo_srtt = transport->srtt;
3363         status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
3364         status.sstat_primary.spinfo_mtu = transport->pathmtu;
3365
3366         if (status.sstat_primary.spinfo_state == SCTP_UNKNOWN)
3367                 status.sstat_primary.spinfo_state = SCTP_ACTIVE;
3368
3369         if (put_user(len, optlen)) {
3370                 retval = -EFAULT;
3371                 goto out;
3372         }
3373
3374         SCTP_DEBUG_PRINTK("sctp_getsockopt_sctp_status(%d): %d %d %d\n",
3375                           len, status.sstat_state, status.sstat_rwnd,
3376                           status.sstat_assoc_id);
3377
3378         if (copy_to_user(optval, &status, len)) {
3379                 retval = -EFAULT;
3380                 goto out;
3381         }
3382
3383 out:
3384         return (retval);
3385 }
3386
3387
3388 /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
3389  *
3390  * Applications can retrieve information about a specific peer address
3391  * of an association, including its reachability state, congestion
3392  * window, and retransmission timer values.  This information is
3393  * read-only.
3394  */
3395 static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
3396                                           char __user *optval,
3397                                           int __user *optlen)
3398 {
3399         struct sctp_paddrinfo pinfo;
3400         struct sctp_transport *transport;
3401         int retval = 0;
3402
3403         if (len != sizeof(pinfo)) {
3404                 retval = -EINVAL;
3405                 goto out;
3406         }
3407
3408         if (copy_from_user(&pinfo, optval, sizeof(pinfo))) {
3409                 retval = -EFAULT;
3410                 goto out;
3411         }
3412
3413         transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
3414                                            pinfo.spinfo_assoc_id);
3415         if (!transport)
3416                 return -EINVAL;
3417
3418         pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
3419         pinfo.spinfo_state = transport->state;
3420         pinfo.spinfo_cwnd = transport->cwnd;
3421         pinfo.spinfo_srtt = transport->srtt;
3422         pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
3423         pinfo.spinfo_mtu = transport->pathmtu;
3424
3425         if (pinfo.spinfo_state == SCTP_UNKNOWN)
3426                 pinfo.spinfo_state = SCTP_ACTIVE;
3427
3428         if (put_user(len, optlen)) {
3429                 retval = -EFAULT;
3430                 goto out;
3431         }
3432
3433         if (copy_to_user(optval, &pinfo, len)) {
3434                 retval = -EFAULT;
3435                 goto out;
3436         }
3437
3438 out:
3439         return (retval);
3440 }
3441
3442 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
3443  *
3444  * This option is a on/off flag.  If enabled no SCTP message
3445  * fragmentation will be performed.  Instead if a message being sent
3446  * exceeds the current PMTU size, the message will NOT be sent and
3447  * instead a error will be indicated to the user.
3448  */
3449 static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
3450                                         char __user *optval, int __user *optlen)
3451 {
3452         int val;
3453
3454         if (len < sizeof(int))
3455                 return -EINVAL;
3456
3457         len = sizeof(int);
3458         val = (sctp_sk(sk)->disable_fragments == 1);
3459         if (put_user(len, optlen))
3460                 return -EFAULT;
3461         if (copy_to_user(optval, &val, len))
3462                 return -EFAULT;
3463         return 0;
3464 }
3465
3466 /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
3467  *
3468  * This socket option is used to specify various notifications and
3469  * ancillary data the user wishes to receive.
3470  */
3471 static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
3472                                   int __user *optlen)
3473 {
3474         if (len != sizeof(struct sctp_event_subscribe))
3475                 return -EINVAL;
3476         if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
3477                 return -EFAULT;
3478         return 0;
3479 }
3480
3481 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
3482  *
3483  * This socket option is applicable to the UDP-style socket only.  When
3484  * set it will cause associations that are idle for more than the
3485  * specified number of seconds to automatically close.  An association
3486  * being idle is defined an association that has NOT sent or received
3487  * user data.  The special value of '0' indicates that no automatic
3488  * close of any associations should be performed.  The option expects an
3489  * integer defining the number of seconds of idle time before an
3490  * association is closed.
3491  */
3492 static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
3493 {
3494         /* Applicable to UDP-style socket only */
3495         if (sctp_style(sk, TCP))
3496                 return -EOPNOTSUPP;
3497         if (len != sizeof(int))
3498                 return -EINVAL;
3499         if (copy_to_user(optval, &sctp_sk(sk)->autoclose, len))
3500                 return -EFAULT;
3501         return 0;
3502 }
3503
3504 /* Helper routine to branch off an association to a new socket.  */
3505 SCTP_STATIC int sctp_do_peeloff(struct sctp_association *asoc,
3506                                 struct socket **sockp)
3507 {
3508         struct sock *sk = asoc->base.sk;
3509         struct socket *sock;
3510         struct inet_sock *inetsk;
3511         int err = 0;
3512
3513         /* An association cannot be branched off from an already peeled-off
3514          * socket, nor is this supported for tcp style sockets.
3515          */
3516         if (!sctp_style(sk, UDP))
3517                 return -EINVAL;
3518
3519         /* Create a new socket.  */
3520         err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
3521         if (err < 0)
3522                 return err;
3523
3524         /* Populate the fields of the newsk from the oldsk and migrate the
3525          * asoc to the newsk.
3526          */
3527         sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
3528
3529         /* Make peeled-off sockets more like 1-1 accepted sockets.
3530          * Set the daddr and initialize id to something more random
3531          */
3532         inetsk = inet_sk(sock->sk);
3533         inetsk->daddr = asoc->peer.primary_addr.v4.sin_addr.s_addr;
3534         inetsk->id = asoc->next_tsn ^ jiffies;
3535
3536         *sockp = sock;
3537
3538         return err;
3539 }
3540
3541 static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
3542 {
3543         sctp_peeloff_arg_t peeloff;
3544         struct socket *newsock;
3545         int retval = 0;
3546         struct sctp_association *asoc;
3547
3548         if (len != sizeof(sctp_peeloff_arg_t))
3549                 return -EINVAL;
3550         if (copy_from_user(&peeloff, optval, len))
3551                 return -EFAULT;
3552
3553         asoc = sctp_id2assoc(sk, peeloff.associd);
3554         if (!asoc) {
3555                 retval = -EINVAL;
3556                 goto out;
3557         }
3558
3559         SCTP_DEBUG_PRINTK("%s: sk: %p asoc: %p\n", __FUNCTION__, sk, asoc);
3560
3561         retval = sctp_do_peeloff(asoc, &newsock);
3562         if (retval < 0)
3563                 goto out;
3564
3565         /* Map the socket to an unused fd that can be returned to the user.  */
3566         retval = sock_map_fd(newsock);
3567         if (retval < 0) {
3568                 sock_release(newsock);
3569                 goto out;
3570         }
3571
3572         SCTP_DEBUG_PRINTK("%s: sk: %p asoc: %p newsk: %p sd: %d\n",
3573                           __FUNCTION__, sk, asoc, newsock->sk, retval);
3574
3575         /* Return the fd mapped to the new socket.  */
3576         peeloff.sd = retval;
3577         if (copy_to_user(optval, &peeloff, len))
3578                 retval = -EFAULT;
3579
3580 out:
3581         return retval;
3582 }
3583
3584 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
3585  *
3586  * Applications can enable or disable heartbeats for any peer address of
3587  * an association, modify an address's heartbeat interval, force a
3588  * heartbeat to be sent immediately, and adjust the address's maximum
3589  * number of retransmissions sent before an address is considered
3590  * unreachable.  The following structure is used to access and modify an
3591  * address's parameters:
3592  *
3593  *  struct sctp_paddrparams {
3594  *     sctp_assoc_t            spp_assoc_id;
3595  *     struct sockaddr_storage spp_address;
3596  *     uint32_t                spp_hbinterval;
3597  *     uint16_t                spp_pathmaxrxt;
3598  *     uint32_t                spp_pathmtu;
3599  *     uint32_t                spp_sackdelay;
3600  *     uint32_t                spp_flags;
3601  * };
3602  *
3603  *   spp_assoc_id    - (one-to-many style socket) This is filled in the
3604  *                     application, and identifies the association for
3605  *                     this query.
3606  *   spp_address     - This specifies which address is of interest.
3607  *   spp_hbinterval  - This contains the value of the heartbeat interval,
3608  *                     in milliseconds.  If a  value of zero
3609  *                     is present in this field then no changes are to
3610  *                     be made to this parameter.
3611  *   spp_pathmaxrxt  - This contains the maximum number of
3612  *                     retransmissions before this address shall be
3613  *                     considered unreachable. If a  value of zero
3614  *                     is present in this field then no changes are to
3615  *                     be made to this parameter.
3616  *   spp_pathmtu     - When Path MTU discovery is disabled the value
3617  *                     specified here will be the "fixed" path mtu.
3618  *                     Note that if the spp_address field is empty
3619  *                     then all associations on this address will
3620  *                     have this fixed path mtu set upon them.
3621  *
3622  *   spp_sackdelay   - When delayed sack is enabled, this value specifies
3623  *                     the number of milliseconds that sacks will be delayed
3624  *                     for. This value will apply to all addresses of an
3625  *                     association if the spp_address field is empty. Note
3626  *                     also, that if delayed sack is enabled and this
3627  *                     value is set to 0, no change is made to the last
3628  *                     recorded delayed sack timer value.
3629  *
3630  *   spp_flags       - These flags are used to control various features
3631  *                     on an association. The flag field may contain
3632  *                     zero or more of the following options.
3633  *
3634  *                     SPP_HB_ENABLE  - Enable heartbeats on the
3635  *                     specified address. Note that if the address
3636  *                     field is empty all addresses for the association
3637  *                     have heartbeats enabled upon them.
3638  *
3639  *                     SPP_HB_DISABLE - Disable heartbeats on the
3640  *                     speicifed address. Note that if the address
3641  *                     field is empty all addresses for the association
3642  *                     will have their heartbeats disabled. Note also
3643  *                     that SPP_HB_ENABLE and SPP_HB_DISABLE are
3644  *                     mutually exclusive, only one of these two should
3645  *                     be specified. Enabling both fields will have
3646  *                     undetermined results.
3647  *
3648  *                     SPP_HB_DEMAND - Request a user initiated heartbeat
3649  *                     to be made immediately.
3650  *
3651  *                     SPP_PMTUD_ENABLE - This field will enable PMTU
3652  *                     discovery upon the specified address. Note that
3653  *                     if the address feild is empty then all addresses
3654  *                     on the association are effected.
3655  *
3656  *                     SPP_PMTUD_DISABLE - This field will disable PMTU
3657  *                     discovery upon the specified address. Note that
3658  *                     if the address feild is empty then all addresses
3659  *                     on the association are effected. Not also that
3660  *                     SPP_PMTUD_ENABLE and SPP_PMTUD_DISABLE are mutually
3661  *                     exclusive. Enabling both will have undetermined
3662  *                     results.
3663  *
3664  *                     SPP_SACKDELAY_ENABLE - Setting this flag turns
3665  *                     on delayed sack. The time specified in spp_sackdelay
3666  *                     is used to specify the sack delay for this address. Note
3667  *                     that if spp_address is empty then all addresses will
3668  *                     enable delayed sack and take on the sack delay
3669  *                     value specified in spp_sackdelay.
3670  *                     SPP_SACKDELAY_DISABLE - Setting this flag turns
3671  *                     off delayed sack. If the spp_address field is blank then
3672  *                     delayed sack is disabled for the entire association. Note
3673  *                     also that this field is mutually exclusive to
3674  *                     SPP_SACKDELAY_ENABLE, setting both will have undefined
3675  *                     results.
3676  */
3677 static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
3678                                             char __user *optval, int __user *optlen)
3679 {
3680         struct sctp_paddrparams  params;
3681         struct sctp_transport   *trans = NULL;
3682         struct sctp_association *asoc = NULL;
3683         struct sctp_sock        *sp = sctp_sk(sk);
3684
3685         if (len != sizeof(struct sctp_paddrparams))
3686                 return -EINVAL;
3687
3688         if (copy_from_user(&params, optval, len))
3689                 return -EFAULT;
3690
3691         /* If an address other than INADDR_ANY is specified, and
3692          * no transport is found, then the request is invalid.
3693          */
3694         if (!sctp_is_any(( union sctp_addr *)&params.spp_address)) {
3695                 trans = sctp_addr_id2transport(sk, &params.spp_address,
3696                                                params.spp_assoc_id);
3697                 if (!trans) {
3698                         SCTP_DEBUG_PRINTK("Failed no transport\n");
3699                         return -EINVAL;
3700                 }
3701         }
3702
3703         /* Get association, if assoc_id != 0 and the socket is a one
3704          * to many style socket, and an association was not found, then
3705          * the id was invalid.
3706          */
3707         asoc = sctp_id2assoc(sk, params.spp_assoc_id);
3708         if (!asoc && params.spp_assoc_id && sctp_style(sk, UDP)) {
3709                 SCTP_DEBUG_PRINTK("Failed no association\n");
3710                 return -EINVAL;
3711         }
3712
3713         if (trans) {
3714                 /* Fetch transport values. */
3715                 params.spp_hbinterval = jiffies_to_msecs(trans->hbinterval);
3716                 params.spp_pathmtu    = trans->pathmtu;
3717                 params.spp_pathmaxrxt = trans->pathmaxrxt;
3718                 params.spp_sackdelay  = jiffies_to_msecs(trans->sackdelay);
3719
3720                 /*draft-11 doesn't say what to return in spp_flags*/
3721                 params.spp_flags      = trans->param_flags;
3722         } else if (asoc) {
3723                 /* Fetch association values. */
3724                 params.spp_hbinterval = jiffies_to_msecs(asoc->hbinterval);
3725                 params.spp_pathmtu    = asoc->pathmtu;
3726                 params.spp_pathmaxrxt = asoc->pathmaxrxt;
3727                 params.spp_sackdelay  = jiffies_to_msecs(asoc->sackdelay);
3728
3729                 /*draft-11 doesn't say what to return in spp_flags*/
3730                 params.spp_flags      = asoc->param_flags;
3731         } else {
3732                 /* Fetch socket values. */
3733                 params.spp_hbinterval = sp->hbinterval;
3734                 params.spp_pathmtu    = sp->pathmtu;
3735                 params.spp_sackdelay  = sp->sackdelay;
3736                 params.spp_pathmaxrxt = sp->pathmaxrxt;
3737
3738                 /*draft-11 doesn't say what to return in spp_flags*/
3739                 params.spp_flags      = sp->param_flags;
3740         }
3741
3742         if (copy_to_user(optval, &params, len))
3743                 return -EFAULT;
3744
3745         if (put_user(len, optlen))
3746                 return -EFAULT;
3747
3748         return 0;
3749 }
3750
3751 /* 7.1.23. Delayed Ack Timer (SCTP_DELAYED_ACK_TIME)
3752  *
3753  *   This options will get or set the delayed ack timer.  The time is set
3754  *   in milliseconds.  If the assoc_id is 0, then this sets or gets the
3755  *   endpoints default delayed ack timer value.  If the assoc_id field is
3756  *   non-zero, then the set or get effects the specified association.
3757  *
3758  *   struct sctp_assoc_value {
3759  *       sctp_assoc_t            assoc_id;
3760  *       uint32_t                assoc_value;
3761  *   };
3762  *
3763  *     assoc_id    - This parameter, indicates which association the
3764  *                   user is preforming an action upon. Note that if
3765  *                   this field's value is zero then the endpoints
3766  *                   default value is changed (effecting future
3767  *                   associations only).
3768  *
3769  *     assoc_value - This parameter contains the number of milliseconds
3770  *                   that the user is requesting the delayed ACK timer
3771  *                   be set to. Note that this value is defined in
3772  *                   the standard to be between 200 and 500 milliseconds.
3773  *
3774  *                   Note: a value of zero will leave the value alone,
3775  *                   but disable SACK delay. A non-zero value will also
3776  *                   enable SACK delay.
3777  */
3778 static int sctp_getsockopt_delayed_ack_time(struct sock *sk, int len,
3779                                             char __user *optval,
3780                                             int __user *optlen)
3781 {
3782         struct sctp_assoc_value  params;
3783         struct sctp_association *asoc = NULL;
3784         struct sctp_sock        *sp = sctp_sk(sk);
3785
3786         if (len != sizeof(struct sctp_assoc_value))
3787                 return - EINVAL;
3788
3789         if (copy_from_user(&params, optval, len))
3790                 return -EFAULT;
3791
3792         /* Get association, if assoc_id != 0 and the socket is a one
3793          * to many style socket, and an association was not found, then
3794          * the id was invalid.
3795          */
3796         asoc = sctp_id2assoc(sk, params.assoc_id);
3797         if (!asoc && params.assoc_id && sctp_style(sk, UDP))
3798                 return -EINVAL;
3799
3800         if (asoc) {
3801                 /* Fetch association values. */
3802                 if (asoc->param_flags & SPP_SACKDELAY_ENABLE)
3803                         params.assoc_value = jiffies_to_msecs(
3804                                 asoc->sackdelay);
3805                 else
3806                         params.assoc_value = 0;
3807         } else {
3808                 /* Fetch socket values. */
3809                 if (sp->param_flags & SPP_SACKDELAY_ENABLE)
3810                         params.assoc_value  = sp->sackdelay;
3811                 else
3812                         params.assoc_value  = 0;
3813         }
3814
3815         if (copy_to_user(optval, &params, len))
3816                 return -EFAULT;
3817
3818         if (put_user(len, optlen))
3819                 return -EFAULT;
3820
3821         return 0;
3822 }
3823
3824 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
3825  *
3826  * Applications can specify protocol parameters for the default association
3827  * initialization.  The option name argument to setsockopt() and getsockopt()
3828  * is SCTP_INITMSG.
3829  *
3830  * Setting initialization parameters is effective only on an unconnected
3831  * socket (for UDP-style sockets only future associations are effected
3832  * by the change).  With TCP-style sockets, this option is inherited by
3833  * sockets derived from a listener socket.
3834  */
3835 static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
3836 {
3837         if (len != sizeof(struct sctp_initmsg))
3838                 return -EINVAL;
3839         if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
3840                 return -EFAULT;
3841         return 0;
3842 }
3843
3844 static int sctp_getsockopt_peer_addrs_num_old(struct sock *sk, int len,
3845                                               char __user *optval,
3846                                               int __user *optlen)
3847 {
3848         sctp_assoc_t id;
3849         struct sctp_association *asoc;
3850         struct list_head *pos;
3851         int cnt = 0;
3852
3853         if (len != sizeof(sctp_assoc_t))
3854                 return -EINVAL;
3855
3856         if (copy_from_user(&id, optval, sizeof(sctp_assoc_t)))
3857                 return -EFAULT;
3858
3859         /* For UDP-style sockets, id specifies the association to query.  */
3860         asoc = sctp_id2assoc(sk, id);
3861         if (!asoc)
3862                 return -EINVAL;
3863
3864         list_for_each(pos, &asoc->peer.transport_addr_list) {
3865                 cnt ++;
3866         }
3867
3868         return cnt;
3869 }
3870
3871 /*
3872  * Old API for getting list of peer addresses. Does not work for 32-bit
3873  * programs running on a 64-bit kernel
3874  */
3875 static int sctp_getsockopt_peer_addrs_old(struct sock *sk, int len,
3876                                           char __user *optval,
3877                                           int __user *optlen)
3878 {
3879         struct sctp_association *asoc;
3880         struct list_head *pos;
3881         int cnt = 0;
3882         struct sctp_getaddrs_old getaddrs;
3883         struct sctp_transport *from;
3884         void __user *to;
3885         union sctp_addr temp;
3886         struct sctp_sock *sp = sctp_sk(sk);
3887         int addrlen;
3888
3889         if (len != sizeof(struct sctp_getaddrs_old))
3890                 return -EINVAL;
3891
3892         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs_old)))
3893                 return -EFAULT;
3894
3895         if (getaddrs.addr_num <= 0) return -EINVAL;
3896
3897         /* For UDP-style sockets, id specifies the association to query.  */
3898         asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
3899         if (!asoc)
3900                 return -EINVAL;
3901
3902         to = (void __user *)getaddrs.addrs;
3903         list_for_each(pos, &asoc->peer.transport_addr_list) {
3904                 from = list_entry(pos, struct sctp_transport, transports);
3905                 memcpy(&temp, &from->ipaddr, sizeof(temp));
3906                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
3907                 addrlen = sctp_get_af_specific(sk->sk_family)->sockaddr_len;
3908                 if (copy_to_user(to, &temp, addrlen))
3909                         return -EFAULT;
3910                 to += addrlen ;
3911                 cnt ++;
3912                 if (cnt >= getaddrs.addr_num) break;
3913         }
3914         getaddrs.addr_num = cnt;
3915         if (copy_to_user(optval, &getaddrs, sizeof(struct sctp_getaddrs_old)))
3916                 return -EFAULT;
3917
3918         return 0;
3919 }
3920
3921 static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
3922                                       char __user *optval, int __user *optlen)
3923 {
3924         struct sctp_association *asoc;
3925         struct list_head *pos;
3926         int cnt = 0;
3927         struct sctp_getaddrs getaddrs;
3928         struct sctp_transport *from;
3929         void __user *to;
3930         union sctp_addr temp;
3931         struct sctp_sock *sp = sctp_sk(sk);
3932         int addrlen;
3933         size_t space_left;
3934         int bytes_copied;
3935
3936         if (len < sizeof(struct sctp_getaddrs))
3937                 return -EINVAL;
3938
3939         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
3940                 return -EFAULT;
3941
3942         /* For UDP-style sockets, id specifies the association to query.  */
3943         asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
3944         if (!asoc)
3945                 return -EINVAL;
3946
3947         to = optval + offsetof(struct sctp_getaddrs,addrs);
3948         space_left = len - sizeof(struct sctp_getaddrs) -
3949                         offsetof(struct sctp_getaddrs,addrs);
3950
3951         list_for_each(pos, &asoc->peer.transport_addr_list) {
3952                 from = list_entry(pos, struct sctp_transport, transports);
3953                 memcpy(&temp, &from->ipaddr, sizeof(temp));
3954                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
3955                 addrlen = sctp_get_af_specific(sk->sk_family)->sockaddr_len;
3956                 if(space_left < addrlen)
3957                         return -ENOMEM;
3958                 if (copy_to_user(to, &temp, addrlen))
3959                         return -EFAULT;
3960                 to += addrlen;
3961                 cnt++;
3962                 space_left -= addrlen;
3963         }
3964
3965         if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
3966                 return -EFAULT;
3967         bytes_copied = ((char __user *)to) - optval;
3968         if (put_user(bytes_copied, optlen))
3969                 return -EFAULT;
3970
3971         return 0;
3972 }
3973
3974 static int sctp_getsockopt_local_addrs_num_old(struct sock *sk, int len,
3975                                                char __user *optval,
3976                                                int __user *optlen)
3977 {
3978         sctp_assoc_t id;
3979         struct sctp_bind_addr *bp;
3980         struct sctp_association *asoc;
3981         struct list_head *pos, *temp;
3982         struct sctp_sockaddr_entry *addr;
3983         rwlock_t *addr_lock;
3984         int cnt = 0;
3985
3986         if (len != sizeof(sctp_assoc_t))
3987                 return -EINVAL;
3988
3989         if (copy_from_user(&id, optval, sizeof(sctp_assoc_t)))
3990                 return -EFAULT;
3991
3992         /*
3993          *  For UDP-style sockets, id specifies the association to query.
3994          *  If the id field is set to the value '0' then the locally bound
3995          *  addresses are returned without regard to any particular
3996          *  association.
3997          */
3998         if (0 == id) {
3999                 bp = &sctp_sk(sk)->ep->base.bind_addr;
4000                 addr_lock = &sctp_sk(sk)->ep->base.addr_lock;
4001         } else {
4002                 asoc = sctp_id2assoc(sk, id);
4003                 if (!asoc)
4004                         return -EINVAL;
4005                 bp = &asoc->base.bind_addr;
4006                 addr_lock = &asoc->base.addr_lock;
4007         }
4008
4009         sctp_read_lock(addr_lock);
4010
4011         /* If the endpoint is bound to 0.0.0.0 or ::0, count the valid
4012          * addresses from the global local address list.
4013          */
4014         if (sctp_list_single_entry(&bp->address_list)) {
4015                 addr = list_entry(bp->address_list.next,
4016                                   struct sctp_sockaddr_entry, list);
4017                 if (sctp_is_any(&addr->a)) {
4018                         list_for_each_safe(pos, temp, &sctp_local_addr_list) {
4019                                 addr = list_entry(pos,
4020                                                   struct sctp_sockaddr_entry,
4021                                                   list);
4022                                 if ((PF_INET == sk->sk_family) &&
4023                                     (AF_INET6 == addr->a.sa.sa_family))
4024                                         continue;
4025                                 cnt++;
4026                         }
4027                 } else {
4028                         cnt = 1;
4029                 }
4030                 goto done;
4031         }
4032
4033         list_for_each(pos, &bp->address_list) {
4034                 cnt ++;
4035         }
4036
4037 done:
4038         sctp_read_unlock(addr_lock);
4039         return cnt;
4040 }
4041
4042 /* Helper function that copies local addresses to user and returns the number
4043  * of addresses copied.
4044  */
4045 static int sctp_copy_laddrs_to_user_old(struct sock *sk, __u16 port, int max_addrs,
4046                                         void __user *to)
4047 {
4048         struct list_head *pos, *next;
4049         struct sctp_sockaddr_entry *addr;
4050         union sctp_addr temp;
4051         int cnt = 0;
4052         int addrlen;
4053
4054         list_for_each_safe(pos, next, &sctp_local_addr_list) {
4055                 addr = list_entry(pos, struct sctp_sockaddr_entry, list);
4056                 if ((PF_INET == sk->sk_family) &&
4057                     (AF_INET6 == addr->a.sa.sa_family))
4058                         continue;
4059                 memcpy(&temp, &addr->a, sizeof(temp));
4060                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
4061                                                                 &temp);
4062                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
4063                 if (copy_to_user(to, &temp, addrlen))
4064                         return -EFAULT;
4065
4066                 to += addrlen;
4067                 cnt ++;
4068                 if (cnt >= max_addrs) break;
4069         }
4070
4071         return cnt;
4072 }
4073
4074 static int sctp_copy_laddrs_to_user(struct sock *sk, __u16 port,
4075                                     void __user **to, size_t space_left)
4076 {
4077         struct list_head *pos, *next;
4078         struct sctp_sockaddr_entry *addr;
4079         union sctp_addr temp;
4080         int cnt = 0;
4081         int addrlen;
4082
4083         list_for_each_safe(pos, next, &sctp_local_addr_list) {
4084                 addr = list_entry(pos, struct sctp_sockaddr_entry, list);
4085                 if ((PF_INET == sk->sk_family) &&
4086                     (AF_INET6 == addr->a.sa.sa_family))
4087                         continue;
4088                 memcpy(&temp, &addr->a, sizeof(temp));
4089                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
4090                                                                 &temp);
4091                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
4092                 if(space_left<addrlen)
4093                         return -ENOMEM;
4094                 if (copy_to_user(*to, &temp, addrlen))
4095                         return -EFAULT;
4096
4097                 *to += addrlen;
4098                 cnt ++;
4099                 space_left -= addrlen;
4100         }
4101
4102         return cnt;
4103 }
4104
4105 /* Old API for getting list of local addresses. Does not work for 32-bit
4106  * programs running on a 64-bit kernel
4107  */
4108 static int sctp_getsockopt_local_addrs_old(struct sock *sk, int len,
4109                                            char __user *optval, int __user *optlen)
4110 {
4111         struct sctp_bind_addr *bp;
4112         struct sctp_association *asoc;
4113         struct list_head *pos;
4114         int cnt = 0;
4115         struct sctp_getaddrs_old getaddrs;
4116         struct sctp_sockaddr_entry *addr;
4117         void __user *to;
4118         union sctp_addr temp;
4119         struct sctp_sock *sp = sctp_sk(sk);
4120         int addrlen;
4121         rwlock_t *addr_lock;
4122         int err = 0;
4123
4124         if (len != sizeof(struct sctp_getaddrs_old))
4125                 return -EINVAL;
4126
4127         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs_old)))
4128                 return -EFAULT;
4129
4130         if (getaddrs.addr_num <= 0) return -EINVAL;
4131         /*
4132          *  For UDP-style sockets, id specifies the association to query.
4133          *  If the id field is set to the value '0' then the locally bound
4134          *  addresses are returned without regard to any particular
4135          *  association.
4136          */
4137         if (0 == getaddrs.assoc_id) {
4138                 bp = &sctp_sk(sk)->ep->base.bind_addr;
4139                 addr_lock = &sctp_sk(sk)->ep->base.addr_lock;
4140         } else {
4141                 asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
4142                 if (!asoc)
4143                         return -EINVAL;
4144                 bp = &asoc->base.bind_addr;
4145                 addr_lock = &asoc->base.addr_lock;
4146         }
4147
4148         to = getaddrs.addrs;
4149
4150         sctp_read_lock(addr_lock);
4151
4152         /* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
4153          * addresses from the global local address list.
4154          */
4155         if (sctp_list_single_entry(&bp->address_list)) {
4156                 addr = list_entry(bp->address_list.next,
4157                                   struct sctp_sockaddr_entry, list);
4158                 if (sctp_is_any(&addr->a)) {
4159                         cnt = sctp_copy_laddrs_to_user_old(sk, bp->port,
4160                                                            getaddrs.addr_num,
4161                                                            to);
4162                         if (cnt < 0) {
4163                                 err = cnt;
4164                                 goto unlock;
4165                         }
4166                         goto copy_getaddrs;
4167                 }
4168         }
4169
4170         list_for_each(pos, &bp->address_list) {
4171                 addr = list_entry(pos, struct sctp_sockaddr_entry, list);
4172                 memcpy(&temp, &addr->a, sizeof(temp));
4173                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
4174                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
4175                 if (copy_to_user(to, &temp, addrlen)) {
4176                         err = -EFAULT;
4177                         goto unlock;
4178                 }
4179                 to += addrlen;
4180                 cnt ++;
4181                 if (cnt >= getaddrs.addr_num) break;
4182         }
4183
4184 copy_getaddrs:
4185         getaddrs.addr_num = cnt;
4186         if (copy_to_user(optval, &getaddrs, sizeof(struct sctp_getaddrs_old)))
4187                 err = -EFAULT;
4188
4189 unlock:
4190         sctp_read_unlock(addr_lock);
4191         return err;
4192 }
4193
4194 static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
4195                                        char __user *optval, int __user *optlen)
4196 {
4197         struct sctp_bind_addr *bp;
4198         struct sctp_association *asoc;
4199         struct list_head *pos;
4200         int cnt = 0;
4201         struct sctp_getaddrs getaddrs;
4202         struct sctp_sockaddr_entry *addr;
4203         void __user *to;
4204         union sctp_addr temp;
4205         struct sctp_sock *sp = sctp_sk(sk);
4206         int addrlen;
4207         rwlock_t *addr_lock;
4208         int err = 0;
4209         size_t space_left;
4210         int bytes_copied;
4211
4212         if (len <= sizeof(struct sctp_getaddrs))
4213                 return -EINVAL;
4214
4215         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
4216                 return -EFAULT;
4217
4218         /*
4219          *  For UDP-style sockets, id specifies the association to query.
4220          *  If the id field is set to the value '0' then the locally bound
4221          *  addresses are returned without regard to any particular
4222          *  association.
4223          */
4224         if (0 == getaddrs.assoc_id) {
4225                 bp = &sctp_sk(sk)->ep->base.bind_addr;
4226                 addr_lock = &sctp_sk(sk)->ep->base.addr_lock;
4227         } else {
4228                 asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
4229                 if (!asoc)
4230                         return -EINVAL;
4231                 bp = &asoc->base.bind_addr;
4232                 addr_lock = &asoc->base.addr_lock;
4233         }
4234
4235         to = optval + offsetof(struct sctp_getaddrs,addrs);
4236         space_left = len - sizeof(struct sctp_getaddrs) -
4237                          offsetof(struct sctp_getaddrs,addrs);
4238
4239         sctp_read_lock(addr_lock);
4240
4241         /* If the endpoint is bound to 0.0.0.0 or ::0, get the valid
4242          * addresses from the global local address list.
4243          */
4244         if (sctp_list_single_entry(&bp->address_list)) {
4245                 addr = list_entry(bp->address_list.next,
4246                                   struct sctp_sockaddr_entry, list);
4247                 if (sctp_is_any(&addr->a)) {
4248                         cnt = sctp_copy_laddrs_to_user(sk, bp->port,
4249                                                        &to, space_left);
4250                         if (cnt < 0) {
4251                                 err = cnt;
4252                                 goto unlock;
4253                         }
4254                         goto copy_getaddrs;
4255                 }
4256         }
4257
4258         list_for_each(pos, &bp->address_list) {
4259                 addr = list_entry(pos, struct sctp_sockaddr_entry, list);
4260                 memcpy(&temp, &addr->a, sizeof(temp));
4261                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
4262                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
4263                 if(space_left < addrlen)
4264                         return -ENOMEM; /*fixme: right error?*/
4265                 if (copy_to_user(to, &temp, addrlen)) {
4266                         err = -EFAULT;
4267                         goto unlock;
4268                 }
4269                 to += addrlen;
4270                 cnt ++;
4271                 space_left -= addrlen;
4272         }
4273
4274 copy_getaddrs:
4275         if (put_user(cnt, &((struct sctp_getaddrs __user *)optval)->addr_num))
4276                 return -EFAULT;
4277         bytes_copied = ((char __user *)to) - optval;
4278         if (put_user(bytes_copied, optlen))
4279                 return -EFAULT;
4280
4281 unlock:
4282         sctp_read_unlock(addr_lock);
4283         return err;
4284 }
4285
4286 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
4287  *
4288  * Requests that the local SCTP stack use the enclosed peer address as
4289  * the association primary.  The enclosed address must be one of the
4290  * association peer's addresses.
4291  */
4292 static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
4293                                         char __user *optval, int __user *optlen)
4294 {
4295         struct sctp_prim prim;
4296         struct sctp_association *asoc;
4297         struct sctp_sock *sp = sctp_sk(sk);
4298
4299         if (len != sizeof(struct sctp_prim))
4300                 return -EINVAL;
4301
4302         if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
4303                 return -EFAULT;
4304
4305         asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
4306         if (!asoc)
4307                 return -EINVAL;
4308
4309         if (!asoc->peer.primary_path)
4310                 return -ENOTCONN;
4311
4312         memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
4313                 asoc->peer.primary_path->af_specific->sockaddr_len);
4314
4315         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp,
4316                         (union sctp_addr *)&prim.ssp_addr);
4317
4318         if (copy_to_user(optval, &prim, sizeof(struct sctp_prim)))
4319                 return -EFAULT;
4320
4321         return 0;
4322 }
4323
4324 /*
4325  * 7.1.11  Set Adaptation Layer Indicator (SCTP_ADAPTATION_LAYER)
4326  *
4327  * Requests that the local endpoint set the specified Adaptation Layer
4328  * Indication parameter for all future INIT and INIT-ACK exchanges.
4329  */
4330 static int sctp_getsockopt_adaptation_layer(struct sock *sk, int len,
4331                                   char __user *optval, int __user *optlen)
4332 {
4333         struct sctp_setadaptation adaptation;
4334
4335         if (len != sizeof(struct sctp_setadaptation))
4336                 return -EINVAL;
4337
4338         adaptation.ssb_adaptation_ind = sctp_sk(sk)->adaptation_ind;
4339         if (copy_to_user(optval, &adaptation, len))
4340                 return -EFAULT;
4341
4342         return 0;
4343 }
4344
4345 /*
4346  *
4347  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
4348  *
4349  *   Applications that wish to use the sendto() system call may wish to
4350  *   specify a default set of parameters that would normally be supplied
4351  *   through the inclusion of ancillary data.  This socket option allows
4352  *   such an application to set the default sctp_sndrcvinfo structure.
4353
4354
4355  *   The application that wishes to use this socket option simply passes
4356  *   in to this call the sctp_sndrcvinfo structure defined in Section
4357  *   5.2.2) The input parameters accepted by this call include
4358  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
4359  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
4360  *   to this call if the caller is using the UDP model.
4361  *
4362  *   For getsockopt, it get the default sctp_sndrcvinfo structure.
4363  */
4364 static int sctp_getsockopt_default_send_param(struct sock *sk,
4365                                         int len, char __user *optval,
4366                                         int __user *optlen)
4367 {
4368         struct sctp_sndrcvinfo info;
4369         struct sctp_association *asoc;
4370         struct sctp_sock *sp = sctp_sk(sk);
4371
4372         if (len != sizeof(struct sctp_sndrcvinfo))
4373                 return -EINVAL;
4374         if (copy_from_user(&info, optval, sizeof(struct sctp_sndrcvinfo)))
4375                 return -EFAULT;
4376
4377         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
4378         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
4379                 return -EINVAL;
4380
4381         if (asoc) {
4382                 info.sinfo_stream = asoc->default_stream;
4383                 info.sinfo_flags = asoc->default_flags;
4384                 info.sinfo_ppid = asoc->default_ppid;
4385                 info.sinfo_context = asoc->default_context;
4386                 info.sinfo_timetolive = asoc->default_timetolive;
4387         } else {
4388                 info.sinfo_stream = sp->default_stream;
4389                 info.sinfo_flags = sp->default_flags;
4390                 info.sinfo_ppid = sp->default_ppid;
4391                 info.sinfo_context = sp->default_context;
4392                 info.sinfo_timetolive = sp->default_timetolive;
4393         }
4394
4395         if (copy_to_user(optval, &info, sizeof(struct sctp_sndrcvinfo)))
4396                 return -EFAULT;
4397
4398         return 0;
4399 }
4400
4401 /*
4402  *
4403  * 7.1.5 SCTP_NODELAY
4404  *
4405  * Turn on/off any Nagle-like algorithm.  This means that packets are
4406  * generally sent as soon as possible and no unnecessary delays are
4407  * introduced, at the cost of more packets in the network.  Expects an
4408  * integer boolean flag.
4409  */
4410
4411 static int sctp_getsockopt_nodelay(struct sock *sk, int len,
4412                                    char __user *optval, int __user *optlen)
4413 {
4414         int val;
4415
4416         if (len < sizeof(int))
4417                 return -EINVAL;
4418
4419         len = sizeof(int);
4420         val = (sctp_sk(sk)->nodelay == 1);
4421         if (put_user(len, optlen))
4422                 return -EFAULT;
4423         if (copy_to_user(optval, &val, len))
4424                 return -EFAULT;
4425         return 0;
4426 }
4427
4428 /*
4429  *
4430  * 7.1.1 SCTP_RTOINFO
4431  *
4432  * The protocol parameters used to initialize and bound retransmission
4433  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
4434  * and modify these parameters.
4435  * All parameters are time values, in milliseconds.  A value of 0, when
4436  * modifying the parameters, indicates that the current value should not
4437  * be changed.
4438  *
4439  */
4440 static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
4441                                 char __user *optval,
4442                                 int __user *optlen) {
4443         struct sctp_rtoinfo rtoinfo;
4444         struct sctp_association *asoc;
4445
4446         if (len != sizeof (struct sctp_rtoinfo))
4447                 return -EINVAL;
4448
4449         if (copy_from_user(&rtoinfo, optval, sizeof (struct sctp_rtoinfo)))
4450                 return -EFAULT;
4451
4452         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
4453
4454         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
4455                 return -EINVAL;
4456
4457         /* Values corresponding to the specific association. */
4458         if (asoc) {
4459                 rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
4460                 rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
4461                 rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
4462         } else {
4463                 /* Values corresponding to the endpoint. */
4464                 struct sctp_sock *sp = sctp_sk(sk);
4465
4466                 rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
4467                 rtoinfo.srto_max = sp->rtoinfo.srto_max;
4468                 rtoinfo.srto_min = sp->rtoinfo.srto_min;
4469         }
4470
4471         if (put_user(len, optlen))
4472                 return -EFAULT;
4473
4474         if (copy_to_user(optval, &rtoinfo, len))
4475                 return -EFAULT;
4476
4477         return 0;
4478 }
4479
4480 /*
4481  *
4482  * 7.1.2 SCTP_ASSOCINFO
4483  *
4484  * This option is used to tune the the maximum retransmission attempts
4485  * of the association.
4486  * Returns an error if the new association retransmission value is
4487  * greater than the sum of the retransmission value  of the peer.
4488  * See [SCTP] for more information.
4489  *
4490  */
4491 static int sctp_getsockopt_associnfo(struct sock *sk, int len,
4492                                      char __user *optval,
4493                                      int __user *optlen)
4494 {
4495
4496         struct sctp_assocparams assocparams;
4497         struct sctp_association *asoc;
4498         struct list_head *pos;
4499         int cnt = 0;
4500
4501         if (len != sizeof (struct sctp_assocparams))
4502                 return -EINVAL;
4503
4504         if (copy_from_user(&assocparams, optval,
4505                         sizeof (struct sctp_assocparams)))
4506                 return -EFAULT;
4507
4508         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
4509
4510         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
4511                 return -EINVAL;
4512
4513         /* Values correspoinding to the specific association */
4514         if (asoc) {
4515                 assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
4516                 assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
4517                 assocparams.sasoc_local_rwnd = asoc->a_rwnd;
4518                 assocparams.sasoc_cookie_life = (asoc->cookie_life.tv_sec
4519                                                 * 1000) +
4520                                                 (asoc->cookie_life.tv_usec
4521                                                 / 1000);
4522
4523                 list_for_each(pos, &asoc->peer.transport_addr_list) {
4524                         cnt ++;
4525                 }
4526
4527                 assocparams.sasoc_number_peer_destinations = cnt;
4528         } else {
4529                 /* Values corresponding to the endpoint */
4530                 struct sctp_sock *sp = sctp_sk(sk);
4531
4532                 assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
4533                 assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
4534                 assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
4535                 assocparams.sasoc_cookie_life =
4536                                         sp->assocparams.sasoc_cookie_life;
4537                 assocparams.sasoc_number_peer_destinations =
4538                                         sp->assocparams.
4539                                         sasoc_number_peer_destinations;
4540         }
4541
4542         if (put_user(len, optlen))
4543                 return -EFAULT;
4544
4545         if (copy_to_user(optval, &assocparams, len))
4546                 return -EFAULT;
4547
4548         return 0;
4549 }
4550
4551 /*
4552  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
4553  *
4554  * This socket option is a boolean flag which turns on or off mapped V4
4555  * addresses.  If this option is turned on and the socket is type
4556  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
4557  * If this option is turned off, then no mapping will be done of V4
4558  * addresses and a user will receive both PF_INET6 and PF_INET type
4559  * addresses on the socket.
4560  */
4561 static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
4562                                     char __user *optval, int __user *optlen)
4563 {
4564         int val;
4565         struct sctp_sock *sp = sctp_sk(sk);
4566
4567         if (len < sizeof(int))
4568                 return -EINVAL;
4569
4570         len = sizeof(int);
4571         val = sp->v4mapped;
4572         if (put_user(len, optlen))
4573                 return -EFAULT;
4574         if (copy_to_user(optval, &val, len))
4575                 return -EFAULT;
4576
4577         return 0;
4578 }
4579
4580 /*
4581  * 7.1.29.  Set or Get the default context (SCTP_CONTEXT)
4582  * (chapter and verse is quoted at sctp_setsockopt_context())
4583  */
4584 static int sctp_getsockopt_context(struct sock *sk, int len,
4585                                    char __user *optval, int __user *optlen)
4586 {
4587         struct sctp_assoc_value params;
4588         struct sctp_sock *sp;
4589         struct sctp_association *asoc;
4590
4591         if (len != sizeof(struct sctp_assoc_value))
4592                 return -EINVAL;
4593
4594         if (copy_from_user(&params, optval, len))
4595                 return -EFAULT;
4596
4597         sp = sctp_sk(sk);
4598
4599         if (params.assoc_id != 0) {
4600                 asoc = sctp_id2assoc(sk, params.assoc_id);
4601                 if (!asoc)
4602                         return -EINVAL;
4603                 params.assoc_value = asoc->default_rcv_context;
4604         } else {
4605                 params.assoc_value = sp->default_rcv_context;
4606         }
4607
4608         if (put_user(len, optlen))
4609                 return -EFAULT;
4610         if (copy_to_user(optval, &params, len))
4611                 return -EFAULT;
4612
4613         return 0;
4614 }
4615
4616 /*
4617  * 7.1.17 Set the maximum fragrmentation size (SCTP_MAXSEG)
4618  *
4619  * This socket option specifies the maximum size to put in any outgoing
4620  * SCTP chunk.  If a message is larger than this size it will be
4621  * fragmented by SCTP into the specified size.  Note that the underlying
4622  * SCTP implementation may fragment into smaller sized chunks when the
4623  * PMTU of the underlying association is smaller than the value set by
4624  * the user.
4625  */
4626 static int sctp_getsockopt_maxseg(struct sock *sk, int len,
4627                                   char __user *optval, int __user *optlen)
4628 {
4629         int val;
4630
4631         if (len < sizeof(int))
4632                 return -EINVAL;
4633
4634         len = sizeof(int);
4635
4636         val = sctp_sk(sk)->user_frag;
4637         if (put_user(len, optlen))
4638                 return -EFAULT;
4639         if (copy_to_user(optval, &val, len))
4640                 return -EFAULT;
4641
4642         return 0;
4643 }
4644
4645 /*
4646  * 7.1.24.  Get or set fragmented interleave (SCTP_FRAGMENT_INTERLEAVE)
4647  * (chapter and verse is quoted at sctp_setsockopt_fragment_interleave())
4648  */
4649 static int sctp_getsockopt_fragment_interleave(struct sock *sk, int len,
4650                                                char __user *optval, int __user *optlen)
4651 {
4652         int val;
4653
4654         if (len < sizeof(int))
4655                 return -EINVAL;
4656
4657         len = sizeof(int);
4658
4659         val = sctp_sk(sk)->frag_interleave;
4660         if (put_user(len, optlen))
4661                 return -EFAULT;
4662         if (copy_to_user(optval, &val, len))
4663                 return -EFAULT;
4664
4665         return 0;
4666 }
4667
4668 /*
4669  * 7.1.25.  Set or Get the sctp partial delivery point
4670  * (chapter and verse is quoted at sctp_setsockopt_partial_delivery_point())
4671  */
4672 static int sctp_getsockopt_partial_delivery_point(struct sock *sk, int len,
4673                                                   char __user *optval,
4674                                                   int __user *optlen)
4675 {
4676         u32 val;
4677
4678         if (len < sizeof(u32))
4679                 return -EINVAL;
4680
4681         len = sizeof(u32);
4682
4683         val = sctp_sk(sk)->pd_point;
4684         if (put_user(len, optlen))
4685                 return -EFAULT;
4686         if (copy_to_user(optval, &val, len))
4687                 return -EFAULT;
4688
4689         return -ENOTSUPP;
4690 }
4691
4692 SCTP_STATIC int sctp_getsockopt(struct sock *sk, int level, int optname,
4693                                 char __user *optval, int __user *optlen)
4694 {
4695         int retval = 0;
4696         int len;
4697
4698         SCTP_DEBUG_PRINTK("sctp_getsockopt(sk: %p... optname: %d)\n",
4699                           sk, optname);
4700
4701         /* I can hardly begin to describe how wrong this is.  This is
4702          * so broken as to be worse than useless.  The API draft
4703          * REALLY is NOT helpful here...  I am not convinced that the
4704          * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
4705          * are at all well-founded.
4706          */
4707         if (level != SOL_SCTP) {
4708                 struct sctp_af *af = sctp_sk(sk)->pf->af;
4709
4710                 retval = af->getsockopt(sk, level, optname, optval, optlen);
4711                 return retval;
4712         }
4713
4714         if (get_user(len, optlen))
4715                 return -EFAULT;
4716
4717         sctp_lock_sock(sk);
4718
4719         switch (optname) {
4720         case SCTP_STATUS:
4721                 retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
4722                 break;
4723         case SCTP_DISABLE_FRAGMENTS:
4724                 retval = sctp_getsockopt_disable_fragments(sk, len, optval,
4725                                                            optlen);
4726                 break;
4727         case SCTP_EVENTS:
4728                 retval = sctp_getsockopt_events(sk, len, optval, optlen);
4729                 break;
4730         case SCTP_AUTOCLOSE:
4731                 retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
4732                 break;
4733         case SCTP_SOCKOPT_PEELOFF:
4734                 retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
4735                 break;
4736         case SCTP_PEER_ADDR_PARAMS:
4737                 retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
4738                                                           optlen);
4739                 break;
4740         case SCTP_DELAYED_ACK_TIME:
4741                 retval = sctp_getsockopt_delayed_ack_time(sk, len, optval,
4742                                                           optlen);
4743                 break;
4744         case SCTP_INITMSG:
4745                 retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
4746                 break;
4747         case SCTP_GET_PEER_ADDRS_NUM_OLD:
4748                 retval = sctp_getsockopt_peer_addrs_num_old(sk, len, optval,
4749                                                             optlen);
4750                 break;
4751         case SCTP_GET_LOCAL_ADDRS_NUM_OLD:
4752                 retval = sctp_getsockopt_local_addrs_num_old(sk, len, optval,
4753                                                              optlen);
4754                 break;
4755         case SCTP_GET_PEER_ADDRS_OLD:
4756                 retval = sctp_getsockopt_peer_addrs_old(sk, len, optval,
4757                                                         optlen);
4758                 break;
4759         case SCTP_GET_LOCAL_ADDRS_OLD:
4760                 retval = sctp_getsockopt_local_addrs_old(sk, len, optval,
4761                                                          optlen);
4762                 break;
4763         case SCTP_GET_PEER_ADDRS:
4764                 retval = sctp_getsockopt_peer_addrs(sk, len, optval,
4765                                                     optlen);
4766                 break;
4767         case SCTP_GET_LOCAL_ADDRS:
4768                 retval = sctp_getsockopt_local_addrs(sk, len, optval,
4769                                                      optlen);
4770                 break;
4771         case SCTP_DEFAULT_SEND_PARAM:
4772                 retval = sctp_getsockopt_default_send_param(sk, len,
4773                                                             optval, optlen);
4774                 break;
4775         case SCTP_PRIMARY_ADDR:
4776                 retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
4777                 break;
4778         case SCTP_NODELAY:
4779                 retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
4780                 break;
4781         case SCTP_RTOINFO:
4782                 retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
4783                 break;
4784         case SCTP_ASSOCINFO:
4785                 retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
4786                 break;
4787         case SCTP_I_WANT_MAPPED_V4_ADDR:
4788                 retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
4789                 break;
4790         case SCTP_MAXSEG:
4791                 retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
4792                 break;
4793         case SCTP_GET_PEER_ADDR_INFO:
4794                 retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
4795                                                         optlen);
4796                 break;
4797         case SCTP_ADAPTATION_LAYER:
4798                 retval = sctp_getsockopt_adaptation_layer(sk, len, optval,
4799                                                         optlen);
4800                 break;
4801         case SCTP_CONTEXT:
4802                 retval = sctp_getsockopt_context(sk, len, optval, optlen);
4803                 break;
4804         case SCTP_FRAGMENT_INTERLEAVE:
4805                 retval = sctp_getsockopt_fragment_interleave(sk, len, optval,
4806                                                              optlen);
4807                 break;
4808         case SCTP_PARTIAL_DELIVERY_POINT:
4809                 retval = sctp_getsockopt_partial_delivery_point(sk, len, optval,
4810                                                                 optlen);
4811                 break;
4812         default:
4813                 retval = -ENOPROTOOPT;
4814                 break;
4815         };
4816
4817         sctp_release_sock(sk);
4818         return retval;
4819 }
4820
4821 static void sctp_hash(struct sock *sk)
4822 {
4823         /* STUB */
4824 }
4825
4826 static void sctp_unhash(struct sock *sk)
4827 {
4828         /* STUB */
4829 }
4830
4831 /* Check if port is acceptable.  Possibly find first available port.
4832  *
4833  * The port hash table (contained in the 'global' SCTP protocol storage
4834  * returned by struct sctp_protocol *sctp_get_protocol()). The hash
4835  * table is an array of 4096 lists (sctp_bind_hashbucket). Each
4836  * list (the list number is the port number hashed out, so as you
4837  * would expect from a hash function, all the ports in a given list have
4838  * such a number that hashes out to the same list number; you were
4839  * expecting that, right?); so each list has a set of ports, with a
4840  * link to the socket (struct sock) that uses it, the port number and
4841  * a fastreuse flag (FIXME: NPI ipg).
4842  */
4843 static struct sctp_bind_bucket *sctp_bucket_create(
4844         struct sctp_bind_hashbucket *head, unsigned short snum);
4845
4846 static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
4847 {
4848         struct sctp_bind_hashbucket *head; /* hash list */
4849         struct sctp_bind_bucket *pp; /* hash list port iterator */
4850         unsigned short snum;
4851         int ret;
4852
4853         snum = ntohs(addr->v4.sin_port);
4854
4855         SCTP_DEBUG_PRINTK("sctp_get_port() begins, snum=%d\n", snum);
4856         sctp_local_bh_disable();
4857
4858         if (snum == 0) {
4859                 /* Search for an available port.
4860                  *
4861                  * 'sctp_port_rover' was the last port assigned, so
4862                  * we start to search from 'sctp_port_rover +
4863                  * 1'. What we do is first check if port 'rover' is
4864                  * already in the hash table; if not, we use that; if
4865                  * it is, we try next.
4866                  */
4867                 int low = sysctl_local_port_range[0];
4868                 int high = sysctl_local_port_range[1];
4869                 int remaining = (high - low) + 1;
4870                 int rover;
4871                 int index;
4872
4873                 sctp_spin_lock(&sctp_port_alloc_lock);
4874                 rover = sctp_port_rover;
4875                 do {
4876                         rover++;
4877                         if ((rover < low) || (rover > high))
4878                                 rover = low;
4879                         index = sctp_phashfn(rover);
4880                         head = &sctp_port_hashtable[index];
4881                         sctp_spin_lock(&head->lock);
4882                         for (pp = head->chain; pp; pp = pp->next)
4883                                 if (pp->port == rover)
4884                                         goto next;
4885                         break;
4886                 next:
4887                         sctp_spin_unlock(&head->lock);
4888                 } while (--remaining > 0);
4889                 sctp_port_rover = rover;
4890                 sctp_spin_unlock(&sctp_port_alloc_lock);
4891
4892                 /* Exhausted local port range during search? */
4893                 ret = 1;
4894                 if (remaining <= 0)
4895                         goto fail;
4896
4897                 /* OK, here is the one we will use.  HEAD (the port
4898                  * hash table list entry) is non-NULL and we hold it's
4899                  * mutex.
4900                  */
4901                 snum = rover;
4902         } else {
4903                 /* We are given an specific port number; we verify
4904                  * that it is not being used. If it is used, we will
4905                  * exahust the search in the hash list corresponding
4906                  * to the port number (snum) - we detect that with the
4907                  * port iterator, pp being NULL.
4908                  */
4909                 head = &sctp_port_hashtable[sctp_phashfn(snum)];
4910                 sctp_spin_lock(&head->lock);
4911                 for (pp = head->chain; pp; pp = pp->next) {
4912                         if (pp->port == snum)
4913                                 goto pp_found;
4914                 }
4915         }
4916         pp = NULL;
4917         goto pp_not_found;
4918 pp_found:
4919         if (!hlist_empty(&pp->owner)) {
4920                 /* We had a port hash table hit - there is an
4921                  * available port (pp != NULL) and it is being
4922                  * used by other socket (pp->owner not empty); that other
4923                  * socket is going to be sk2.
4924                  */
4925                 int reuse = sk->sk_reuse;
4926                 struct sock *sk2;
4927                 struct hlist_node *node;
4928
4929                 SCTP_DEBUG_PRINTK("sctp_get_port() found a possible match\n");
4930                 if (pp->fastreuse && sk->sk_reuse)
4931                         goto success;
4932
4933                 /* Run through the list of sockets bound to the port
4934                  * (pp->port) [via the pointers bind_next and
4935                  * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
4936                  * we get the endpoint they describe and run through
4937                  * the endpoint's list of IP (v4 or v6) addresses,
4938                  * comparing each of the addresses with the address of
4939                  * the socket sk. If we find a match, then that means
4940                  * that this port/socket (sk) combination are already
4941                  * in an endpoint.
4942                  */
4943                 sk_for_each_bound(sk2, node, &pp->owner) {
4944                         struct sctp_endpoint *ep2;
4945                         ep2 = sctp_sk(sk2)->ep;
4946
4947                         if (reuse && sk2->sk_reuse)
4948                                 continue;
4949
4950                         if (sctp_bind_addr_match(&ep2->base.bind_addr, addr,
4951                                                  sctp_sk(sk))) {
4952                                 ret = (long)sk2;
4953                                 goto fail_unlock;
4954                         }
4955                 }
4956                 SCTP_DEBUG_PRINTK("sctp_get_port(): Found a match\n");
4957         }
4958 pp_not_found:
4959         /* If there was a hash table miss, create a new port.  */
4960         ret = 1;
4961         if (!pp && !(pp = sctp_bucket_create(head, snum)))
4962                 goto fail_unlock;
4963
4964         /* In either case (hit or miss), make sure fastreuse is 1 only
4965          * if sk->sk_reuse is too (that is, if the caller requested
4966          * SO_REUSEADDR on this socket -sk-).
4967          */
4968         if (hlist_empty(&pp->owner))
4969                 pp->fastreuse = sk->sk_reuse ? 1 : 0;
4970         else if (pp->fastreuse && !sk->sk_reuse)
4971                 pp->fastreuse = 0;
4972
4973         /* We are set, so fill up all the data in the hash table
4974          * entry, tie the socket list information with the rest of the
4975          * sockets FIXME: Blurry, NPI (ipg).
4976          */
4977 success:
4978         inet_sk(sk)->num = snum;
4979         if (!sctp_sk(sk)->bind_hash) {
4980                 sk_add_bind_node(sk, &pp->owner);
4981                 sctp_sk(sk)->bind_hash = pp;
4982         }
4983         ret = 0;
4984
4985 fail_unlock:
4986         sctp_spin_unlock(&head->lock);
4987
4988 fail:
4989         sctp_local_bh_enable();
4990         return ret;
4991 }
4992
4993 /* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
4994  * port is requested.
4995  */
4996 static int sctp_get_port(struct sock *sk, unsigned short snum)
4997 {
4998         long ret;
4999         union sctp_addr addr;
5000         struct sctp_af *af = sctp_sk(sk)->pf->af;
5001
5002         /* Set up a dummy address struct from the sk. */
5003         af->from_sk(&addr, sk);
5004         addr.v4.sin_port = htons(snum);
5005
5006         /* Note: sk->sk_num gets filled in if ephemeral port request. */
5007         ret = sctp_get_port_local(sk, &addr);
5008
5009         return (ret ? 1 : 0);
5010 }
5011
5012 /*
5013  * 3.1.3 listen() - UDP Style Syntax
5014  *
5015  *   By default, new associations are not accepted for UDP style sockets.
5016  *   An application uses listen() to mark a socket as being able to
5017  *   accept new associations.
5018  */
5019 SCTP_STATIC int sctp_seqpacket_listen(struct sock *sk, int backlog)
5020 {
5021         struct sctp_sock *sp = sctp_sk(sk);
5022         struct sctp_endpoint *ep = sp->ep;
5023
5024         /* Only UDP style sockets that are not peeled off are allowed to
5025          * listen().
5026          */
5027         if (!sctp_style(sk, UDP))
5028                 return -EINVAL;
5029
5030         /* If backlog is zero, disable listening. */
5031         if (!backlog) {
5032                 if (sctp_sstate(sk, CLOSED))
5033                         return 0;
5034
5035                 sctp_unhash_endpoint(ep);
5036                 sk->sk_state = SCTP_SS_CLOSED;
5037         }
5038
5039         /* Return if we are already listening. */
5040         if (sctp_sstate(sk, LISTENING))
5041                 return 0;
5042
5043         /*
5044          * If a bind() or sctp_bindx() is not called prior to a listen()
5045          * call that allows new associations to be accepted, the system
5046          * picks an ephemeral port and will choose an address set equivalent
5047          * to binding with a wildcard address.
5048          *
5049          * This is not currently spelled out in the SCTP sockets
5050          * extensions draft, but follows the practice as seen in TCP
5051          * sockets.
5052          */
5053         if (!ep->base.bind_addr.port) {
5054                 if (sctp_autobind(sk))
5055                         return -EAGAIN;
5056         }
5057         sk->sk_state = SCTP_SS_LISTENING;
5058         sctp_hash_endpoint(ep);
5059         return 0;
5060 }
5061
5062 /*
5063  * 4.1.3 listen() - TCP Style Syntax
5064  *
5065  *   Applications uses listen() to ready the SCTP endpoint for accepting
5066  *   inbound associations.
5067  */
5068 SCTP_STATIC int sctp_stream_listen(struct sock *sk, int backlog)
5069 {
5070         struct sctp_sock *sp = sctp_sk(sk);
5071         struct sctp_endpoint *ep = sp->ep;
5072
5073         /* If backlog is zero, disable listening. */
5074         if (!backlog) {
5075                 if (sctp_sstate(sk, CLOSED))
5076                         return 0;
5077
5078                 sctp_unhash_endpoint(ep);
5079                 sk->sk_state = SCTP_SS_CLOSED;
5080         }
5081
5082         if (sctp_sstate(sk, LISTENING))
5083                 return 0;
5084
5085         /*
5086          * If a bind() or sctp_bindx() is not called prior to a listen()
5087          * call that allows new associations to be accepted, the system
5088          * picks an ephemeral port and will choose an address set equivalent
5089          * to binding with a wildcard address.
5090          *
5091          * This is not currently spelled out in the SCTP sockets
5092          * extensions draft, but follows the practice as seen in TCP
5093          * sockets.
5094          */
5095         if (!ep->base.bind_addr.port) {
5096                 if (sctp_autobind(sk))
5097                         return -EAGAIN;
5098         }
5099         sk->sk_state = SCTP_SS_LISTENING;
5100         sk->sk_max_ack_backlog = backlog;
5101         sctp_hash_endpoint(ep);
5102         return 0;
5103 }
5104
5105 /*
5106  *  Move a socket to LISTENING state.
5107  */
5108 int sctp_inet_listen(struct socket *sock, int backlog)
5109 {
5110         struct sock *sk = sock->sk;
5111         struct crypto_hash *tfm = NULL;
5112         int err = -EINVAL;
5113
5114         if (unlikely(backlog < 0))
5115                 goto out;
5116
5117         sctp_lock_sock(sk);
5118
5119         if (sock->state != SS_UNCONNECTED)
5120                 goto out;
5121
5122         /* Allocate HMAC for generating cookie. */
5123         if (sctp_hmac_alg) {
5124                 tfm = crypto_alloc_hash(sctp_hmac_alg, 0, CRYPTO_ALG_ASYNC);
5125                 if (!tfm) {
5126                         err = -ENOSYS;
5127                         goto out;
5128                 }
5129         }
5130
5131         switch (sock->type) {
5132         case SOCK_SEQPACKET:
5133                 err = sctp_seqpacket_listen(sk, backlog);
5134                 break;
5135         case SOCK_STREAM:
5136                 err = sctp_stream_listen(sk, backlog);
5137                 break;
5138         default:
5139                 break;
5140         };
5141         if (err)
5142                 goto cleanup;
5143
5144         /* Store away the transform reference. */
5145         sctp_sk(sk)->hmac = tfm;
5146 out:
5147         sctp_release_sock(sk);
5148         return err;
5149 cleanup:
5150         crypto_free_hash(tfm);
5151         goto out;
5152 }
5153
5154 /*
5155  * This function is done by modeling the current datagram_poll() and the
5156  * tcp_poll().  Note that, based on these implementations, we don't
5157  * lock the socket in this function, even though it seems that,
5158  * ideally, locking or some other mechanisms can be used to ensure
5159  * the integrity of the counters (sndbuf and wmem_alloc) used
5160  * in this place.  We assume that we don't need locks either until proven
5161  * otherwise.
5162  *
5163  * Another thing to note is that we include the Async I/O support
5164  * here, again, by modeling the current TCP/UDP code.  We don't have
5165  * a good way to test with it yet.
5166  */
5167 unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
5168 {
5169         struct sock *sk = sock->sk;
5170         struct sctp_sock *sp = sctp_sk(sk);
5171         unsigned int mask;
5172
5173         poll_wait(file, sk->sk_sleep, wait);
5174
5175         /* A TCP-style listening socket becomes readable when the accept queue
5176          * is not empty.
5177          */
5178         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
5179                 return (!list_empty(&sp->ep->asocs)) ?
5180                         (POLLIN | POLLRDNORM) : 0;
5181
5182         mask = 0;
5183
5184         /* Is there any exceptional events?  */
5185         if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
5186                 mask |= POLLERR;
5187         if (sk->sk_shutdown & RCV_SHUTDOWN)
5188                 mask |= POLLRDHUP;
5189         if (sk->sk_shutdown == SHUTDOWN_MASK)
5190                 mask |= POLLHUP;
5191
5192         /* Is it readable?  Reconsider this code with TCP-style support.  */
5193         if (!skb_queue_empty(&sk->sk_receive_queue) ||
5194             (sk->sk_shutdown & RCV_SHUTDOWN))
5195                 mask |= POLLIN | POLLRDNORM;
5196
5197         /* The association is either gone or not ready.  */
5198         if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
5199                 return mask;
5200
5201         /* Is it writable?  */
5202         if (sctp_writeable(sk)) {
5203                 mask |= POLLOUT | POLLWRNORM;
5204         } else {
5205                 set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
5206                 /*
5207                  * Since the socket is not locked, the buffer
5208                  * might be made available after the writeable check and
5209                  * before the bit is set.  This could cause a lost I/O
5210                  * signal.  tcp_poll() has a race breaker for this race
5211                  * condition.  Based on their implementation, we put
5212                  * in the following code to cover it as well.
5213                  */
5214                 if (sctp_writeable(sk))
5215                         mask |= POLLOUT | POLLWRNORM;
5216         }
5217         return mask;
5218 }
5219
5220 /********************************************************************
5221  * 2nd Level Abstractions
5222  ********************************************************************/
5223
5224 static struct sctp_bind_bucket *sctp_bucket_create(
5225         struct sctp_bind_hashbucket *head, unsigned short snum)
5226 {
5227         struct sctp_bind_bucket *pp;
5228
5229         pp = kmem_cache_alloc(sctp_bucket_cachep, GFP_ATOMIC);
5230         SCTP_DBG_OBJCNT_INC(bind_bucket);
5231         if (pp) {
5232                 pp->port = snum;
5233                 pp->fastreuse = 0;
5234                 INIT_HLIST_HEAD(&pp->owner);
5235                 if ((pp->next = head->chain) != NULL)
5236                         pp->next->pprev = &pp->next;
5237                 head->chain = pp;
5238                 pp->pprev = &head->chain;
5239         }
5240         return pp;
5241 }
5242
5243 /* Caller must hold hashbucket lock for this tb with local BH disabled */
5244 static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
5245 {
5246         if (pp && hlist_empty(&pp->owner)) {
5247                 if (pp->next)
5248                         pp->next->pprev = pp->pprev;
5249                 *(pp->pprev) = pp->next;
5250                 kmem_cache_free(sctp_bucket_cachep, pp);
5251                 SCTP_DBG_OBJCNT_DEC(bind_bucket);
5252         }
5253 }
5254
5255 /* Release this socket's reference to a local port.  */
5256 static inline void __sctp_put_port(struct sock *sk)
5257 {
5258         struct sctp_bind_hashbucket *head =
5259                 &sctp_port_hashtable[sctp_phashfn(inet_sk(sk)->num)];
5260         struct sctp_bind_bucket *pp;
5261
5262         sctp_spin_lock(&head->lock);
5263         pp = sctp_sk(sk)->bind_hash;
5264         __sk_del_bind_node(sk);
5265         sctp_sk(sk)->bind_hash = NULL;
5266         inet_sk(sk)->num = 0;
5267         sctp_bucket_destroy(pp);
5268         sctp_spin_unlock(&head->lock);
5269 }
5270
5271 void sctp_put_port(struct sock *sk)
5272 {
5273         sctp_local_bh_disable();
5274         __sctp_put_port(sk);
5275         sctp_local_bh_enable();
5276 }
5277
5278 /*
5279  * The system picks an ephemeral port and choose an address set equivalent
5280  * to binding with a wildcard address.
5281  * One of those addresses will be the primary address for the association.
5282  * This automatically enables the multihoming capability of SCTP.
5283  */
5284 static int sctp_autobind(struct sock *sk)
5285 {
5286         union sctp_addr autoaddr;
5287         struct sctp_af *af;
5288         __be16 port;
5289
5290         /* Initialize a local sockaddr structure to INADDR_ANY. */
5291         af = sctp_sk(sk)->pf->af;
5292
5293         port = htons(inet_sk(sk)->num);
5294         af->inaddr_any(&autoaddr, port);
5295
5296         return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
5297 }
5298
5299 /* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
5300  *
5301  * From RFC 2292
5302  * 4.2 The cmsghdr Structure *
5303  *
5304  * When ancillary data is sent or received, any number of ancillary data
5305  * objects can be specified by the msg_control and msg_controllen members of
5306  * the msghdr structure, because each object is preceded by
5307  * a cmsghdr structure defining the object's length (the cmsg_len member).
5308  * Historically Berkeley-derived implementations have passed only one object
5309  * at a time, but this API allows multiple objects to be
5310  * passed in a single call to sendmsg() or recvmsg(). The following example
5311  * shows two ancillary data objects in a control buffer.
5312  *
5313  *   |<--------------------------- msg_controllen -------------------------->|
5314  *   |                                                                       |
5315  *
5316  *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
5317  *
5318  *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
5319  *   |                                   |                                   |
5320  *
5321  *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
5322  *
5323  *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
5324  *   |                                |  |                                |  |
5325  *
5326  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
5327  *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
5328  *
5329  *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
5330  *
5331  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
5332  *    ^
5333  *    |
5334  *
5335  * msg_control
5336  * points here
5337  */
5338 SCTP_STATIC int sctp_msghdr_parse(const struct msghdr *msg,
5339                                   sctp_cmsgs_t *cmsgs)
5340 {
5341         struct cmsghdr *cmsg;
5342
5343         for (cmsg = CMSG_FIRSTHDR(msg);
5344              cmsg != NULL;
5345              cmsg = CMSG_NXTHDR((struct msghdr*)msg, cmsg)) {
5346                 if (!CMSG_OK(msg, cmsg))
5347                         return -EINVAL;
5348
5349                 /* Should we parse this header or ignore?  */
5350                 if (cmsg->cmsg_level != IPPROTO_SCTP)
5351                         continue;
5352
5353                 /* Strictly check lengths following example in SCM code.  */
5354                 switch (cmsg->cmsg_type) {
5355                 case SCTP_INIT:
5356                         /* SCTP Socket API Extension
5357                          * 5.2.1 SCTP Initiation Structure (SCTP_INIT)
5358                          *
5359                          * This cmsghdr structure provides information for
5360                          * initializing new SCTP associations with sendmsg().
5361                          * The SCTP_INITMSG socket option uses this same data
5362                          * structure.  This structure is not used for
5363                          * recvmsg().
5364                          *
5365                          * cmsg_level    cmsg_type      cmsg_data[]
5366                          * ------------  ------------   ----------------------
5367                          * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
5368                          */
5369                         if (cmsg->cmsg_len !=
5370                             CMSG_LEN(sizeof(struct sctp_initmsg)))
5371                                 return -EINVAL;
5372                         cmsgs->init = (struct sctp_initmsg *)CMSG_DATA(cmsg);
5373                         break;
5374
5375                 case SCTP_SNDRCV:
5376                         /* SCTP Socket API Extension
5377                          * 5.2.2 SCTP Header Information Structure(SCTP_SNDRCV)
5378                          *
5379                          * This cmsghdr structure specifies SCTP options for
5380                          * sendmsg() and describes SCTP header information
5381                          * about a received message through recvmsg().
5382                          *
5383                          * cmsg_level    cmsg_type      cmsg_data[]
5384                          * ------------  ------------   ----------------------
5385                          * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
5386                          */
5387                         if (cmsg->cmsg_len !=
5388                             CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
5389                                 return -EINVAL;
5390
5391                         cmsgs->info =
5392                                 (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
5393
5394                         /* Minimally, validate the sinfo_flags. */
5395                         if (cmsgs->info->sinfo_flags &
5396                             ~(SCTP_UNORDERED | SCTP_ADDR_OVER |
5397                               SCTP_ABORT | SCTP_EOF))
5398                                 return -EINVAL;
5399                         break;
5400
5401                 default:
5402                         return -EINVAL;
5403                 };
5404         }
5405         return 0;
5406 }
5407
5408 /*
5409  * Wait for a packet..
5410  * Note: This function is the same function as in core/datagram.c
5411  * with a few modifications to make lksctp work.
5412  */
5413 static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p)
5414 {
5415         int error;
5416         DEFINE_WAIT(wait);
5417
5418         prepare_to_wait_exclusive(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
5419
5420         /* Socket errors? */
5421         error = sock_error(sk);
5422         if (error)
5423                 goto out;
5424
5425         if (!skb_queue_empty(&sk->sk_receive_queue))
5426                 goto ready;
5427
5428         /* Socket shut down?  */
5429         if (sk->sk_shutdown & RCV_SHUTDOWN)
5430                 goto out;
5431
5432         /* Sequenced packets can come disconnected.  If so we report the
5433          * problem.
5434          */
5435         error = -ENOTCONN;
5436
5437         /* Is there a good reason to think that we may receive some data?  */
5438         if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
5439                 goto out;
5440
5441         /* Handle signals.  */
5442         if (signal_pending(current))
5443                 goto interrupted;
5444
5445         /* Let another process have a go.  Since we are going to sleep
5446          * anyway.  Note: This may cause odd behaviors if the message
5447          * does not fit in the user's buffer, but this seems to be the
5448          * only way to honor MSG_DONTWAIT realistically.
5449          */
5450         sctp_release_sock(sk);
5451         *timeo_p = schedule_timeout(*timeo_p);
5452         sctp_lock_sock(sk);
5453
5454 ready:
5455         finish_wait(sk->sk_sleep, &wait);
5456         return 0;
5457
5458 interrupted:
5459         error = sock_intr_errno(*timeo_p);
5460
5461 out:
5462         finish_wait(sk->sk_sleep, &wait);
5463         *err = error;
5464         return error;
5465 }
5466
5467 /* Receive a datagram.
5468  * Note: This is pretty much the same routine as in core/datagram.c
5469  * with a few changes to make lksctp work.
5470  */
5471 static struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
5472                                               int noblock, int *err)
5473 {
5474         int error;
5475         struct sk_buff *skb;
5476         long timeo;
5477
5478         timeo = sock_rcvtimeo(sk, noblock);
5479
5480         SCTP_DEBUG_PRINTK("Timeout: timeo: %ld, MAX: %ld.\n",
5481                           timeo, MAX_SCHEDULE_TIMEOUT);
5482
5483         do {
5484                 /* Again only user level code calls this function,
5485                  * so nothing interrupt level
5486                  * will suddenly eat the receive_queue.
5487                  *
5488                  *  Look at current nfs client by the way...
5489                  *  However, this function was corrent in any case. 8)
5490                  */
5491                 if (flags & MSG_PEEK) {
5492                         spin_lock_bh(&sk->sk_receive_queue.lock);
5493                         skb = skb_peek(&sk->sk_receive_queue);
5494                         if (skb)
5495                                 atomic_inc(&skb->users);
5496                         spin_unlock_bh(&sk->sk_receive_queue.lock);
5497                 } else {
5498                         skb = skb_dequeue(&sk->sk_receive_queue);
5499                 }
5500
5501                 if (skb)
5502                         return skb;
5503
5504                 /* Caller is allowed not to check sk->sk_err before calling. */
5505                 error = sock_error(sk);
5506                 if (error)
5507                         goto no_packet;
5508
5509                 if (sk->sk_shutdown & RCV_SHUTDOWN)
5510                         break;
5511
5512                 /* User doesn't want to wait.  */
5513                 error = -EAGAIN;
5514                 if (!timeo)
5515                         goto no_packet;
5516         } while (sctp_wait_for_packet(sk, err, &timeo) == 0);
5517
5518         return NULL;
5519
5520 no_packet:
5521         *err = error;
5522         return NULL;
5523 }
5524
5525 /* If sndbuf has changed, wake up per association sndbuf waiters.  */
5526 static void __sctp_write_space(struct sctp_association *asoc)
5527 {
5528         struct sock *sk = asoc->base.sk;
5529         struct socket *sock = sk->sk_socket;
5530
5531         if ((sctp_wspace(asoc) > 0) && sock) {
5532                 if (waitqueue_active(&asoc->wait))
5533                         wake_up_interruptible(&asoc->wait);
5534
5535                 if (sctp_writeable(sk)) {
5536                         if (sk->sk_sleep && waitqueue_active(sk->sk_sleep))
5537                                 wake_up_interruptible(sk->sk_sleep);
5538
5539                         /* Note that we try to include the Async I/O support
5540                          * here by modeling from the current TCP/UDP code.
5541                          * We have not tested with it yet.
5542                          */
5543                         if (sock->fasync_list &&
5544                             !(sk->sk_shutdown & SEND_SHUTDOWN))
5545                                 sock_wake_async(sock, 2, POLL_OUT);
5546                 }
5547         }
5548 }
5549
5550 /* Do accounting for the sndbuf space.
5551  * Decrement the used sndbuf space of the corresponding association by the
5552  * data size which was just transmitted(freed).
5553  */
5554 static void sctp_wfree(struct sk_buff *skb)
5555 {
5556         struct sctp_association *asoc;
5557         struct sctp_chunk *chunk;
5558         struct sock *sk;
5559
5560         /* Get the saved chunk pointer.  */
5561         chunk = *((struct sctp_chunk **)(skb->cb));
5562         asoc = chunk->asoc;
5563         sk = asoc->base.sk;
5564         asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk) +
5565                                 sizeof(struct sk_buff) +
5566                                 sizeof(struct sctp_chunk);
5567
5568         atomic_sub(sizeof(struct sctp_chunk), &sk->sk_wmem_alloc);
5569
5570         sock_wfree(skb);
5571         __sctp_write_space(asoc);
5572
5573         sctp_association_put(asoc);
5574 }
5575
5576 /* Do accounting for the receive space on the socket.
5577  * Accounting for the association is done in ulpevent.c
5578  * We set this as a destructor for the cloned data skbs so that
5579  * accounting is done at the correct time.
5580  */
5581 void sctp_sock_rfree(struct sk_buff *skb)
5582 {
5583         struct sock *sk = skb->sk;
5584         struct sctp_ulpevent *event = sctp_skb2event(skb);
5585
5586         atomic_sub(event->rmem_len, &sk->sk_rmem_alloc);
5587 }
5588
5589
5590 /* Helper function to wait for space in the sndbuf.  */
5591 static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
5592                                 size_t msg_len)
5593 {
5594         struct sock *sk = asoc->base.sk;
5595         int err = 0;
5596         long current_timeo = *timeo_p;
5597         DEFINE_WAIT(wait);
5598
5599         SCTP_DEBUG_PRINTK("wait_for_sndbuf: asoc=%p, timeo=%ld, msg_len=%zu\n",
5600                           asoc, (long)(*timeo_p), msg_len);
5601
5602         /* Increment the association's refcnt.  */
5603         sctp_association_hold(asoc);
5604
5605         /* Wait on the association specific sndbuf space. */
5606         for (;;) {
5607                 prepare_to_wait_exclusive(&asoc->wait, &wait,
5608                                           TASK_INTERRUPTIBLE);
5609                 if (!*timeo_p)
5610                         goto do_nonblock;
5611                 if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
5612                     asoc->base.dead)
5613                         goto do_error;
5614                 if (signal_pending(current))
5615                         goto do_interrupted;
5616                 if (msg_len <= sctp_wspace(asoc))
5617                         break;
5618
5619                 /* Let another process have a go.  Since we are going
5620                  * to sleep anyway.
5621                  */
5622                 sctp_release_sock(sk);
5623                 current_timeo = schedule_timeout(current_timeo);
5624                 BUG_ON(sk != asoc->base.sk);
5625                 sctp_lock_sock(sk);
5626
5627                 *timeo_p = current_timeo;
5628         }
5629
5630 out:
5631         finish_wait(&asoc->wait, &wait);
5632
5633         /* Release the association's refcnt.  */
5634         sctp_association_put(asoc);
5635
5636         return err;
5637
5638 do_error:
5639         err = -EPIPE;
5640         goto out;
5641
5642 do_interrupted:
5643         err = sock_intr_errno(*timeo_p);
5644         goto out;
5645
5646 do_nonblock:
5647         err = -EAGAIN;
5648         goto out;
5649 }
5650
5651 /* If socket sndbuf has changed, wake up all per association waiters.  */
5652 void sctp_write_space(struct sock *sk)
5653 {
5654         struct sctp_association *asoc;
5655         struct list_head *pos;
5656
5657         /* Wake up the tasks in each wait queue.  */
5658         list_for_each(pos, &((sctp_sk(sk))->ep->asocs)) {
5659                 asoc = list_entry(pos, struct sctp_association, asocs);
5660                 __sctp_write_space(asoc);
5661         }
5662 }
5663
5664 /* Is there any sndbuf space available on the socket?
5665  *
5666  * Note that sk_wmem_alloc is the sum of the send buffers on all of the
5667  * associations on the same socket.  For a UDP-style socket with
5668  * multiple associations, it is possible for it to be "unwriteable"
5669  * prematurely.  I assume that this is acceptable because
5670  * a premature "unwriteable" is better than an accidental "writeable" which
5671  * would cause an unwanted block under certain circumstances.  For the 1-1
5672  * UDP-style sockets or TCP-style sockets, this code should work.
5673  *  - Daisy
5674  */
5675 static int sctp_writeable(struct sock *sk)
5676 {
5677         int amt = 0;
5678
5679         amt = sk->sk_sndbuf - atomic_read(&sk->sk_wmem_alloc);
5680         if (amt < 0)
5681                 amt = 0;
5682         return amt;
5683 }
5684
5685 /* Wait for an association to go into ESTABLISHED state. If timeout is 0,
5686  * returns immediately with EINPROGRESS.
5687  */
5688 static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
5689 {
5690         struct sock *sk = asoc->base.sk;
5691         int err = 0;
5692         long current_timeo = *timeo_p;
5693         DEFINE_WAIT(wait);
5694
5695         SCTP_DEBUG_PRINTK("%s: asoc=%p, timeo=%ld\n", __FUNCTION__, asoc,
5696                           (long)(*timeo_p));
5697
5698         /* Increment the association's refcnt.  */
5699         sctp_association_hold(asoc);
5700
5701         for (;;) {
5702                 prepare_to_wait_exclusive(&asoc->wait, &wait,
5703                                           TASK_INTERRUPTIBLE);
5704                 if (!*timeo_p)
5705                         goto do_nonblock;
5706                 if (sk->sk_shutdown & RCV_SHUTDOWN)
5707                         break;
5708                 if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
5709                     asoc->base.dead)
5710                         goto do_error;
5711                 if (signal_pending(current))
5712                         goto do_interrupted;
5713
5714                 if (sctp_state(asoc, ESTABLISHED))
5715                         break;
5716
5717                 /* Let another process have a go.  Since we are going
5718                  * to sleep anyway.
5719                  */
5720                 sctp_release_sock(sk);
5721                 current_timeo = schedule_timeout(current_timeo);
5722                 sctp_lock_sock(sk);
5723
5724                 *timeo_p = current_timeo;
5725         }
5726
5727 out:
5728         finish_wait(&asoc->wait, &wait);
5729
5730         /* Release the association's refcnt.  */
5731         sctp_association_put(asoc);
5732
5733         return err;
5734
5735 do_error:
5736         if (asoc->init_err_counter + 1 > asoc->max_init_attempts)
5737                 err = -ETIMEDOUT;
5738         else
5739                 err = -ECONNREFUSED;
5740         goto out;
5741
5742 do_interrupted:
5743         err = sock_intr_errno(*timeo_p);
5744         goto out;
5745
5746 do_nonblock:
5747         err = -EINPROGRESS;
5748         goto out;
5749 }
5750
5751 static int sctp_wait_for_accept(struct sock *sk, long timeo)
5752 {
5753         struct sctp_endpoint *ep;
5754         int err = 0;
5755         DEFINE_WAIT(wait);
5756
5757         ep = sctp_sk(sk)->ep;
5758
5759
5760         for (;;) {
5761                 prepare_to_wait_exclusive(sk->sk_sleep, &wait,
5762                                           TASK_INTERRUPTIBLE);
5763
5764                 if (list_empty(&ep->asocs)) {
5765                         sctp_release_sock(sk);
5766                         timeo = schedule_timeout(timeo);
5767                         sctp_lock_sock(sk);
5768                 }
5769
5770                 err = -EINVAL;
5771                 if (!sctp_sstate(sk, LISTENING))
5772                         break;
5773
5774                 err = 0;
5775                 if (!list_empty(&ep->asocs))
5776                         break;
5777
5778                 err = sock_intr_errno(timeo);
5779                 if (signal_pending(current))
5780                         break;
5781
5782                 err = -EAGAIN;
5783                 if (!timeo)
5784                         break;
5785         }
5786
5787         finish_wait(sk->sk_sleep, &wait);
5788
5789         return err;
5790 }
5791
5792 void sctp_wait_for_close(struct sock *sk, long timeout)
5793 {
5794         DEFINE_WAIT(wait);
5795
5796         do {
5797                 prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
5798                 if (list_empty(&sctp_sk(sk)->ep->asocs))
5799                         break;
5800                 sctp_release_sock(sk);
5801                 timeout = schedule_timeout(timeout);
5802                 sctp_lock_sock(sk);
5803         } while (!signal_pending(current) && timeout);
5804
5805         finish_wait(sk->sk_sleep, &wait);
5806 }
5807
5808 static void sctp_sock_rfree_frag(struct sk_buff *skb)
5809 {
5810         struct sk_buff *frag;
5811
5812         if (!skb->data_len)
5813                 goto done;
5814
5815         /* Don't forget the fragments. */
5816         for (frag = skb_shinfo(skb)->frag_list; frag; frag = frag->next)
5817                 sctp_sock_rfree_frag(frag);
5818
5819 done:
5820         sctp_sock_rfree(skb);
5821 }
5822
5823 static void sctp_skb_set_owner_r_frag(struct sk_buff *skb, struct sock *sk)
5824 {
5825         struct sk_buff *frag;
5826
5827         if (!skb->data_len)
5828                 goto done;
5829
5830         /* Don't forget the fragments. */
5831         for (frag = skb_shinfo(skb)->frag_list; frag; frag = frag->next)
5832                 sctp_skb_set_owner_r_frag(frag, sk);
5833
5834 done:
5835         sctp_skb_set_owner_r(skb, sk);
5836 }
5837
5838 /* Populate the fields of the newsk from the oldsk and migrate the assoc
5839  * and its messages to the newsk.
5840  */
5841 static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
5842                               struct sctp_association *assoc,
5843                               sctp_socket_type_t type)
5844 {
5845         struct sctp_sock *oldsp = sctp_sk(oldsk);
5846         struct sctp_sock *newsp = sctp_sk(newsk);
5847         struct sctp_bind_bucket *pp; /* hash list port iterator */
5848         struct sctp_endpoint *newep = newsp->ep;
5849         struct sk_buff *skb, *tmp;
5850         struct sctp_ulpevent *event;
5851         int flags = 0;
5852
5853         /* Migrate socket buffer sizes and all the socket level options to the
5854          * new socket.
5855          */
5856         newsk->sk_sndbuf = oldsk->sk_sndbuf;
5857         newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
5858         /* Brute force copy old sctp opt. */
5859         inet_sk_copy_descendant(newsk, oldsk);
5860
5861         /* Restore the ep value that was overwritten with the above structure
5862          * copy.
5863          */
5864         newsp->ep = newep;
5865         newsp->hmac = NULL;
5866
5867         /* Hook this new socket in to the bind_hash list. */
5868         pp = sctp_sk(oldsk)->bind_hash;
5869         sk_add_bind_node(newsk, &pp->owner);
5870         sctp_sk(newsk)->bind_hash = pp;
5871         inet_sk(newsk)->num = inet_sk(oldsk)->num;
5872
5873         /* Copy the bind_addr list from the original endpoint to the new
5874          * endpoint so that we can handle restarts properly
5875          */
5876         if (PF_INET6 == assoc->base.sk->sk_family)
5877                 flags = SCTP_ADDR6_ALLOWED;
5878         if (assoc->peer.ipv4_address)
5879                 flags |= SCTP_ADDR4_PEERSUPP;
5880         if (assoc->peer.ipv6_address)
5881                 flags |= SCTP_ADDR6_PEERSUPP;
5882         sctp_bind_addr_copy(&newsp->ep->base.bind_addr,
5883                              &oldsp->ep->base.bind_addr,
5884                              SCTP_SCOPE_GLOBAL, GFP_KERNEL, flags);
5885
5886         /* Move any messages in the old socket's receive queue that are for the
5887          * peeled off association to the new socket's receive queue.
5888          */
5889         sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
5890                 event = sctp_skb2event(skb);
5891                 if (event->asoc == assoc) {
5892                         sctp_sock_rfree_frag(skb);
5893                         __skb_unlink(skb, &oldsk->sk_receive_queue);
5894                         __skb_queue_tail(&newsk->sk_receive_queue, skb);
5895                         sctp_skb_set_owner_r_frag(skb, newsk);
5896                 }
5897         }
5898
5899         /* Clean up any messages pending delivery due to partial
5900          * delivery.   Three cases:
5901          * 1) No partial deliver;  no work.
5902          * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
5903          * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
5904          */
5905         skb_queue_head_init(&newsp->pd_lobby);
5906         atomic_set(&sctp_sk(newsk)->pd_mode, assoc->ulpq.pd_mode);
5907
5908         if (atomic_read(&sctp_sk(oldsk)->pd_mode)) {
5909                 struct sk_buff_head *queue;
5910
5911                 /* Decide which queue to move pd_lobby skbs to. */
5912                 if (assoc->ulpq.pd_mode) {
5913                         queue = &newsp->pd_lobby;
5914                 } else
5915                         queue = &newsk->sk_receive_queue;
5916
5917                 /* Walk through the pd_lobby, looking for skbs that
5918                  * need moved to the new socket.
5919                  */
5920                 sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
5921                         event = sctp_skb2event(skb);
5922                         if (event->asoc == assoc) {
5923                                 sctp_sock_rfree_frag(skb);
5924                                 __skb_unlink(skb, &oldsp->pd_lobby);
5925                                 __skb_queue_tail(queue, skb);
5926                                 sctp_skb_set_owner_r_frag(skb, newsk);
5927                         }
5928                 }
5929
5930                 /* Clear up any skbs waiting for the partial
5931                  * delivery to finish.
5932                  */
5933                 if (assoc->ulpq.pd_mode)
5934                         sctp_clear_pd(oldsk, NULL);
5935
5936         }
5937
5938         sctp_skb_for_each(skb, &assoc->ulpq.reasm, tmp) {
5939                 sctp_sock_rfree_frag(skb);
5940                 sctp_skb_set_owner_r_frag(skb, newsk);
5941         }
5942
5943         sctp_skb_for_each(skb, &assoc->ulpq.lobby, tmp) {
5944                 sctp_sock_rfree_frag(skb);
5945                 sctp_skb_set_owner_r_frag(skb, newsk);
5946         }
5947
5948         /* Set the type of socket to indicate that it is peeled off from the
5949          * original UDP-style socket or created with the accept() call on a
5950          * TCP-style socket..
5951          */
5952         newsp->type = type;
5953
5954         /* Mark the new socket "in-use" by the user so that any packets
5955          * that may arrive on the association after we've moved it are
5956          * queued to the backlog.  This prevents a potential race between
5957          * backlog processing on the old socket and new-packet processing
5958          * on the new socket.
5959          */
5960         sctp_lock_sock(newsk);
5961         sctp_assoc_migrate(assoc, newsk);
5962
5963         /* If the association on the newsk is already closed before accept()
5964          * is called, set RCV_SHUTDOWN flag.
5965          */
5966         if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
5967                 newsk->sk_shutdown |= RCV_SHUTDOWN;
5968
5969         newsk->sk_state = SCTP_SS_ESTABLISHED;
5970         sctp_release_sock(newsk);
5971 }
5972
5973 /* This proto struct describes the ULP interface for SCTP.  */
5974 struct proto sctp_prot = {
5975         .name        =  "SCTP",
5976         .owner       =  THIS_MODULE,
5977         .close       =  sctp_close,
5978         .connect     =  sctp_connect,
5979         .disconnect  =  sctp_disconnect,
5980         .accept      =  sctp_accept,
5981         .ioctl       =  sctp_ioctl,
5982         .init        =  sctp_init_sock,
5983         .destroy     =  sctp_destroy_sock,
5984         .shutdown    =  sctp_shutdown,
5985         .setsockopt  =  sctp_setsockopt,
5986         .getsockopt  =  sctp_getsockopt,
5987         .sendmsg     =  sctp_sendmsg,
5988         .recvmsg     =  sctp_recvmsg,
5989         .bind        =  sctp_bind,
5990         .backlog_rcv =  sctp_backlog_rcv,
5991         .hash        =  sctp_hash,
5992         .unhash      =  sctp_unhash,
5993         .get_port    =  sctp_get_port,
5994         .obj_size    =  sizeof(struct sctp_sock),
5995 };
5996
5997 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
5998 struct proto sctpv6_prot = {
5999         .name           = "SCTPv6",
6000         .owner          = THIS_MODULE,
6001         .close          = sctp_close,
6002         .connect        = sctp_connect,
6003         .disconnect     = sctp_disconnect,
6004         .accept         = sctp_accept,
6005         .ioctl          = sctp_ioctl,
6006         .init           = sctp_init_sock,
6007         .destroy        = sctp_destroy_sock,
6008         .shutdown       = sctp_shutdown,
6009         .setsockopt     = sctp_setsockopt,
6010         .getsockopt     = sctp_getsockopt,
6011         .sendmsg        = sctp_sendmsg,
6012         .recvmsg        = sctp_recvmsg,
6013         .bind           = sctp_bind,
6014         .backlog_rcv    = sctp_backlog_rcv,
6015         .hash           = sctp_hash,
6016         .unhash         = sctp_unhash,
6017         .get_port       = sctp_get_port,
6018         .obj_size       = sizeof(struct sctp6_sock),
6019 };
6020 #endif /* defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) */