upgrade to linux 2.6.10-1.12_FC2
[linux-2.6.git] / 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/config.h>
61 #include <linux/types.h>
62 #include <linux/kernel.h>
63 #include <linux/wait.h>
64 #include <linux/time.h>
65 #include <linux/ip.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_opt *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 kmem_cache_t *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         amt = sk->sk_sndbuf - asoc->sndbuf_used;
119         if (amt < 0)
120                 amt = 0;
121         return amt;
122 }
123
124 /* Increment the used sndbuf space count of the corresponding association by
125  * the size of the outgoing data chunk.
126  * Also, set the skb destructor for sndbuf accounting later.
127  *
128  * Since it is always 1-1 between chunk and skb, and also a new skb is always
129  * allocated for chunk bundling in sctp_packet_transmit(), we can use the
130  * destructor in the data chunk skb for the purpose of the sndbuf space
131  * tracking.
132  */
133 static inline void sctp_set_owner_w(struct sctp_chunk *chunk)
134 {
135         struct sctp_association *asoc = chunk->asoc;
136         struct sock *sk = asoc->base.sk;
137
138         /* The sndbuf space is tracked per association.  */
139         sctp_association_hold(asoc);
140
141         chunk->skb->destructor = sctp_wfree;
142         /* Save the chunk pointer in skb for sctp_wfree to use later.  */
143         *((struct sctp_chunk **)(chunk->skb->cb)) = chunk;
144
145         asoc->sndbuf_used += SCTP_DATA_SNDSIZE(chunk);
146         sk->sk_wmem_queued += SCTP_DATA_SNDSIZE(chunk);
147 }
148
149 /* Verify that this is a valid address. */
150 static inline int sctp_verify_addr(struct sock *sk, union sctp_addr *addr,
151                                    int len)
152 {
153         struct sctp_af *af;
154
155         /* Verify basic sockaddr. */
156         af = sctp_sockaddr_af(sctp_sk(sk), addr, len);
157         if (!af)
158                 return -EINVAL;
159
160         /* Is this a valid SCTP address?  */
161         if (!af->addr_valid(addr, sctp_sk(sk)))
162                 return -EINVAL;
163
164         if (!sctp_sk(sk)->pf->send_verify(sctp_sk(sk), (addr)))
165                 return -EINVAL;
166
167         return 0;
168 }
169
170 /* Look up the association by its id.  If this is not a UDP-style
171  * socket, the ID field is always ignored.
172  */
173 struct sctp_association *sctp_id2assoc(struct sock *sk, sctp_assoc_t id)
174 {
175         struct sctp_association *asoc = NULL;
176
177         /* If this is not a UDP-style socket, assoc id should be ignored. */
178         if (!sctp_style(sk, UDP)) {
179                 /* Return NULL if the socket state is not ESTABLISHED. It
180                  * could be a TCP-style listening socket or a socket which
181                  * hasn't yet called connect() to establish an association.
182                  */
183                 if (!sctp_sstate(sk, ESTABLISHED))
184                         return NULL;
185
186                 /* Get the first and the only association from the list. */
187                 if (!list_empty(&sctp_sk(sk)->ep->asocs))
188                         asoc = list_entry(sctp_sk(sk)->ep->asocs.next,
189                                           struct sctp_association, asocs);
190                 return asoc;
191         }
192
193         /* Otherwise this is a UDP-style socket. */
194         if (!id || (id == (sctp_assoc_t)-1))
195                 return NULL;
196
197         spin_lock_bh(&sctp_assocs_id_lock);
198         asoc = (struct sctp_association *)idr_find(&sctp_assocs_id, (int)id);
199         spin_unlock_bh(&sctp_assocs_id_lock);
200
201         if (!asoc || (asoc->base.sk != sk) || asoc->base.dead)
202                 return NULL;
203
204         return asoc;
205 }
206
207 /* Look up the transport from an address and an assoc id. If both address and
208  * id are specified, the associations matching the address and the id should be
209  * the same.
210  */
211 struct sctp_transport *sctp_addr_id2transport(struct sock *sk,
212                                               struct sockaddr_storage *addr,
213                                               sctp_assoc_t id)
214 {
215         struct sctp_association *addr_asoc = NULL, *id_asoc = NULL;
216         struct sctp_transport *transport;
217         union sctp_addr *laddr = (union sctp_addr *)addr;
218
219         laddr->v4.sin_port = ntohs(laddr->v4.sin_port);
220         addr_asoc = sctp_endpoint_lookup_assoc(sctp_sk(sk)->ep,
221                                                (union sctp_addr *)addr,
222                                                &transport);
223         laddr->v4.sin_port = htons(laddr->v4.sin_port);
224
225         if (!addr_asoc)
226                 return NULL;
227
228         id_asoc = sctp_id2assoc(sk, id);
229         if (id_asoc && (id_asoc != addr_asoc))
230                 return NULL;
231
232         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
233                                                 (union sctp_addr *)addr);
234
235         return transport;
236 }
237
238 /* API 3.1.2 bind() - UDP Style Syntax
239  * The syntax of bind() is,
240  *
241  *   ret = bind(int sd, struct sockaddr *addr, int addrlen);
242  *
243  *   sd      - the socket descriptor returned by socket().
244  *   addr    - the address structure (struct sockaddr_in or struct
245  *             sockaddr_in6 [RFC 2553]),
246  *   addr_len - the size of the address structure.
247  */
248 int sctp_bind(struct sock *sk, struct sockaddr *uaddr, int addr_len)
249 {
250         int retval = 0;
251
252         sctp_lock_sock(sk);
253
254         SCTP_DEBUG_PRINTK("sctp_bind(sk: %p, uaddr: %p, addr_len: %d)\n",
255                           sk, uaddr, addr_len);
256
257         /* Disallow binding twice. */
258         if (!sctp_sk(sk)->ep->base.bind_addr.port)
259                 retval = sctp_do_bind(sk, (union sctp_addr *)uaddr,
260                                       addr_len);
261         else
262                 retval = -EINVAL;
263
264         sctp_release_sock(sk);
265
266         return retval;
267 }
268
269 static long sctp_get_port_local(struct sock *, union sctp_addr *);
270
271 /* Verify this is a valid sockaddr. */
272 static struct sctp_af *sctp_sockaddr_af(struct sctp_opt *opt,
273                                         union sctp_addr *addr, int len)
274 {
275         struct sctp_af *af;
276
277         /* Check minimum size.  */
278         if (len < sizeof (struct sockaddr))
279                 return NULL;
280
281         /* Does this PF support this AF? */
282         if (!opt->pf->af_supported(addr->sa.sa_family, opt))
283                 return NULL;
284
285         /* If we get this far, af is valid. */
286         af = sctp_get_af_specific(addr->sa.sa_family);
287
288         if (len < af->sockaddr_len)
289                 return NULL;
290
291         return af;
292 }
293
294 /* Bind a local address either to an endpoint or to an association.  */
295 SCTP_STATIC int sctp_do_bind(struct sock *sk, union sctp_addr *addr, int len)
296 {
297         struct sctp_opt *sp = sctp_sk(sk);
298         struct sctp_endpoint *ep = sp->ep;
299         struct sctp_bind_addr *bp = &ep->base.bind_addr;
300         struct sctp_af *af;
301         unsigned short snum;
302         int ret = 0;
303
304         SCTP_DEBUG_PRINTK("sctp_do_bind(sk: %p, newaddr: %p, len: %d)\n",
305                           sk, addr, len);
306
307         /* Common sockaddr verification. */
308         af = sctp_sockaddr_af(sp, addr, len);
309         if (!af)
310                 return -EINVAL;
311
312         /* PF specific bind() address verification. */
313         if (!sp->pf->bind_verify(sp, addr))
314                 return -EADDRNOTAVAIL;
315
316         snum= ntohs(addr->v4.sin_port);
317
318         SCTP_DEBUG_PRINTK("sctp_do_bind: port: %d, new port: %d\n",
319                           bp->port, snum);
320
321         /* We must either be unbound, or bind to the same port.  */
322         if (bp->port && (snum != bp->port)) {
323                 SCTP_DEBUG_PRINTK("sctp_do_bind:"
324                                   " New port %d does not match existing port "
325                                   "%d.\n", snum, bp->port);
326                 return -EINVAL;
327         }
328
329         if (snum && snum < PROT_SOCK && !capable(CAP_NET_BIND_SERVICE))
330                 return -EACCES;
331
332         /* Make sure we are allowed to bind here.
333          * The function sctp_get_port_local() does duplicate address
334          * detection.
335          */
336         if ((ret = sctp_get_port_local(sk, addr))) {
337                 if (ret == (long) sk) {
338                         /* This endpoint has a conflicting address. */
339                         return -EINVAL;
340                 } else {
341                         return -EADDRINUSE;
342                 }
343         }
344
345         /* Refresh ephemeral port.  */
346         if (!snum)
347                 snum = inet_sk(sk)->num;
348
349         /* Add the address to the bind address list.  */
350         sctp_local_bh_disable();
351         sctp_write_lock(&ep->base.addr_lock);
352
353         /* Use GFP_ATOMIC since BHs are disabled.  */
354         addr->v4.sin_port = ntohs(addr->v4.sin_port);
355         ret = sctp_add_bind_addr(bp, addr, GFP_ATOMIC);
356         addr->v4.sin_port = htons(addr->v4.sin_port);
357         if (!ret && !bp->port)
358                 bp->port = snum;
359         sctp_write_unlock(&ep->base.addr_lock);
360         sctp_local_bh_enable();
361
362         /* Copy back into socket for getsockname() use. */
363         if (!ret) {
364                 inet_sk(sk)->sport = htons(inet_sk(sk)->num);
365                 af->to_sk_saddr(addr, sk);
366         }
367
368         return ret;
369 }
370
371  /* ADDIP Section 4.1.1 Congestion Control of ASCONF Chunks
372  *
373  * R1) One and only one ASCONF Chunk MAY be in transit and unacknowledged 
374  * at any one time.  If a sender, after sending an ASCONF chunk, decides
375  * it needs to transfer another ASCONF Chunk, it MUST wait until the 
376  * ASCONF-ACK Chunk returns from the previous ASCONF Chunk before sending a
377  * subsequent ASCONF. Note this restriction binds each side, so at any 
378  * time two ASCONF may be in-transit on any given association (one sent 
379  * from each endpoint).
380  */
381 static int sctp_send_asconf(struct sctp_association *asoc,
382                             struct sctp_chunk *chunk)
383 {
384         int             retval = 0;
385
386         /* If there is an outstanding ASCONF chunk, queue it for later
387          * transmission.
388          */     
389         if (asoc->addip_last_asconf) {
390                 __skb_queue_tail(&asoc->addip_chunks, (struct sk_buff *)chunk);
391                 goto out;       
392         }
393
394         /* Hold the chunk until an ASCONF_ACK is received. */
395         sctp_chunk_hold(chunk);
396         retval = sctp_primitive_ASCONF(asoc, chunk);
397         if (retval)
398                 sctp_chunk_free(chunk);
399         else
400                 asoc->addip_last_asconf = chunk;
401
402 out:
403         return retval;
404 }
405
406 /* Add a list of addresses as bind addresses to local endpoint or
407  * association.
408  *
409  * Basically run through each address specified in the addrs/addrcnt
410  * array/length pair, determine if it is IPv6 or IPv4 and call
411  * sctp_do_bind() on it.
412  *
413  * If any of them fails, then the operation will be reversed and the
414  * ones that were added will be removed.
415  *
416  * Only sctp_setsockopt_bindx() is supposed to call this function.
417  */
418 int sctp_bindx_add(struct sock *sk, struct sockaddr *addrs, int addrcnt)
419 {
420         int cnt;
421         int retval = 0;
422         void *addr_buf;
423         struct sockaddr *sa_addr;
424         struct sctp_af *af;
425
426         SCTP_DEBUG_PRINTK("sctp_bindx_add (sk: %p, addrs: %p, addrcnt: %d)\n",
427                           sk, addrs, addrcnt);
428
429         addr_buf = addrs;
430         for (cnt = 0; cnt < addrcnt; cnt++) {
431                 /* The list may contain either IPv4 or IPv6 address;
432                  * determine the address length for walking thru the list.
433                  */
434                 sa_addr = (struct sockaddr *)addr_buf;
435                 af = sctp_get_af_specific(sa_addr->sa_family);
436                 if (!af) {
437                         retval = -EINVAL;
438                         goto err_bindx_add;
439                 }
440
441                 retval = sctp_do_bind(sk, (union sctp_addr *)sa_addr, 
442                                       af->sockaddr_len);
443
444                 addr_buf += af->sockaddr_len;
445
446 err_bindx_add:
447                 if (retval < 0) {
448                         /* Failed. Cleanup the ones that have been added */
449                         if (cnt > 0)
450                                 sctp_bindx_rem(sk, addrs, cnt);
451                         return retval;
452                 }
453         }
454
455         return retval;
456 }
457
458 /* Send an ASCONF chunk with Add IP address parameters to all the peers of the
459  * associations that are part of the endpoint indicating that a list of local
460  * addresses are added to the endpoint.
461  *
462  * If any of the addresses is already in the bind address list of the 
463  * association, we do not send the chunk for that association.  But it will not
464  * affect other associations.
465  *
466  * Only sctp_setsockopt_bindx() is supposed to call this function.
467  */
468 static int sctp_send_asconf_add_ip(struct sock          *sk, 
469                                    struct sockaddr      *addrs,
470                                    int                  addrcnt)
471 {
472         struct sctp_opt                 *sp;
473         struct sctp_endpoint            *ep;
474         struct sctp_association         *asoc;
475         struct sctp_bind_addr           *bp;
476         struct sctp_chunk               *chunk;
477         struct sctp_sockaddr_entry      *laddr;
478         union sctp_addr                 *addr;
479         void                            *addr_buf;
480         struct sctp_af                  *af;
481         struct list_head                *pos;
482         struct list_head                *p;
483         int                             i;
484         int                             retval = 0;
485
486         if (!sctp_addip_enable)
487                 return retval;
488
489         sp = sctp_sk(sk);
490         ep = sp->ep;
491
492         SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n",
493                           __FUNCTION__, sk, addrs, addrcnt);
494
495         list_for_each(pos, &ep->asocs) {
496                 asoc = list_entry(pos, struct sctp_association, asocs);
497
498                 if (!asoc->peer.asconf_capable)
499                         continue;
500
501                 if (asoc->peer.addip_disabled_mask & SCTP_PARAM_ADD_IP)
502                         continue;
503
504                 if (!sctp_state(asoc, ESTABLISHED))
505                         continue;
506
507                 /* Check if any address in the packed array of addresses is
508                  * in the bind address list of the association. If so, 
509                  * do not send the asconf chunk to its peer, but continue with 
510                  * other associations.
511                  */
512                 addr_buf = addrs;
513                 for (i = 0; i < addrcnt; i++) {
514                         addr = (union sctp_addr *)addr_buf;
515                         af = sctp_get_af_specific(addr->v4.sin_family);
516                         if (!af) {
517                                 retval = -EINVAL;
518                                 goto out;
519                         }
520
521                         if (sctp_assoc_lookup_laddr(asoc, addr))
522                                 break;
523
524                         addr_buf += af->sockaddr_len;
525                 }
526                 if (i < addrcnt)
527                         continue;
528
529                 /* Use the first address in bind addr list of association as
530                  * Address Parameter of ASCONF CHUNK.
531                  */
532                 sctp_read_lock(&asoc->base.addr_lock);
533                 bp = &asoc->base.bind_addr;
534                 p = bp->address_list.next;
535                 laddr = list_entry(p, struct sctp_sockaddr_entry, list);
536                 sctp_read_unlock(&asoc->base.addr_lock);
537
538                 chunk = sctp_make_asconf_update_ip(asoc, &laddr->a, addrs,
539                                                    addrcnt, SCTP_PARAM_ADD_IP);
540                 if (!chunk) {
541                         retval = -ENOMEM;
542                         goto out;
543                 }
544
545                 retval = sctp_send_asconf(asoc, chunk);
546
547                 /* FIXME: After sending the add address ASCONF chunk, we
548                  * cannot append the address to the association's binding
549                  * address list, because the new address may be used as the
550                  * source of a message sent to the peer before the ASCONF
551                  * chunk is received by the peer.  So we should wait until
552                  * ASCONF_ACK is received.
553                  */
554         }
555
556 out:
557         return retval;
558 }
559
560 /* Remove a list of addresses from bind addresses list.  Do not remove the
561  * last address.
562  *
563  * Basically run through each address specified in the addrs/addrcnt
564  * array/length pair, determine if it is IPv6 or IPv4 and call
565  * sctp_del_bind() on it.
566  *
567  * If any of them fails, then the operation will be reversed and the
568  * ones that were removed will be added back.
569  *
570  * At least one address has to be left; if only one address is
571  * available, the operation will return -EBUSY.
572  *
573  * Only sctp_setsockopt_bindx() is supposed to call this function.
574  */
575 int sctp_bindx_rem(struct sock *sk, struct sockaddr *addrs, int addrcnt)
576 {
577         struct sctp_opt *sp = sctp_sk(sk);
578         struct sctp_endpoint *ep = sp->ep;
579         int cnt;
580         struct sctp_bind_addr *bp = &ep->base.bind_addr;
581         int retval = 0;
582         union sctp_addr saveaddr;
583         void *addr_buf;
584         struct sockaddr *sa_addr;
585         struct sctp_af *af;
586
587         SCTP_DEBUG_PRINTK("sctp_bindx_rem (sk: %p, addrs: %p, addrcnt: %d)\n",
588                           sk, addrs, addrcnt);
589
590         addr_buf = addrs;
591         for (cnt = 0; cnt < addrcnt; cnt++) {
592                 /* If the bind address list is empty or if there is only one
593                  * bind address, there is nothing more to be removed (we need
594                  * at least one address here).
595                  */
596                 if (list_empty(&bp->address_list) ||
597                     (sctp_list_single_entry(&bp->address_list))) {
598                         retval = -EBUSY;
599                         goto err_bindx_rem;
600                 }
601
602                 /* The list may contain either IPv4 or IPv6 address;
603                  * determine the address length to copy the address to
604                  * saveaddr. 
605                  */
606                 sa_addr = (struct sockaddr *)addr_buf;
607                 af = sctp_get_af_specific(sa_addr->sa_family);
608                 if (!af) {
609                         retval = -EINVAL;
610                         goto err_bindx_rem;
611                 }
612                 memcpy(&saveaddr, sa_addr, af->sockaddr_len); 
613                 saveaddr.v4.sin_port = ntohs(saveaddr.v4.sin_port);
614                 if (saveaddr.v4.sin_port != bp->port) {
615                         retval = -EINVAL;
616                         goto err_bindx_rem;
617                 }
618
619                 /* FIXME - There is probably a need to check if sk->sk_saddr and
620                  * sk->sk_rcv_addr are currently set to one of the addresses to
621                  * be removed. This is something which needs to be looked into
622                  * when we are fixing the outstanding issues with multi-homing
623                  * socket routing and failover schemes. Refer to comments in
624                  * sctp_do_bind(). -daisy
625                  */
626                 sctp_local_bh_disable();
627                 sctp_write_lock(&ep->base.addr_lock);
628
629                 retval = sctp_del_bind_addr(bp, &saveaddr);
630
631                 sctp_write_unlock(&ep->base.addr_lock);
632                 sctp_local_bh_enable();
633
634                 addr_buf += af->sockaddr_len;
635 err_bindx_rem:
636                 if (retval < 0) {
637                         /* Failed. Add the ones that has been removed back */
638                         if (cnt > 0)
639                                 sctp_bindx_add(sk, addrs, cnt);
640                         return retval;
641                 }
642         }
643
644         return retval;
645 }
646
647 /* Send an ASCONF chunk with Delete IP address parameters to all the peers of
648  * the associations that are part of the endpoint indicating that a list of
649  * local addresses are removed from the endpoint.
650  *
651  * If any of the addresses is already in the bind address list of the 
652  * association, we do not send the chunk for that association.  But it will not
653  * affect other associations.
654  *
655  * Only sctp_setsockopt_bindx() is supposed to call this function.
656  */
657 static int sctp_send_asconf_del_ip(struct sock          *sk,
658                                    struct sockaddr      *addrs,
659                                    int                  addrcnt)
660 {
661         struct sctp_opt         *sp;
662         struct sctp_endpoint    *ep;
663         struct sctp_association *asoc;
664         struct sctp_bind_addr   *bp;
665         struct sctp_chunk       *chunk;
666         union sctp_addr         *laddr;
667         void                    *addr_buf;
668         struct sctp_af          *af;
669         struct list_head        *pos;
670         int                     i;
671         int                     retval = 0;
672
673         if (!sctp_addip_enable)
674                 return retval;
675
676         sp = sctp_sk(sk);
677         ep = sp->ep;
678
679         SCTP_DEBUG_PRINTK("%s: (sk: %p, addrs: %p, addrcnt: %d)\n",
680                           __FUNCTION__, sk, addrs, addrcnt);
681
682         list_for_each(pos, &ep->asocs) {
683                 asoc = list_entry(pos, struct sctp_association, asocs);
684
685                 if (!asoc->peer.asconf_capable)
686                         continue;
687
688                 if (asoc->peer.addip_disabled_mask & SCTP_PARAM_DEL_IP)
689                         continue;
690
691                 if (!sctp_state(asoc, ESTABLISHED))
692                         continue;
693
694                 /* Check if any address in the packed array of addresses is
695                  * not present in the bind address list of the association.
696                  * If so, do not send the asconf chunk to its peer, but
697                  * continue with other associations.
698                  */
699                 addr_buf = addrs;
700                 for (i = 0; i < addrcnt; i++) {
701                         laddr = (union sctp_addr *)addr_buf;
702                         af = sctp_get_af_specific(laddr->v4.sin_family);
703                         if (!af) {
704                                 retval = -EINVAL;
705                                 goto out;
706                         }
707
708                         if (!sctp_assoc_lookup_laddr(asoc, laddr))
709                                 break;
710
711                         addr_buf += af->sockaddr_len;
712                 }
713                 if (i < addrcnt)
714                         continue;
715
716                 /* Find one address in the association's bind address list
717                  * that is not in the packed array of addresses. This is to
718                  * make sure that we do not delete all the addresses in the
719                  * association.
720                  */
721                 sctp_read_lock(&asoc->base.addr_lock);
722                 bp = &asoc->base.bind_addr;
723                 laddr = sctp_find_unmatch_addr(bp, (union sctp_addr *)addrs,
724                                                addrcnt, sp);
725                 sctp_read_unlock(&asoc->base.addr_lock);
726                 if (!laddr)
727                         continue;
728
729                 chunk = sctp_make_asconf_update_ip(asoc, laddr, addrs, addrcnt,
730                                                    SCTP_PARAM_DEL_IP);
731                 if (!chunk) {
732                         retval = -ENOMEM;
733                         goto out;
734                 }
735
736                 retval = sctp_send_asconf(asoc, chunk);
737
738                 /* FIXME: After sending the delete address ASCONF chunk, we
739                  * cannot remove the addresses from the association's bind
740                  * address list, because there maybe some packet send to
741                  * the delete addresses, so we should wait until ASCONF_ACK
742                  * packet is received.
743                  */
744         }
745 out:
746         return retval;
747 }
748
749 /* Helper for tunneling sctp_bindx() requests through sctp_setsockopt()
750  *
751  * API 8.1
752  * int sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt,
753  *                int flags);
754  *
755  * If sd is an IPv4 socket, the addresses passed must be IPv4 addresses.
756  * If the sd is an IPv6 socket, the addresses passed can either be IPv4
757  * or IPv6 addresses.
758  *
759  * A single address may be specified as INADDR_ANY or IN6ADDR_ANY, see
760  * Section 3.1.2 for this usage.
761  *
762  * addrs is a pointer to an array of one or more socket addresses. Each
763  * address is contained in its appropriate structure (i.e. struct
764  * sockaddr_in or struct sockaddr_in6) the family of the address type
765  * must be used to distengish the address length (note that this
766  * representation is termed a "packed array" of addresses). The caller
767  * specifies the number of addresses in the array with addrcnt.
768  *
769  * On success, sctp_bindx() returns 0. On failure, sctp_bindx() returns
770  * -1, and sets errno to the appropriate error code.
771  *
772  * For SCTP, the port given in each socket address must be the same, or
773  * sctp_bindx() will fail, setting errno to EINVAL.
774  *
775  * The flags parameter is formed from the bitwise OR of zero or more of
776  * the following currently defined flags:
777  *
778  * SCTP_BINDX_ADD_ADDR
779  *
780  * SCTP_BINDX_REM_ADDR
781  *
782  * SCTP_BINDX_ADD_ADDR directs SCTP to add the given addresses to the
783  * association, and SCTP_BINDX_REM_ADDR directs SCTP to remove the given
784  * addresses from the association. The two flags are mutually exclusive;
785  * if both are given, sctp_bindx() will fail with EINVAL. A caller may
786  * not remove all addresses from an association; sctp_bindx() will
787  * reject such an attempt with EINVAL.
788  *
789  * An application can use sctp_bindx(SCTP_BINDX_ADD_ADDR) to associate
790  * additional addresses with an endpoint after calling bind().  Or use
791  * sctp_bindx(SCTP_BINDX_REM_ADDR) to remove some addresses a listening
792  * socket is associated with so that no new association accepted will be
793  * associated with those addresses. If the endpoint supports dynamic
794  * address a SCTP_BINDX_REM_ADDR or SCTP_BINDX_ADD_ADDR may cause a
795  * endpoint to send the appropriate message to the peer to change the
796  * peers address lists.
797  *
798  * Adding and removing addresses from a connected association is
799  * optional functionality. Implementations that do not support this
800  * functionality should return EOPNOTSUPP.
801  *
802  * Basically do nothing but copying the addresses from user to kernel
803  * land and invoking either sctp_bindx_add() or sctp_bindx_rem() on the sk.
804  * This is used for tunneling the sctp_bindx() request through sctp_setsockopt() * from userspace.
805  *
806  * We don't use copy_from_user() for optimization: we first do the
807  * sanity checks (buffer size -fast- and access check-healthy
808  * pointer); if all of those succeed, then we can alloc the memory
809  * (expensive operation) needed to copy the data to kernel. Then we do
810  * the copying without checking the user space area
811  * (__copy_from_user()).
812  *
813  * On exit there is no need to do sockfd_put(), sys_setsockopt() does
814  * it.
815  *
816  * sk        The sk of the socket
817  * addrs     The pointer to the addresses in user land
818  * addrssize Size of the addrs buffer
819  * op        Operation to perform (add or remove, see the flags of
820  *           sctp_bindx)
821  *
822  * Returns 0 if ok, <0 errno code on error.
823  */
824 SCTP_STATIC int sctp_setsockopt_bindx(struct sock* sk,
825                                       struct sockaddr __user *addrs,
826                                       int addrs_size, int op)
827 {
828         struct sockaddr *kaddrs;
829         int err;
830         int addrcnt = 0;
831         int walk_size = 0;
832         struct sockaddr *sa_addr;
833         void *addr_buf;
834         struct sctp_af *af;
835
836         SCTP_DEBUG_PRINTK("sctp_setsocktopt_bindx: sk %p addrs %p"
837                           " addrs_size %d opt %d\n", sk, addrs, addrs_size, op);
838
839         if (unlikely(addrs_size <= 0))
840                 return -EINVAL;
841
842         /* Check the user passed a healthy pointer.  */
843         if (unlikely(!access_ok(VERIFY_READ, addrs, addrs_size)))
844                 return -EFAULT;
845
846         /* Alloc space for the address array in kernel memory.  */
847         kaddrs = (struct sockaddr *)kmalloc(addrs_size, GFP_KERNEL);
848         if (unlikely(!kaddrs))
849                 return -ENOMEM;
850
851         if (__copy_from_user(kaddrs, addrs, addrs_size)) {
852                 kfree(kaddrs);
853                 return -EFAULT;
854         }
855
856         /* Walk through the addrs buffer and count the number of addresses. */ 
857         addr_buf = kaddrs;
858         while (walk_size < addrs_size) {
859                 sa_addr = (struct sockaddr *)addr_buf;
860                 af = sctp_get_af_specific(sa_addr->sa_family);
861
862                 /* If the address family is not supported or if this address
863                  * causes the address buffer to overflow return EINVAL.
864                  */ 
865                 if (!af || (walk_size + af->sockaddr_len) > addrs_size) {
866                         kfree(kaddrs);
867                         return -EINVAL;
868                 }
869                 addrcnt++;
870                 addr_buf += af->sockaddr_len;
871                 walk_size += af->sockaddr_len;
872         }
873
874         /* Do the work. */
875         switch (op) {
876         case SCTP_BINDX_ADD_ADDR:
877                 err = sctp_bindx_add(sk, kaddrs, addrcnt);
878                 if (err)
879                         goto out;
880                 err = sctp_send_asconf_add_ip(sk, kaddrs, addrcnt);
881                 break;
882
883         case SCTP_BINDX_REM_ADDR:
884                 err = sctp_bindx_rem(sk, kaddrs, addrcnt);
885                 if (err)
886                         goto out;
887                 err = sctp_send_asconf_del_ip(sk, kaddrs, addrcnt);
888                 break;
889
890         default:
891                 err = -EINVAL;
892                 break;
893         };
894
895 out:
896         kfree(kaddrs);
897
898         return err;
899 }
900
901 /* API 3.1.4 close() - UDP Style Syntax
902  * Applications use close() to perform graceful shutdown (as described in
903  * Section 10.1 of [SCTP]) on ALL the associations currently represented
904  * by a UDP-style socket.
905  *
906  * The syntax is
907  *
908  *   ret = close(int sd);
909  *
910  *   sd      - the socket descriptor of the associations to be closed.
911  *
912  * To gracefully shutdown a specific association represented by the
913  * UDP-style socket, an application should use the sendmsg() call,
914  * passing no user data, but including the appropriate flag in the
915  * ancillary data (see Section xxxx).
916  *
917  * If sd in the close() call is a branched-off socket representing only
918  * one association, the shutdown is performed on that association only.
919  *
920  * 4.1.6 close() - TCP Style Syntax
921  *
922  * Applications use close() to gracefully close down an association.
923  *
924  * The syntax is:
925  *
926  *    int close(int sd);
927  *
928  *      sd      - the socket descriptor of the association to be closed.
929  *
930  * After an application calls close() on a socket descriptor, no further
931  * socket operations will succeed on that descriptor.
932  *
933  * API 7.1.4 SO_LINGER
934  *
935  * An application using the TCP-style socket can use this option to
936  * perform the SCTP ABORT primitive.  The linger option structure is:
937  *
938  *  struct  linger {
939  *     int     l_onoff;                // option on/off
940  *     int     l_linger;               // linger time
941  * };
942  *
943  * To enable the option, set l_onoff to 1.  If the l_linger value is set
944  * to 0, calling close() is the same as the ABORT primitive.  If the
945  * value is set to a negative value, the setsockopt() call will return
946  * an error.  If the value is set to a positive value linger_time, the
947  * close() can be blocked for at most linger_time ms.  If the graceful
948  * shutdown phase does not finish during this period, close() will
949  * return but the graceful shutdown phase continues in the system.
950  */
951 SCTP_STATIC void sctp_close(struct sock *sk, long timeout)
952 {
953         struct sctp_endpoint *ep;
954         struct sctp_association *asoc;
955         struct list_head *pos, *temp;
956
957         SCTP_DEBUG_PRINTK("sctp_close(sk: 0x%p, timeout:%ld)\n", sk, timeout);
958
959         sctp_lock_sock(sk);
960         sk->sk_shutdown = SHUTDOWN_MASK;
961
962         ep = sctp_sk(sk)->ep;
963
964         /* Walk all associations on a socket, not on an endpoint.  */
965         list_for_each_safe(pos, temp, &ep->asocs) {
966                 asoc = list_entry(pos, struct sctp_association, asocs);
967
968                 if (sctp_style(sk, TCP)) {
969                         /* A closed association can still be in the list if
970                          * it belongs to a TCP-style listening socket that is
971                          * not yet accepted. If so, free it. If not, send an
972                          * ABORT or SHUTDOWN based on the linger options.
973                          */
974                         if (sctp_state(asoc, CLOSED)) {
975                                 sctp_unhash_established(asoc);
976                                 sctp_association_free(asoc);
977
978                         } else if (sock_flag(sk, SOCK_LINGER) &&
979                                    !sk->sk_lingertime)
980                                 sctp_primitive_ABORT(asoc, NULL);
981                         else
982                                 sctp_primitive_SHUTDOWN(asoc, NULL);
983                 } else
984                         sctp_primitive_SHUTDOWN(asoc, NULL);
985         }
986
987         /* Clean up any skbs sitting on the receive queue.  */
988         sctp_queue_purge_ulpevents(&sk->sk_receive_queue);
989         sctp_queue_purge_ulpevents(&sctp_sk(sk)->pd_lobby);
990
991         /* On a TCP-style socket, block for at most linger_time if set. */
992         if (sctp_style(sk, TCP) && timeout)
993                 sctp_wait_for_close(sk, timeout);
994
995         /* This will run the backlog queue.  */
996         sctp_release_sock(sk);
997
998         /* Supposedly, no process has access to the socket, but
999          * the net layers still may.
1000          */
1001         sctp_local_bh_disable();
1002         sctp_bh_lock_sock(sk);
1003
1004         /* Hold the sock, since sk_common_release() will put sock_put()
1005          * and we have just a little more cleanup.
1006          */
1007         sock_hold(sk);
1008         sk_common_release(sk);
1009
1010         sctp_bh_unlock_sock(sk);
1011         sctp_local_bh_enable();
1012
1013         sock_put(sk);
1014
1015         SCTP_DBG_OBJCNT_DEC(sock);
1016 }
1017
1018 /* Handle EPIPE error. */
1019 static int sctp_error(struct sock *sk, int flags, int err)
1020 {
1021         if (err == -EPIPE)
1022                 err = sock_error(sk) ? : -EPIPE;
1023         if (err == -EPIPE && !(flags & MSG_NOSIGNAL))
1024                 send_sig(SIGPIPE, current, 0);
1025         return err;
1026 }
1027
1028 /* API 3.1.3 sendmsg() - UDP Style Syntax
1029  *
1030  * An application uses sendmsg() and recvmsg() calls to transmit data to
1031  * and receive data from its peer.
1032  *
1033  *  ssize_t sendmsg(int socket, const struct msghdr *message,
1034  *                  int flags);
1035  *
1036  *  socket  - the socket descriptor of the endpoint.
1037  *  message - pointer to the msghdr structure which contains a single
1038  *            user message and possibly some ancillary data.
1039  *
1040  *            See Section 5 for complete description of the data
1041  *            structures.
1042  *
1043  *  flags   - flags sent or received with the user message, see Section
1044  *            5 for complete description of the flags.
1045  *
1046  * Note:  This function could use a rewrite especially when explicit
1047  * connect support comes in.
1048  */
1049 /* BUG:  We do not implement the equivalent of sk_stream_wait_memory(). */
1050
1051 SCTP_STATIC int sctp_msghdr_parse(const struct msghdr *, sctp_cmsgs_t *);
1052
1053 SCTP_STATIC int sctp_sendmsg(struct kiocb *iocb, struct sock *sk,
1054                              struct msghdr *msg, size_t msg_len)
1055 {
1056         struct sctp_opt *sp;
1057         struct sctp_endpoint *ep;
1058         struct sctp_association *new_asoc=NULL, *asoc=NULL;
1059         struct sctp_transport *transport, *chunk_tp;
1060         struct sctp_chunk *chunk;
1061         union sctp_addr to;
1062         struct sockaddr *msg_name = NULL;
1063         struct sctp_sndrcvinfo default_sinfo = { 0 };
1064         struct sctp_sndrcvinfo *sinfo;
1065         struct sctp_initmsg *sinit;
1066         sctp_assoc_t associd = 0;
1067         sctp_cmsgs_t cmsgs = { NULL };
1068         int err;
1069         sctp_scope_t scope;
1070         long timeo;
1071         __u16 sinfo_flags = 0;
1072         struct sctp_datamsg *datamsg;
1073         struct list_head *pos;
1074         int msg_flags = msg->msg_flags;
1075
1076         SCTP_DEBUG_PRINTK("sctp_sendmsg(sk: %p, msg: %p, msg_len: %zu)\n",
1077                           sk, msg, msg_len);
1078
1079         err = 0;
1080         sp = sctp_sk(sk);
1081         ep = sp->ep;
1082
1083         SCTP_DEBUG_PRINTK("Using endpoint: %s.\n", ep->debug_name);
1084
1085         /* We cannot send a message over a TCP-style listening socket. */
1086         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING)) {
1087                 err = -EPIPE;
1088                 goto out_nounlock;
1089         }
1090
1091         /* Parse out the SCTP CMSGs.  */
1092         err = sctp_msghdr_parse(msg, &cmsgs);
1093
1094         if (err) {
1095                 SCTP_DEBUG_PRINTK("msghdr parse err = %x\n", err);
1096                 goto out_nounlock;
1097         }
1098
1099         /* Fetch the destination address for this packet.  This
1100          * address only selects the association--it is not necessarily
1101          * the address we will send to.
1102          * For a peeled-off socket, msg_name is ignored.
1103          */
1104         if (!sctp_style(sk, UDP_HIGH_BANDWIDTH) && msg->msg_name) {
1105                 int msg_namelen = msg->msg_namelen;
1106
1107                 err = sctp_verify_addr(sk, (union sctp_addr *)msg->msg_name,
1108                                        msg_namelen);
1109                 if (err)
1110                         return err;
1111
1112                 if (msg_namelen > sizeof(to))
1113                         msg_namelen = sizeof(to);
1114                 memcpy(&to, msg->msg_name, msg_namelen);
1115                 SCTP_DEBUG_PRINTK("Just memcpy'd. msg_name is "
1116                                   "0x%x:%u.\n",
1117                                   to.v4.sin_addr.s_addr, to.v4.sin_port);
1118
1119                 to.v4.sin_port = ntohs(to.v4.sin_port);
1120                 msg_name = msg->msg_name;
1121         }
1122
1123         sinfo = cmsgs.info;
1124         sinit = cmsgs.init;
1125
1126         /* Did the user specify SNDRCVINFO?  */
1127         if (sinfo) {
1128                 sinfo_flags = sinfo->sinfo_flags;
1129                 associd = sinfo->sinfo_assoc_id;
1130         }
1131
1132         SCTP_DEBUG_PRINTK("msg_len: %zu, sinfo_flags: 0x%x\n",
1133                           msg_len, sinfo_flags);
1134
1135         /* MSG_EOF or MSG_ABORT cannot be set on a TCP-style socket. */
1136         if (sctp_style(sk, TCP) && (sinfo_flags & (MSG_EOF | MSG_ABORT))) {
1137                 err = -EINVAL;
1138                 goto out_nounlock;
1139         }
1140
1141         /* If MSG_EOF is set, no data can be sent. Disallow sending zero
1142          * length messages when MSG_EOF|MSG_ABORT is not set.
1143          * If MSG_ABORT is set, the message length could be non zero with
1144          * the msg_iov set to the user abort reason.
1145          */
1146         if (((sinfo_flags & MSG_EOF) && (msg_len > 0)) ||
1147             (!(sinfo_flags & (MSG_EOF|MSG_ABORT)) && (msg_len == 0))) {
1148                 err = -EINVAL;
1149                 goto out_nounlock;
1150         }
1151
1152         /* If MSG_ADDR_OVER is set, there must be an address
1153          * specified in msg_name.
1154          */
1155         if ((sinfo_flags & MSG_ADDR_OVER) && (!msg->msg_name)) {
1156                 err = -EINVAL;
1157                 goto out_nounlock;
1158         }
1159
1160         transport = NULL;
1161
1162         SCTP_DEBUG_PRINTK("About to look up association.\n");
1163
1164         sctp_lock_sock(sk);
1165
1166         /* If a msg_name has been specified, assume this is to be used.  */
1167         if (msg_name) {
1168                 /* Look for a matching association on the endpoint. */
1169                 asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
1170                 if (!asoc) {
1171                         /* If we could not find a matching association on the
1172                          * endpoint, make sure that it is not a TCP-style
1173                          * socket that already has an association or there is
1174                          * no peeled-off association on another socket.
1175                          */
1176                         if ((sctp_style(sk, TCP) &&
1177                              sctp_sstate(sk, ESTABLISHED)) ||
1178                             sctp_endpoint_is_peeled_off(ep, &to)) {
1179                                 err = -EADDRNOTAVAIL;
1180                                 goto out_unlock;
1181                         }
1182                 }
1183         } else {
1184                 asoc = sctp_id2assoc(sk, associd);
1185                 if (!asoc) {
1186                         err = -EPIPE;
1187                         goto out_unlock;
1188                 }
1189         }
1190
1191         if (asoc) {
1192                 SCTP_DEBUG_PRINTK("Just looked up association: %p.\n", asoc);
1193
1194                 /* We cannot send a message on a TCP-style SCTP_SS_ESTABLISHED
1195                  * socket that has an association in CLOSED state. This can
1196                  * happen when an accepted socket has an association that is
1197                  * already CLOSED.
1198                  */
1199                 if (sctp_state(asoc, CLOSED) && sctp_style(sk, TCP)) {
1200                         err = -EPIPE;
1201                         goto out_unlock;
1202                 }
1203
1204                 if (sinfo_flags & MSG_EOF) {
1205                         SCTP_DEBUG_PRINTK("Shutting down association: %p\n",
1206                                           asoc);
1207                         sctp_primitive_SHUTDOWN(asoc, NULL);
1208                         err = 0;
1209                         goto out_unlock;
1210                 }
1211                 if (sinfo_flags & MSG_ABORT) {
1212                         SCTP_DEBUG_PRINTK("Aborting association: %p\n", asoc);
1213                         sctp_primitive_ABORT(asoc, msg);
1214                         err = 0;
1215                         goto out_unlock;
1216                 }
1217         }
1218
1219         /* Do we need to create the association?  */
1220         if (!asoc) {
1221                 SCTP_DEBUG_PRINTK("There is no association yet.\n");
1222
1223                 if (sinfo_flags & (MSG_EOF | MSG_ABORT)) {
1224                         err = -EINVAL;
1225                         goto out_unlock;
1226                 }
1227
1228                 /* Check for invalid stream against the stream counts,
1229                  * either the default or the user specified stream counts.
1230                  */
1231                 if (sinfo) {
1232                         if (!sinit || (sinit && !sinit->sinit_num_ostreams)) {
1233                                 /* Check against the defaults. */
1234                                 if (sinfo->sinfo_stream >=
1235                                     sp->initmsg.sinit_num_ostreams) {
1236                                         err = -EINVAL;
1237                                         goto out_unlock;
1238                                 }
1239                         } else {
1240                                 /* Check against the requested.  */
1241                                 if (sinfo->sinfo_stream >=
1242                                     sinit->sinit_num_ostreams) {
1243                                         err = -EINVAL;
1244                                         goto out_unlock;
1245                                 }
1246                         }
1247                 }
1248
1249                 /*
1250                  * API 3.1.2 bind() - UDP Style Syntax
1251                  * If a bind() or sctp_bindx() is not called prior to a
1252                  * sendmsg() call that initiates a new association, the
1253                  * system picks an ephemeral port and will choose an address
1254                  * set equivalent to binding with a wildcard address.
1255                  */
1256                 if (!ep->base.bind_addr.port) {
1257                         if (sctp_autobind(sk)) {
1258                                 err = -EAGAIN;
1259                                 goto out_unlock;
1260                         }
1261                 }
1262
1263                 scope = sctp_scope(&to);
1264                 new_asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
1265                 if (!new_asoc) {
1266                         err = -ENOMEM;
1267                         goto out_unlock;
1268                 }
1269                 asoc = new_asoc;
1270
1271                 /* If the SCTP_INIT ancillary data is specified, set all
1272                  * the association init values accordingly.
1273                  */
1274                 if (sinit) {
1275                         if (sinit->sinit_num_ostreams) {
1276                                 asoc->c.sinit_num_ostreams =
1277                                         sinit->sinit_num_ostreams;
1278                         }
1279                         if (sinit->sinit_max_instreams) {
1280                                 asoc->c.sinit_max_instreams =
1281                                         sinit->sinit_max_instreams;
1282                         }
1283                         if (sinit->sinit_max_attempts) {
1284                                 asoc->max_init_attempts
1285                                         = sinit->sinit_max_attempts;
1286                         }
1287                         if (sinit->sinit_max_init_timeo) {
1288                                 asoc->max_init_timeo = 
1289                                  msecs_to_jiffies(sinit->sinit_max_init_timeo);
1290                         }
1291                 }
1292
1293                 /* Prime the peer's transport structures.  */
1294                 transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL);
1295                 if (!transport) {
1296                         err = -ENOMEM;
1297                         goto out_free;
1298                 }
1299                 err = sctp_assoc_set_bind_addr_from_ep(asoc, GFP_KERNEL);
1300                 if (err < 0) {
1301                         err = -ENOMEM;
1302                         goto out_free;
1303                 }
1304         }
1305
1306         /* ASSERT: we have a valid association at this point.  */
1307         SCTP_DEBUG_PRINTK("We have a valid association.\n");
1308
1309         if (!sinfo) {
1310                 /* If the user didn't specify SNDRCVINFO, make up one with
1311                  * some defaults.
1312                  */
1313                 default_sinfo.sinfo_stream = asoc->default_stream;
1314                 default_sinfo.sinfo_flags = asoc->default_flags;
1315                 default_sinfo.sinfo_ppid = asoc->default_ppid;
1316                 default_sinfo.sinfo_context = asoc->default_context;
1317                 default_sinfo.sinfo_timetolive = asoc->default_timetolive;
1318                 default_sinfo.sinfo_assoc_id = sctp_assoc2id(asoc);
1319                 sinfo = &default_sinfo;
1320         }
1321
1322         /* API 7.1.7, the sndbuf size per association bounds the
1323          * maximum size of data that can be sent in a single send call.
1324          */
1325         if (msg_len > sk->sk_sndbuf) {
1326                 err = -EMSGSIZE;
1327                 goto out_free;
1328         }
1329
1330         /* If fragmentation is disabled and the message length exceeds the
1331          * association fragmentation point, return EMSGSIZE.  The I-D
1332          * does not specify what this error is, but this looks like
1333          * a great fit.
1334          */
1335         if (sctp_sk(sk)->disable_fragments && (msg_len > asoc->frag_point)) {
1336                 err = -EMSGSIZE;
1337                 goto out_free;
1338         }
1339
1340         if (sinfo) {
1341                 /* Check for invalid stream. */
1342                 if (sinfo->sinfo_stream >= asoc->c.sinit_num_ostreams) {
1343                         err = -EINVAL;
1344                         goto out_free;
1345                 }
1346         }
1347
1348         timeo = sock_sndtimeo(sk, msg->msg_flags & MSG_DONTWAIT);
1349         if (!sctp_wspace(asoc)) {
1350                 err = sctp_wait_for_sndbuf(asoc, &timeo, msg_len);
1351                 if (err)
1352                         goto out_free;
1353         }
1354
1355         /* If an address is passed with the sendto/sendmsg call, it is used
1356          * to override the primary destination address in the TCP model, or
1357          * when MSG_ADDR_OVER flag is set in the UDP model.
1358          */
1359         if ((sctp_style(sk, TCP) && msg_name) ||
1360             (sinfo_flags & MSG_ADDR_OVER)) {
1361                 chunk_tp = sctp_assoc_lookup_paddr(asoc, &to);
1362                 if (!chunk_tp) {
1363                         err = -EINVAL;
1364                         goto out_free;
1365                 }
1366         } else
1367                 chunk_tp = NULL;
1368
1369         /* Auto-connect, if we aren't connected already. */
1370         if (sctp_state(asoc, CLOSED)) {
1371                 err = sctp_primitive_ASSOCIATE(asoc, NULL);
1372                 if (err < 0)
1373                         goto out_free;
1374                 SCTP_DEBUG_PRINTK("We associated primitively.\n");
1375         }
1376
1377         /* Break the message into multiple chunks of maximum size. */
1378         datamsg = sctp_datamsg_from_user(asoc, sinfo, msg, msg_len);
1379         if (!datamsg) {
1380                 err = -ENOMEM;
1381                 goto out_free;
1382         }
1383
1384         /* Now send the (possibly) fragmented message. */
1385         list_for_each(pos, &datamsg->chunks) {
1386                 chunk = list_entry(pos, struct sctp_chunk, frag_list);
1387                 sctp_datamsg_track(chunk);
1388
1389                 /* Do accounting for the write space.  */
1390                 sctp_set_owner_w(chunk);
1391
1392                 chunk->transport = chunk_tp;
1393
1394                 /* Send it to the lower layers.  Note:  all chunks
1395                  * must either fail or succeed.   The lower layer
1396                  * works that way today.  Keep it that way or this
1397                  * breaks.
1398                  */
1399                 err = sctp_primitive_SEND(asoc, chunk);
1400                 /* Did the lower layer accept the chunk? */
1401                 if (err)
1402                         sctp_chunk_free(chunk);
1403                 SCTP_DEBUG_PRINTK("We sent primitively.\n");
1404         }
1405
1406         sctp_datamsg_free(datamsg);
1407         if (err)
1408                 goto out_free;
1409         else
1410                 err = msg_len;
1411
1412         /* If we are already past ASSOCIATE, the lower
1413          * layers are responsible for association cleanup.
1414          */
1415         goto out_unlock;
1416
1417 out_free:
1418         if (new_asoc)
1419                 sctp_association_free(asoc);
1420 out_unlock:
1421         sctp_release_sock(sk);
1422
1423 out_nounlock:
1424         return sctp_error(sk, msg_flags, err);
1425
1426 #if 0
1427 do_sock_err:
1428         if (msg_len)
1429                 err = msg_len;
1430         else
1431                 err = sock_error(sk);
1432         goto out;
1433
1434 do_interrupted:
1435         if (msg_len)
1436                 err = msg_len;
1437         goto out;
1438 #endif /* 0 */
1439 }
1440
1441 /* This is an extended version of skb_pull() that removes the data from the
1442  * start of a skb even when data is spread across the list of skb's in the
1443  * frag_list. len specifies the total amount of data that needs to be removed.
1444  * when 'len' bytes could be removed from the skb, it returns 0.
1445  * If 'len' exceeds the total skb length,  it returns the no. of bytes that
1446  * could not be removed.
1447  */
1448 static int sctp_skb_pull(struct sk_buff *skb, int len)
1449 {
1450         struct sk_buff *list;
1451         int skb_len = skb_headlen(skb);
1452         int rlen;
1453
1454         if (len <= skb_len) {
1455                 __skb_pull(skb, len);
1456                 return 0;
1457         }
1458         len -= skb_len;
1459         __skb_pull(skb, skb_len);
1460
1461         for (list = skb_shinfo(skb)->frag_list; list; list = list->next) {
1462                 rlen = sctp_skb_pull(list, len);
1463                 skb->len -= (len-rlen);
1464                 skb->data_len -= (len-rlen);
1465
1466                 if (!rlen)
1467                         return 0;
1468
1469                 len = rlen;
1470         }
1471
1472         return len;
1473 }
1474
1475 /* API 3.1.3  recvmsg() - UDP Style Syntax
1476  *
1477  *  ssize_t recvmsg(int socket, struct msghdr *message,
1478  *                    int flags);
1479  *
1480  *  socket  - the socket descriptor of the endpoint.
1481  *  message - pointer to the msghdr structure which contains a single
1482  *            user message and possibly some ancillary data.
1483  *
1484  *            See Section 5 for complete description of the data
1485  *            structures.
1486  *
1487  *  flags   - flags sent or received with the user message, see Section
1488  *            5 for complete description of the flags.
1489  */
1490 static struct sk_buff *sctp_skb_recv_datagram(struct sock *, int, int, int *);
1491
1492 SCTP_STATIC int sctp_recvmsg(struct kiocb *iocb, struct sock *sk,
1493                              struct msghdr *msg, size_t len, int noblock,
1494                              int flags, int *addr_len)
1495 {
1496         struct sctp_ulpevent *event = NULL;
1497         struct sctp_opt *sp = sctp_sk(sk);
1498         struct sk_buff *skb;
1499         int copied;
1500         int err = 0;
1501         int skb_len;
1502
1503         SCTP_DEBUG_PRINTK("sctp_recvmsg(%s: %p, %s: %p, %s: %zd, %s: %d, %s: "
1504                           "0x%x, %s: %p)\n", "sk", sk, "msghdr", msg,
1505                           "len", len, "knoblauch", noblock,
1506                           "flags", flags, "addr_len", addr_len);
1507
1508         sctp_lock_sock(sk);
1509
1510         if (sctp_style(sk, TCP) && !sctp_sstate(sk, ESTABLISHED)) {
1511                 err = -ENOTCONN;
1512                 goto out;
1513         }
1514
1515         skb = sctp_skb_recv_datagram(sk, flags, noblock, &err);
1516         if (!skb)
1517                 goto out;
1518
1519         /* Get the total length of the skb including any skb's in the
1520          * frag_list.
1521          */
1522         skb_len = skb->len;
1523
1524         copied = skb_len;
1525         if (copied > len)
1526                 copied = len;
1527
1528         err = skb_copy_datagram_iovec(skb, 0, msg->msg_iov, copied);
1529
1530         event = sctp_skb2event(skb);
1531
1532         if (err)
1533                 goto out_free;
1534
1535         sock_recv_timestamp(msg, sk, skb);
1536         if (sctp_ulpevent_is_notification(event)) {
1537                 msg->msg_flags |= MSG_NOTIFICATION;
1538                 sp->pf->event_msgname(event, msg->msg_name, addr_len);
1539         } else {
1540                 sp->pf->skb_msgname(skb, msg->msg_name, addr_len);
1541         }
1542
1543         /* Check if we allow SCTP_SNDRCVINFO. */
1544         if (sp->subscribe.sctp_data_io_event)
1545                 sctp_ulpevent_read_sndrcvinfo(event, msg);
1546 #if 0
1547         /* FIXME: we should be calling IP/IPv6 layers.  */
1548         if (sk->sk_protinfo.af_inet.cmsg_flags)
1549                 ip_cmsg_recv(msg, skb);
1550 #endif
1551
1552         err = copied;
1553
1554         /* If skb's length exceeds the user's buffer, update the skb and
1555          * push it back to the receive_queue so that the next call to
1556          * recvmsg() will return the remaining data. Don't set MSG_EOR.
1557          */
1558         if (skb_len > copied) {
1559                 msg->msg_flags &= ~MSG_EOR;
1560                 if (flags & MSG_PEEK)
1561                         goto out_free;
1562                 sctp_skb_pull(skb, copied);
1563                 skb_queue_head(&sk->sk_receive_queue, skb);
1564
1565                 /* When only partial message is copied to the user, increase
1566                  * rwnd by that amount. If all the data in the skb is read,
1567                  * rwnd is updated when the event is freed.
1568                  */
1569                 sctp_assoc_rwnd_increase(event->asoc, copied);
1570                 goto out;
1571         } else if ((event->msg_flags & MSG_NOTIFICATION) ||
1572                    (event->msg_flags & MSG_EOR))
1573                 msg->msg_flags |= MSG_EOR;
1574         else
1575                 msg->msg_flags &= ~MSG_EOR;
1576
1577 out_free:
1578         if (flags & MSG_PEEK) {
1579                 /* Release the skb reference acquired after peeking the skb in
1580                  * sctp_skb_recv_datagram().
1581                  */
1582                 kfree_skb(skb);
1583         } else {
1584                 /* Free the event which includes releasing the reference to
1585                  * the owner of the skb, freeing the skb and updating the
1586                  * rwnd.
1587                  */
1588                 sctp_ulpevent_free(event);
1589         }
1590 out:
1591         sctp_release_sock(sk);
1592         return err;
1593 }
1594
1595 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
1596  *
1597  * This option is a on/off flag.  If enabled no SCTP message
1598  * fragmentation will be performed.  Instead if a message being sent
1599  * exceeds the current PMTU size, the message will NOT be sent and
1600  * instead a error will be indicated to the user.
1601  */
1602 static int sctp_setsockopt_disable_fragments(struct sock *sk,
1603                                             char __user *optval, int optlen)
1604 {
1605         int val;
1606
1607         if (optlen < sizeof(int))
1608                 return -EINVAL;
1609
1610         if (get_user(val, (int __user *)optval))
1611                 return -EFAULT;
1612
1613         sctp_sk(sk)->disable_fragments = (val == 0) ? 0 : 1;
1614
1615         return 0;
1616 }
1617
1618 static int sctp_setsockopt_events(struct sock *sk, char __user *optval,
1619                                         int optlen)
1620 {
1621         if (optlen != sizeof(struct sctp_event_subscribe))
1622                 return -EINVAL;
1623         if (copy_from_user(&sctp_sk(sk)->subscribe, optval, optlen))
1624                 return -EFAULT;
1625         return 0;
1626 }
1627
1628 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
1629  *
1630  * This socket option is applicable to the UDP-style socket only.  When
1631  * set it will cause associations that are idle for more than the
1632  * specified number of seconds to automatically close.  An association
1633  * being idle is defined an association that has NOT sent or received
1634  * user data.  The special value of '0' indicates that no automatic
1635  * close of any associations should be performed.  The option expects an
1636  * integer defining the number of seconds of idle time before an
1637  * association is closed.
1638  */
1639 static int sctp_setsockopt_autoclose(struct sock *sk, char __user *optval,
1640                                             int optlen)
1641 {
1642         struct sctp_opt *sp = sctp_sk(sk);
1643
1644         /* Applicable to UDP-style socket only */
1645         if (sctp_style(sk, TCP))
1646                 return -EOPNOTSUPP;
1647         if (optlen != sizeof(int))
1648                 return -EINVAL;
1649         if (copy_from_user(&sp->autoclose, optval, optlen))
1650                 return -EFAULT;
1651
1652         sp->ep->timeouts[SCTP_EVENT_TIMEOUT_AUTOCLOSE] = sp->autoclose * HZ;
1653         return 0;
1654 }
1655
1656 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
1657  *
1658  * Applications can enable or disable heartbeats for any peer address of
1659  * an association, modify an address's heartbeat interval, force a
1660  * heartbeat to be sent immediately, and adjust the address's maximum
1661  * number of retransmissions sent before an address is considered
1662  * unreachable.  The following structure is used to access and modify an
1663  * address's parameters:
1664  *
1665  *  struct sctp_paddrparams {
1666  *      sctp_assoc_t            spp_assoc_id;
1667  *      struct sockaddr_storage spp_address;
1668  *      uint32_t                spp_hbinterval;
1669  *      uint16_t                spp_pathmaxrxt;
1670  *  };
1671  *
1672  *   spp_assoc_id    - (UDP style socket) This is filled in the application,
1673  *                     and identifies the association for this query.
1674  *   spp_address     - This specifies which address is of interest.
1675  *   spp_hbinterval  - This contains the value of the heartbeat interval,
1676  *                     in milliseconds.  A value of 0, when modifying the
1677  *                     parameter, specifies that the heartbeat on this
1678  *                     address should be disabled. A value of UINT32_MAX
1679  *                     (4294967295), when modifying the parameter,
1680  *                     specifies that a heartbeat should be sent
1681  *                     immediately to the peer address, and the current
1682  *                     interval should remain unchanged.
1683  *   spp_pathmaxrxt  - This contains the maximum number of
1684  *                     retransmissions before this address shall be
1685  *                     considered unreachable.
1686  */
1687 static int sctp_setsockopt_peer_addr_params(struct sock *sk,
1688                                             char __user *optval, int optlen)
1689 {
1690         struct sctp_paddrparams params;
1691         struct sctp_transport *trans;
1692         int error;
1693
1694         if (optlen != sizeof(struct sctp_paddrparams))
1695                 return -EINVAL;
1696         if (copy_from_user(&params, optval, optlen))
1697                 return -EFAULT;
1698
1699         /*
1700          * API 7. Socket Options (setting the default value for the endpoint)
1701          * All options that support specific settings on an association by
1702          * filling in either an association id variable or a sockaddr_storage
1703          * SHOULD also support setting of the same value for the entire endpoint
1704          * (i.e. future associations). To accomplish this the following logic is
1705          * used when setting one of these options:
1706
1707          * c) If neither the sockaddr_storage or association identification is
1708          *    set i.e. the sockaddr_storage is set to all 0's (INADDR_ANY) and
1709          *    the association identification is 0, the settings are a default
1710          *    and to be applied to the endpoint (all future associations).
1711          */
1712
1713         /* update default value for endpoint (all future associations) */
1714         if (!params.spp_assoc_id && 
1715             sctp_is_any(( union sctp_addr *)&params.spp_address)) {
1716                 if (params.spp_hbinterval)
1717                         sctp_sk(sk)->paddrparam.spp_hbinterval =
1718                                                 params.spp_hbinterval;
1719                 if (sctp_max_retrans_path)
1720                         sctp_sk(sk)->paddrparam.spp_pathmaxrxt =
1721                                                 params.spp_pathmaxrxt;
1722                 return 0;
1723         }
1724
1725         trans = sctp_addr_id2transport(sk, &params.spp_address,
1726                                        params.spp_assoc_id);
1727         if (!trans)
1728                 return -EINVAL;
1729
1730         /* Applications can enable or disable heartbeats for any peer address
1731          * of an association, modify an address's heartbeat interval, force a
1732          * heartbeat to be sent immediately, and adjust the address's maximum
1733          * number of retransmissions sent before an address is considered
1734          * unreachable.
1735          *
1736          * The value of the heartbeat interval, in milliseconds. A value of
1737          * UINT32_MAX (4294967295), when modifying the parameter, specifies
1738          * that a heartbeat should be sent immediately to the peer address,
1739          * and the current interval should remain unchanged.
1740          */
1741         if (0xffffffff == params.spp_hbinterval) {
1742                 error = sctp_primitive_REQUESTHEARTBEAT (trans->asoc, trans);
1743                 if (error)
1744                         return error;
1745         } else {
1746         /* The value of the heartbeat interval, in milliseconds. A value of 0,
1747          * when modifying the parameter, specifies that the heartbeat on this
1748          * address should be disabled.
1749          */
1750                 if (params.spp_hbinterval) {
1751                         trans->hb_allowed = 1;
1752                         trans->hb_interval = 
1753                                 msecs_to_jiffies(params.spp_hbinterval);
1754                 } else
1755                         trans->hb_allowed = 0;
1756         }
1757
1758         /* spp_pathmaxrxt contains the maximum number of retransmissions
1759          * before this address shall be considered unreachable.
1760          */
1761         trans->error_threshold = params.spp_pathmaxrxt;
1762
1763         return 0;
1764 }
1765
1766 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
1767  *
1768  * Applications can specify protocol parameters for the default association
1769  * initialization.  The option name argument to setsockopt() and getsockopt()
1770  * is SCTP_INITMSG.
1771  *
1772  * Setting initialization parameters is effective only on an unconnected
1773  * socket (for UDP-style sockets only future associations are effected
1774  * by the change).  With TCP-style sockets, this option is inherited by
1775  * sockets derived from a listener socket.
1776  */
1777 static int sctp_setsockopt_initmsg(struct sock *sk, char __user *optval, int optlen)
1778 {
1779         struct sctp_initmsg sinit;
1780         struct sctp_opt *sp = sctp_sk(sk);
1781
1782         if (optlen != sizeof(struct sctp_initmsg))
1783                 return -EINVAL;
1784         if (copy_from_user(&sinit, optval, optlen))
1785                 return -EFAULT;
1786
1787         if (sinit.sinit_num_ostreams)
1788                 sp->initmsg.sinit_num_ostreams = sinit.sinit_num_ostreams;      
1789         if (sinit.sinit_max_instreams)
1790                 sp->initmsg.sinit_max_instreams = sinit.sinit_max_instreams;    
1791         if (sinit.sinit_max_attempts)
1792                 sp->initmsg.sinit_max_attempts = sinit.sinit_max_attempts;      
1793         if (sinit.sinit_max_init_timeo)
1794                 sp->initmsg.sinit_max_init_timeo = sinit.sinit_max_init_timeo;  
1795
1796         return 0;
1797 }
1798
1799 /*
1800  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
1801  *
1802  *   Applications that wish to use the sendto() system call may wish to
1803  *   specify a default set of parameters that would normally be supplied
1804  *   through the inclusion of ancillary data.  This socket option allows
1805  *   such an application to set the default sctp_sndrcvinfo structure.
1806  *   The application that wishes to use this socket option simply passes
1807  *   in to this call the sctp_sndrcvinfo structure defined in Section
1808  *   5.2.2) The input parameters accepted by this call include
1809  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
1810  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
1811  *   to this call if the caller is using the UDP model.
1812  */
1813 static int sctp_setsockopt_default_send_param(struct sock *sk,
1814                                                 char __user *optval, int optlen)
1815 {
1816         struct sctp_sndrcvinfo info;
1817         struct sctp_association *asoc;
1818         struct sctp_opt *sp = sctp_sk(sk);
1819
1820         if (optlen != sizeof(struct sctp_sndrcvinfo))
1821                 return -EINVAL;
1822         if (copy_from_user(&info, optval, optlen))
1823                 return -EFAULT;
1824
1825         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
1826         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
1827                 return -EINVAL;
1828
1829         if (asoc) {
1830                 asoc->default_stream = info.sinfo_stream;
1831                 asoc->default_flags = info.sinfo_flags;
1832                 asoc->default_ppid = info.sinfo_ppid;
1833                 asoc->default_context = info.sinfo_context;
1834                 asoc->default_timetolive = info.sinfo_timetolive;
1835         } else {
1836                 sp->default_stream = info.sinfo_stream;
1837                 sp->default_flags = info.sinfo_flags;
1838                 sp->default_ppid = info.sinfo_ppid;
1839                 sp->default_context = info.sinfo_context;
1840                 sp->default_timetolive = info.sinfo_timetolive;
1841         }
1842
1843         return 0;
1844 }
1845
1846 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
1847  *
1848  * Requests that the local SCTP stack use the enclosed peer address as
1849  * the association primary.  The enclosed address must be one of the
1850  * association peer's addresses.
1851  */
1852 static int sctp_setsockopt_primary_addr(struct sock *sk, char __user *optval,
1853                                         int optlen)
1854 {
1855         struct sctp_prim prim;
1856         struct sctp_transport *trans;
1857
1858         if (optlen != sizeof(struct sctp_prim))
1859                 return -EINVAL;
1860
1861         if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
1862                 return -EFAULT;
1863
1864         trans = sctp_addr_id2transport(sk, &prim.ssp_addr, prim.ssp_assoc_id);
1865         if (!trans)
1866                 return -EINVAL;
1867
1868         sctp_assoc_set_primary(trans->asoc, trans);
1869
1870         return 0;
1871 }
1872
1873 /*
1874  * 7.1.5 SCTP_NODELAY
1875  *
1876  * Turn on/off any Nagle-like algorithm.  This means that packets are
1877  * generally sent as soon as possible and no unnecessary delays are
1878  * introduced, at the cost of more packets in the network.  Expects an
1879  *  integer boolean flag.
1880  */
1881 static int sctp_setsockopt_nodelay(struct sock *sk, char __user *optval,
1882                                         int optlen)
1883 {
1884         int val;
1885
1886         if (optlen < sizeof(int))
1887                 return -EINVAL;
1888         if (get_user(val, (int __user *)optval))
1889                 return -EFAULT;
1890
1891         sctp_sk(sk)->nodelay = (val == 0) ? 0 : 1;
1892         return 0;
1893 }
1894
1895 /*
1896  *
1897  * 7.1.1 SCTP_RTOINFO
1898  *
1899  * The protocol parameters used to initialize and bound retransmission
1900  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
1901  * and modify these parameters.
1902  * All parameters are time values, in milliseconds.  A value of 0, when
1903  * modifying the parameters, indicates that the current value should not
1904  * be changed.
1905  *
1906  */
1907 static int sctp_setsockopt_rtoinfo(struct sock *sk, char __user *optval, int optlen) {
1908         struct sctp_rtoinfo rtoinfo;
1909         struct sctp_association *asoc;
1910
1911         if (optlen != sizeof (struct sctp_rtoinfo))
1912                 return -EINVAL;
1913
1914         if (copy_from_user(&rtoinfo, optval, optlen))
1915                 return -EFAULT;
1916
1917         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
1918
1919         /* Set the values to the specific association */
1920         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
1921                 return -EINVAL;
1922
1923         if (asoc) {
1924                 if (rtoinfo.srto_initial != 0)
1925                         asoc->rto_initial = 
1926                                 msecs_to_jiffies(rtoinfo.srto_initial);
1927                 if (rtoinfo.srto_max != 0)
1928                         asoc->rto_max = msecs_to_jiffies(rtoinfo.srto_max);
1929                 if (rtoinfo.srto_min != 0)
1930                         asoc->rto_min = msecs_to_jiffies(rtoinfo.srto_min);
1931         } else {
1932                 /* If there is no association or the association-id = 0
1933                  * set the values to the endpoint.
1934                  */
1935                 struct sctp_opt *sp = sctp_sk(sk);
1936
1937                 if (rtoinfo.srto_initial != 0)
1938                         sp->rtoinfo.srto_initial = rtoinfo.srto_initial;
1939                 if (rtoinfo.srto_max != 0)
1940                         sp->rtoinfo.srto_max = rtoinfo.srto_max;
1941                 if (rtoinfo.srto_min != 0)
1942                         sp->rtoinfo.srto_min = rtoinfo.srto_min;
1943         }
1944
1945         return 0;
1946 }
1947
1948 /*
1949  *
1950  * 7.1.2 SCTP_ASSOCINFO
1951  *
1952  * This option is used to tune the the maximum retransmission attempts
1953  * of the association.
1954  * Returns an error if the new association retransmission value is
1955  * greater than the sum of the retransmission value  of the peer.
1956  * See [SCTP] for more information.
1957  *
1958  */
1959 static int sctp_setsockopt_associnfo(struct sock *sk, char __user *optval, int optlen)
1960 {
1961
1962         struct sctp_assocparams assocparams;
1963         struct sctp_association *asoc;
1964
1965         if (optlen != sizeof(struct sctp_assocparams))
1966                 return -EINVAL;
1967         if (copy_from_user(&assocparams, optval, optlen))
1968                 return -EFAULT;
1969
1970         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
1971
1972         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
1973                 return -EINVAL;
1974
1975         /* Set the values to the specific association */
1976         if (asoc) {
1977                 if (assocparams.sasoc_asocmaxrxt != 0)
1978                         asoc->max_retrans = assocparams.sasoc_asocmaxrxt;
1979                 if (assocparams.sasoc_cookie_life != 0) {
1980                         asoc->cookie_life.tv_sec =
1981                                         assocparams.sasoc_cookie_life / 1000;
1982                         asoc->cookie_life.tv_usec =
1983                                         (assocparams.sasoc_cookie_life % 1000)
1984                                         * 1000;
1985                 }
1986         } else {
1987                 /* Set the values to the endpoint */
1988                 struct sctp_opt *sp = sctp_sk(sk);
1989
1990                 if (assocparams.sasoc_asocmaxrxt != 0)
1991                         sp->assocparams.sasoc_asocmaxrxt =
1992                                                 assocparams.sasoc_asocmaxrxt;
1993                 if (assocparams.sasoc_cookie_life != 0)
1994                         sp->assocparams.sasoc_cookie_life =
1995                                                 assocparams.sasoc_cookie_life;
1996         }
1997         return 0;
1998 }
1999
2000 /*
2001  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
2002  *
2003  * This socket option is a boolean flag which turns on or off mapped V4
2004  * addresses.  If this option is turned on and the socket is type
2005  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
2006  * If this option is turned off, then no mapping will be done of V4
2007  * addresses and a user will receive both PF_INET6 and PF_INET type
2008  * addresses on the socket.
2009  */
2010 static int sctp_setsockopt_mappedv4(struct sock *sk, char __user *optval, int optlen)
2011 {
2012         int val;
2013         struct sctp_opt *sp = sctp_sk(sk);
2014
2015         if (optlen < sizeof(int))
2016                 return -EINVAL;
2017         if (get_user(val, (int __user *)optval))
2018                 return -EFAULT;
2019         if (val)
2020                 sp->v4mapped = 1;
2021         else
2022                 sp->v4mapped = 0;
2023
2024         return 0;
2025 }
2026
2027 /*
2028  * 7.1.17 Set the maximum fragrmentation size (SCTP_MAXSEG)
2029  *
2030  * This socket option specifies the maximum size to put in any outgoing
2031  * SCTP chunk.  If a message is larger than this size it will be
2032  * fragmented by SCTP into the specified size.  Note that the underlying
2033  * SCTP implementation may fragment into smaller sized chunks when the
2034  * PMTU of the underlying association is smaller than the value set by
2035  * the user.
2036  */
2037 static int sctp_setsockopt_maxseg(struct sock *sk, char __user *optval, int optlen)
2038 {
2039         struct sctp_association *asoc;
2040         struct list_head *pos;
2041         struct sctp_opt *sp = sctp_sk(sk);
2042         int val;
2043
2044         if (optlen < sizeof(int))
2045                 return -EINVAL;
2046         if (get_user(val, (int __user *)optval))
2047                 return -EFAULT;
2048         if ((val < 8) || (val > SCTP_MAX_CHUNK_LEN))
2049                 return -EINVAL;
2050         sp->user_frag = val;
2051
2052         if (val) {
2053                 /* Update the frag_point of the existing associations. */
2054                 list_for_each(pos, &(sp->ep->asocs)) {
2055                         asoc = list_entry(pos, struct sctp_association, asocs);
2056                         asoc->frag_point = sctp_frag_point(sp, asoc->pmtu); 
2057                 }
2058         }
2059
2060         return 0;
2061 }
2062
2063
2064 /*
2065  *  7.1.9 Set Peer Primary Address (SCTP_SET_PEER_PRIMARY_ADDR)
2066  *
2067  *   Requests that the peer mark the enclosed address as the association
2068  *   primary. The enclosed address must be one of the association's
2069  *   locally bound addresses. The following structure is used to make a
2070  *   set primary request:
2071  */
2072 static int sctp_setsockopt_peer_primary_addr(struct sock *sk, char __user *optval,
2073                                              int optlen)
2074 {
2075         struct sctp_opt         *sp;
2076         struct sctp_endpoint    *ep;
2077         struct sctp_association *asoc = NULL;
2078         struct sctp_setpeerprim prim;
2079         struct sctp_chunk       *chunk;
2080         int                     err;
2081
2082         sp = sctp_sk(sk);
2083         ep = sp->ep;
2084
2085         if (!sctp_addip_enable)
2086                 return -EPERM;
2087
2088         if (optlen != sizeof(struct sctp_setpeerprim))
2089                 return -EINVAL;
2090
2091         if (copy_from_user(&prim, optval, optlen))
2092                 return -EFAULT;
2093
2094         asoc = sctp_id2assoc(sk, prim.sspp_assoc_id);
2095         if (!asoc) 
2096                 return -EINVAL;
2097
2098         if (!asoc->peer.asconf_capable)
2099                 return -EPERM;
2100
2101         if (asoc->peer.addip_disabled_mask & SCTP_PARAM_SET_PRIMARY)
2102                 return -EPERM;
2103
2104         if (!sctp_state(asoc, ESTABLISHED))
2105                 return -ENOTCONN;
2106
2107         if (!sctp_assoc_lookup_laddr(asoc, (union sctp_addr *)&prim.sspp_addr))
2108                 return -EADDRNOTAVAIL;
2109
2110         /* Create an ASCONF chunk with SET_PRIMARY parameter    */
2111         chunk = sctp_make_asconf_set_prim(asoc,
2112                                           (union sctp_addr *)&prim.sspp_addr);
2113         if (!chunk)
2114                 return -ENOMEM;
2115
2116         err = sctp_send_asconf(asoc, chunk);
2117
2118         SCTP_DEBUG_PRINTK("We set peer primary addr primitively.\n");
2119
2120         return err;
2121 }
2122
2123 static int sctp_setsockopt_adaption_layer(struct sock *sk, char __user *optval,
2124                                           int optlen)
2125 {
2126         __u32 val;
2127
2128         if (optlen < sizeof(__u32))
2129                 return -EINVAL;
2130         if (copy_from_user(&val, optval, sizeof(__u32)))
2131                 return -EFAULT;
2132
2133         sctp_sk(sk)->adaption_ind = val;
2134
2135         return 0;
2136 }
2137
2138 /* API 6.2 setsockopt(), getsockopt()
2139  *
2140  * Applications use setsockopt() and getsockopt() to set or retrieve
2141  * socket options.  Socket options are used to change the default
2142  * behavior of sockets calls.  They are described in Section 7.
2143  *
2144  * The syntax is:
2145  *
2146  *   ret = getsockopt(int sd, int level, int optname, void __user *optval,
2147  *                    int __user *optlen);
2148  *   ret = setsockopt(int sd, int level, int optname, const void __user *optval,
2149  *                    int optlen);
2150  *
2151  *   sd      - the socket descript.
2152  *   level   - set to IPPROTO_SCTP for all SCTP options.
2153  *   optname - the option name.
2154  *   optval  - the buffer to store the value of the option.
2155  *   optlen  - the size of the buffer.
2156  */
2157 SCTP_STATIC int sctp_setsockopt(struct sock *sk, int level, int optname,
2158                                 char __user *optval, int optlen)
2159 {
2160         int retval = 0;
2161
2162         SCTP_DEBUG_PRINTK("sctp_setsockopt(sk: %p... optname: %d)\n",
2163                           sk, optname);
2164
2165         /* I can hardly begin to describe how wrong this is.  This is
2166          * so broken as to be worse than useless.  The API draft
2167          * REALLY is NOT helpful here...  I am not convinced that the
2168          * semantics of setsockopt() with a level OTHER THAN SOL_SCTP
2169          * are at all well-founded.
2170          */
2171         if (level != SOL_SCTP) {
2172                 struct sctp_af *af = sctp_sk(sk)->pf->af;
2173                 retval = af->setsockopt(sk, level, optname, optval, optlen);
2174                 goto out_nounlock;
2175         }
2176
2177         sctp_lock_sock(sk);
2178
2179         switch (optname) {
2180         case SCTP_SOCKOPT_BINDX_ADD:
2181                 /* 'optlen' is the size of the addresses buffer. */
2182                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
2183                                                optlen, SCTP_BINDX_ADD_ADDR);
2184                 break;
2185
2186         case SCTP_SOCKOPT_BINDX_REM:
2187                 /* 'optlen' is the size of the addresses buffer. */
2188                 retval = sctp_setsockopt_bindx(sk, (struct sockaddr __user *)optval,
2189                                                optlen, SCTP_BINDX_REM_ADDR);
2190                 break;
2191
2192         case SCTP_DISABLE_FRAGMENTS:
2193                 retval = sctp_setsockopt_disable_fragments(sk, optval, optlen);
2194                 break;
2195
2196         case SCTP_EVENTS:
2197                 retval = sctp_setsockopt_events(sk, optval, optlen);
2198                 break;
2199
2200         case SCTP_AUTOCLOSE:
2201                 retval = sctp_setsockopt_autoclose(sk, optval, optlen);
2202                 break;
2203
2204         case SCTP_PEER_ADDR_PARAMS:
2205                 retval = sctp_setsockopt_peer_addr_params(sk, optval, optlen);
2206                 break;
2207
2208         case SCTP_INITMSG:
2209                 retval = sctp_setsockopt_initmsg(sk, optval, optlen);
2210                 break;
2211         case SCTP_DEFAULT_SEND_PARAM:
2212                 retval = sctp_setsockopt_default_send_param(sk, optval,
2213                                                             optlen);
2214                 break;
2215         case SCTP_PRIMARY_ADDR:
2216                 retval = sctp_setsockopt_primary_addr(sk, optval, optlen);
2217                 break;
2218         case SCTP_SET_PEER_PRIMARY_ADDR:
2219                 retval = sctp_setsockopt_peer_primary_addr(sk, optval, optlen);
2220                 break;
2221         case SCTP_NODELAY:
2222                 retval = sctp_setsockopt_nodelay(sk, optval, optlen);
2223                 break;
2224         case SCTP_RTOINFO:
2225                 retval = sctp_setsockopt_rtoinfo(sk, optval, optlen);
2226                 break;
2227         case SCTP_ASSOCINFO:
2228                 retval = sctp_setsockopt_associnfo(sk, optval, optlen);
2229                 break;
2230         case SCTP_I_WANT_MAPPED_V4_ADDR:
2231                 retval = sctp_setsockopt_mappedv4(sk, optval, optlen);
2232                 break;
2233         case SCTP_MAXSEG:
2234                 retval = sctp_setsockopt_maxseg(sk, optval, optlen);
2235                 break;
2236         case SCTP_ADAPTION_LAYER:
2237                 retval = sctp_setsockopt_adaption_layer(sk, optval, optlen);
2238                 break;
2239
2240         default:
2241                 retval = -ENOPROTOOPT;
2242                 break;
2243         };
2244
2245         sctp_release_sock(sk);
2246
2247 out_nounlock:
2248         return retval;
2249 }
2250
2251 /* API 3.1.6 connect() - UDP Style Syntax
2252  *
2253  * An application may use the connect() call in the UDP model to initiate an
2254  * association without sending data.
2255  *
2256  * The syntax is:
2257  *
2258  * ret = connect(int sd, const struct sockaddr *nam, socklen_t len);
2259  *
2260  * sd: the socket descriptor to have a new association added to.
2261  *
2262  * nam: the address structure (either struct sockaddr_in or struct
2263  *    sockaddr_in6 defined in RFC2553 [7]).
2264  *
2265  * len: the size of the address.
2266  */
2267 SCTP_STATIC int sctp_connect(struct sock *sk, struct sockaddr *uaddr,
2268                              int addr_len)
2269 {
2270         struct sctp_opt *sp;
2271         struct sctp_endpoint *ep;
2272         struct sctp_association *asoc;
2273         struct sctp_transport *transport;
2274         union sctp_addr to;
2275         struct sctp_af *af;
2276         sctp_scope_t scope;
2277         long timeo;
2278         int err = 0;
2279
2280         sctp_lock_sock(sk);
2281
2282         SCTP_DEBUG_PRINTK("%s - sk: %p, sockaddr: %p, addr_len: %d)\n",
2283                           __FUNCTION__, sk, uaddr, addr_len);
2284
2285         sp = sctp_sk(sk);
2286         ep = sp->ep;
2287
2288         /* connect() cannot be done on a socket that is already in ESTABLISHED
2289          * state - UDP-style peeled off socket or a TCP-style socket that
2290          * is already connected.
2291          * It cannot be done even on a TCP-style listening socket.
2292          */
2293         if (sctp_sstate(sk, ESTABLISHED) ||
2294             (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))) {
2295                 err = -EISCONN;
2296                 goto out_unlock;
2297         }
2298
2299         err = sctp_verify_addr(sk, (union sctp_addr *)uaddr, addr_len);
2300         if (err)
2301                 goto out_unlock;
2302
2303         if (addr_len > sizeof(to))
2304                 addr_len = sizeof(to);
2305         memcpy(&to, uaddr, addr_len);
2306         to.v4.sin_port = ntohs(to.v4.sin_port);
2307
2308         asoc = sctp_endpoint_lookup_assoc(ep, &to, &transport);
2309         if (asoc) {
2310                 if (asoc->state >= SCTP_STATE_ESTABLISHED)
2311                         err = -EISCONN;
2312                 else
2313                         err = -EALREADY;
2314                 goto out_unlock;
2315         }
2316
2317         /* If we could not find a matching association on the endpoint,
2318          * make sure that there is no peeled-off association matching the
2319          * peer address even on another socket.
2320          */
2321         if (sctp_endpoint_is_peeled_off(ep, &to)) {
2322                 err = -EADDRNOTAVAIL;
2323                 goto out_unlock;
2324         }
2325
2326         /* If a bind() or sctp_bindx() is not called prior to a connect()
2327          * call, the system picks an ephemeral port and will choose an address
2328          * set equivalent to binding with a wildcard address.
2329          */
2330         if (!ep->base.bind_addr.port) {
2331                 if (sctp_autobind(sk)) {
2332                         err = -EAGAIN;
2333                         goto out_unlock;
2334                 }
2335         }
2336
2337         scope = sctp_scope(&to);
2338         asoc = sctp_association_new(ep, sk, scope, GFP_KERNEL);
2339         if (!asoc) {
2340                 err = -ENOMEM;
2341                 goto out_unlock;
2342         }
2343
2344         /* Prime the peer's transport structures.  */
2345         transport = sctp_assoc_add_peer(asoc, &to, GFP_KERNEL);
2346         if (!transport) {
2347                 sctp_association_free(asoc);
2348                 goto out_unlock;
2349         }
2350         err = sctp_assoc_set_bind_addr_from_ep(asoc, GFP_KERNEL);
2351         if (err < 0) {
2352                 sctp_association_free(asoc);
2353                 goto out_unlock;
2354         }
2355
2356         err = sctp_primitive_ASSOCIATE(asoc, NULL);
2357         if (err < 0) {
2358                 sctp_association_free(asoc);
2359                 goto out_unlock;
2360         }
2361
2362         /* Initialize sk's dport and daddr for getpeername() */
2363         inet_sk(sk)->dport = htons(asoc->peer.port);
2364         af = sctp_get_af_specific(to.sa.sa_family);
2365         af->to_sk_daddr(&to, sk);
2366
2367         timeo = sock_sndtimeo(sk, sk->sk_socket->file->f_flags & O_NONBLOCK);
2368         err = sctp_wait_for_connect(asoc, &timeo);
2369
2370 out_unlock:
2371         sctp_release_sock(sk);
2372
2373         return err;
2374 }
2375
2376 /* FIXME: Write comments. */
2377 SCTP_STATIC int sctp_disconnect(struct sock *sk, int flags)
2378 {
2379         return -EOPNOTSUPP; /* STUB */
2380 }
2381
2382 /* 4.1.4 accept() - TCP Style Syntax
2383  *
2384  * Applications use accept() call to remove an established SCTP
2385  * association from the accept queue of the endpoint.  A new socket
2386  * descriptor will be returned from accept() to represent the newly
2387  * formed association.
2388  */
2389 SCTP_STATIC struct sock *sctp_accept(struct sock *sk, int flags, int *err)
2390 {
2391         struct sctp_opt *sp;
2392         struct sctp_endpoint *ep;
2393         struct sock *newsk = NULL;
2394         struct sctp_association *asoc;
2395         long timeo;
2396         int error = 0;
2397
2398         sctp_lock_sock(sk);
2399
2400         sp = sctp_sk(sk);
2401         ep = sp->ep;
2402
2403         if (!sctp_style(sk, TCP)) {
2404                 error = -EOPNOTSUPP;
2405                 goto out;
2406         }
2407
2408         if (!sctp_sstate(sk, LISTENING)) {
2409                 error = -EINVAL;
2410                 goto out;
2411         }
2412
2413         timeo = sock_rcvtimeo(sk, sk->sk_socket->file->f_flags & O_NONBLOCK);
2414
2415         error = sctp_wait_for_accept(sk, timeo);
2416         if (error)
2417                 goto out;
2418
2419         /* We treat the list of associations on the endpoint as the accept
2420          * queue and pick the first association on the list.
2421          */
2422         asoc = list_entry(ep->asocs.next, struct sctp_association, asocs);
2423
2424         newsk = sp->pf->create_accept_sk(sk, asoc);
2425         if (!newsk) {
2426                 error = -ENOMEM;
2427                 goto out;
2428         }
2429
2430         /* Populate the fields of the newsk from the oldsk and migrate the
2431          * asoc to the newsk.
2432          */
2433         sctp_sock_migrate(sk, newsk, asoc, SCTP_SOCKET_TCP);
2434
2435 out:
2436         sctp_release_sock(sk);
2437         *err = error;
2438         return newsk;
2439 }
2440
2441 /* The SCTP ioctl handler. */
2442 SCTP_STATIC int sctp_ioctl(struct sock *sk, int cmd, unsigned long arg)
2443 {
2444         return -ENOIOCTLCMD;
2445 }
2446
2447 /* This is the function which gets called during socket creation to
2448  * initialized the SCTP-specific portion of the sock.
2449  * The sock structure should already be zero-filled memory.
2450  */
2451 SCTP_STATIC int sctp_init_sock(struct sock *sk)
2452 {
2453         struct sctp_endpoint *ep;
2454         struct sctp_opt *sp;
2455
2456         SCTP_DEBUG_PRINTK("sctp_init_sock(sk: %p)\n", sk);
2457
2458         sp = sctp_sk(sk);
2459
2460         /* Initialize the SCTP per socket area.  */
2461         switch (sk->sk_type) {
2462         case SOCK_SEQPACKET:
2463                 sp->type = SCTP_SOCKET_UDP;
2464                 break;
2465         case SOCK_STREAM:
2466                 sp->type = SCTP_SOCKET_TCP;
2467                 break;
2468         default:
2469                 return -ESOCKTNOSUPPORT;
2470         }
2471
2472         /* Initialize default send parameters. These parameters can be
2473          * modified with the SCTP_DEFAULT_SEND_PARAM socket option.
2474          */
2475         sp->default_stream = 0;
2476         sp->default_ppid = 0;
2477         sp->default_flags = 0;
2478         sp->default_context = 0;
2479         sp->default_timetolive = 0;
2480
2481         /* Initialize default setup parameters. These parameters
2482          * can be modified with the SCTP_INITMSG socket option or
2483          * overridden by the SCTP_INIT CMSG.
2484          */
2485         sp->initmsg.sinit_num_ostreams   = sctp_max_outstreams;
2486         sp->initmsg.sinit_max_instreams  = sctp_max_instreams;
2487         sp->initmsg.sinit_max_attempts   = sctp_max_retrans_init;
2488         sp->initmsg.sinit_max_init_timeo = jiffies_to_msecs(sctp_rto_max);
2489
2490         /* Initialize default RTO related parameters.  These parameters can
2491          * be modified for with the SCTP_RTOINFO socket option.
2492          */
2493         sp->rtoinfo.srto_initial = jiffies_to_msecs(sctp_rto_initial);
2494         sp->rtoinfo.srto_max     = jiffies_to_msecs(sctp_rto_max);
2495         sp->rtoinfo.srto_min     = jiffies_to_msecs(sctp_rto_min);
2496
2497         /* Initialize default association related parameters. These parameters
2498          * can be modified with the SCTP_ASSOCINFO socket option.
2499          */
2500         sp->assocparams.sasoc_asocmaxrxt = sctp_max_retrans_association;
2501         sp->assocparams.sasoc_number_peer_destinations = 0;
2502         sp->assocparams.sasoc_peer_rwnd = 0;
2503         sp->assocparams.sasoc_local_rwnd = 0;
2504         sp->assocparams.sasoc_cookie_life = 
2505                 jiffies_to_msecs(sctp_valid_cookie_life);
2506
2507         /* Initialize default event subscriptions. By default, all the
2508          * options are off. 
2509          */
2510         memset(&sp->subscribe, 0, sizeof(struct sctp_event_subscribe));
2511
2512         /* Default Peer Address Parameters.  These defaults can
2513          * be modified via SCTP_PEER_ADDR_PARAMS
2514          */
2515         sp->paddrparam.spp_hbinterval = jiffies_to_msecs(sctp_hb_interval);
2516         sp->paddrparam.spp_pathmaxrxt = sctp_max_retrans_path;
2517
2518         /* If enabled no SCTP message fragmentation will be performed.
2519          * Configure through SCTP_DISABLE_FRAGMENTS socket option.
2520          */
2521         sp->disable_fragments = 0;
2522
2523         /* Turn on/off any Nagle-like algorithm.  */
2524         sp->nodelay           = 1;
2525
2526         /* Enable by default. */
2527         sp->v4mapped          = 1;
2528
2529         /* Auto-close idle associations after the configured
2530          * number of seconds.  A value of 0 disables this
2531          * feature.  Configure through the SCTP_AUTOCLOSE socket option,
2532          * for UDP-style sockets only.
2533          */
2534         sp->autoclose         = 0;
2535
2536         /* User specified fragmentation limit. */
2537         sp->user_frag         = 0;
2538
2539         sp->adaption_ind = 0;
2540
2541         sp->pf = sctp_get_pf_specific(sk->sk_family);
2542
2543         /* Control variables for partial data delivery. */
2544         sp->pd_mode           = 0;
2545         skb_queue_head_init(&sp->pd_lobby);
2546
2547         /* Create a per socket endpoint structure.  Even if we
2548          * change the data structure relationships, this may still
2549          * be useful for storing pre-connect address information.
2550          */
2551         ep = sctp_endpoint_new(sk, GFP_KERNEL);
2552         if (!ep)
2553                 return -ENOMEM;
2554
2555         sp->ep = ep;
2556         sp->hmac = NULL;
2557
2558         SCTP_DBG_OBJCNT_INC(sock);
2559         return 0;
2560 }
2561
2562 /* Cleanup any SCTP per socket resources.  */
2563 SCTP_STATIC int sctp_destroy_sock(struct sock *sk)
2564 {
2565         struct sctp_endpoint *ep;
2566
2567         SCTP_DEBUG_PRINTK("sctp_destroy_sock(sk: %p)\n", sk);
2568
2569         /* Release our hold on the endpoint. */
2570         ep = sctp_sk(sk)->ep;
2571         sctp_endpoint_free(ep);
2572
2573         return 0;
2574 }
2575
2576 /* API 4.1.7 shutdown() - TCP Style Syntax
2577  *     int shutdown(int socket, int how);
2578  *
2579  *     sd      - the socket descriptor of the association to be closed.
2580  *     how     - Specifies the type of shutdown.  The  values  are
2581  *               as follows:
2582  *               SHUT_RD
2583  *                     Disables further receive operations. No SCTP
2584  *                     protocol action is taken.
2585  *               SHUT_WR
2586  *                     Disables further send operations, and initiates
2587  *                     the SCTP shutdown sequence.
2588  *               SHUT_RDWR
2589  *                     Disables further send  and  receive  operations
2590  *                     and initiates the SCTP shutdown sequence.
2591  */
2592 SCTP_STATIC void sctp_shutdown(struct sock *sk, int how)
2593 {
2594         struct sctp_endpoint *ep;
2595         struct sctp_association *asoc;
2596
2597         if (!sctp_style(sk, TCP))
2598                 return;
2599
2600         if (how & SEND_SHUTDOWN) {
2601                 ep = sctp_sk(sk)->ep;
2602                 if (!list_empty(&ep->asocs)) {
2603                         asoc = list_entry(ep->asocs.next,
2604                                           struct sctp_association, asocs);
2605                         sctp_primitive_SHUTDOWN(asoc, NULL);
2606                 }
2607         }
2608 }
2609
2610 /* 7.2.1 Association Status (SCTP_STATUS)
2611
2612  * Applications can retrieve current status information about an
2613  * association, including association state, peer receiver window size,
2614  * number of unacked data chunks, and number of data chunks pending
2615  * receipt.  This information is read-only.
2616  */
2617 static int sctp_getsockopt_sctp_status(struct sock *sk, int len,
2618                                        char __user *optval,
2619                                        int __user *optlen)
2620 {
2621         struct sctp_status status;
2622         struct sctp_association *asoc = NULL;
2623         struct sctp_transport *transport;
2624         sctp_assoc_t associd;
2625         int retval = 0;
2626
2627         if (len != sizeof(status)) {
2628                 retval = -EINVAL;
2629                 goto out;
2630         }
2631
2632         if (copy_from_user(&status, optval, sizeof(status))) {
2633                 retval = -EFAULT;
2634                 goto out;
2635         }
2636
2637         associd = status.sstat_assoc_id;
2638         asoc = sctp_id2assoc(sk, associd);
2639         if (!asoc) {
2640                 retval = -EINVAL;
2641                 goto out;
2642         }
2643
2644         transport = asoc->peer.primary_path;
2645
2646         status.sstat_assoc_id = sctp_assoc2id(asoc);
2647         status.sstat_state = asoc->state;
2648         status.sstat_rwnd =  asoc->peer.rwnd;
2649         status.sstat_unackdata = asoc->unack_data;
2650
2651         status.sstat_penddata = sctp_tsnmap_pending(&asoc->peer.tsn_map);
2652         status.sstat_instrms = asoc->c.sinit_max_instreams;
2653         status.sstat_outstrms = asoc->c.sinit_num_ostreams;
2654         status.sstat_fragmentation_point = asoc->frag_point;
2655         status.sstat_primary.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
2656         memcpy(&status.sstat_primary.spinfo_address,
2657                &(transport->ipaddr), sizeof(union sctp_addr));
2658         /* Map ipv4 address into v4-mapped-on-v6 address.  */
2659         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sctp_sk(sk),
2660                 (union sctp_addr *)&status.sstat_primary.spinfo_address);
2661         status.sstat_primary.spinfo_state = transport->active;
2662         status.sstat_primary.spinfo_cwnd = transport->cwnd;
2663         status.sstat_primary.spinfo_srtt = transport->srtt;
2664         status.sstat_primary.spinfo_rto = jiffies_to_msecs(transport->rto);
2665         status.sstat_primary.spinfo_mtu = transport->pmtu;
2666
2667         if (put_user(len, optlen)) {
2668                 retval = -EFAULT;
2669                 goto out;
2670         }
2671
2672         SCTP_DEBUG_PRINTK("sctp_getsockopt_sctp_status(%d): %d %d %d\n",
2673                           len, status.sstat_state, status.sstat_rwnd,
2674                           status.sstat_assoc_id);
2675
2676         if (copy_to_user(optval, &status, len)) {
2677                 retval = -EFAULT;
2678                 goto out;
2679         }
2680
2681 out:
2682         return (retval);
2683 }
2684
2685
2686 /* 7.2.2 Peer Address Information (SCTP_GET_PEER_ADDR_INFO)
2687  *
2688  * Applications can retrieve information about a specific peer address
2689  * of an association, including its reachability state, congestion
2690  * window, and retransmission timer values.  This information is
2691  * read-only.
2692  */
2693 static int sctp_getsockopt_peer_addr_info(struct sock *sk, int len,
2694                                           char __user *optval,
2695                                           int __user *optlen)
2696 {
2697         struct sctp_paddrinfo pinfo;
2698         struct sctp_transport *transport;
2699         int retval = 0;
2700
2701         if (len != sizeof(pinfo)) {
2702                 retval = -EINVAL;
2703                 goto out;
2704         }
2705
2706         if (copy_from_user(&pinfo, optval, sizeof(pinfo))) {
2707                 retval = -EFAULT;
2708                 goto out;
2709         }
2710
2711         transport = sctp_addr_id2transport(sk, &pinfo.spinfo_address,
2712                                            pinfo.spinfo_assoc_id);
2713         if (!transport)
2714                 return -EINVAL;
2715
2716         pinfo.spinfo_assoc_id = sctp_assoc2id(transport->asoc);
2717         pinfo.spinfo_state = transport->active;
2718         pinfo.spinfo_cwnd = transport->cwnd;
2719         pinfo.spinfo_srtt = transport->srtt;
2720         pinfo.spinfo_rto = jiffies_to_msecs(transport->rto);
2721         pinfo.spinfo_mtu = transport->pmtu;
2722
2723         if (put_user(len, optlen)) {
2724                 retval = -EFAULT;
2725                 goto out;
2726         }
2727
2728         if (copy_to_user(optval, &pinfo, len)) {
2729                 retval = -EFAULT;
2730                 goto out;
2731         }
2732
2733 out:
2734         return (retval);
2735 }
2736
2737 /* 7.1.12 Enable/Disable message fragmentation (SCTP_DISABLE_FRAGMENTS)
2738  *
2739  * This option is a on/off flag.  If enabled no SCTP message
2740  * fragmentation will be performed.  Instead if a message being sent
2741  * exceeds the current PMTU size, the message will NOT be sent and
2742  * instead a error will be indicated to the user.
2743  */
2744 static int sctp_getsockopt_disable_fragments(struct sock *sk, int len,
2745                                         char __user *optval, int __user *optlen)
2746 {
2747         int val;
2748
2749         if (len < sizeof(int))
2750                 return -EINVAL;
2751
2752         len = sizeof(int);
2753         val = (sctp_sk(sk)->disable_fragments == 1);
2754         if (put_user(len, optlen))
2755                 return -EFAULT;
2756         if (copy_to_user(optval, &val, len))
2757                 return -EFAULT;
2758         return 0;
2759 }
2760
2761 /* 7.1.15 Set notification and ancillary events (SCTP_EVENTS)
2762  *
2763  * This socket option is used to specify various notifications and
2764  * ancillary data the user wishes to receive.
2765  */
2766 static int sctp_getsockopt_events(struct sock *sk, int len, char __user *optval,
2767                                   int __user *optlen)
2768 {
2769         if (len != sizeof(struct sctp_event_subscribe))
2770                 return -EINVAL;
2771         if (copy_to_user(optval, &sctp_sk(sk)->subscribe, len))
2772                 return -EFAULT;
2773         return 0;
2774 }
2775
2776 /* 7.1.8 Automatic Close of associations (SCTP_AUTOCLOSE)
2777  *
2778  * This socket option is applicable to the UDP-style socket only.  When
2779  * set it will cause associations that are idle for more than the
2780  * specified number of seconds to automatically close.  An association
2781  * being idle is defined an association that has NOT sent or received
2782  * user data.  The special value of '0' indicates that no automatic
2783  * close of any associations should be performed.  The option expects an
2784  * integer defining the number of seconds of idle time before an
2785  * association is closed.
2786  */
2787 static int sctp_getsockopt_autoclose(struct sock *sk, int len, char __user *optval, int __user *optlen)
2788 {
2789         /* Applicable to UDP-style socket only */
2790         if (sctp_style(sk, TCP))
2791                 return -EOPNOTSUPP;
2792         if (len != sizeof(int))
2793                 return -EINVAL;
2794         if (copy_to_user(optval, &sctp_sk(sk)->autoclose, len))
2795                 return -EFAULT;
2796         return 0;
2797 }
2798
2799 /* Helper routine to branch off an association to a new socket.  */
2800 SCTP_STATIC int sctp_do_peeloff(struct sctp_association *asoc,
2801                                 struct socket **sockp)
2802 {
2803         struct sock *sk = asoc->base.sk;
2804         struct socket *sock;
2805         int err = 0;
2806
2807         /* An association cannot be branched off from an already peeled-off
2808          * socket, nor is this supported for tcp style sockets.
2809          */
2810         if (!sctp_style(sk, UDP))
2811                 return -EINVAL;
2812
2813         /* Create a new socket.  */
2814         err = sock_create(sk->sk_family, SOCK_SEQPACKET, IPPROTO_SCTP, &sock);
2815         if (err < 0)
2816                 return err;
2817
2818         /* Populate the fields of the newsk from the oldsk and migrate the
2819          * asoc to the newsk.
2820          */
2821         sctp_sock_migrate(sk, sock->sk, asoc, SCTP_SOCKET_UDP_HIGH_BANDWIDTH);
2822         *sockp = sock;
2823
2824         return err;
2825 }
2826
2827 static int sctp_getsockopt_peeloff(struct sock *sk, int len, char __user *optval, int __user *optlen)
2828 {
2829         sctp_peeloff_arg_t peeloff;
2830         struct socket *newsock;
2831         int retval = 0;
2832         struct sctp_association *asoc;
2833
2834         if (len != sizeof(sctp_peeloff_arg_t))
2835                 return -EINVAL;
2836         if (copy_from_user(&peeloff, optval, len))
2837                 return -EFAULT;
2838
2839         asoc = sctp_id2assoc(sk, peeloff.associd);
2840         if (!asoc) {
2841                 retval = -EINVAL;
2842                 goto out;
2843         }
2844
2845         SCTP_DEBUG_PRINTK("%s: sk: %p asoc: %p\n", __FUNCTION__, sk, asoc);
2846
2847         retval = sctp_do_peeloff(asoc, &newsock);
2848         if (retval < 0)
2849                 goto out;
2850
2851         /* Map the socket to an unused fd that can be returned to the user.  */
2852         retval = sock_map_fd(newsock);
2853         if (retval < 0) {
2854                 sock_release(newsock);
2855                 goto out;
2856         }
2857
2858         SCTP_DEBUG_PRINTK("%s: sk: %p asoc: %p newsk: %p sd: %d\n",
2859                           __FUNCTION__, sk, asoc, newsock->sk, retval);
2860
2861         /* Return the fd mapped to the new socket.  */
2862         peeloff.sd = retval;
2863         if (copy_to_user(optval, &peeloff, len))
2864                 retval = -EFAULT;
2865
2866 out:
2867         return retval;
2868 }
2869
2870 /* 7.1.13 Peer Address Parameters (SCTP_PEER_ADDR_PARAMS)
2871  *
2872  * Applications can enable or disable heartbeats for any peer address of
2873  * an association, modify an address's heartbeat interval, force a
2874  * heartbeat to be sent immediately, and adjust the address's maximum
2875  * number of retransmissions sent before an address is considered
2876  * unreachable.  The following structure is used to access and modify an
2877  * address's parameters:
2878  *
2879  *  struct sctp_paddrparams {
2880  *      sctp_assoc_t            spp_assoc_id;
2881  *      struct sockaddr_storage spp_address;
2882  *      uint32_t                spp_hbinterval;
2883  *      uint16_t                spp_pathmaxrxt;
2884  *  };
2885  *
2886  *   spp_assoc_id    - (UDP style socket) This is filled in the application,
2887  *                     and identifies the association for this query.
2888  *   spp_address     - This specifies which address is of interest.
2889  *   spp_hbinterval  - This contains the value of the heartbeat interval,
2890  *                     in milliseconds.  A value of 0, when modifying the
2891  *                     parameter, specifies that the heartbeat on this
2892  *                     address should be disabled. A value of UINT32_MAX
2893  *                     (4294967295), when modifying the parameter,
2894  *                     specifies that a heartbeat should be sent
2895  *                     immediately to the peer address, and the current
2896  *                     interval should remain unchanged.
2897  *   spp_pathmaxrxt  - This contains the maximum number of
2898  *                     retransmissions before this address shall be
2899  *                     considered unreachable.
2900  */
2901 static int sctp_getsockopt_peer_addr_params(struct sock *sk, int len,
2902                                                 char __user *optval, int __user *optlen)
2903 {
2904         struct sctp_paddrparams params;
2905         struct sctp_transport *trans;
2906
2907         if (len != sizeof(struct sctp_paddrparams))
2908                 return -EINVAL;
2909         if (copy_from_user(&params, optval, len))
2910                 return -EFAULT;
2911
2912         /* If no association id is specified retrieve the default value
2913          * for the endpoint that will be used for all future associations
2914          */
2915         if (!params.spp_assoc_id &&
2916             sctp_is_any(( union sctp_addr *)&params.spp_address)) {
2917                 params.spp_hbinterval = sctp_sk(sk)->paddrparam.spp_hbinterval;
2918                 params.spp_pathmaxrxt = sctp_sk(sk)->paddrparam.spp_pathmaxrxt;
2919
2920                 goto done;
2921         }
2922
2923         trans = sctp_addr_id2transport(sk, &params.spp_address,
2924                                        params.spp_assoc_id);
2925         if (!trans)
2926                 return -EINVAL;
2927
2928         /* The value of the heartbeat interval, in milliseconds. A value of 0,
2929          * when modifying the parameter, specifies that the heartbeat on this
2930          * address should be disabled.
2931          */
2932         if (!trans->hb_allowed)
2933                 params.spp_hbinterval = 0;
2934         else
2935                 params.spp_hbinterval = jiffies_to_msecs(trans->hb_interval);
2936
2937         /* spp_pathmaxrxt contains the maximum number of retransmissions
2938          * before this address shall be considered unreachable.
2939          */
2940         params.spp_pathmaxrxt = trans->error_threshold;
2941
2942 done:
2943         if (copy_to_user(optval, &params, len))
2944                 return -EFAULT;
2945
2946         if (put_user(len, optlen))
2947                 return -EFAULT;
2948
2949         return 0;
2950 }
2951
2952 /* 7.1.3 Initialization Parameters (SCTP_INITMSG)
2953  *
2954  * Applications can specify protocol parameters for the default association
2955  * initialization.  The option name argument to setsockopt() and getsockopt()
2956  * is SCTP_INITMSG.
2957  *
2958  * Setting initialization parameters is effective only on an unconnected
2959  * socket (for UDP-style sockets only future associations are effected
2960  * by the change).  With TCP-style sockets, this option is inherited by
2961  * sockets derived from a listener socket.
2962  */
2963 static int sctp_getsockopt_initmsg(struct sock *sk, int len, char __user *optval, int __user *optlen)
2964 {
2965         if (len != sizeof(struct sctp_initmsg))
2966                 return -EINVAL;
2967         if (copy_to_user(optval, &sctp_sk(sk)->initmsg, len))
2968                 return -EFAULT;
2969         return 0;
2970 }
2971
2972 static int sctp_getsockopt_peer_addrs_num(struct sock *sk, int len,
2973                                           char __user *optval, int __user *optlen)
2974 {
2975         sctp_assoc_t id;
2976         struct sctp_association *asoc;
2977         struct list_head *pos;
2978         int cnt = 0;
2979
2980         if (len != sizeof(sctp_assoc_t))
2981                 return -EINVAL;
2982
2983         if (copy_from_user(&id, optval, sizeof(sctp_assoc_t)))
2984                 return -EFAULT;
2985
2986         /* For UDP-style sockets, id specifies the association to query.  */
2987         asoc = sctp_id2assoc(sk, id);
2988         if (!asoc)
2989                 return -EINVAL;
2990
2991         list_for_each(pos, &asoc->peer.transport_addr_list) {
2992                 cnt ++;
2993         }
2994
2995         return cnt;
2996 }
2997
2998 static int sctp_getsockopt_peer_addrs(struct sock *sk, int len,
2999                                       char __user *optval, int __user *optlen)
3000 {
3001         struct sctp_association *asoc;
3002         struct list_head *pos;
3003         int cnt = 0;
3004         struct sctp_getaddrs getaddrs;
3005         struct sctp_transport *from;
3006         void __user *to;
3007         union sctp_addr temp;
3008         struct sctp_opt *sp = sctp_sk(sk);
3009         int addrlen;
3010
3011         if (len != sizeof(struct sctp_getaddrs))
3012                 return -EINVAL;
3013
3014         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
3015                 return -EFAULT;
3016
3017         if (getaddrs.addr_num <= 0) return -EINVAL;
3018
3019         /* For UDP-style sockets, id specifies the association to query.  */
3020         asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
3021         if (!asoc)
3022                 return -EINVAL;
3023
3024         to = (void __user *)getaddrs.addrs;
3025         list_for_each(pos, &asoc->peer.transport_addr_list) {
3026                 from = list_entry(pos, struct sctp_transport, transports);
3027                 memcpy(&temp, &from->ipaddr, sizeof(temp));
3028                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
3029                 addrlen = sctp_get_af_specific(sk->sk_family)->sockaddr_len;
3030                 temp.v4.sin_port = htons(temp.v4.sin_port);
3031                 if (copy_to_user(to, &temp, addrlen))
3032                         return -EFAULT;
3033                 to += addrlen ;
3034                 cnt ++;
3035                 if (cnt >= getaddrs.addr_num) break;
3036         }
3037         getaddrs.addr_num = cnt;
3038         if (copy_to_user(optval, &getaddrs, sizeof(struct sctp_getaddrs)))
3039                 return -EFAULT;
3040
3041         return 0;
3042 }
3043
3044 static int sctp_getsockopt_local_addrs_num(struct sock *sk, int len,
3045                                                 char __user *optval,
3046                                                 int __user *optlen)
3047 {
3048         sctp_assoc_t id;
3049         struct sctp_bind_addr *bp;
3050         struct sctp_association *asoc;
3051         struct list_head *pos;
3052         int cnt = 0;
3053
3054         if (len != sizeof(sctp_assoc_t))
3055                 return -EINVAL;
3056
3057         if (copy_from_user(&id, optval, sizeof(sctp_assoc_t)))
3058                 return -EFAULT;
3059
3060         /*
3061          *  For UDP-style sockets, id specifies the association to query.
3062          *  If the id field is set to the value '0' then the locally bound
3063          *  addresses are returned without regard to any particular
3064          *  association.
3065          */
3066         if (0 == id) {
3067                 bp = &sctp_sk(sk)->ep->base.bind_addr;
3068         } else {
3069                 asoc = sctp_id2assoc(sk, id);
3070                 if (!asoc)
3071                         return -EINVAL;
3072                 bp = &asoc->base.bind_addr;
3073         }
3074
3075         list_for_each(pos, &bp->address_list) {
3076                 cnt ++;
3077         }
3078
3079         return cnt;
3080 }
3081
3082 static int sctp_getsockopt_local_addrs(struct sock *sk, int len,
3083                                         char __user *optval, int __user *optlen)
3084 {
3085         struct sctp_bind_addr *bp;
3086         struct sctp_association *asoc;
3087         struct list_head *pos;
3088         int cnt = 0;
3089         struct sctp_getaddrs getaddrs;
3090         struct sctp_sockaddr_entry *from;
3091         void __user *to;
3092         union sctp_addr temp;
3093         struct sctp_opt *sp = sctp_sk(sk);
3094         int addrlen;
3095
3096         if (len != sizeof(struct sctp_getaddrs))
3097                 return -EINVAL;
3098
3099         if (copy_from_user(&getaddrs, optval, sizeof(struct sctp_getaddrs)))
3100                 return -EFAULT;
3101
3102         if (getaddrs.addr_num <= 0) return -EINVAL;
3103         /*
3104          *  For UDP-style sockets, id specifies the association to query.
3105          *  If the id field is set to the value '0' then the locally bound
3106          *  addresses are returned without regard to any particular
3107          *  association.
3108          */
3109         if (0 == getaddrs.assoc_id) {
3110                 bp = &sctp_sk(sk)->ep->base.bind_addr;
3111         } else {
3112                 asoc = sctp_id2assoc(sk, getaddrs.assoc_id);
3113                 if (!asoc)
3114                         return -EINVAL;
3115                 bp = &asoc->base.bind_addr;
3116         }
3117
3118         to = getaddrs.addrs;
3119         list_for_each(pos, &bp->address_list) {
3120                 from = list_entry(pos,
3121                                 struct sctp_sockaddr_entry,
3122                                 list);
3123                 memcpy(&temp, &from->a, sizeof(temp));
3124                 sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp, &temp);
3125                 addrlen = sctp_get_af_specific(temp.sa.sa_family)->sockaddr_len;
3126                 temp.v4.sin_port = htons(temp.v4.sin_port);
3127                 if (copy_to_user(to, &temp, addrlen))
3128                         return -EFAULT;
3129                 to += addrlen;
3130                 cnt ++;
3131                 if (cnt >= getaddrs.addr_num) break;
3132         }
3133         getaddrs.addr_num = cnt;
3134         if (copy_to_user(optval, &getaddrs, sizeof(struct sctp_getaddrs)))
3135                 return -EFAULT;
3136
3137         return 0;
3138 }
3139
3140 /* 7.1.10 Set Primary Address (SCTP_PRIMARY_ADDR)
3141  *
3142  * Requests that the local SCTP stack use the enclosed peer address as
3143  * the association primary.  The enclosed address must be one of the
3144  * association peer's addresses.
3145  */
3146 static int sctp_getsockopt_primary_addr(struct sock *sk, int len,
3147                                         char __user *optval, int __user *optlen)
3148 {
3149         struct sctp_prim prim;
3150         struct sctp_association *asoc;
3151         struct sctp_opt *sp = sctp_sk(sk);
3152
3153         if (len != sizeof(struct sctp_prim))
3154                 return -EINVAL;
3155
3156         if (copy_from_user(&prim, optval, sizeof(struct sctp_prim)))
3157                 return -EFAULT;
3158
3159         asoc = sctp_id2assoc(sk, prim.ssp_assoc_id);
3160         if (!asoc)
3161                 return -EINVAL;
3162
3163         if (!asoc->peer.primary_path)
3164                 return -ENOTCONN;
3165         
3166         asoc->peer.primary_path->ipaddr.v4.sin_port =
3167                 htons(asoc->peer.primary_path->ipaddr.v4.sin_port);
3168         memcpy(&prim.ssp_addr, &asoc->peer.primary_path->ipaddr,
3169                sizeof(union sctp_addr));
3170         asoc->peer.primary_path->ipaddr.v4.sin_port =
3171                 ntohs(asoc->peer.primary_path->ipaddr.v4.sin_port);
3172
3173         sctp_get_pf_specific(sk->sk_family)->addr_v4map(sp,
3174                         (union sctp_addr *)&prim.ssp_addr);
3175
3176         if (copy_to_user(optval, &prim, sizeof(struct sctp_prim)))
3177                 return -EFAULT;
3178
3179         return 0;
3180 }
3181
3182 /*
3183  * 7.1.11  Set Adaption Layer Indicator (SCTP_ADAPTION_LAYER)
3184  *
3185  * Requests that the local endpoint set the specified Adaption Layer
3186  * Indication parameter for all future INIT and INIT-ACK exchanges.
3187  */
3188 static int sctp_getsockopt_adaption_layer(struct sock *sk, int len,
3189                                   char __user *optval, int __user *optlen)
3190 {
3191         __u32 val;
3192
3193         if (len < sizeof(__u32))
3194                 return -EINVAL;
3195
3196         len = sizeof(__u32);
3197         val = sctp_sk(sk)->adaption_ind;
3198         if (put_user(len, optlen))
3199                 return -EFAULT;
3200         if (copy_to_user(optval, &val, len))
3201                 return -EFAULT;
3202         return 0;
3203 }
3204
3205 /*
3206  *
3207  * 7.1.14 Set default send parameters (SCTP_DEFAULT_SEND_PARAM)
3208  *
3209  *   Applications that wish to use the sendto() system call may wish to
3210  *   specify a default set of parameters that would normally be supplied
3211  *   through the inclusion of ancillary data.  This socket option allows
3212  *   such an application to set the default sctp_sndrcvinfo structure.
3213
3214
3215  *   The application that wishes to use this socket option simply passes
3216  *   in to this call the sctp_sndrcvinfo structure defined in Section
3217  *   5.2.2) The input parameters accepted by this call include
3218  *   sinfo_stream, sinfo_flags, sinfo_ppid, sinfo_context,
3219  *   sinfo_timetolive.  The user must provide the sinfo_assoc_id field in
3220  *   to this call if the caller is using the UDP model.
3221  *
3222  *   For getsockopt, it get the default sctp_sndrcvinfo structure.
3223  */
3224 static int sctp_getsockopt_default_send_param(struct sock *sk,
3225                                         int len, char __user *optval,
3226                                         int __user *optlen)
3227 {
3228         struct sctp_sndrcvinfo info;
3229         struct sctp_association *asoc;
3230         struct sctp_opt *sp = sctp_sk(sk);
3231
3232         if (len != sizeof(struct sctp_sndrcvinfo))
3233                 return -EINVAL;
3234         if (copy_from_user(&info, optval, sizeof(struct sctp_sndrcvinfo)))
3235                 return -EFAULT;
3236
3237         asoc = sctp_id2assoc(sk, info.sinfo_assoc_id);
3238         if (!asoc && info.sinfo_assoc_id && sctp_style(sk, UDP))
3239                 return -EINVAL;
3240
3241         if (asoc) {
3242                 info.sinfo_stream = asoc->default_stream;
3243                 info.sinfo_flags = asoc->default_flags;
3244                 info.sinfo_ppid = asoc->default_ppid;
3245                 info.sinfo_context = asoc->default_context;
3246                 info.sinfo_timetolive = asoc->default_timetolive;
3247         } else {
3248                 info.sinfo_stream = sp->default_stream;
3249                 info.sinfo_flags = sp->default_flags;
3250                 info.sinfo_ppid = sp->default_ppid;
3251                 info.sinfo_context = sp->default_context;
3252                 info.sinfo_timetolive = sp->default_timetolive;
3253         }
3254
3255         if (copy_to_user(optval, &info, sizeof(struct sctp_sndrcvinfo)))
3256                 return -EFAULT;
3257
3258         return 0;
3259 }
3260
3261 /*
3262  *
3263  * 7.1.5 SCTP_NODELAY
3264  *
3265  * Turn on/off any Nagle-like algorithm.  This means that packets are
3266  * generally sent as soon as possible and no unnecessary delays are
3267  * introduced, at the cost of more packets in the network.  Expects an
3268  * integer boolean flag.
3269  */
3270
3271 static int sctp_getsockopt_nodelay(struct sock *sk, int len,
3272                                    char __user *optval, int __user *optlen)
3273 {
3274         int val;
3275
3276         if (len < sizeof(int))
3277                 return -EINVAL;
3278
3279         len = sizeof(int);
3280         val = (sctp_sk(sk)->nodelay == 1);
3281         if (put_user(len, optlen))
3282                 return -EFAULT;
3283         if (copy_to_user(optval, &val, len))
3284                 return -EFAULT;
3285         return 0;
3286 }
3287
3288 /*
3289  *
3290  * 7.1.1 SCTP_RTOINFO
3291  *
3292  * The protocol parameters used to initialize and bound retransmission
3293  * timeout (RTO) are tunable. sctp_rtoinfo structure is used to access
3294  * and modify these parameters.
3295  * All parameters are time values, in milliseconds.  A value of 0, when
3296  * modifying the parameters, indicates that the current value should not
3297  * be changed.
3298  *
3299  */
3300 static int sctp_getsockopt_rtoinfo(struct sock *sk, int len,
3301                                 char __user *optval,
3302                                 int __user *optlen) {
3303         struct sctp_rtoinfo rtoinfo;
3304         struct sctp_association *asoc;
3305
3306         if (len != sizeof (struct sctp_rtoinfo))
3307                 return -EINVAL;
3308
3309         if (copy_from_user(&rtoinfo, optval, sizeof (struct sctp_rtoinfo)))
3310                 return -EFAULT;
3311
3312         asoc = sctp_id2assoc(sk, rtoinfo.srto_assoc_id);
3313
3314         if (!asoc && rtoinfo.srto_assoc_id && sctp_style(sk, UDP))
3315                 return -EINVAL;
3316
3317         /* Values corresponding to the specific association. */
3318         if (asoc) {
3319                 rtoinfo.srto_initial = jiffies_to_msecs(asoc->rto_initial);
3320                 rtoinfo.srto_max = jiffies_to_msecs(asoc->rto_max);
3321                 rtoinfo.srto_min = jiffies_to_msecs(asoc->rto_min);
3322         } else {
3323                 /* Values corresponding to the endpoint. */
3324                 struct sctp_opt *sp = sctp_sk(sk);
3325
3326                 rtoinfo.srto_initial = sp->rtoinfo.srto_initial;
3327                 rtoinfo.srto_max = sp->rtoinfo.srto_max;
3328                 rtoinfo.srto_min = sp->rtoinfo.srto_min;
3329         }
3330
3331         if (put_user(len, optlen))
3332                 return -EFAULT;
3333
3334         if (copy_to_user(optval, &rtoinfo, len))
3335                 return -EFAULT;
3336
3337         return 0;
3338 }
3339
3340 /*
3341  *
3342  * 7.1.2 SCTP_ASSOCINFO
3343  *
3344  * This option is used to tune the the maximum retransmission attempts
3345  * of the association.
3346  * Returns an error if the new association retransmission value is
3347  * greater than the sum of the retransmission value  of the peer.
3348  * See [SCTP] for more information.
3349  *
3350  */
3351 static int sctp_getsockopt_associnfo(struct sock *sk, int len,
3352                                      char __user *optval,
3353                                      int __user *optlen)
3354 {
3355
3356         struct sctp_assocparams assocparams;
3357         struct sctp_association *asoc;
3358         struct list_head *pos;
3359         int cnt = 0;
3360
3361         if (len != sizeof (struct sctp_assocparams))
3362                 return -EINVAL;
3363
3364         if (copy_from_user(&assocparams, optval,
3365                         sizeof (struct sctp_assocparams)))
3366                 return -EFAULT;
3367
3368         asoc = sctp_id2assoc(sk, assocparams.sasoc_assoc_id);
3369
3370         if (!asoc && assocparams.sasoc_assoc_id && sctp_style(sk, UDP))
3371                 return -EINVAL;
3372
3373         /* Values correspoinding to the specific association */
3374         if (assocparams.sasoc_assoc_id != 0) {
3375                 assocparams.sasoc_asocmaxrxt = asoc->max_retrans;
3376                 assocparams.sasoc_peer_rwnd = asoc->peer.rwnd;
3377                 assocparams.sasoc_local_rwnd = asoc->a_rwnd;
3378                 assocparams.sasoc_cookie_life = (asoc->cookie_life.tv_sec
3379                                                 * 1000) +
3380                                                 (asoc->cookie_life.tv_usec
3381                                                 / 1000);
3382
3383                 list_for_each(pos, &asoc->peer.transport_addr_list) {
3384                         cnt ++;
3385                 }
3386
3387                 assocparams.sasoc_number_peer_destinations = cnt;
3388         } else {
3389                 /* Values corresponding to the endpoint */
3390                 struct sctp_opt *sp = sctp_sk(sk);
3391
3392                 assocparams.sasoc_asocmaxrxt = sp->assocparams.sasoc_asocmaxrxt;
3393                 assocparams.sasoc_peer_rwnd = sp->assocparams.sasoc_peer_rwnd;
3394                 assocparams.sasoc_local_rwnd = sp->assocparams.sasoc_local_rwnd;
3395                 assocparams.sasoc_cookie_life =
3396                                         sp->assocparams.sasoc_cookie_life;
3397                 assocparams.sasoc_number_peer_destinations =
3398                                         sp->assocparams.
3399                                         sasoc_number_peer_destinations;
3400         }
3401
3402         if (put_user(len, optlen))
3403                 return -EFAULT;
3404
3405         if (copy_to_user(optval, &assocparams, len))
3406                 return -EFAULT;
3407
3408         return 0;
3409 }
3410
3411 /*
3412  * 7.1.16 Set/clear IPv4 mapped addresses (SCTP_I_WANT_MAPPED_V4_ADDR)
3413  *
3414  * This socket option is a boolean flag which turns on or off mapped V4
3415  * addresses.  If this option is turned on and the socket is type
3416  * PF_INET6, then IPv4 addresses will be mapped to V6 representation.
3417  * If this option is turned off, then no mapping will be done of V4
3418  * addresses and a user will receive both PF_INET6 and PF_INET type
3419  * addresses on the socket.
3420  */
3421 static int sctp_getsockopt_mappedv4(struct sock *sk, int len,
3422                                     char __user *optval, int __user *optlen)
3423 {
3424         int val;
3425         struct sctp_opt *sp = sctp_sk(sk);
3426
3427         if (len < sizeof(int))
3428                 return -EINVAL;
3429
3430         len = sizeof(int);
3431         val = sp->v4mapped;
3432         if (put_user(len, optlen))
3433                 return -EFAULT;
3434         if (copy_to_user(optval, &val, len))
3435                 return -EFAULT;
3436
3437         return 0;
3438 }
3439
3440 /*
3441  * 7.1.17 Set the maximum fragrmentation size (SCTP_MAXSEG)
3442  *
3443  * This socket option specifies the maximum size to put in any outgoing
3444  * SCTP chunk.  If a message is larger than this size it will be
3445  * fragmented by SCTP into the specified size.  Note that the underlying
3446  * SCTP implementation may fragment into smaller sized chunks when the
3447  * PMTU of the underlying association is smaller than the value set by
3448  * the user.
3449  */
3450 static int sctp_getsockopt_maxseg(struct sock *sk, int len,
3451                                   char __user *optval, int __user *optlen)
3452 {
3453         int val;
3454
3455         if (len < sizeof(int))
3456                 return -EINVAL;
3457
3458         len = sizeof(int);
3459
3460         val = sctp_sk(sk)->user_frag;
3461         if (put_user(len, optlen))
3462                 return -EFAULT;
3463         if (copy_to_user(optval, &val, len))
3464                 return -EFAULT;
3465
3466         return 0;
3467 }
3468
3469 SCTP_STATIC int sctp_getsockopt(struct sock *sk, int level, int optname,
3470                                 char __user *optval, int __user *optlen)
3471 {
3472         int retval = 0;
3473         int len;
3474
3475         SCTP_DEBUG_PRINTK("sctp_getsockopt(sk: %p, ...)\n", sk);
3476
3477         /* I can hardly begin to describe how wrong this is.  This is
3478          * so broken as to be worse than useless.  The API draft
3479          * REALLY is NOT helpful here...  I am not convinced that the
3480          * semantics of getsockopt() with a level OTHER THAN SOL_SCTP
3481          * are at all well-founded.
3482          */
3483         if (level != SOL_SCTP) {
3484                 struct sctp_af *af = sctp_sk(sk)->pf->af;
3485
3486                 retval = af->getsockopt(sk, level, optname, optval, optlen);
3487                 return retval;
3488         }
3489
3490         if (get_user(len, optlen))
3491                 return -EFAULT;
3492
3493         sctp_lock_sock(sk);
3494
3495         switch (optname) {
3496         case SCTP_STATUS:
3497                 retval = sctp_getsockopt_sctp_status(sk, len, optval, optlen);
3498                 break;
3499         case SCTP_DISABLE_FRAGMENTS:
3500                 retval = sctp_getsockopt_disable_fragments(sk, len, optval,
3501                                                            optlen);
3502                 break;
3503         case SCTP_EVENTS:
3504                 retval = sctp_getsockopt_events(sk, len, optval, optlen);
3505                 break;
3506         case SCTP_AUTOCLOSE:
3507                 retval = sctp_getsockopt_autoclose(sk, len, optval, optlen);
3508                 break;
3509         case SCTP_SOCKOPT_PEELOFF:
3510                 retval = sctp_getsockopt_peeloff(sk, len, optval, optlen);
3511                 break;
3512         case SCTP_PEER_ADDR_PARAMS:
3513                 retval = sctp_getsockopt_peer_addr_params(sk, len, optval,
3514                                                           optlen);
3515                 break;
3516         case SCTP_INITMSG:
3517                 retval = sctp_getsockopt_initmsg(sk, len, optval, optlen);
3518                 break;
3519         case SCTP_GET_PEER_ADDRS_NUM:
3520                 retval = sctp_getsockopt_peer_addrs_num(sk, len, optval,
3521                                                         optlen);
3522                 break;
3523         case SCTP_GET_LOCAL_ADDRS_NUM:
3524                 retval = sctp_getsockopt_local_addrs_num(sk, len, optval,
3525                                                          optlen);
3526                 break;
3527         case SCTP_GET_PEER_ADDRS:
3528                 retval = sctp_getsockopt_peer_addrs(sk, len, optval,
3529                                                     optlen);
3530                 break;
3531         case SCTP_GET_LOCAL_ADDRS:
3532                 retval = sctp_getsockopt_local_addrs(sk, len, optval,
3533                                                      optlen);
3534                 break;
3535         case SCTP_DEFAULT_SEND_PARAM:
3536                 retval = sctp_getsockopt_default_send_param(sk, len,
3537                                                             optval, optlen);
3538                 break;
3539         case SCTP_PRIMARY_ADDR:
3540                 retval = sctp_getsockopt_primary_addr(sk, len, optval, optlen);
3541                 break;
3542         case SCTP_NODELAY:
3543                 retval = sctp_getsockopt_nodelay(sk, len, optval, optlen);
3544                 break;
3545         case SCTP_RTOINFO:
3546                 retval = sctp_getsockopt_rtoinfo(sk, len, optval, optlen);
3547                 break;
3548         case SCTP_ASSOCINFO:
3549                 retval = sctp_getsockopt_associnfo(sk, len, optval, optlen);
3550                 break;
3551         case SCTP_I_WANT_MAPPED_V4_ADDR:
3552                 retval = sctp_getsockopt_mappedv4(sk, len, optval, optlen);
3553                 break;
3554         case SCTP_MAXSEG:
3555                 retval = sctp_getsockopt_maxseg(sk, len, optval, optlen);
3556                 break;
3557         case SCTP_GET_PEER_ADDR_INFO:
3558                 retval = sctp_getsockopt_peer_addr_info(sk, len, optval,
3559                                                         optlen);
3560                 break;
3561         case SCTP_ADAPTION_LAYER:
3562                 retval = sctp_getsockopt_adaption_layer(sk, len, optval,
3563                                                         optlen);
3564                 break;
3565         default:
3566                 retval = -ENOPROTOOPT;
3567                 break;
3568         };
3569
3570         sctp_release_sock(sk);
3571         return retval;
3572 }
3573
3574 static void sctp_hash(struct sock *sk)
3575 {
3576         /* STUB */
3577 }
3578
3579 static void sctp_unhash(struct sock *sk)
3580 {
3581         /* STUB */
3582 }
3583
3584 /* Check if port is acceptable.  Possibly find first available port.
3585  *
3586  * The port hash table (contained in the 'global' SCTP protocol storage
3587  * returned by struct sctp_protocol *sctp_get_protocol()). The hash
3588  * table is an array of 4096 lists (sctp_bind_hashbucket). Each
3589  * list (the list number is the port number hashed out, so as you
3590  * would expect from a hash function, all the ports in a given list have
3591  * such a number that hashes out to the same list number; you were
3592  * expecting that, right?); so each list has a set of ports, with a
3593  * link to the socket (struct sock) that uses it, the port number and
3594  * a fastreuse flag (FIXME: NPI ipg).
3595  */
3596 static struct sctp_bind_bucket *sctp_bucket_create(
3597         struct sctp_bind_hashbucket *head, unsigned short snum);
3598
3599 static long sctp_get_port_local(struct sock *sk, union sctp_addr *addr)
3600 {
3601         struct sctp_bind_hashbucket *head; /* hash list */
3602         struct sctp_bind_bucket *pp; /* hash list port iterator */
3603         unsigned short snum;
3604         int ret;
3605
3606         /* NOTE:  Remember to put this back to net order. */
3607         addr->v4.sin_port = ntohs(addr->v4.sin_port);
3608         snum = addr->v4.sin_port;
3609
3610         SCTP_DEBUG_PRINTK("sctp_get_port() begins, snum=%d\n", snum);
3611         sctp_local_bh_disable();
3612
3613         if (snum == 0) {
3614                 /* Search for an available port.
3615                  *
3616                  * 'sctp_port_rover' was the last port assigned, so
3617                  * we start to search from 'sctp_port_rover +
3618                  * 1'. What we do is first check if port 'rover' is
3619                  * already in the hash table; if not, we use that; if
3620                  * it is, we try next.
3621                  */
3622                 int low = sysctl_local_port_range[0];
3623                 int high = sysctl_local_port_range[1];
3624                 int remaining = (high - low) + 1;
3625                 int rover;
3626                 int index;
3627
3628                 sctp_spin_lock(&sctp_port_alloc_lock);
3629                 rover = sctp_port_rover;
3630                 do {
3631                         rover++;
3632                         if ((rover < low) || (rover > high))
3633                                 rover = low;
3634                         index = sctp_phashfn(rover);
3635                         head = &sctp_port_hashtable[index];
3636                         sctp_spin_lock(&head->lock);
3637                         for (pp = head->chain; pp; pp = pp->next)
3638                                 if (pp->port == rover)
3639                                         goto next;
3640                         break;
3641                 next:
3642                         sctp_spin_unlock(&head->lock);
3643                 } while (--remaining > 0);
3644                 sctp_port_rover = rover;
3645                 sctp_spin_unlock(&sctp_port_alloc_lock);
3646
3647                 /* Exhausted local port range during search? */
3648                 ret = 1;
3649                 if (remaining <= 0)
3650                         goto fail;
3651
3652                 /* OK, here is the one we will use.  HEAD (the port
3653                  * hash table list entry) is non-NULL and we hold it's
3654                  * mutex.
3655                  */
3656                 snum = rover;
3657         } else {
3658                 /* We are given an specific port number; we verify
3659                  * that it is not being used. If it is used, we will
3660                  * exahust the search in the hash list corresponding
3661                  * to the port number (snum) - we detect that with the
3662                  * port iterator, pp being NULL.
3663                  */
3664                 head = &sctp_port_hashtable[sctp_phashfn(snum)];
3665                 sctp_spin_lock(&head->lock);
3666                 for (pp = head->chain; pp; pp = pp->next) {
3667                         if (pp->port == snum)
3668                                 goto pp_found;
3669                 }
3670         }
3671         pp = NULL;
3672         goto pp_not_found;
3673 pp_found:
3674         if (!hlist_empty(&pp->owner)) {
3675                 /* We had a port hash table hit - there is an
3676                  * available port (pp != NULL) and it is being
3677                  * used by other socket (pp->owner not empty); that other
3678                  * socket is going to be sk2.
3679                  */
3680                 int reuse = sk->sk_reuse;
3681                 struct sock *sk2;
3682                 struct hlist_node *node;
3683
3684                 SCTP_DEBUG_PRINTK("sctp_get_port() found a possible match\n");
3685                 if (pp->fastreuse && sk->sk_reuse)
3686                         goto success;
3687
3688                 /* Run through the list of sockets bound to the port
3689                  * (pp->port) [via the pointers bind_next and
3690                  * bind_pprev in the struct sock *sk2 (pp->sk)]. On each one,
3691                  * we get the endpoint they describe and run through
3692                  * the endpoint's list of IP (v4 or v6) addresses,
3693                  * comparing each of the addresses with the address of
3694                  * the socket sk. If we find a match, then that means
3695                  * that this port/socket (sk) combination are already
3696                  * in an endpoint.
3697                  */
3698                 sk_for_each_bound(sk2, node, &pp->owner) {
3699                         struct sctp_endpoint *ep2;
3700                         ep2 = sctp_sk(sk2)->ep;
3701
3702                         if (reuse && sk2->sk_reuse)
3703                                 continue;
3704
3705                         if (sctp_bind_addr_match(&ep2->base.bind_addr, addr,
3706                                                  sctp_sk(sk))) {
3707                                 ret = (long)sk2;
3708                                 goto fail_unlock;
3709                         }
3710                 }
3711                 SCTP_DEBUG_PRINTK("sctp_get_port(): Found a match\n");
3712         }
3713 pp_not_found:
3714         /* If there was a hash table miss, create a new port.  */
3715         ret = 1;
3716         if (!pp && !(pp = sctp_bucket_create(head, snum)))
3717                 goto fail_unlock;
3718
3719         /* In either case (hit or miss), make sure fastreuse is 1 only
3720          * if sk->sk_reuse is too (that is, if the caller requested
3721          * SO_REUSEADDR on this socket -sk-).
3722          */
3723         if (hlist_empty(&pp->owner))
3724                 pp->fastreuse = sk->sk_reuse ? 1 : 0;
3725         else if (pp->fastreuse && !sk->sk_reuse)
3726                 pp->fastreuse = 0;
3727
3728         /* We are set, so fill up all the data in the hash table
3729          * entry, tie the socket list information with the rest of the
3730          * sockets FIXME: Blurry, NPI (ipg).
3731          */
3732 success:
3733         inet_sk(sk)->num = snum;
3734         if (!sctp_sk(sk)->bind_hash) {
3735                 sk_add_bind_node(sk, &pp->owner);
3736                 sctp_sk(sk)->bind_hash = pp;
3737         }
3738         ret = 0;
3739
3740 fail_unlock:
3741         sctp_spin_unlock(&head->lock);
3742
3743 fail:
3744         sctp_local_bh_enable();
3745         addr->v4.sin_port = htons(addr->v4.sin_port);
3746         return ret;
3747 }
3748
3749 /* Assign a 'snum' port to the socket.  If snum == 0, an ephemeral
3750  * port is requested.
3751  */
3752 static int sctp_get_port(struct sock *sk, unsigned short snum)
3753 {
3754         long ret;
3755         union sctp_addr addr;
3756         struct sctp_af *af = sctp_sk(sk)->pf->af;
3757
3758         /* Set up a dummy address struct from the sk. */
3759         af->from_sk(&addr, sk);
3760         addr.v4.sin_port = htons(snum);
3761
3762         /* Note: sk->sk_num gets filled in if ephemeral port request. */
3763         ret = sctp_get_port_local(sk, &addr);
3764
3765         return (ret ? 1 : 0);
3766 }
3767
3768 /*
3769  * 3.1.3 listen() - UDP Style Syntax
3770  *
3771  *   By default, new associations are not accepted for UDP style sockets.
3772  *   An application uses listen() to mark a socket as being able to
3773  *   accept new associations.
3774  */
3775 SCTP_STATIC int sctp_seqpacket_listen(struct sock *sk, int backlog)
3776 {
3777         struct sctp_opt *sp = sctp_sk(sk);
3778         struct sctp_endpoint *ep = sp->ep;
3779
3780         /* Only UDP style sockets that are not peeled off are allowed to
3781          * listen().
3782          */
3783         if (!sctp_style(sk, UDP))
3784                 return -EINVAL;
3785
3786         /* If backlog is zero, disable listening. */
3787         if (!backlog) {
3788                 if (sctp_sstate(sk, CLOSED))
3789                         return 0;
3790                 
3791                 sctp_unhash_endpoint(ep);
3792                 sk->sk_state = SCTP_SS_CLOSED;
3793         }
3794
3795         /* Return if we are already listening. */
3796         if (sctp_sstate(sk, LISTENING))
3797                 return 0;
3798                 
3799         /*
3800          * If a bind() or sctp_bindx() is not called prior to a listen()
3801          * call that allows new associations to be accepted, the system
3802          * picks an ephemeral port and will choose an address set equivalent
3803          * to binding with a wildcard address.
3804          *
3805          * This is not currently spelled out in the SCTP sockets
3806          * extensions draft, but follows the practice as seen in TCP
3807          * sockets.
3808          */
3809         if (!ep->base.bind_addr.port) {
3810                 if (sctp_autobind(sk))
3811                         return -EAGAIN;
3812         }
3813         sk->sk_state = SCTP_SS_LISTENING;
3814         sctp_hash_endpoint(ep);
3815         return 0;
3816 }
3817
3818 /*
3819  * 4.1.3 listen() - TCP Style Syntax
3820  *
3821  *   Applications uses listen() to ready the SCTP endpoint for accepting
3822  *   inbound associations.
3823  */
3824 SCTP_STATIC int sctp_stream_listen(struct sock *sk, int backlog)
3825 {
3826         struct sctp_opt *sp = sctp_sk(sk);
3827         struct sctp_endpoint *ep = sp->ep;
3828
3829         /* If backlog is zero, disable listening. */
3830         if (!backlog) {
3831                 if (sctp_sstate(sk, CLOSED))
3832                         return 0;
3833                 
3834                 sctp_unhash_endpoint(ep);
3835                 sk->sk_state = SCTP_SS_CLOSED;
3836         }
3837
3838         if (sctp_sstate(sk, LISTENING))
3839                 return 0;
3840
3841         /*
3842          * If a bind() or sctp_bindx() is not called prior to a listen()
3843          * call that allows new associations to be accepted, the system
3844          * picks an ephemeral port and will choose an address set equivalent
3845          * to binding with a wildcard address.
3846          *
3847          * This is not currently spelled out in the SCTP sockets
3848          * extensions draft, but follows the practice as seen in TCP
3849          * sockets.
3850          */
3851         if (!ep->base.bind_addr.port) {
3852                 if (sctp_autobind(sk))
3853                         return -EAGAIN;
3854         }
3855         sk->sk_state = SCTP_SS_LISTENING;
3856         sk->sk_max_ack_backlog = backlog;
3857         sctp_hash_endpoint(ep);
3858         return 0;
3859 }
3860
3861 /*
3862  *  Move a socket to LISTENING state.
3863  */
3864 int sctp_inet_listen(struct socket *sock, int backlog)
3865 {
3866         struct sock *sk = sock->sk;
3867         struct crypto_tfm *tfm=NULL;
3868         int err = -EINVAL;
3869
3870         if (unlikely(backlog < 0))
3871                 goto out;
3872
3873         sctp_lock_sock(sk);
3874
3875         if (sock->state != SS_UNCONNECTED)
3876                 goto out;
3877
3878         /* Allocate HMAC for generating cookie. */
3879         if (sctp_hmac_alg) {
3880                 tfm = sctp_crypto_alloc_tfm(sctp_hmac_alg, 0);
3881                 if (!tfm) {
3882                         err = -ENOSYS;
3883                         goto out;
3884                 }
3885         }
3886
3887         switch (sock->type) {
3888         case SOCK_SEQPACKET:
3889                 err = sctp_seqpacket_listen(sk, backlog);
3890                 break;
3891         case SOCK_STREAM:
3892                 err = sctp_stream_listen(sk, backlog);
3893                 break;
3894         default:
3895                 break;
3896         };
3897         if (err)
3898                 goto cleanup;
3899
3900         /* Store away the transform reference. */
3901         sctp_sk(sk)->hmac = tfm;
3902 out:
3903         sctp_release_sock(sk);
3904         return err;
3905 cleanup:
3906         if (tfm)
3907                 sctp_crypto_free_tfm(tfm);
3908         goto out;
3909 }
3910
3911 /*
3912  * This function is done by modeling the current datagram_poll() and the
3913  * tcp_poll().  Note that, based on these implementations, we don't
3914  * lock the socket in this function, even though it seems that,
3915  * ideally, locking or some other mechanisms can be used to ensure
3916  * the integrity of the counters (sndbuf and wmem_queued) used
3917  * in this place.  We assume that we don't need locks either until proven
3918  * otherwise.
3919  *
3920  * Another thing to note is that we include the Async I/O support
3921  * here, again, by modeling the current TCP/UDP code.  We don't have
3922  * a good way to test with it yet.
3923  */
3924 unsigned int sctp_poll(struct file *file, struct socket *sock, poll_table *wait)
3925 {
3926         struct sock *sk = sock->sk;
3927         struct sctp_opt *sp = sctp_sk(sk);
3928         unsigned int mask;
3929
3930         poll_wait(file, sk->sk_sleep, wait);
3931
3932         /* A TCP-style listening socket becomes readable when the accept queue
3933          * is not empty.
3934          */
3935         if (sctp_style(sk, TCP) && sctp_sstate(sk, LISTENING))
3936                 return (!list_empty(&sp->ep->asocs)) ?
3937                         (POLLIN | POLLRDNORM) : 0;
3938
3939         mask = 0;
3940
3941         /* Is there any exceptional events?  */
3942         if (sk->sk_err || !skb_queue_empty(&sk->sk_error_queue))
3943                 mask |= POLLERR;
3944         if (sk->sk_shutdown == SHUTDOWN_MASK)
3945                 mask |= POLLHUP;
3946
3947         /* Is it readable?  Reconsider this code with TCP-style support.  */
3948         if (!skb_queue_empty(&sk->sk_receive_queue) ||
3949             (sk->sk_shutdown & RCV_SHUTDOWN))
3950                 mask |= POLLIN | POLLRDNORM;
3951
3952         /* The association is either gone or not ready.  */
3953         if (!sctp_style(sk, UDP) && sctp_sstate(sk, CLOSED))
3954                 return mask;
3955
3956         /* Is it writable?  */
3957         if (sctp_writeable(sk)) {
3958                 mask |= POLLOUT | POLLWRNORM;
3959         } else {
3960                 set_bit(SOCK_ASYNC_NOSPACE, &sk->sk_socket->flags);
3961                 /*
3962                  * Since the socket is not locked, the buffer
3963                  * might be made available after the writeable check and
3964                  * before the bit is set.  This could cause a lost I/O
3965                  * signal.  tcp_poll() has a race breaker for this race
3966                  * condition.  Based on their implementation, we put
3967                  * in the following code to cover it as well.
3968                  */
3969                 if (sctp_writeable(sk))
3970                         mask |= POLLOUT | POLLWRNORM;
3971         }
3972         return mask;
3973 }
3974
3975 /********************************************************************
3976  * 2nd Level Abstractions
3977  ********************************************************************/
3978
3979 static struct sctp_bind_bucket *sctp_bucket_create(
3980         struct sctp_bind_hashbucket *head, unsigned short snum)
3981 {
3982         struct sctp_bind_bucket *pp;
3983
3984         pp = kmem_cache_alloc(sctp_bucket_cachep, SLAB_ATOMIC);
3985         SCTP_DBG_OBJCNT_INC(bind_bucket);
3986         if (pp) {
3987                 pp->port = snum;
3988                 pp->fastreuse = 0;
3989                 INIT_HLIST_HEAD(&pp->owner);
3990                 if ((pp->next = head->chain) != NULL)
3991                         pp->next->pprev = &pp->next;
3992                 head->chain = pp;
3993                 pp->pprev = &head->chain;
3994         }
3995         return pp;
3996 }
3997
3998 /* Caller must hold hashbucket lock for this tb with local BH disabled */
3999 static void sctp_bucket_destroy(struct sctp_bind_bucket *pp)
4000 {
4001         if (hlist_empty(&pp->owner)) {
4002                 if (pp->next)
4003                         pp->next->pprev = pp->pprev;
4004                 *(pp->pprev) = pp->next;
4005                 kmem_cache_free(sctp_bucket_cachep, pp);
4006                 SCTP_DBG_OBJCNT_DEC(bind_bucket);
4007         }
4008 }
4009
4010 /* Release this socket's reference to a local port.  */
4011 static inline void __sctp_put_port(struct sock *sk)
4012 {
4013         struct sctp_bind_hashbucket *head =
4014                 &sctp_port_hashtable[sctp_phashfn(inet_sk(sk)->num)];
4015         struct sctp_bind_bucket *pp;
4016
4017         sctp_spin_lock(&head->lock);
4018         pp = sctp_sk(sk)->bind_hash;
4019         __sk_del_bind_node(sk);
4020         sctp_sk(sk)->bind_hash = NULL;
4021         inet_sk(sk)->num = 0;
4022         sctp_bucket_destroy(pp);
4023         sctp_spin_unlock(&head->lock);
4024 }
4025
4026 void sctp_put_port(struct sock *sk)
4027 {
4028         sctp_local_bh_disable();
4029         __sctp_put_port(sk);
4030         sctp_local_bh_enable();
4031 }
4032
4033 /*
4034  * The system picks an ephemeral port and choose an address set equivalent
4035  * to binding with a wildcard address.
4036  * One of those addresses will be the primary address for the association.
4037  * This automatically enables the multihoming capability of SCTP.
4038  */
4039 static int sctp_autobind(struct sock *sk)
4040 {
4041         union sctp_addr autoaddr;
4042         struct sctp_af *af;
4043         unsigned short port;
4044
4045         /* Initialize a local sockaddr structure to INADDR_ANY. */
4046         af = sctp_sk(sk)->pf->af;
4047
4048         port = htons(inet_sk(sk)->num);
4049         af->inaddr_any(&autoaddr, port);
4050
4051         return sctp_do_bind(sk, &autoaddr, af->sockaddr_len);
4052 }
4053
4054 /* Parse out IPPROTO_SCTP CMSG headers.  Perform only minimal validation.
4055  *
4056  * From RFC 2292
4057  * 4.2 The cmsghdr Structure *
4058  *
4059  * When ancillary data is sent or received, any number of ancillary data
4060  * objects can be specified by the msg_control and msg_controllen members of
4061  * the msghdr structure, because each object is preceded by
4062  * a cmsghdr structure defining the object's length (the cmsg_len member).
4063  * Historically Berkeley-derived implementations have passed only one object
4064  * at a time, but this API allows multiple objects to be
4065  * passed in a single call to sendmsg() or recvmsg(). The following example
4066  * shows two ancillary data objects in a control buffer.
4067  *
4068  *   |<--------------------------- msg_controllen -------------------------->|
4069  *   |                                                                       |
4070  *
4071  *   |<----- ancillary data object ----->|<----- ancillary data object ----->|
4072  *
4073  *   |<---------- CMSG_SPACE() --------->|<---------- CMSG_SPACE() --------->|
4074  *   |                                   |                                   |
4075  *
4076  *   |<---------- cmsg_len ---------->|  |<--------- cmsg_len ----------->|  |
4077  *
4078  *   |<--------- CMSG_LEN() --------->|  |<-------- CMSG_LEN() ---------->|  |
4079  *   |                                |  |                                |  |
4080  *
4081  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
4082  *   |cmsg_|cmsg_|cmsg_|XX|           |XX|cmsg_|cmsg_|cmsg_|XX|           |XX|
4083  *
4084  *   |len  |level|type |XX|cmsg_data[]|XX|len  |level|type |XX|cmsg_data[]|XX|
4085  *
4086  *   +-----+-----+-----+--+-----------+--+-----+-----+-----+--+-----------+--+
4087  *    ^
4088  *    |
4089  *
4090  * msg_control
4091  * points here
4092  */
4093 SCTP_STATIC int sctp_msghdr_parse(const struct msghdr *msg,
4094                                   sctp_cmsgs_t *cmsgs)
4095 {
4096         struct cmsghdr *cmsg;
4097
4098         for (cmsg = CMSG_FIRSTHDR(msg);
4099              cmsg != NULL;
4100              cmsg = CMSG_NXTHDR((struct msghdr*)msg, cmsg)) {
4101                 if (!CMSG_OK(msg, cmsg))
4102                         return -EINVAL;
4103
4104                 /* Should we parse this header or ignore?  */
4105                 if (cmsg->cmsg_level != IPPROTO_SCTP)
4106                         continue;
4107
4108                 /* Strictly check lengths following example in SCM code.  */
4109                 switch (cmsg->cmsg_type) {
4110                 case SCTP_INIT:
4111                         /* SCTP Socket API Extension
4112                          * 5.2.1 SCTP Initiation Structure (SCTP_INIT)
4113                          *
4114                          * This cmsghdr structure provides information for
4115                          * initializing new SCTP associations with sendmsg().
4116                          * The SCTP_INITMSG socket option uses this same data
4117                          * structure.  This structure is not used for
4118                          * recvmsg().
4119                          *
4120                          * cmsg_level    cmsg_type      cmsg_data[]
4121                          * ------------  ------------   ----------------------
4122                          * IPPROTO_SCTP  SCTP_INIT      struct sctp_initmsg
4123                          */
4124                         if (cmsg->cmsg_len !=
4125                             CMSG_LEN(sizeof(struct sctp_initmsg)))
4126                                 return -EINVAL;
4127                         cmsgs->init = (struct sctp_initmsg *)CMSG_DATA(cmsg);
4128                         break;
4129
4130                 case SCTP_SNDRCV:
4131                         /* SCTP Socket API Extension
4132                          * 5.2.2 SCTP Header Information Structure(SCTP_SNDRCV)
4133                          *
4134                          * This cmsghdr structure specifies SCTP options for
4135                          * sendmsg() and describes SCTP header information
4136                          * about a received message through recvmsg().
4137                          *
4138                          * cmsg_level    cmsg_type      cmsg_data[]
4139                          * ------------  ------------   ----------------------
4140                          * IPPROTO_SCTP  SCTP_SNDRCV    struct sctp_sndrcvinfo
4141                          */
4142                         if (cmsg->cmsg_len !=
4143                             CMSG_LEN(sizeof(struct sctp_sndrcvinfo)))
4144                                 return -EINVAL;
4145
4146                         cmsgs->info =
4147                                 (struct sctp_sndrcvinfo *)CMSG_DATA(cmsg);
4148
4149                         /* Minimally, validate the sinfo_flags. */
4150                         if (cmsgs->info->sinfo_flags &
4151                             ~(MSG_UNORDERED | MSG_ADDR_OVER |
4152                               MSG_ABORT | MSG_EOF))
4153                                 return -EINVAL;
4154                         break;
4155
4156                 default:
4157                         return -EINVAL;
4158                 };
4159         }
4160         return 0;
4161 }
4162
4163 /*
4164  * Wait for a packet..
4165  * Note: This function is the same function as in core/datagram.c
4166  * with a few modifications to make lksctp work.
4167  */
4168 static int sctp_wait_for_packet(struct sock * sk, int *err, long *timeo_p)
4169 {
4170         int error;
4171         DEFINE_WAIT(wait);
4172
4173         prepare_to_wait_exclusive(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
4174
4175         /* Socket errors? */
4176         error = sock_error(sk);
4177         if (error)
4178                 goto out;
4179
4180         if (!skb_queue_empty(&sk->sk_receive_queue))
4181                 goto ready;
4182
4183         /* Socket shut down?  */
4184         if (sk->sk_shutdown & RCV_SHUTDOWN)
4185                 goto out;
4186
4187         /* Sequenced packets can come disconnected.  If so we report the
4188          * problem.
4189          */
4190         error = -ENOTCONN;
4191
4192         /* Is there a good reason to think that we may receive some data?  */
4193         if (list_empty(&sctp_sk(sk)->ep->asocs) && !sctp_sstate(sk, LISTENING))
4194                 goto out;
4195
4196         /* Handle signals.  */
4197         if (signal_pending(current))
4198                 goto interrupted;
4199
4200         /* Let another process have a go.  Since we are going to sleep
4201          * anyway.  Note: This may cause odd behaviors if the message
4202          * does not fit in the user's buffer, but this seems to be the
4203          * only way to honor MSG_DONTWAIT realistically.
4204          */
4205         sctp_release_sock(sk);
4206         *timeo_p = schedule_timeout(*timeo_p);
4207         sctp_lock_sock(sk);
4208
4209 ready:
4210         finish_wait(sk->sk_sleep, &wait);
4211         return 0;
4212
4213 interrupted:
4214         error = sock_intr_errno(*timeo_p);
4215
4216 out:
4217         finish_wait(sk->sk_sleep, &wait);
4218         *err = error;
4219         return error;
4220 }
4221
4222 /* Receive a datagram.
4223  * Note: This is pretty much the same routine as in core/datagram.c
4224  * with a few changes to make lksctp work.
4225  */
4226 static struct sk_buff *sctp_skb_recv_datagram(struct sock *sk, int flags,
4227                                               int noblock, int *err)
4228 {
4229         int error;
4230         struct sk_buff *skb;
4231         long timeo;
4232
4233         /* Caller is allowed not to check sk->sk_err before calling.  */
4234         error = sock_error(sk);
4235         if (error)
4236                 goto no_packet;
4237
4238         timeo = sock_rcvtimeo(sk, noblock);
4239
4240         SCTP_DEBUG_PRINTK("Timeout: timeo: %ld, MAX: %ld.\n",
4241                           timeo, MAX_SCHEDULE_TIMEOUT);
4242
4243         do {
4244                 /* Again only user level code calls this function,
4245                  * so nothing interrupt level
4246                  * will suddenly eat the receive_queue.
4247                  *
4248                  *  Look at current nfs client by the way...
4249                  *  However, this function was corrent in any case. 8)
4250                  */
4251                 if (flags & MSG_PEEK) {
4252                         unsigned long cpu_flags;
4253
4254                         sctp_spin_lock_irqsave(&sk->sk_receive_queue.lock,
4255                                                cpu_flags);
4256                         skb = skb_peek(&sk->sk_receive_queue);
4257                         if (skb)
4258                                 atomic_inc(&skb->users);
4259                         sctp_spin_unlock_irqrestore(&sk->sk_receive_queue.lock,
4260                                                     cpu_flags);
4261                 } else {
4262                         skb = skb_dequeue(&sk->sk_receive_queue);
4263                 }
4264
4265                 if (skb)
4266                         return skb;
4267
4268                 if (sk->sk_shutdown & RCV_SHUTDOWN)
4269                         break;
4270
4271                 /* User doesn't want to wait.  */
4272                 error = -EAGAIN;
4273                 if (!timeo)
4274                         goto no_packet;
4275         } while (sctp_wait_for_packet(sk, err, &timeo) == 0);
4276
4277         return NULL;
4278
4279 no_packet:
4280         *err = error;
4281         return NULL;
4282 }
4283
4284 /* If sndbuf has changed, wake up per association sndbuf waiters.  */
4285 static void __sctp_write_space(struct sctp_association *asoc)
4286 {
4287         struct sock *sk = asoc->base.sk;
4288         struct socket *sock = sk->sk_socket;
4289
4290         if ((sctp_wspace(asoc) > 0) && sock) {
4291                 if (waitqueue_active(&asoc->wait))
4292                         wake_up_interruptible(&asoc->wait);
4293
4294                 if (sctp_writeable(sk)) {
4295                         if (sk->sk_sleep && waitqueue_active(sk->sk_sleep))
4296                                 wake_up_interruptible(sk->sk_sleep);
4297
4298                         /* Note that we try to include the Async I/O support
4299                          * here by modeling from the current TCP/UDP code.
4300                          * We have not tested with it yet.
4301                          */
4302                         if (sock->fasync_list &&
4303                             !(sk->sk_shutdown & SEND_SHUTDOWN))
4304                                 sock_wake_async(sock, 2, POLL_OUT);
4305                 }
4306         }
4307 }
4308
4309 /* Do accounting for the sndbuf space.
4310  * Decrement the used sndbuf space of the corresponding association by the
4311  * data size which was just transmitted(freed).
4312  */
4313 static void sctp_wfree(struct sk_buff *skb)
4314 {
4315         struct sctp_association *asoc;
4316         struct sctp_chunk *chunk;
4317         struct sock *sk;
4318
4319         /* Get the saved chunk pointer.  */
4320         chunk = *((struct sctp_chunk **)(skb->cb));
4321         asoc = chunk->asoc;
4322         sk = asoc->base.sk;
4323         asoc->sndbuf_used -= SCTP_DATA_SNDSIZE(chunk);
4324         sk->sk_wmem_queued -= SCTP_DATA_SNDSIZE(chunk);
4325         __sctp_write_space(asoc);
4326
4327         sctp_association_put(asoc);
4328 }
4329
4330 /* Helper function to wait for space in the sndbuf.  */
4331 static int sctp_wait_for_sndbuf(struct sctp_association *asoc, long *timeo_p,
4332                                 size_t msg_len)
4333 {
4334         struct sock *sk = asoc->base.sk;
4335         int err = 0;
4336         long current_timeo = *timeo_p;
4337         DEFINE_WAIT(wait);
4338
4339         SCTP_DEBUG_PRINTK("wait_for_sndbuf: asoc=%p, timeo=%ld, msg_len=%zu\n",
4340                           asoc, (long)(*timeo_p), msg_len);
4341
4342         /* Increment the association's refcnt.  */
4343         sctp_association_hold(asoc);
4344
4345         /* Wait on the association specific sndbuf space. */
4346         for (;;) {
4347                 prepare_to_wait_exclusive(&asoc->wait, &wait,
4348                                           TASK_INTERRUPTIBLE);
4349                 if (!*timeo_p)
4350                         goto do_nonblock;
4351                 if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
4352                     asoc->base.dead)
4353                         goto do_error;
4354                 if (signal_pending(current))
4355                         goto do_interrupted;
4356                 if (msg_len <= sctp_wspace(asoc))
4357                         break;
4358
4359                 /* Let another process have a go.  Since we are going
4360                  * to sleep anyway.
4361                  */
4362                 sctp_release_sock(sk);
4363                 current_timeo = schedule_timeout(current_timeo);
4364                 sctp_lock_sock(sk);
4365
4366                 *timeo_p = current_timeo;
4367         }
4368
4369 out:
4370         finish_wait(&asoc->wait, &wait);
4371
4372         /* Release the association's refcnt.  */
4373         sctp_association_put(asoc);
4374
4375         return err;
4376
4377 do_error:
4378         err = -EPIPE;
4379         goto out;
4380
4381 do_interrupted:
4382         err = sock_intr_errno(*timeo_p);
4383         goto out;
4384
4385 do_nonblock:
4386         err = -EAGAIN;
4387         goto out;
4388 }
4389
4390 /* If socket sndbuf has changed, wake up all per association waiters.  */
4391 void sctp_write_space(struct sock *sk)
4392 {
4393         struct sctp_association *asoc;
4394         struct list_head *pos;
4395
4396         /* Wake up the tasks in each wait queue.  */
4397         list_for_each(pos, &((sctp_sk(sk))->ep->asocs)) {
4398                 asoc = list_entry(pos, struct sctp_association, asocs);
4399                 __sctp_write_space(asoc);
4400         }
4401 }
4402
4403 /* Is there any sndbuf space available on the socket?
4404  *
4405  * Note that wmem_queued is the sum of the send buffers on all of the
4406  * associations on the same socket.  For a UDP-style socket with
4407  * multiple associations, it is possible for it to be "unwriteable"
4408  * prematurely.  I assume that this is acceptable because
4409  * a premature "unwriteable" is better than an accidental "writeable" which
4410  * would cause an unwanted block under certain circumstances.  For the 1-1
4411  * UDP-style sockets or TCP-style sockets, this code should work.
4412  *  - Daisy
4413  */
4414 static int sctp_writeable(struct sock *sk)
4415 {
4416         int amt = 0;
4417
4418         amt = sk->sk_sndbuf - sk->sk_wmem_queued;
4419         if (amt < 0)
4420                 amt = 0;
4421         return amt;
4422 }
4423
4424 /* Wait for an association to go into ESTABLISHED state. If timeout is 0,
4425  * returns immediately with EINPROGRESS.
4426  */
4427 static int sctp_wait_for_connect(struct sctp_association *asoc, long *timeo_p)
4428 {
4429         struct sock *sk = asoc->base.sk;
4430         int err = 0;
4431         long current_timeo = *timeo_p;
4432         DEFINE_WAIT(wait);
4433
4434         SCTP_DEBUG_PRINTK("%s: asoc=%p, timeo=%ld\n", __FUNCTION__, asoc,
4435                           (long)(*timeo_p));
4436
4437         /* Increment the association's refcnt.  */
4438         sctp_association_hold(asoc);
4439
4440         for (;;) {
4441                 prepare_to_wait_exclusive(&asoc->wait, &wait,
4442                                           TASK_INTERRUPTIBLE);
4443                 if (!*timeo_p)
4444                         goto do_nonblock;
4445                 if (sk->sk_shutdown & RCV_SHUTDOWN)
4446                         break;
4447                 if (sk->sk_err || asoc->state >= SCTP_STATE_SHUTDOWN_PENDING ||
4448                     asoc->base.dead)
4449                         goto do_error;
4450                 if (signal_pending(current))
4451                         goto do_interrupted;
4452
4453                 if (sctp_state(asoc, ESTABLISHED))
4454                         break;
4455
4456                 /* Let another process have a go.  Since we are going
4457                  * to sleep anyway.
4458                  */
4459                 sctp_release_sock(sk);
4460                 current_timeo = schedule_timeout(current_timeo);
4461                 sctp_lock_sock(sk);
4462
4463                 *timeo_p = current_timeo;
4464         }
4465
4466 out:
4467         finish_wait(&asoc->wait, &wait);
4468
4469         /* Release the association's refcnt.  */
4470         sctp_association_put(asoc);
4471
4472         return err;
4473
4474 do_error:
4475         if (asoc->counters[SCTP_COUNTER_INIT_ERROR] + 1 >=
4476                                                 asoc->max_init_attempts)
4477                 err = -ETIMEDOUT;
4478         else
4479                 err = -ECONNREFUSED;
4480         goto out;
4481
4482 do_interrupted:
4483         err = sock_intr_errno(*timeo_p);
4484         goto out;
4485
4486 do_nonblock:
4487         err = -EINPROGRESS;
4488         goto out;
4489 }
4490
4491 static int sctp_wait_for_accept(struct sock *sk, long timeo)
4492 {
4493         struct sctp_endpoint *ep;
4494         int err = 0;
4495         DEFINE_WAIT(wait);
4496
4497         ep = sctp_sk(sk)->ep;
4498
4499
4500         for (;;) {
4501                 prepare_to_wait_exclusive(sk->sk_sleep, &wait,
4502                                           TASK_INTERRUPTIBLE);
4503
4504                 if (list_empty(&ep->asocs)) {
4505                         sctp_release_sock(sk);
4506                         timeo = schedule_timeout(timeo);
4507                         sctp_lock_sock(sk);
4508                 }
4509
4510                 err = -EINVAL;
4511                 if (!sctp_sstate(sk, LISTENING))
4512                         break;
4513
4514                 err = 0;
4515                 if (!list_empty(&ep->asocs))
4516                         break;
4517
4518                 err = sock_intr_errno(timeo);
4519                 if (signal_pending(current))
4520                         break;
4521
4522                 err = -EAGAIN;
4523                 if (!timeo)
4524                         break;
4525         }
4526
4527         finish_wait(sk->sk_sleep, &wait);
4528
4529         return err;
4530 }
4531
4532 void sctp_wait_for_close(struct sock *sk, long timeout)
4533 {
4534         DEFINE_WAIT(wait);
4535
4536         do {
4537                 prepare_to_wait(sk->sk_sleep, &wait, TASK_INTERRUPTIBLE);
4538                 if (list_empty(&sctp_sk(sk)->ep->asocs))
4539                         break;
4540                 sctp_release_sock(sk);
4541                 timeout = schedule_timeout(timeout);
4542                 sctp_lock_sock(sk);
4543         } while (!signal_pending(current) && timeout);
4544
4545         finish_wait(sk->sk_sleep, &wait);
4546 }
4547
4548 /* Populate the fields of the newsk from the oldsk and migrate the assoc
4549  * and its messages to the newsk.
4550  */
4551 static void sctp_sock_migrate(struct sock *oldsk, struct sock *newsk,
4552                               struct sctp_association *assoc,
4553                               sctp_socket_type_t type)
4554 {
4555         struct sctp_opt *oldsp = sctp_sk(oldsk);
4556         struct sctp_opt *newsp = sctp_sk(newsk);
4557         struct sctp_bind_bucket *pp; /* hash list port iterator */
4558         struct sctp_endpoint *newep = newsp->ep;
4559         struct sk_buff *skb, *tmp;
4560         struct sctp_ulpevent *event;
4561
4562         /* Migrate socket buffer sizes and all the socket level options to the
4563          * new socket.
4564          */
4565         newsk->sk_sndbuf = oldsk->sk_sndbuf;
4566         newsk->sk_rcvbuf = oldsk->sk_rcvbuf;
4567         /* Brute force copy old sctp opt. */
4568         memcpy(newsp, oldsp, sizeof(struct sctp_opt));
4569
4570         /* Restore the ep value that was overwritten with the above structure
4571          * copy.
4572          */
4573         newsp->ep = newep;
4574         newsp->hmac = NULL;
4575
4576         /* Hook this new socket in to the bind_hash list. */
4577         pp = sctp_sk(oldsk)->bind_hash;
4578         sk_add_bind_node(newsk, &pp->owner);
4579         sctp_sk(newsk)->bind_hash = pp;
4580         inet_sk(newsk)->num = inet_sk(oldsk)->num;
4581
4582         /* Move any messages in the old socket's receive queue that are for the
4583          * peeled off association to the new socket's receive queue.
4584          */
4585         sctp_skb_for_each(skb, &oldsk->sk_receive_queue, tmp) {
4586                 event = sctp_skb2event(skb);
4587                 if (event->asoc == assoc) {
4588                         __skb_unlink(skb, skb->list);
4589                         __skb_queue_tail(&newsk->sk_receive_queue, skb);
4590                 }
4591         }
4592
4593         /* Clean up any messages pending delivery due to partial
4594          * delivery.   Three cases:
4595          * 1) No partial deliver;  no work.
4596          * 2) Peeling off partial delivery; keep pd_lobby in new pd_lobby.
4597          * 3) Peeling off non-partial delivery; move pd_lobby to receive_queue.
4598          */
4599         skb_queue_head_init(&newsp->pd_lobby);
4600         sctp_sk(newsk)->pd_mode = assoc->ulpq.pd_mode;
4601
4602         if (sctp_sk(oldsk)->pd_mode) {
4603                 struct sk_buff_head *queue;
4604
4605                 /* Decide which queue to move pd_lobby skbs to. */
4606                 if (assoc->ulpq.pd_mode) {
4607                         queue = &newsp->pd_lobby;
4608                 } else
4609                         queue = &newsk->sk_receive_queue;
4610
4611                 /* Walk through the pd_lobby, looking for skbs that
4612                  * need moved to the new socket.
4613                  */
4614                 sctp_skb_for_each(skb, &oldsp->pd_lobby, tmp) {
4615                         event = sctp_skb2event(skb);
4616                         if (event->asoc == assoc) {
4617                                 __skb_unlink(skb, skb->list);
4618                                 __skb_queue_tail(queue, skb);
4619                         }
4620                 }
4621
4622                 /* Clear up any skbs waiting for the partial
4623                  * delivery to finish.
4624                  */
4625                 if (assoc->ulpq.pd_mode)
4626                         sctp_clear_pd(oldsk);
4627
4628         }
4629
4630         /* Set the type of socket to indicate that it is peeled off from the
4631          * original UDP-style socket or created with the accept() call on a
4632          * TCP-style socket..
4633          */
4634         newsp->type = type;
4635
4636         /* Migrate the association to the new socket. */
4637         sctp_assoc_migrate(assoc, newsk);
4638
4639         /* If the association on the newsk is already closed before accept()
4640          * is called, set RCV_SHUTDOWN flag.
4641          */
4642         if (sctp_state(assoc, CLOSED) && sctp_style(newsk, TCP))
4643                 newsk->sk_shutdown |= RCV_SHUTDOWN;
4644
4645         newsk->sk_state = SCTP_SS_ESTABLISHED;
4646 }
4647
4648 /* This proto struct describes the ULP interface for SCTP.  */
4649 struct proto sctp_prot = {
4650         .name        =  "SCTP",
4651         .owner       =  THIS_MODULE,
4652         .close       =  sctp_close,
4653         .connect     =  sctp_connect,
4654         .disconnect  =  sctp_disconnect,
4655         .accept      =  sctp_accept,
4656         .ioctl       =  sctp_ioctl,
4657         .init        =  sctp_init_sock,
4658         .destroy     =  sctp_destroy_sock,
4659         .shutdown    =  sctp_shutdown,
4660         .setsockopt  =  sctp_setsockopt,
4661         .getsockopt  =  sctp_getsockopt,
4662         .sendmsg     =  sctp_sendmsg,
4663         .recvmsg     =  sctp_recvmsg,
4664         .bind        =  sctp_bind,
4665         .backlog_rcv =  sctp_backlog_rcv,
4666         .hash        =  sctp_hash,
4667         .unhash      =  sctp_unhash,
4668         .get_port    =  sctp_get_port,
4669         .slab_obj_size = sizeof(struct sctp_sock),
4670 };
4671
4672 #if defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE)
4673 struct proto sctpv6_prot = {
4674         .name           = "SCTPv6",
4675         .owner          = THIS_MODULE,
4676         .close          = sctp_close,
4677         .connect        = sctp_connect,
4678         .disconnect     = sctp_disconnect,
4679         .accept         = sctp_accept,
4680         .ioctl          = sctp_ioctl,
4681         .init           = sctp_init_sock,
4682         .destroy        = sctp_destroy_sock,
4683         .shutdown       = sctp_shutdown,
4684         .setsockopt     = sctp_setsockopt,
4685         .getsockopt     = sctp_getsockopt,
4686         .sendmsg        = sctp_sendmsg,
4687         .recvmsg        = sctp_recvmsg,
4688         .bind           = sctp_bind,
4689         .backlog_rcv    = sctp_backlog_rcv,
4690         .hash           = sctp_hash,
4691         .unhash         = sctp_unhash,
4692         .get_port       = sctp_get_port,
4693         .slab_obj_size  = sizeof(struct sctp6_sock),
4694 };
4695 #endif /* defined(CONFIG_IPV6) || defined(CONFIG_IPV6_MODULE) */