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