sctp: allow sctp_transmit_packet and others to use gfp
[cascardo/linux.git] / net / sctp / sm_make_chunk.c
1 /* SCTP kernel implementation
2  * (C) Copyright IBM Corp. 2001, 2004
3  * Copyright (c) 1999-2000 Cisco, Inc.
4  * Copyright (c) 1999-2001 Motorola, Inc.
5  * Copyright (c) 2001-2002 Intel Corp.
6  *
7  * This file is part of the SCTP kernel implementation
8  *
9  * These functions work with the state functions in sctp_sm_statefuns.c
10  * to implement the state operations.  These functions implement the
11  * steps which require modifying existing data structures.
12  *
13  * This SCTP implementation is free software;
14  * you can redistribute it and/or modify it under the terms of
15  * the GNU General Public License as published by
16  * the Free Software Foundation; either version 2, or (at your option)
17  * any later version.
18  *
19  * This SCTP implementation is distributed in the hope that it
20  * will be useful, but WITHOUT ANY WARRANTY; without even the implied
21  *                 ************************
22  * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
23  * See the GNU General Public License for more details.
24  *
25  * You should have received a copy of the GNU General Public License
26  * along with GNU CC; see the file COPYING.  If not, see
27  * <http://www.gnu.org/licenses/>.
28  *
29  * Please send any bug reports or fixes you make to the
30  * email address(es):
31  *    lksctp developers <linux-sctp@vger.kernel.org>
32  *
33  * Written or modified by:
34  *    La Monte H.P. Yarroll <piggy@acm.org>
35  *    Karl Knutson          <karl@athena.chicago.il.us>
36  *    C. Robin              <chris@hundredacre.ac.uk>
37  *    Jon Grimm             <jgrimm@us.ibm.com>
38  *    Xingang Guo           <xingang.guo@intel.com>
39  *    Dajiang Zhang         <dajiang.zhang@nokia.com>
40  *    Sridhar Samudrala     <sri@us.ibm.com>
41  *    Daisy Chang           <daisyc@us.ibm.com>
42  *    Ardelle Fan           <ardelle.fan@intel.com>
43  *    Kevin Gao             <kevin.gao@intel.com>
44  */
45
46 #define pr_fmt(fmt) KBUILD_MODNAME ": " fmt
47
48 #include <linux/types.h>
49 #include <linux/kernel.h>
50 #include <linux/ip.h>
51 #include <linux/ipv6.h>
52 #include <linux/net.h>
53 #include <linux/inet.h>
54 #include <linux/scatterlist.h>
55 #include <linux/crypto.h>
56 #include <linux/slab.h>
57 #include <net/sock.h>
58
59 #include <linux/skbuff.h>
60 #include <linux/random.h>       /* for get_random_bytes */
61 #include <net/sctp/sctp.h>
62 #include <net/sctp/sm.h>
63
64 static struct sctp_chunk *sctp_make_control(const struct sctp_association *asoc,
65                                             __u8 type, __u8 flags, int paylen,
66                                             gfp_t gfp);
67 static struct sctp_chunk *sctp_make_data(const struct sctp_association *asoc,
68                                          __u8 flags, int paylen, gfp_t gfp);
69 static struct sctp_chunk *_sctp_make_chunk(const struct sctp_association *asoc,
70                                            __u8 type, __u8 flags, int paylen,
71                                            gfp_t gfp);
72 static sctp_cookie_param_t *sctp_pack_cookie(const struct sctp_endpoint *ep,
73                                         const struct sctp_association *asoc,
74                                         const struct sctp_chunk *init_chunk,
75                                         int *cookie_len,
76                                         const __u8 *raw_addrs, int addrs_len);
77 static int sctp_process_param(struct sctp_association *asoc,
78                               union sctp_params param,
79                               const union sctp_addr *peer_addr,
80                               gfp_t gfp);
81 static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
82                               const void *data);
83 static void  *sctp_addto_chunk_fixed(struct sctp_chunk *, int len,
84                                      const void *data);
85
86 /* Control chunk destructor */
87 static void sctp_control_release_owner(struct sk_buff *skb)
88 {
89         /*TODO: do memory release */
90 }
91
92 static void sctp_control_set_owner_w(struct sctp_chunk *chunk)
93 {
94         struct sctp_association *asoc = chunk->asoc;
95         struct sk_buff *skb = chunk->skb;
96
97         /* TODO: properly account for control chunks.
98          * To do it right we'll need:
99          *  1) endpoint if association isn't known.
100          *  2) proper memory accounting.
101          *
102          *  For now don't do anything for now.
103          */
104         skb->sk = asoc ? asoc->base.sk : NULL;
105         skb->destructor = sctp_control_release_owner;
106 }
107
108 /* What was the inbound interface for this chunk? */
109 int sctp_chunk_iif(const struct sctp_chunk *chunk)
110 {
111         struct sctp_af *af;
112         int iif = 0;
113
114         af = sctp_get_af_specific(ipver2af(ip_hdr(chunk->skb)->version));
115         if (af)
116                 iif = af->skb_iif(chunk->skb);
117
118         return iif;
119 }
120
121 /* RFC 2960 3.3.2 Initiation (INIT) (1)
122  *
123  * Note 2: The ECN capable field is reserved for future use of
124  * Explicit Congestion Notification.
125  */
126 static const struct sctp_paramhdr ecap_param = {
127         SCTP_PARAM_ECN_CAPABLE,
128         cpu_to_be16(sizeof(struct sctp_paramhdr)),
129 };
130 static const struct sctp_paramhdr prsctp_param = {
131         SCTP_PARAM_FWD_TSN_SUPPORT,
132         cpu_to_be16(sizeof(struct sctp_paramhdr)),
133 };
134
135 /* A helper to initialize an op error inside a
136  * provided chunk, as most cause codes will be embedded inside an
137  * abort chunk.
138  */
139 void  sctp_init_cause(struct sctp_chunk *chunk, __be16 cause_code,
140                       size_t paylen)
141 {
142         sctp_errhdr_t err;
143         __u16 len;
144
145         /* Cause code constants are now defined in network order.  */
146         err.cause = cause_code;
147         len = sizeof(sctp_errhdr_t) + paylen;
148         err.length  = htons(len);
149         chunk->subh.err_hdr = sctp_addto_chunk(chunk, sizeof(sctp_errhdr_t), &err);
150 }
151
152 /* A helper to initialize an op error inside a
153  * provided chunk, as most cause codes will be embedded inside an
154  * abort chunk.  Differs from sctp_init_cause in that it won't oops
155  * if there isn't enough space in the op error chunk
156  */
157 static int sctp_init_cause_fixed(struct sctp_chunk *chunk, __be16 cause_code,
158                       size_t paylen)
159 {
160         sctp_errhdr_t err;
161         __u16 len;
162
163         /* Cause code constants are now defined in network order.  */
164         err.cause = cause_code;
165         len = sizeof(sctp_errhdr_t) + paylen;
166         err.length  = htons(len);
167
168         if (skb_tailroom(chunk->skb) < len)
169                 return -ENOSPC;
170         chunk->subh.err_hdr = sctp_addto_chunk_fixed(chunk,
171                                                      sizeof(sctp_errhdr_t),
172                                                      &err);
173         return 0;
174 }
175 /* 3.3.2 Initiation (INIT) (1)
176  *
177  * This chunk is used to initiate a SCTP association between two
178  * endpoints. The format of the INIT chunk is shown below:
179  *
180  *     0                   1                   2                   3
181  *     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
182  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
183  *    |   Type = 1    |  Chunk Flags  |      Chunk Length             |
184  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
185  *    |                         Initiate Tag                          |
186  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
187  *    |           Advertised Receiver Window Credit (a_rwnd)          |
188  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
189  *    |  Number of Outbound Streams   |  Number of Inbound Streams    |
190  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
191  *    |                          Initial TSN                          |
192  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
193  *    \                                                               \
194  *    /              Optional/Variable-Length Parameters              /
195  *    \                                                               \
196  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
197  *
198  *
199  * The INIT chunk contains the following parameters. Unless otherwise
200  * noted, each parameter MUST only be included once in the INIT chunk.
201  *
202  * Fixed Parameters                     Status
203  * ----------------------------------------------
204  * Initiate Tag                        Mandatory
205  * Advertised Receiver Window Credit   Mandatory
206  * Number of Outbound Streams          Mandatory
207  * Number of Inbound Streams           Mandatory
208  * Initial TSN                         Mandatory
209  *
210  * Variable Parameters                  Status     Type Value
211  * -------------------------------------------------------------
212  * IPv4 Address (Note 1)               Optional    5
213  * IPv6 Address (Note 1)               Optional    6
214  * Cookie Preservative                 Optional    9
215  * Reserved for ECN Capable (Note 2)   Optional    32768 (0x8000)
216  * Host Name Address (Note 3)          Optional    11
217  * Supported Address Types (Note 4)    Optional    12
218  */
219 struct sctp_chunk *sctp_make_init(const struct sctp_association *asoc,
220                              const struct sctp_bind_addr *bp,
221                              gfp_t gfp, int vparam_len)
222 {
223         struct net *net = sock_net(asoc->base.sk);
224         struct sctp_endpoint *ep = asoc->ep;
225         sctp_inithdr_t init;
226         union sctp_params addrs;
227         size_t chunksize;
228         struct sctp_chunk *retval = NULL;
229         int num_types, addrs_len = 0;
230         struct sctp_sock *sp;
231         sctp_supported_addrs_param_t sat;
232         __be16 types[2];
233         sctp_adaptation_ind_param_t aiparam;
234         sctp_supported_ext_param_t ext_param;
235         int num_ext = 0;
236         __u8 extensions[3];
237         sctp_paramhdr_t *auth_chunks = NULL,
238                         *auth_hmacs = NULL;
239
240         /* RFC 2960 3.3.2 Initiation (INIT) (1)
241          *
242          * Note 1: The INIT chunks can contain multiple addresses that
243          * can be IPv4 and/or IPv6 in any combination.
244          */
245         retval = NULL;
246
247         /* Convert the provided bind address list to raw format. */
248         addrs = sctp_bind_addrs_to_raw(bp, &addrs_len, gfp);
249
250         init.init_tag              = htonl(asoc->c.my_vtag);
251         init.a_rwnd                = htonl(asoc->rwnd);
252         init.num_outbound_streams  = htons(asoc->c.sinit_num_ostreams);
253         init.num_inbound_streams   = htons(asoc->c.sinit_max_instreams);
254         init.initial_tsn           = htonl(asoc->c.initial_tsn);
255
256         /* How many address types are needed? */
257         sp = sctp_sk(asoc->base.sk);
258         num_types = sp->pf->supported_addrs(sp, types);
259
260         chunksize = sizeof(init) + addrs_len;
261         chunksize += WORD_ROUND(SCTP_SAT_LEN(num_types));
262         chunksize += sizeof(ecap_param);
263
264         if (net->sctp.prsctp_enable)
265                 chunksize += sizeof(prsctp_param);
266
267         /* ADDIP: Section 4.2.7:
268          *  An implementation supporting this extension [ADDIP] MUST list
269          *  the ASCONF,the ASCONF-ACK, and the AUTH  chunks in its INIT and
270          *  INIT-ACK parameters.
271          */
272         if (net->sctp.addip_enable) {
273                 extensions[num_ext] = SCTP_CID_ASCONF;
274                 extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
275                 num_ext += 2;
276         }
277
278         if (sp->adaptation_ind)
279                 chunksize += sizeof(aiparam);
280
281         chunksize += vparam_len;
282
283         /* Account for AUTH related parameters */
284         if (ep->auth_enable) {
285                 /* Add random parameter length*/
286                 chunksize += sizeof(asoc->c.auth_random);
287
288                 /* Add HMACS parameter length if any were defined */
289                 auth_hmacs = (sctp_paramhdr_t *)asoc->c.auth_hmacs;
290                 if (auth_hmacs->length)
291                         chunksize += WORD_ROUND(ntohs(auth_hmacs->length));
292                 else
293                         auth_hmacs = NULL;
294
295                 /* Add CHUNKS parameter length */
296                 auth_chunks = (sctp_paramhdr_t *)asoc->c.auth_chunks;
297                 if (auth_chunks->length)
298                         chunksize += WORD_ROUND(ntohs(auth_chunks->length));
299                 else
300                         auth_chunks = NULL;
301
302                 extensions[num_ext] = SCTP_CID_AUTH;
303                 num_ext += 1;
304         }
305
306         /* If we have any extensions to report, account for that */
307         if (num_ext)
308                 chunksize += WORD_ROUND(sizeof(sctp_supported_ext_param_t) +
309                                         num_ext);
310
311         /* RFC 2960 3.3.2 Initiation (INIT) (1)
312          *
313          * Note 3: An INIT chunk MUST NOT contain more than one Host
314          * Name address parameter. Moreover, the sender of the INIT
315          * MUST NOT combine any other address types with the Host Name
316          * address in the INIT. The receiver of INIT MUST ignore any
317          * other address types if the Host Name address parameter is
318          * present in the received INIT chunk.
319          *
320          * PLEASE DO NOT FIXME [This version does not support Host Name.]
321          */
322
323         retval = sctp_make_control(asoc, SCTP_CID_INIT, 0, chunksize, gfp);
324         if (!retval)
325                 goto nodata;
326
327         retval->subh.init_hdr =
328                 sctp_addto_chunk(retval, sizeof(init), &init);
329         retval->param_hdr.v =
330                 sctp_addto_chunk(retval, addrs_len, addrs.v);
331
332         /* RFC 2960 3.3.2 Initiation (INIT) (1)
333          *
334          * Note 4: This parameter, when present, specifies all the
335          * address types the sending endpoint can support. The absence
336          * of this parameter indicates that the sending endpoint can
337          * support any address type.
338          */
339         sat.param_hdr.type = SCTP_PARAM_SUPPORTED_ADDRESS_TYPES;
340         sat.param_hdr.length = htons(SCTP_SAT_LEN(num_types));
341         sctp_addto_chunk(retval, sizeof(sat), &sat);
342         sctp_addto_chunk(retval, num_types * sizeof(__u16), &types);
343
344         sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
345
346         /* Add the supported extensions parameter.  Be nice and add this
347          * fist before addiding the parameters for the extensions themselves
348          */
349         if (num_ext) {
350                 ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
351                 ext_param.param_hdr.length =
352                             htons(sizeof(sctp_supported_ext_param_t) + num_ext);
353                 sctp_addto_chunk(retval, sizeof(sctp_supported_ext_param_t),
354                                 &ext_param);
355                 sctp_addto_param(retval, num_ext, extensions);
356         }
357
358         if (net->sctp.prsctp_enable)
359                 sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
360
361         if (sp->adaptation_ind) {
362                 aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
363                 aiparam.param_hdr.length = htons(sizeof(aiparam));
364                 aiparam.adaptation_ind = htonl(sp->adaptation_ind);
365                 sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
366         }
367
368         /* Add SCTP-AUTH chunks to the parameter list */
369         if (ep->auth_enable) {
370                 sctp_addto_chunk(retval, sizeof(asoc->c.auth_random),
371                                  asoc->c.auth_random);
372                 if (auth_hmacs)
373                         sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
374                                         auth_hmacs);
375                 if (auth_chunks)
376                         sctp_addto_chunk(retval, ntohs(auth_chunks->length),
377                                         auth_chunks);
378         }
379 nodata:
380         kfree(addrs.v);
381         return retval;
382 }
383
384 struct sctp_chunk *sctp_make_init_ack(const struct sctp_association *asoc,
385                                  const struct sctp_chunk *chunk,
386                                  gfp_t gfp, int unkparam_len)
387 {
388         sctp_inithdr_t initack;
389         struct sctp_chunk *retval;
390         union sctp_params addrs;
391         struct sctp_sock *sp;
392         int addrs_len;
393         sctp_cookie_param_t *cookie;
394         int cookie_len;
395         size_t chunksize;
396         sctp_adaptation_ind_param_t aiparam;
397         sctp_supported_ext_param_t ext_param;
398         int num_ext = 0;
399         __u8 extensions[3];
400         sctp_paramhdr_t *auth_chunks = NULL,
401                         *auth_hmacs = NULL,
402                         *auth_random = NULL;
403
404         retval = NULL;
405
406         /* Note: there may be no addresses to embed. */
407         addrs = sctp_bind_addrs_to_raw(&asoc->base.bind_addr, &addrs_len, gfp);
408
409         initack.init_tag                = htonl(asoc->c.my_vtag);
410         initack.a_rwnd                  = htonl(asoc->rwnd);
411         initack.num_outbound_streams    = htons(asoc->c.sinit_num_ostreams);
412         initack.num_inbound_streams     = htons(asoc->c.sinit_max_instreams);
413         initack.initial_tsn             = htonl(asoc->c.initial_tsn);
414
415         /* FIXME:  We really ought to build the cookie right
416          * into the packet instead of allocating more fresh memory.
417          */
418         cookie = sctp_pack_cookie(asoc->ep, asoc, chunk, &cookie_len,
419                                   addrs.v, addrs_len);
420         if (!cookie)
421                 goto nomem_cookie;
422
423         /* Calculate the total size of allocation, include the reserved
424          * space for reporting unknown parameters if it is specified.
425          */
426         sp = sctp_sk(asoc->base.sk);
427         chunksize = sizeof(initack) + addrs_len + cookie_len + unkparam_len;
428
429         /* Tell peer that we'll do ECN only if peer advertised such cap.  */
430         if (asoc->peer.ecn_capable)
431                 chunksize += sizeof(ecap_param);
432
433         if (asoc->peer.prsctp_capable)
434                 chunksize += sizeof(prsctp_param);
435
436         if (asoc->peer.asconf_capable) {
437                 extensions[num_ext] = SCTP_CID_ASCONF;
438                 extensions[num_ext+1] = SCTP_CID_ASCONF_ACK;
439                 num_ext += 2;
440         }
441
442         if (sp->adaptation_ind)
443                 chunksize += sizeof(aiparam);
444
445         if (asoc->peer.auth_capable) {
446                 auth_random = (sctp_paramhdr_t *)asoc->c.auth_random;
447                 chunksize += ntohs(auth_random->length);
448
449                 auth_hmacs = (sctp_paramhdr_t *)asoc->c.auth_hmacs;
450                 if (auth_hmacs->length)
451                         chunksize += WORD_ROUND(ntohs(auth_hmacs->length));
452                 else
453                         auth_hmacs = NULL;
454
455                 auth_chunks = (sctp_paramhdr_t *)asoc->c.auth_chunks;
456                 if (auth_chunks->length)
457                         chunksize += WORD_ROUND(ntohs(auth_chunks->length));
458                 else
459                         auth_chunks = NULL;
460
461                 extensions[num_ext] = SCTP_CID_AUTH;
462                 num_ext += 1;
463         }
464
465         if (num_ext)
466                 chunksize += WORD_ROUND(sizeof(sctp_supported_ext_param_t) +
467                                         num_ext);
468
469         /* Now allocate and fill out the chunk.  */
470         retval = sctp_make_control(asoc, SCTP_CID_INIT_ACK, 0, chunksize, gfp);
471         if (!retval)
472                 goto nomem_chunk;
473
474         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
475          *
476          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
477          * HEARTBEAT ACK, * etc.) to the same destination transport
478          * address from which it received the DATA or control chunk
479          * to which it is replying.
480          *
481          * [INIT ACK back to where the INIT came from.]
482          */
483         retval->transport = chunk->transport;
484
485         retval->subh.init_hdr =
486                 sctp_addto_chunk(retval, sizeof(initack), &initack);
487         retval->param_hdr.v = sctp_addto_chunk(retval, addrs_len, addrs.v);
488         sctp_addto_chunk(retval, cookie_len, cookie);
489         if (asoc->peer.ecn_capable)
490                 sctp_addto_chunk(retval, sizeof(ecap_param), &ecap_param);
491         if (num_ext) {
492                 ext_param.param_hdr.type = SCTP_PARAM_SUPPORTED_EXT;
493                 ext_param.param_hdr.length =
494                             htons(sizeof(sctp_supported_ext_param_t) + num_ext);
495                 sctp_addto_chunk(retval, sizeof(sctp_supported_ext_param_t),
496                                  &ext_param);
497                 sctp_addto_param(retval, num_ext, extensions);
498         }
499         if (asoc->peer.prsctp_capable)
500                 sctp_addto_chunk(retval, sizeof(prsctp_param), &prsctp_param);
501
502         if (sp->adaptation_ind) {
503                 aiparam.param_hdr.type = SCTP_PARAM_ADAPTATION_LAYER_IND;
504                 aiparam.param_hdr.length = htons(sizeof(aiparam));
505                 aiparam.adaptation_ind = htonl(sp->adaptation_ind);
506                 sctp_addto_chunk(retval, sizeof(aiparam), &aiparam);
507         }
508
509         if (asoc->peer.auth_capable) {
510                 sctp_addto_chunk(retval, ntohs(auth_random->length),
511                                  auth_random);
512                 if (auth_hmacs)
513                         sctp_addto_chunk(retval, ntohs(auth_hmacs->length),
514                                         auth_hmacs);
515                 if (auth_chunks)
516                         sctp_addto_chunk(retval, ntohs(auth_chunks->length),
517                                         auth_chunks);
518         }
519
520         /* We need to remove the const qualifier at this point.  */
521         retval->asoc = (struct sctp_association *) asoc;
522
523 nomem_chunk:
524         kfree(cookie);
525 nomem_cookie:
526         kfree(addrs.v);
527         return retval;
528 }
529
530 /* 3.3.11 Cookie Echo (COOKIE ECHO) (10):
531  *
532  * This chunk is used only during the initialization of an association.
533  * It is sent by the initiator of an association to its peer to complete
534  * the initialization process. This chunk MUST precede any DATA chunk
535  * sent within the association, but MAY be bundled with one or more DATA
536  * chunks in the same packet.
537  *
538  *      0                   1                   2                   3
539  *      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
540  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
541  *     |   Type = 10   |Chunk  Flags   |         Length                |
542  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
543  *     /                     Cookie                                    /
544  *     \                                                               \
545  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
546  *
547  * Chunk Flags: 8 bit
548  *
549  *   Set to zero on transmit and ignored on receipt.
550  *
551  * Length: 16 bits (unsigned integer)
552  *
553  *   Set to the size of the chunk in bytes, including the 4 bytes of
554  *   the chunk header and the size of the Cookie.
555  *
556  * Cookie: variable size
557  *
558  *   This field must contain the exact cookie received in the
559  *   State Cookie parameter from the previous INIT ACK.
560  *
561  *   An implementation SHOULD make the cookie as small as possible
562  *   to insure interoperability.
563  */
564 struct sctp_chunk *sctp_make_cookie_echo(const struct sctp_association *asoc,
565                                     const struct sctp_chunk *chunk)
566 {
567         struct sctp_chunk *retval;
568         void *cookie;
569         int cookie_len;
570
571         cookie = asoc->peer.cookie;
572         cookie_len = asoc->peer.cookie_len;
573
574         /* Build a cookie echo chunk.  */
575         retval = sctp_make_control(asoc, SCTP_CID_COOKIE_ECHO, 0,
576                                    cookie_len, GFP_ATOMIC);
577         if (!retval)
578                 goto nodata;
579         retval->subh.cookie_hdr =
580                 sctp_addto_chunk(retval, cookie_len, cookie);
581
582         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
583          *
584          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
585          * HEARTBEAT ACK, * etc.) to the same destination transport
586          * address from which it * received the DATA or control chunk
587          * to which it is replying.
588          *
589          * [COOKIE ECHO back to where the INIT ACK came from.]
590          */
591         if (chunk)
592                 retval->transport = chunk->transport;
593
594 nodata:
595         return retval;
596 }
597
598 /* 3.3.12 Cookie Acknowledgement (COOKIE ACK) (11):
599  *
600  * This chunk is used only during the initialization of an
601  * association.  It is used to acknowledge the receipt of a COOKIE
602  * ECHO chunk.  This chunk MUST precede any DATA or SACK chunk sent
603  * within the association, but MAY be bundled with one or more DATA
604  * chunks or SACK chunk in the same SCTP packet.
605  *
606  *      0                   1                   2                   3
607  *      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
608  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
609  *     |   Type = 11   |Chunk  Flags   |     Length = 4                |
610  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
611  *
612  * Chunk Flags: 8 bits
613  *
614  *   Set to zero on transmit and ignored on receipt.
615  */
616 struct sctp_chunk *sctp_make_cookie_ack(const struct sctp_association *asoc,
617                                    const struct sctp_chunk *chunk)
618 {
619         struct sctp_chunk *retval;
620
621         retval = sctp_make_control(asoc, SCTP_CID_COOKIE_ACK, 0, 0, GFP_ATOMIC);
622
623         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
624          *
625          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
626          * HEARTBEAT ACK, * etc.) to the same destination transport
627          * address from which it * received the DATA or control chunk
628          * to which it is replying.
629          *
630          * [COOKIE ACK back to where the COOKIE ECHO came from.]
631          */
632         if (retval && chunk)
633                 retval->transport = chunk->transport;
634
635         return retval;
636 }
637
638 /*
639  *  Appendix A: Explicit Congestion Notification:
640  *  CWR:
641  *
642  *  RFC 2481 details a specific bit for a sender to send in the header of
643  *  its next outbound TCP segment to indicate to its peer that it has
644  *  reduced its congestion window.  This is termed the CWR bit.  For
645  *  SCTP the same indication is made by including the CWR chunk.
646  *  This chunk contains one data element, i.e. the TSN number that
647  *  was sent in the ECNE chunk.  This element represents the lowest
648  *  TSN number in the datagram that was originally marked with the
649  *  CE bit.
650  *
651  *     0                   1                   2                   3
652  *     0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
653  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
654  *    | Chunk Type=13 | Flags=00000000|    Chunk Length = 8           |
655  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
656  *    |                      Lowest TSN Number                        |
657  *    +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
658  *
659  *     Note: The CWR is considered a Control chunk.
660  */
661 struct sctp_chunk *sctp_make_cwr(const struct sctp_association *asoc,
662                             const __u32 lowest_tsn,
663                             const struct sctp_chunk *chunk)
664 {
665         struct sctp_chunk *retval;
666         sctp_cwrhdr_t cwr;
667
668         cwr.lowest_tsn = htonl(lowest_tsn);
669         retval = sctp_make_control(asoc, SCTP_CID_ECN_CWR, 0,
670                                    sizeof(sctp_cwrhdr_t), GFP_ATOMIC);
671
672         if (!retval)
673                 goto nodata;
674
675         retval->subh.ecn_cwr_hdr =
676                 sctp_addto_chunk(retval, sizeof(cwr), &cwr);
677
678         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
679          *
680          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
681          * HEARTBEAT ACK, * etc.) to the same destination transport
682          * address from which it * received the DATA or control chunk
683          * to which it is replying.
684          *
685          * [Report a reduced congestion window back to where the ECNE
686          * came from.]
687          */
688         if (chunk)
689                 retval->transport = chunk->transport;
690
691 nodata:
692         return retval;
693 }
694
695 /* Make an ECNE chunk.  This is a congestion experienced report.  */
696 struct sctp_chunk *sctp_make_ecne(const struct sctp_association *asoc,
697                              const __u32 lowest_tsn)
698 {
699         struct sctp_chunk *retval;
700         sctp_ecnehdr_t ecne;
701
702         ecne.lowest_tsn = htonl(lowest_tsn);
703         retval = sctp_make_control(asoc, SCTP_CID_ECN_ECNE, 0,
704                                    sizeof(sctp_ecnehdr_t), GFP_ATOMIC);
705         if (!retval)
706                 goto nodata;
707         retval->subh.ecne_hdr =
708                 sctp_addto_chunk(retval, sizeof(ecne), &ecne);
709
710 nodata:
711         return retval;
712 }
713
714 /* Make a DATA chunk for the given association from the provided
715  * parameters.  However, do not populate the data payload.
716  */
717 struct sctp_chunk *sctp_make_datafrag_empty(struct sctp_association *asoc,
718                                        const struct sctp_sndrcvinfo *sinfo,
719                                        int data_len, __u8 flags, __u16 ssn,
720                                        gfp_t gfp)
721 {
722         struct sctp_chunk *retval;
723         struct sctp_datahdr dp;
724         int chunk_len;
725
726         /* We assign the TSN as LATE as possible, not here when
727          * creating the chunk.
728          */
729         dp.tsn = 0;
730         dp.stream = htons(sinfo->sinfo_stream);
731         dp.ppid   = sinfo->sinfo_ppid;
732
733         /* Set the flags for an unordered send.  */
734         if (sinfo->sinfo_flags & SCTP_UNORDERED) {
735                 flags |= SCTP_DATA_UNORDERED;
736                 dp.ssn = 0;
737         } else
738                 dp.ssn = htons(ssn);
739
740         chunk_len = sizeof(dp) + data_len;
741         retval = sctp_make_data(asoc, flags, chunk_len, gfp);
742         if (!retval)
743                 goto nodata;
744
745         retval->subh.data_hdr = sctp_addto_chunk(retval, sizeof(dp), &dp);
746         memcpy(&retval->sinfo, sinfo, sizeof(struct sctp_sndrcvinfo));
747
748 nodata:
749         return retval;
750 }
751
752 /* Create a selective ackowledgement (SACK) for the given
753  * association.  This reports on which TSN's we've seen to date,
754  * including duplicates and gaps.
755  */
756 struct sctp_chunk *sctp_make_sack(const struct sctp_association *asoc)
757 {
758         struct sctp_chunk *retval;
759         struct sctp_sackhdr sack;
760         int len;
761         __u32 ctsn;
762         __u16 num_gabs, num_dup_tsns;
763         struct sctp_association *aptr = (struct sctp_association *)asoc;
764         struct sctp_tsnmap *map = (struct sctp_tsnmap *)&asoc->peer.tsn_map;
765         struct sctp_gap_ack_block gabs[SCTP_MAX_GABS];
766         struct sctp_transport *trans;
767
768         memset(gabs, 0, sizeof(gabs));
769         ctsn = sctp_tsnmap_get_ctsn(map);
770
771         pr_debug("%s: sackCTSNAck sent:0x%x\n", __func__, ctsn);
772
773         /* How much room is needed in the chunk? */
774         num_gabs = sctp_tsnmap_num_gabs(map, gabs);
775         num_dup_tsns = sctp_tsnmap_num_dups(map);
776
777         /* Initialize the SACK header.  */
778         sack.cum_tsn_ack            = htonl(ctsn);
779         sack.a_rwnd                 = htonl(asoc->a_rwnd);
780         sack.num_gap_ack_blocks     = htons(num_gabs);
781         sack.num_dup_tsns           = htons(num_dup_tsns);
782
783         len = sizeof(sack)
784                 + sizeof(struct sctp_gap_ack_block) * num_gabs
785                 + sizeof(__u32) * num_dup_tsns;
786
787         /* Create the chunk.  */
788         retval = sctp_make_control(asoc, SCTP_CID_SACK, 0, len, GFP_ATOMIC);
789         if (!retval)
790                 goto nodata;
791
792         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
793          *
794          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
795          * HEARTBEAT ACK, etc.) to the same destination transport
796          * address from which it received the DATA or control chunk to
797          * which it is replying.  This rule should also be followed if
798          * the endpoint is bundling DATA chunks together with the
799          * reply chunk.
800          *
801          * However, when acknowledging multiple DATA chunks received
802          * in packets from different source addresses in a single
803          * SACK, the SACK chunk may be transmitted to one of the
804          * destination transport addresses from which the DATA or
805          * control chunks being acknowledged were received.
806          *
807          * [BUG:  We do not implement the following paragraph.
808          * Perhaps we should remember the last transport we used for a
809          * SACK and avoid that (if possible) if we have seen any
810          * duplicates. --piggy]
811          *
812          * When a receiver of a duplicate DATA chunk sends a SACK to a
813          * multi- homed endpoint it MAY be beneficial to vary the
814          * destination address and not use the source address of the
815          * DATA chunk.  The reason being that receiving a duplicate
816          * from a multi-homed endpoint might indicate that the return
817          * path (as specified in the source address of the DATA chunk)
818          * for the SACK is broken.
819          *
820          * [Send to the address from which we last received a DATA chunk.]
821          */
822         retval->transport = asoc->peer.last_data_from;
823
824         retval->subh.sack_hdr =
825                 sctp_addto_chunk(retval, sizeof(sack), &sack);
826
827         /* Add the gap ack block information.   */
828         if (num_gabs)
829                 sctp_addto_chunk(retval, sizeof(__u32) * num_gabs,
830                                  gabs);
831
832         /* Add the duplicate TSN information.  */
833         if (num_dup_tsns) {
834                 aptr->stats.idupchunks += num_dup_tsns;
835                 sctp_addto_chunk(retval, sizeof(__u32) * num_dup_tsns,
836                                  sctp_tsnmap_get_dups(map));
837         }
838         /* Once we have a sack generated, check to see what our sack
839          * generation is, if its 0, reset the transports to 0, and reset
840          * the association generation to 1
841          *
842          * The idea is that zero is never used as a valid generation for the
843          * association so no transport will match after a wrap event like this,
844          * Until the next sack
845          */
846         if (++aptr->peer.sack_generation == 0) {
847                 list_for_each_entry(trans, &asoc->peer.transport_addr_list,
848                                     transports)
849                         trans->sack_generation = 0;
850                 aptr->peer.sack_generation = 1;
851         }
852 nodata:
853         return retval;
854 }
855
856 /* Make a SHUTDOWN chunk. */
857 struct sctp_chunk *sctp_make_shutdown(const struct sctp_association *asoc,
858                                       const struct sctp_chunk *chunk)
859 {
860         struct sctp_chunk *retval;
861         sctp_shutdownhdr_t shut;
862         __u32 ctsn;
863
864         ctsn = sctp_tsnmap_get_ctsn(&asoc->peer.tsn_map);
865         shut.cum_tsn_ack = htonl(ctsn);
866
867         retval = sctp_make_control(asoc, SCTP_CID_SHUTDOWN, 0,
868                                    sizeof(sctp_shutdownhdr_t), GFP_ATOMIC);
869         if (!retval)
870                 goto nodata;
871
872         retval->subh.shutdown_hdr =
873                 sctp_addto_chunk(retval, sizeof(shut), &shut);
874
875         if (chunk)
876                 retval->transport = chunk->transport;
877 nodata:
878         return retval;
879 }
880
881 struct sctp_chunk *sctp_make_shutdown_ack(const struct sctp_association *asoc,
882                                      const struct sctp_chunk *chunk)
883 {
884         struct sctp_chunk *retval;
885
886         retval = sctp_make_control(asoc, SCTP_CID_SHUTDOWN_ACK, 0, 0,
887                                    GFP_ATOMIC);
888
889         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
890          *
891          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
892          * HEARTBEAT ACK, * etc.) to the same destination transport
893          * address from which it * received the DATA or control chunk
894          * to which it is replying.
895          *
896          * [ACK back to where the SHUTDOWN came from.]
897          */
898         if (retval && chunk)
899                 retval->transport = chunk->transport;
900
901         return retval;
902 }
903
904 struct sctp_chunk *sctp_make_shutdown_complete(
905         const struct sctp_association *asoc,
906         const struct sctp_chunk *chunk)
907 {
908         struct sctp_chunk *retval;
909         __u8 flags = 0;
910
911         /* Set the T-bit if we have no association (vtag will be
912          * reflected)
913          */
914         flags |= asoc ? 0 : SCTP_CHUNK_FLAG_T;
915
916         retval = sctp_make_control(asoc, SCTP_CID_SHUTDOWN_COMPLETE, flags,
917                                    0, GFP_ATOMIC);
918
919         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
920          *
921          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
922          * HEARTBEAT ACK, * etc.) to the same destination transport
923          * address from which it * received the DATA or control chunk
924          * to which it is replying.
925          *
926          * [Report SHUTDOWN COMPLETE back to where the SHUTDOWN ACK
927          * came from.]
928          */
929         if (retval && chunk)
930                 retval->transport = chunk->transport;
931
932         return retval;
933 }
934
935 /* Create an ABORT.  Note that we set the T bit if we have no
936  * association, except when responding to an INIT (sctpimpguide 2.41).
937  */
938 struct sctp_chunk *sctp_make_abort(const struct sctp_association *asoc,
939                               const struct sctp_chunk *chunk,
940                               const size_t hint)
941 {
942         struct sctp_chunk *retval;
943         __u8 flags = 0;
944
945         /* Set the T-bit if we have no association and 'chunk' is not
946          * an INIT (vtag will be reflected).
947          */
948         if (!asoc) {
949                 if (chunk && chunk->chunk_hdr &&
950                     chunk->chunk_hdr->type == SCTP_CID_INIT)
951                         flags = 0;
952                 else
953                         flags = SCTP_CHUNK_FLAG_T;
954         }
955
956         retval = sctp_make_control(asoc, SCTP_CID_ABORT, flags, hint,
957                                    GFP_ATOMIC);
958
959         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
960          *
961          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
962          * HEARTBEAT ACK, * etc.) to the same destination transport
963          * address from which it * received the DATA or control chunk
964          * to which it is replying.
965          *
966          * [ABORT back to where the offender came from.]
967          */
968         if (retval && chunk)
969                 retval->transport = chunk->transport;
970
971         return retval;
972 }
973
974 /* Helper to create ABORT with a NO_USER_DATA error.  */
975 struct sctp_chunk *sctp_make_abort_no_data(
976         const struct sctp_association *asoc,
977         const struct sctp_chunk *chunk, __u32 tsn)
978 {
979         struct sctp_chunk *retval;
980         __be32 payload;
981
982         retval = sctp_make_abort(asoc, chunk, sizeof(sctp_errhdr_t)
983                                  + sizeof(tsn));
984
985         if (!retval)
986                 goto no_mem;
987
988         /* Put the tsn back into network byte order.  */
989         payload = htonl(tsn);
990         sctp_init_cause(retval, SCTP_ERROR_NO_DATA, sizeof(payload));
991         sctp_addto_chunk(retval, sizeof(payload), (const void *)&payload);
992
993         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
994          *
995          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
996          * HEARTBEAT ACK, * etc.) to the same destination transport
997          * address from which it * received the DATA or control chunk
998          * to which it is replying.
999          *
1000          * [ABORT back to where the offender came from.]
1001          */
1002         if (chunk)
1003                 retval->transport = chunk->transport;
1004
1005 no_mem:
1006         return retval;
1007 }
1008
1009 /* Helper to create ABORT with a SCTP_ERROR_USER_ABORT error.  */
1010 struct sctp_chunk *sctp_make_abort_user(const struct sctp_association *asoc,
1011                                         struct msghdr *msg,
1012                                         size_t paylen)
1013 {
1014         struct sctp_chunk *retval;
1015         void *payload = NULL;
1016         int err;
1017
1018         retval = sctp_make_abort(asoc, NULL, sizeof(sctp_errhdr_t) + paylen);
1019         if (!retval)
1020                 goto err_chunk;
1021
1022         if (paylen) {
1023                 /* Put the msg_iov together into payload.  */
1024                 payload = kmalloc(paylen, GFP_KERNEL);
1025                 if (!payload)
1026                         goto err_payload;
1027
1028                 err = memcpy_from_msg(payload, msg, paylen);
1029                 if (err < 0)
1030                         goto err_copy;
1031         }
1032
1033         sctp_init_cause(retval, SCTP_ERROR_USER_ABORT, paylen);
1034         sctp_addto_chunk(retval, paylen, payload);
1035
1036         if (paylen)
1037                 kfree(payload);
1038
1039         return retval;
1040
1041 err_copy:
1042         kfree(payload);
1043 err_payload:
1044         sctp_chunk_free(retval);
1045         retval = NULL;
1046 err_chunk:
1047         return retval;
1048 }
1049
1050 /* Append bytes to the end of a parameter.  Will panic if chunk is not big
1051  * enough.
1052  */
1053 static void *sctp_addto_param(struct sctp_chunk *chunk, int len,
1054                               const void *data)
1055 {
1056         void *target;
1057         int chunklen = ntohs(chunk->chunk_hdr->length);
1058
1059         target = skb_put(chunk->skb, len);
1060
1061         if (data)
1062                 memcpy(target, data, len);
1063         else
1064                 memset(target, 0, len);
1065
1066         /* Adjust the chunk length field.  */
1067         chunk->chunk_hdr->length = htons(chunklen + len);
1068         chunk->chunk_end = skb_tail_pointer(chunk->skb);
1069
1070         return target;
1071 }
1072
1073 /* Make an ABORT chunk with a PROTOCOL VIOLATION cause code. */
1074 struct sctp_chunk *sctp_make_abort_violation(
1075         const struct sctp_association *asoc,
1076         const struct sctp_chunk *chunk,
1077         const __u8   *payload,
1078         const size_t paylen)
1079 {
1080         struct sctp_chunk  *retval;
1081         struct sctp_paramhdr phdr;
1082
1083         retval = sctp_make_abort(asoc, chunk, sizeof(sctp_errhdr_t) + paylen
1084                                         + sizeof(sctp_paramhdr_t));
1085         if (!retval)
1086                 goto end;
1087
1088         sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION, paylen
1089                                         + sizeof(sctp_paramhdr_t));
1090
1091         phdr.type = htons(chunk->chunk_hdr->type);
1092         phdr.length = chunk->chunk_hdr->length;
1093         sctp_addto_chunk(retval, paylen, payload);
1094         sctp_addto_param(retval, sizeof(sctp_paramhdr_t), &phdr);
1095
1096 end:
1097         return retval;
1098 }
1099
1100 struct sctp_chunk *sctp_make_violation_paramlen(
1101         const struct sctp_association *asoc,
1102         const struct sctp_chunk *chunk,
1103         struct sctp_paramhdr *param)
1104 {
1105         struct sctp_chunk *retval;
1106         static const char error[] = "The following parameter had invalid length:";
1107         size_t payload_len = sizeof(error) + sizeof(sctp_errhdr_t) +
1108                                 sizeof(sctp_paramhdr_t);
1109
1110         retval = sctp_make_abort(asoc, chunk, payload_len);
1111         if (!retval)
1112                 goto nodata;
1113
1114         sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION,
1115                         sizeof(error) + sizeof(sctp_paramhdr_t));
1116         sctp_addto_chunk(retval, sizeof(error), error);
1117         sctp_addto_param(retval, sizeof(sctp_paramhdr_t), param);
1118
1119 nodata:
1120         return retval;
1121 }
1122
1123 struct sctp_chunk *sctp_make_violation_max_retrans(
1124         const struct sctp_association *asoc,
1125         const struct sctp_chunk *chunk)
1126 {
1127         struct sctp_chunk *retval;
1128         static const char error[] = "Association exceeded its max_retans count";
1129         size_t payload_len = sizeof(error) + sizeof(sctp_errhdr_t);
1130
1131         retval = sctp_make_abort(asoc, chunk, payload_len);
1132         if (!retval)
1133                 goto nodata;
1134
1135         sctp_init_cause(retval, SCTP_ERROR_PROTO_VIOLATION, sizeof(error));
1136         sctp_addto_chunk(retval, sizeof(error), error);
1137
1138 nodata:
1139         return retval;
1140 }
1141
1142 /* Make a HEARTBEAT chunk.  */
1143 struct sctp_chunk *sctp_make_heartbeat(const struct sctp_association *asoc,
1144                                   const struct sctp_transport *transport)
1145 {
1146         struct sctp_chunk *retval;
1147         sctp_sender_hb_info_t hbinfo;
1148
1149         retval = sctp_make_control(asoc, SCTP_CID_HEARTBEAT, 0,
1150                                    sizeof(hbinfo), GFP_ATOMIC);
1151
1152         if (!retval)
1153                 goto nodata;
1154
1155         hbinfo.param_hdr.type = SCTP_PARAM_HEARTBEAT_INFO;
1156         hbinfo.param_hdr.length = htons(sizeof(sctp_sender_hb_info_t));
1157         hbinfo.daddr = transport->ipaddr;
1158         hbinfo.sent_at = jiffies;
1159         hbinfo.hb_nonce = transport->hb_nonce;
1160
1161         /* Cast away the 'const', as this is just telling the chunk
1162          * what transport it belongs to.
1163          */
1164         retval->transport = (struct sctp_transport *) transport;
1165         retval->subh.hbs_hdr = sctp_addto_chunk(retval, sizeof(hbinfo),
1166                                                 &hbinfo);
1167
1168 nodata:
1169         return retval;
1170 }
1171
1172 struct sctp_chunk *sctp_make_heartbeat_ack(const struct sctp_association *asoc,
1173                                       const struct sctp_chunk *chunk,
1174                                       const void *payload, const size_t paylen)
1175 {
1176         struct sctp_chunk *retval;
1177
1178         retval  = sctp_make_control(asoc, SCTP_CID_HEARTBEAT_ACK, 0, paylen,
1179                                     GFP_ATOMIC);
1180         if (!retval)
1181                 goto nodata;
1182
1183         retval->subh.hbs_hdr = sctp_addto_chunk(retval, paylen, payload);
1184
1185         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
1186          *
1187          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
1188          * HEARTBEAT ACK, * etc.) to the same destination transport
1189          * address from which it * received the DATA or control chunk
1190          * to which it is replying.
1191          *
1192          * [HBACK back to where the HEARTBEAT came from.]
1193          */
1194         if (chunk)
1195                 retval->transport = chunk->transport;
1196
1197 nodata:
1198         return retval;
1199 }
1200
1201 /* Create an Operation Error chunk with the specified space reserved.
1202  * This routine can be used for containing multiple causes in the chunk.
1203  */
1204 static struct sctp_chunk *sctp_make_op_error_space(
1205         const struct sctp_association *asoc,
1206         const struct sctp_chunk *chunk,
1207         size_t size)
1208 {
1209         struct sctp_chunk *retval;
1210
1211         retval = sctp_make_control(asoc, SCTP_CID_ERROR, 0,
1212                                    sizeof(sctp_errhdr_t) + size, GFP_ATOMIC);
1213         if (!retval)
1214                 goto nodata;
1215
1216         /* RFC 2960 6.4 Multi-homed SCTP Endpoints
1217          *
1218          * An endpoint SHOULD transmit reply chunks (e.g., SACK,
1219          * HEARTBEAT ACK, etc.) to the same destination transport
1220          * address from which it received the DATA or control chunk
1221          * to which it is replying.
1222          *
1223          */
1224         if (chunk)
1225                 retval->transport = chunk->transport;
1226
1227 nodata:
1228         return retval;
1229 }
1230
1231 /* Create an Operation Error chunk of a fixed size,
1232  * specifically, max(asoc->pathmtu, SCTP_DEFAULT_MAXSEGMENT)
1233  * This is a helper function to allocate an error chunk for
1234  * for those invalid parameter codes in which we may not want
1235  * to report all the errors, if the incoming chunk is large
1236  */
1237 static inline struct sctp_chunk *sctp_make_op_error_fixed(
1238         const struct sctp_association *asoc,
1239         const struct sctp_chunk *chunk)
1240 {
1241         size_t size = asoc ? asoc->pathmtu : 0;
1242
1243         if (!size)
1244                 size = SCTP_DEFAULT_MAXSEGMENT;
1245
1246         return sctp_make_op_error_space(asoc, chunk, size);
1247 }
1248
1249 /* Create an Operation Error chunk.  */
1250 struct sctp_chunk *sctp_make_op_error(const struct sctp_association *asoc,
1251                                  const struct sctp_chunk *chunk,
1252                                  __be16 cause_code, const void *payload,
1253                                  size_t paylen, size_t reserve_tail)
1254 {
1255         struct sctp_chunk *retval;
1256
1257         retval = sctp_make_op_error_space(asoc, chunk, paylen + reserve_tail);
1258         if (!retval)
1259                 goto nodata;
1260
1261         sctp_init_cause(retval, cause_code, paylen + reserve_tail);
1262         sctp_addto_chunk(retval, paylen, payload);
1263         if (reserve_tail)
1264                 sctp_addto_param(retval, reserve_tail, NULL);
1265
1266 nodata:
1267         return retval;
1268 }
1269
1270 struct sctp_chunk *sctp_make_auth(const struct sctp_association *asoc)
1271 {
1272         struct sctp_chunk *retval;
1273         struct sctp_hmac *hmac_desc;
1274         struct sctp_authhdr auth_hdr;
1275         __u8 *hmac;
1276
1277         /* Get the first hmac that the peer told us to use */
1278         hmac_desc = sctp_auth_asoc_get_hmac(asoc);
1279         if (unlikely(!hmac_desc))
1280                 return NULL;
1281
1282         retval = sctp_make_control(asoc, SCTP_CID_AUTH, 0,
1283                         hmac_desc->hmac_len + sizeof(sctp_authhdr_t),
1284                         GFP_ATOMIC);
1285         if (!retval)
1286                 return NULL;
1287
1288         auth_hdr.hmac_id = htons(hmac_desc->hmac_id);
1289         auth_hdr.shkey_id = htons(asoc->active_key_id);
1290
1291         retval->subh.auth_hdr = sctp_addto_chunk(retval, sizeof(sctp_authhdr_t),
1292                                                 &auth_hdr);
1293
1294         hmac = skb_put(retval->skb, hmac_desc->hmac_len);
1295         memset(hmac, 0, hmac_desc->hmac_len);
1296
1297         /* Adjust the chunk header to include the empty MAC */
1298         retval->chunk_hdr->length =
1299                 htons(ntohs(retval->chunk_hdr->length) + hmac_desc->hmac_len);
1300         retval->chunk_end = skb_tail_pointer(retval->skb);
1301
1302         return retval;
1303 }
1304
1305
1306 /********************************************************************
1307  * 2nd Level Abstractions
1308  ********************************************************************/
1309
1310 /* Turn an skb into a chunk.
1311  * FIXME: Eventually move the structure directly inside the skb->cb[].
1312  *
1313  * sctpimpguide-05.txt Section 2.8.2
1314  * M1) Each time a new DATA chunk is transmitted
1315  * set the 'TSN.Missing.Report' count for that TSN to 0. The
1316  * 'TSN.Missing.Report' count will be used to determine missing chunks
1317  * and when to fast retransmit.
1318  *
1319  */
1320 struct sctp_chunk *sctp_chunkify(struct sk_buff *skb,
1321                             const struct sctp_association *asoc,
1322                             struct sock *sk, gfp_t gfp)
1323 {
1324         struct sctp_chunk *retval;
1325
1326         retval = kmem_cache_zalloc(sctp_chunk_cachep, gfp);
1327
1328         if (!retval)
1329                 goto nodata;
1330         if (!sk)
1331                 pr_debug("%s: chunkifying skb:%p w/o an sk\n", __func__, skb);
1332
1333         INIT_LIST_HEAD(&retval->list);
1334         retval->skb             = skb;
1335         retval->asoc            = (struct sctp_association *)asoc;
1336         retval->singleton       = 1;
1337
1338         retval->fast_retransmit = SCTP_CAN_FRTX;
1339
1340         /* Polish the bead hole.  */
1341         INIT_LIST_HEAD(&retval->transmitted_list);
1342         INIT_LIST_HEAD(&retval->frag_list);
1343         SCTP_DBG_OBJCNT_INC(chunk);
1344         atomic_set(&retval->refcnt, 1);
1345
1346 nodata:
1347         return retval;
1348 }
1349
1350 /* Set chunk->source and dest based on the IP header in chunk->skb.  */
1351 void sctp_init_addrs(struct sctp_chunk *chunk, union sctp_addr *src,
1352                      union sctp_addr *dest)
1353 {
1354         memcpy(&chunk->source, src, sizeof(union sctp_addr));
1355         memcpy(&chunk->dest, dest, sizeof(union sctp_addr));
1356 }
1357
1358 /* Extract the source address from a chunk.  */
1359 const union sctp_addr *sctp_source(const struct sctp_chunk *chunk)
1360 {
1361         /* If we have a known transport, use that.  */
1362         if (chunk->transport) {
1363                 return &chunk->transport->ipaddr;
1364         } else {
1365                 /* Otherwise, extract it from the IP header.  */
1366                 return &chunk->source;
1367         }
1368 }
1369
1370 /* Create a new chunk, setting the type and flags headers from the
1371  * arguments, reserving enough space for a 'paylen' byte payload.
1372  */
1373 static struct sctp_chunk *_sctp_make_chunk(const struct sctp_association *asoc,
1374                                             __u8 type, __u8 flags, int paylen,
1375                                             gfp_t gfp)
1376 {
1377         struct sctp_chunk *retval;
1378         sctp_chunkhdr_t *chunk_hdr;
1379         struct sk_buff *skb;
1380         struct sock *sk;
1381
1382         /* No need to allocate LL here, as this is only a chunk. */
1383         skb = alloc_skb(WORD_ROUND(sizeof(sctp_chunkhdr_t) + paylen), gfp);
1384         if (!skb)
1385                 goto nodata;
1386
1387         /* Make room for the chunk header.  */
1388         chunk_hdr = (sctp_chunkhdr_t *)skb_put(skb, sizeof(sctp_chunkhdr_t));
1389         chunk_hdr->type   = type;
1390         chunk_hdr->flags  = flags;
1391         chunk_hdr->length = htons(sizeof(sctp_chunkhdr_t));
1392
1393         sk = asoc ? asoc->base.sk : NULL;
1394         retval = sctp_chunkify(skb, asoc, sk, gfp);
1395         if (!retval) {
1396                 kfree_skb(skb);
1397                 goto nodata;
1398         }
1399
1400         retval->chunk_hdr = chunk_hdr;
1401         retval->chunk_end = ((__u8 *)chunk_hdr) + sizeof(struct sctp_chunkhdr);
1402
1403         /* Determine if the chunk needs to be authenticated */
1404         if (sctp_auth_send_cid(type, asoc))
1405                 retval->auth = 1;
1406
1407         return retval;
1408 nodata:
1409         return NULL;
1410 }
1411
1412 static struct sctp_chunk *sctp_make_data(const struct sctp_association *asoc,
1413                                          __u8 flags, int paylen, gfp_t gfp)
1414 {
1415         return _sctp_make_chunk(asoc, SCTP_CID_DATA, flags, paylen, gfp);
1416 }
1417
1418 static struct sctp_chunk *sctp_make_control(const struct sctp_association *asoc,
1419                                             __u8 type, __u8 flags, int paylen,
1420                                             gfp_t gfp)
1421 {
1422         struct sctp_chunk *chunk;
1423
1424         chunk = _sctp_make_chunk(asoc, type, flags, paylen, gfp);
1425         if (chunk)
1426                 sctp_control_set_owner_w(chunk);
1427
1428         return chunk;
1429 }
1430
1431 /* Release the memory occupied by a chunk.  */
1432 static void sctp_chunk_destroy(struct sctp_chunk *chunk)
1433 {
1434         BUG_ON(!list_empty(&chunk->list));
1435         list_del_init(&chunk->transmitted_list);
1436
1437         consume_skb(chunk->skb);
1438         consume_skb(chunk->auth_chunk);
1439
1440         SCTP_DBG_OBJCNT_DEC(chunk);
1441         kmem_cache_free(sctp_chunk_cachep, chunk);
1442 }
1443
1444 /* Possibly, free the chunk.  */
1445 void sctp_chunk_free(struct sctp_chunk *chunk)
1446 {
1447         /* Release our reference on the message tracker. */
1448         if (chunk->msg)
1449                 sctp_datamsg_put(chunk->msg);
1450
1451         sctp_chunk_put(chunk);
1452 }
1453
1454 /* Grab a reference to the chunk. */
1455 void sctp_chunk_hold(struct sctp_chunk *ch)
1456 {
1457         atomic_inc(&ch->refcnt);
1458 }
1459
1460 /* Release a reference to the chunk. */
1461 void sctp_chunk_put(struct sctp_chunk *ch)
1462 {
1463         if (atomic_dec_and_test(&ch->refcnt))
1464                 sctp_chunk_destroy(ch);
1465 }
1466
1467 /* Append bytes to the end of a chunk.  Will panic if chunk is not big
1468  * enough.
1469  */
1470 void *sctp_addto_chunk(struct sctp_chunk *chunk, int len, const void *data)
1471 {
1472         void *target;
1473         void *padding;
1474         int chunklen = ntohs(chunk->chunk_hdr->length);
1475         int padlen = WORD_ROUND(chunklen) - chunklen;
1476
1477         padding = skb_put(chunk->skb, padlen);
1478         target = skb_put(chunk->skb, len);
1479
1480         memset(padding, 0, padlen);
1481         memcpy(target, data, len);
1482
1483         /* Adjust the chunk length field.  */
1484         chunk->chunk_hdr->length = htons(chunklen + padlen + len);
1485         chunk->chunk_end = skb_tail_pointer(chunk->skb);
1486
1487         return target;
1488 }
1489
1490 /* Append bytes to the end of a chunk. Returns NULL if there isn't sufficient
1491  * space in the chunk
1492  */
1493 static void *sctp_addto_chunk_fixed(struct sctp_chunk *chunk,
1494                                     int len, const void *data)
1495 {
1496         if (skb_tailroom(chunk->skb) >= len)
1497                 return sctp_addto_chunk(chunk, len, data);
1498         else
1499                 return NULL;
1500 }
1501
1502 /* Append bytes from user space to the end of a chunk.  Will panic if
1503  * chunk is not big enough.
1504  * Returns a kernel err value.
1505  */
1506 int sctp_user_addto_chunk(struct sctp_chunk *chunk, int len,
1507                           struct iov_iter *from)
1508 {
1509         void *target;
1510         ssize_t copied;
1511
1512         /* Make room in chunk for data.  */
1513         target = skb_put(chunk->skb, len);
1514
1515         /* Copy data (whole iovec) into chunk */
1516         copied = copy_from_iter(target, len, from);
1517         if (copied != len)
1518                 return -EFAULT;
1519
1520         /* Adjust the chunk length field.  */
1521         chunk->chunk_hdr->length =
1522                 htons(ntohs(chunk->chunk_hdr->length) + len);
1523         chunk->chunk_end = skb_tail_pointer(chunk->skb);
1524
1525         return 0;
1526 }
1527
1528 /* Helper function to assign a TSN if needed.  This assumes that both
1529  * the data_hdr and association have already been assigned.
1530  */
1531 void sctp_chunk_assign_ssn(struct sctp_chunk *chunk)
1532 {
1533         struct sctp_datamsg *msg;
1534         struct sctp_chunk *lchunk;
1535         struct sctp_stream *stream;
1536         __u16 ssn;
1537         __u16 sid;
1538
1539         if (chunk->has_ssn)
1540                 return;
1541
1542         /* All fragments will be on the same stream */
1543         sid = ntohs(chunk->subh.data_hdr->stream);
1544         stream = &chunk->asoc->ssnmap->out;
1545
1546         /* Now assign the sequence number to the entire message.
1547          * All fragments must have the same stream sequence number.
1548          */
1549         msg = chunk->msg;
1550         list_for_each_entry(lchunk, &msg->chunks, frag_list) {
1551                 if (lchunk->chunk_hdr->flags & SCTP_DATA_UNORDERED) {
1552                         ssn = 0;
1553                 } else {
1554                         if (lchunk->chunk_hdr->flags & SCTP_DATA_LAST_FRAG)
1555                                 ssn = sctp_ssn_next(stream, sid);
1556                         else
1557                                 ssn = sctp_ssn_peek(stream, sid);
1558                 }
1559
1560                 lchunk->subh.data_hdr->ssn = htons(ssn);
1561                 lchunk->has_ssn = 1;
1562         }
1563 }
1564
1565 /* Helper function to assign a TSN if needed.  This assumes that both
1566  * the data_hdr and association have already been assigned.
1567  */
1568 void sctp_chunk_assign_tsn(struct sctp_chunk *chunk)
1569 {
1570         if (!chunk->has_tsn) {
1571                 /* This is the last possible instant to
1572                  * assign a TSN.
1573                  */
1574                 chunk->subh.data_hdr->tsn =
1575                         htonl(sctp_association_get_next_tsn(chunk->asoc));
1576                 chunk->has_tsn = 1;
1577         }
1578 }
1579
1580 /* Create a CLOSED association to use with an incoming packet.  */
1581 struct sctp_association *sctp_make_temp_asoc(const struct sctp_endpoint *ep,
1582                                         struct sctp_chunk *chunk,
1583                                         gfp_t gfp)
1584 {
1585         struct sctp_association *asoc;
1586         struct sk_buff *skb;
1587         sctp_scope_t scope;
1588         struct sctp_af *af;
1589
1590         /* Create the bare association.  */
1591         scope = sctp_scope(sctp_source(chunk));
1592         asoc = sctp_association_new(ep, ep->base.sk, scope, gfp);
1593         if (!asoc)
1594                 goto nodata;
1595         asoc->temp = 1;
1596         skb = chunk->skb;
1597         /* Create an entry for the source address of the packet.  */
1598         af = sctp_get_af_specific(ipver2af(ip_hdr(skb)->version));
1599         if (unlikely(!af))
1600                 goto fail;
1601         af->from_skb(&asoc->c.peer_addr, skb, 1);
1602 nodata:
1603         return asoc;
1604
1605 fail:
1606         sctp_association_free(asoc);
1607         return NULL;
1608 }
1609
1610 /* Build a cookie representing asoc.
1611  * This INCLUDES the param header needed to put the cookie in the INIT ACK.
1612  */
1613 static sctp_cookie_param_t *sctp_pack_cookie(const struct sctp_endpoint *ep,
1614                                       const struct sctp_association *asoc,
1615                                       const struct sctp_chunk *init_chunk,
1616                                       int *cookie_len,
1617                                       const __u8 *raw_addrs, int addrs_len)
1618 {
1619         sctp_cookie_param_t *retval;
1620         struct sctp_signed_cookie *cookie;
1621         struct scatterlist sg;
1622         int headersize, bodysize;
1623
1624         /* Header size is static data prior to the actual cookie, including
1625          * any padding.
1626          */
1627         headersize = sizeof(sctp_paramhdr_t) +
1628                      (sizeof(struct sctp_signed_cookie) -
1629                       sizeof(struct sctp_cookie));
1630         bodysize = sizeof(struct sctp_cookie)
1631                 + ntohs(init_chunk->chunk_hdr->length) + addrs_len;
1632
1633         /* Pad out the cookie to a multiple to make the signature
1634          * functions simpler to write.
1635          */
1636         if (bodysize % SCTP_COOKIE_MULTIPLE)
1637                 bodysize += SCTP_COOKIE_MULTIPLE
1638                         - (bodysize % SCTP_COOKIE_MULTIPLE);
1639         *cookie_len = headersize + bodysize;
1640
1641         /* Clear this memory since we are sending this data structure
1642          * out on the network.
1643          */
1644         retval = kzalloc(*cookie_len, GFP_ATOMIC);
1645         if (!retval)
1646                 goto nodata;
1647
1648         cookie = (struct sctp_signed_cookie *) retval->body;
1649
1650         /* Set up the parameter header.  */
1651         retval->p.type = SCTP_PARAM_STATE_COOKIE;
1652         retval->p.length = htons(*cookie_len);
1653
1654         /* Copy the cookie part of the association itself.  */
1655         cookie->c = asoc->c;
1656         /* Save the raw address list length in the cookie. */
1657         cookie->c.raw_addr_list_len = addrs_len;
1658
1659         /* Remember PR-SCTP capability. */
1660         cookie->c.prsctp_capable = asoc->peer.prsctp_capable;
1661
1662         /* Save adaptation indication in the cookie. */
1663         cookie->c.adaptation_ind = asoc->peer.adaptation_ind;
1664
1665         /* Set an expiration time for the cookie.  */
1666         cookie->c.expiration = ktime_add(asoc->cookie_life,
1667                                          ktime_get_real());
1668
1669         /* Copy the peer's init packet.  */
1670         memcpy(&cookie->c.peer_init[0], init_chunk->chunk_hdr,
1671                ntohs(init_chunk->chunk_hdr->length));
1672
1673         /* Copy the raw local address list of the association. */
1674         memcpy((__u8 *)&cookie->c.peer_init[0] +
1675                ntohs(init_chunk->chunk_hdr->length), raw_addrs, addrs_len);
1676
1677         if (sctp_sk(ep->base.sk)->hmac) {
1678                 struct hash_desc desc;
1679
1680                 /* Sign the message.  */
1681                 sg_init_one(&sg, &cookie->c, bodysize);
1682                 desc.tfm = sctp_sk(ep->base.sk)->hmac;
1683                 desc.flags = 0;
1684
1685                 if (crypto_hash_setkey(desc.tfm, ep->secret_key,
1686                                        sizeof(ep->secret_key)) ||
1687                     crypto_hash_digest(&desc, &sg, bodysize, cookie->signature))
1688                         goto free_cookie;
1689         }
1690
1691         return retval;
1692
1693 free_cookie:
1694         kfree(retval);
1695 nodata:
1696         *cookie_len = 0;
1697         return NULL;
1698 }
1699
1700 /* Unpack the cookie from COOKIE ECHO chunk, recreating the association.  */
1701 struct sctp_association *sctp_unpack_cookie(
1702         const struct sctp_endpoint *ep,
1703         const struct sctp_association *asoc,
1704         struct sctp_chunk *chunk, gfp_t gfp,
1705         int *error, struct sctp_chunk **errp)
1706 {
1707         struct sctp_association *retval = NULL;
1708         struct sctp_signed_cookie *cookie;
1709         struct sctp_cookie *bear_cookie;
1710         int headersize, bodysize, fixed_size;
1711         __u8 *digest = ep->digest;
1712         struct scatterlist sg;
1713         unsigned int len;
1714         sctp_scope_t scope;
1715         struct sk_buff *skb = chunk->skb;
1716         ktime_t kt;
1717         struct hash_desc desc;
1718
1719         /* Header size is static data prior to the actual cookie, including
1720          * any padding.
1721          */
1722         headersize = sizeof(sctp_chunkhdr_t) +
1723                      (sizeof(struct sctp_signed_cookie) -
1724                       sizeof(struct sctp_cookie));
1725         bodysize = ntohs(chunk->chunk_hdr->length) - headersize;
1726         fixed_size = headersize + sizeof(struct sctp_cookie);
1727
1728         /* Verify that the chunk looks like it even has a cookie.
1729          * There must be enough room for our cookie and our peer's
1730          * INIT chunk.
1731          */
1732         len = ntohs(chunk->chunk_hdr->length);
1733         if (len < fixed_size + sizeof(struct sctp_chunkhdr))
1734                 goto malformed;
1735
1736         /* Verify that the cookie has been padded out. */
1737         if (bodysize % SCTP_COOKIE_MULTIPLE)
1738                 goto malformed;
1739
1740         /* Process the cookie.  */
1741         cookie = chunk->subh.cookie_hdr;
1742         bear_cookie = &cookie->c;
1743
1744         if (!sctp_sk(ep->base.sk)->hmac)
1745                 goto no_hmac;
1746
1747         /* Check the signature.  */
1748         sg_init_one(&sg, bear_cookie, bodysize);
1749         desc.tfm = sctp_sk(ep->base.sk)->hmac;
1750         desc.flags = 0;
1751
1752         memset(digest, 0x00, SCTP_SIGNATURE_SIZE);
1753         if (crypto_hash_setkey(desc.tfm, ep->secret_key,
1754                                sizeof(ep->secret_key)) ||
1755             crypto_hash_digest(&desc, &sg, bodysize, digest)) {
1756                 *error = -SCTP_IERROR_NOMEM;
1757                 goto fail;
1758         }
1759
1760         if (memcmp(digest, cookie->signature, SCTP_SIGNATURE_SIZE)) {
1761                 *error = -SCTP_IERROR_BAD_SIG;
1762                 goto fail;
1763         }
1764
1765 no_hmac:
1766         /* IG Section 2.35.2:
1767          *  3) Compare the port numbers and the verification tag contained
1768          *     within the COOKIE ECHO chunk to the actual port numbers and the
1769          *     verification tag within the SCTP common header of the received
1770          *     packet. If these values do not match the packet MUST be silently
1771          *     discarded,
1772          */
1773         if (ntohl(chunk->sctp_hdr->vtag) != bear_cookie->my_vtag) {
1774                 *error = -SCTP_IERROR_BAD_TAG;
1775                 goto fail;
1776         }
1777
1778         if (chunk->sctp_hdr->source != bear_cookie->peer_addr.v4.sin_port ||
1779             ntohs(chunk->sctp_hdr->dest) != bear_cookie->my_port) {
1780                 *error = -SCTP_IERROR_BAD_PORTS;
1781                 goto fail;
1782         }
1783
1784         /* Check to see if the cookie is stale.  If there is already
1785          * an association, there is no need to check cookie's expiration
1786          * for init collision case of lost COOKIE ACK.
1787          * If skb has been timestamped, then use the stamp, otherwise
1788          * use current time.  This introduces a small possibility that
1789          * that a cookie may be considered expired, but his would only slow
1790          * down the new association establishment instead of every packet.
1791          */
1792         if (sock_flag(ep->base.sk, SOCK_TIMESTAMP))
1793                 kt = skb_get_ktime(skb);
1794         else
1795                 kt = ktime_get_real();
1796
1797         if (!asoc && ktime_before(bear_cookie->expiration, kt)) {
1798                 /*
1799                  * Section 3.3.10.3 Stale Cookie Error (3)
1800                  *
1801                  * Cause of error
1802                  * ---------------
1803                  * Stale Cookie Error:  Indicates the receipt of a valid State
1804                  * Cookie that has expired.
1805                  */
1806                 len = ntohs(chunk->chunk_hdr->length);
1807                 *errp = sctp_make_op_error_space(asoc, chunk, len);
1808                 if (*errp) {
1809                         suseconds_t usecs = ktime_to_us(ktime_sub(kt, bear_cookie->expiration));
1810                         __be32 n = htonl(usecs);
1811
1812                         sctp_init_cause(*errp, SCTP_ERROR_STALE_COOKIE,
1813                                         sizeof(n));
1814                         sctp_addto_chunk(*errp, sizeof(n), &n);
1815                         *error = -SCTP_IERROR_STALE_COOKIE;
1816                 } else
1817                         *error = -SCTP_IERROR_NOMEM;
1818
1819                 goto fail;
1820         }
1821
1822         /* Make a new base association.  */
1823         scope = sctp_scope(sctp_source(chunk));
1824         retval = sctp_association_new(ep, ep->base.sk, scope, gfp);
1825         if (!retval) {
1826                 *error = -SCTP_IERROR_NOMEM;
1827                 goto fail;
1828         }
1829
1830         /* Set up our peer's port number.  */
1831         retval->peer.port = ntohs(chunk->sctp_hdr->source);
1832
1833         /* Populate the association from the cookie.  */
1834         memcpy(&retval->c, bear_cookie, sizeof(*bear_cookie));
1835
1836         if (sctp_assoc_set_bind_addr_from_cookie(retval, bear_cookie,
1837                                                  GFP_ATOMIC) < 0) {
1838                 *error = -SCTP_IERROR_NOMEM;
1839                 goto fail;
1840         }
1841
1842         /* Also, add the destination address. */
1843         if (list_empty(&retval->base.bind_addr.address_list)) {
1844                 sctp_add_bind_addr(&retval->base.bind_addr, &chunk->dest,
1845                                 SCTP_ADDR_SRC, GFP_ATOMIC);
1846         }
1847
1848         retval->next_tsn = retval->c.initial_tsn;
1849         retval->ctsn_ack_point = retval->next_tsn - 1;
1850         retval->addip_serial = retval->c.initial_tsn;
1851         retval->adv_peer_ack_point = retval->ctsn_ack_point;
1852         retval->peer.prsctp_capable = retval->c.prsctp_capable;
1853         retval->peer.adaptation_ind = retval->c.adaptation_ind;
1854
1855         /* The INIT stuff will be done by the side effects.  */
1856         return retval;
1857
1858 fail:
1859         if (retval)
1860                 sctp_association_free(retval);
1861
1862         return NULL;
1863
1864 malformed:
1865         /* Yikes!  The packet is either corrupt or deliberately
1866          * malformed.
1867          */
1868         *error = -SCTP_IERROR_MALFORMED;
1869         goto fail;
1870 }
1871
1872 /********************************************************************
1873  * 3rd Level Abstractions
1874  ********************************************************************/
1875
1876 struct __sctp_missing {
1877         __be32 num_missing;
1878         __be16 type;
1879 }  __packed;
1880
1881 /*
1882  * Report a missing mandatory parameter.
1883  */
1884 static int sctp_process_missing_param(const struct sctp_association *asoc,
1885                                       sctp_param_t paramtype,
1886                                       struct sctp_chunk *chunk,
1887                                       struct sctp_chunk **errp)
1888 {
1889         struct __sctp_missing report;
1890         __u16 len;
1891
1892         len = WORD_ROUND(sizeof(report));
1893
1894         /* Make an ERROR chunk, preparing enough room for
1895          * returning multiple unknown parameters.
1896          */
1897         if (!*errp)
1898                 *errp = sctp_make_op_error_space(asoc, chunk, len);
1899
1900         if (*errp) {
1901                 report.num_missing = htonl(1);
1902                 report.type = paramtype;
1903                 sctp_init_cause(*errp, SCTP_ERROR_MISS_PARAM,
1904                                 sizeof(report));
1905                 sctp_addto_chunk(*errp, sizeof(report), &report);
1906         }
1907
1908         /* Stop processing this chunk. */
1909         return 0;
1910 }
1911
1912 /* Report an Invalid Mandatory Parameter.  */
1913 static int sctp_process_inv_mandatory(const struct sctp_association *asoc,
1914                                       struct sctp_chunk *chunk,
1915                                       struct sctp_chunk **errp)
1916 {
1917         /* Invalid Mandatory Parameter Error has no payload. */
1918
1919         if (!*errp)
1920                 *errp = sctp_make_op_error_space(asoc, chunk, 0);
1921
1922         if (*errp)
1923                 sctp_init_cause(*errp, SCTP_ERROR_INV_PARAM, 0);
1924
1925         /* Stop processing this chunk. */
1926         return 0;
1927 }
1928
1929 static int sctp_process_inv_paramlength(const struct sctp_association *asoc,
1930                                         struct sctp_paramhdr *param,
1931                                         const struct sctp_chunk *chunk,
1932                                         struct sctp_chunk **errp)
1933 {
1934         /* This is a fatal error.  Any accumulated non-fatal errors are
1935          * not reported.
1936          */
1937         if (*errp)
1938                 sctp_chunk_free(*errp);
1939
1940         /* Create an error chunk and fill it in with our payload. */
1941         *errp = sctp_make_violation_paramlen(asoc, chunk, param);
1942
1943         return 0;
1944 }
1945
1946
1947 /* Do not attempt to handle the HOST_NAME parm.  However, do
1948  * send back an indicator to the peer.
1949  */
1950 static int sctp_process_hn_param(const struct sctp_association *asoc,
1951                                  union sctp_params param,
1952                                  struct sctp_chunk *chunk,
1953                                  struct sctp_chunk **errp)
1954 {
1955         __u16 len = ntohs(param.p->length);
1956
1957         /* Processing of the HOST_NAME parameter will generate an
1958          * ABORT.  If we've accumulated any non-fatal errors, they
1959          * would be unrecognized parameters and we should not include
1960          * them in the ABORT.
1961          */
1962         if (*errp)
1963                 sctp_chunk_free(*errp);
1964
1965         *errp = sctp_make_op_error_space(asoc, chunk, len);
1966
1967         if (*errp) {
1968                 sctp_init_cause(*errp, SCTP_ERROR_DNS_FAILED, len);
1969                 sctp_addto_chunk(*errp, len, param.v);
1970         }
1971
1972         /* Stop processing this chunk. */
1973         return 0;
1974 }
1975
1976 static int sctp_verify_ext_param(struct net *net, union sctp_params param)
1977 {
1978         __u16 num_ext = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
1979         int have_auth = 0;
1980         int have_asconf = 0;
1981         int i;
1982
1983         for (i = 0; i < num_ext; i++) {
1984                 switch (param.ext->chunks[i]) {
1985                 case SCTP_CID_AUTH:
1986                         have_auth = 1;
1987                         break;
1988                 case SCTP_CID_ASCONF:
1989                 case SCTP_CID_ASCONF_ACK:
1990                         have_asconf = 1;
1991                         break;
1992                 }
1993         }
1994
1995         /* ADD-IP Security: The draft requires us to ABORT or ignore the
1996          * INIT/INIT-ACK if ADD-IP is listed, but AUTH is not.  Do this
1997          * only if ADD-IP is turned on and we are not backward-compatible
1998          * mode.
1999          */
2000         if (net->sctp.addip_noauth)
2001                 return 1;
2002
2003         if (net->sctp.addip_enable && !have_auth && have_asconf)
2004                 return 0;
2005
2006         return 1;
2007 }
2008
2009 static void sctp_process_ext_param(struct sctp_association *asoc,
2010                                     union sctp_params param)
2011 {
2012         struct net *net = sock_net(asoc->base.sk);
2013         __u16 num_ext = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
2014         int i;
2015
2016         for (i = 0; i < num_ext; i++) {
2017                 switch (param.ext->chunks[i]) {
2018                 case SCTP_CID_FWD_TSN:
2019                         if (net->sctp.prsctp_enable && !asoc->peer.prsctp_capable)
2020                                     asoc->peer.prsctp_capable = 1;
2021                         break;
2022                 case SCTP_CID_AUTH:
2023                         /* if the peer reports AUTH, assume that he
2024                          * supports AUTH.
2025                          */
2026                         if (asoc->ep->auth_enable)
2027                                 asoc->peer.auth_capable = 1;
2028                         break;
2029                 case SCTP_CID_ASCONF:
2030                 case SCTP_CID_ASCONF_ACK:
2031                         if (net->sctp.addip_enable)
2032                                 asoc->peer.asconf_capable = 1;
2033                         break;
2034                 default:
2035                         break;
2036                 }
2037         }
2038 }
2039
2040 /* RFC 3.2.1 & the Implementers Guide 2.2.
2041  *
2042  * The Parameter Types are encoded such that the
2043  * highest-order two bits specify the action that must be
2044  * taken if the processing endpoint does not recognize the
2045  * Parameter Type.
2046  *
2047  * 00 - Stop processing this parameter; do not process any further
2048  *      parameters within this chunk
2049  *
2050  * 01 - Stop processing this parameter, do not process any further
2051  *      parameters within this chunk, and report the unrecognized
2052  *      parameter in an 'Unrecognized Parameter' ERROR chunk.
2053  *
2054  * 10 - Skip this parameter and continue processing.
2055  *
2056  * 11 - Skip this parameter and continue processing but
2057  *      report the unrecognized parameter in an
2058  *      'Unrecognized Parameter' ERROR chunk.
2059  *
2060  * Return value:
2061  *      SCTP_IERROR_NO_ERROR - continue with the chunk
2062  *      SCTP_IERROR_ERROR    - stop and report an error.
2063  *      SCTP_IERROR_NOMEME   - out of memory.
2064  */
2065 static sctp_ierror_t sctp_process_unk_param(const struct sctp_association *asoc,
2066                                             union sctp_params param,
2067                                             struct sctp_chunk *chunk,
2068                                             struct sctp_chunk **errp)
2069 {
2070         int retval = SCTP_IERROR_NO_ERROR;
2071
2072         switch (param.p->type & SCTP_PARAM_ACTION_MASK) {
2073         case SCTP_PARAM_ACTION_DISCARD:
2074                 retval =  SCTP_IERROR_ERROR;
2075                 break;
2076         case SCTP_PARAM_ACTION_SKIP:
2077                 break;
2078         case SCTP_PARAM_ACTION_DISCARD_ERR:
2079                 retval =  SCTP_IERROR_ERROR;
2080                 /* Fall through */
2081         case SCTP_PARAM_ACTION_SKIP_ERR:
2082                 /* Make an ERROR chunk, preparing enough room for
2083                  * returning multiple unknown parameters.
2084                  */
2085                 if (NULL == *errp)
2086                         *errp = sctp_make_op_error_fixed(asoc, chunk);
2087
2088                 if (*errp) {
2089                         if (!sctp_init_cause_fixed(*errp, SCTP_ERROR_UNKNOWN_PARAM,
2090                                         WORD_ROUND(ntohs(param.p->length))))
2091                                 sctp_addto_chunk_fixed(*errp,
2092                                                 WORD_ROUND(ntohs(param.p->length)),
2093                                                 param.v);
2094                 } else {
2095                         /* If there is no memory for generating the ERROR
2096                          * report as specified, an ABORT will be triggered
2097                          * to the peer and the association won't be
2098                          * established.
2099                          */
2100                         retval = SCTP_IERROR_NOMEM;
2101                 }
2102                 break;
2103         default:
2104                 break;
2105         }
2106
2107         return retval;
2108 }
2109
2110 /* Verify variable length parameters
2111  * Return values:
2112  *      SCTP_IERROR_ABORT - trigger an ABORT
2113  *      SCTP_IERROR_NOMEM - out of memory (abort)
2114  *      SCTP_IERROR_ERROR - stop processing, trigger an ERROR
2115  *      SCTP_IERROR_NO_ERROR - continue with the chunk
2116  */
2117 static sctp_ierror_t sctp_verify_param(struct net *net,
2118                                         const struct sctp_endpoint *ep,
2119                                         const struct sctp_association *asoc,
2120                                         union sctp_params param,
2121                                         sctp_cid_t cid,
2122                                         struct sctp_chunk *chunk,
2123                                         struct sctp_chunk **err_chunk)
2124 {
2125         struct sctp_hmac_algo_param *hmacs;
2126         int retval = SCTP_IERROR_NO_ERROR;
2127         __u16 n_elt, id = 0;
2128         int i;
2129
2130         /* FIXME - This routine is not looking at each parameter per the
2131          * chunk type, i.e., unrecognized parameters should be further
2132          * identified based on the chunk id.
2133          */
2134
2135         switch (param.p->type) {
2136         case SCTP_PARAM_IPV4_ADDRESS:
2137         case SCTP_PARAM_IPV6_ADDRESS:
2138         case SCTP_PARAM_COOKIE_PRESERVATIVE:
2139         case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
2140         case SCTP_PARAM_STATE_COOKIE:
2141         case SCTP_PARAM_HEARTBEAT_INFO:
2142         case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
2143         case SCTP_PARAM_ECN_CAPABLE:
2144         case SCTP_PARAM_ADAPTATION_LAYER_IND:
2145                 break;
2146
2147         case SCTP_PARAM_SUPPORTED_EXT:
2148                 if (!sctp_verify_ext_param(net, param))
2149                         return SCTP_IERROR_ABORT;
2150                 break;
2151
2152         case SCTP_PARAM_SET_PRIMARY:
2153                 if (net->sctp.addip_enable)
2154                         break;
2155                 goto fallthrough;
2156
2157         case SCTP_PARAM_HOST_NAME_ADDRESS:
2158                 /* Tell the peer, we won't support this param.  */
2159                 sctp_process_hn_param(asoc, param, chunk, err_chunk);
2160                 retval = SCTP_IERROR_ABORT;
2161                 break;
2162
2163         case SCTP_PARAM_FWD_TSN_SUPPORT:
2164                 if (net->sctp.prsctp_enable)
2165                         break;
2166                 goto fallthrough;
2167
2168         case SCTP_PARAM_RANDOM:
2169                 if (!ep->auth_enable)
2170                         goto fallthrough;
2171
2172                 /* SCTP-AUTH: Secion 6.1
2173                  * If the random number is not 32 byte long the association
2174                  * MUST be aborted.  The ABORT chunk SHOULD contain the error
2175                  * cause 'Protocol Violation'.
2176                  */
2177                 if (SCTP_AUTH_RANDOM_LENGTH !=
2178                         ntohs(param.p->length) - sizeof(sctp_paramhdr_t)) {
2179                         sctp_process_inv_paramlength(asoc, param.p,
2180                                                         chunk, err_chunk);
2181                         retval = SCTP_IERROR_ABORT;
2182                 }
2183                 break;
2184
2185         case SCTP_PARAM_CHUNKS:
2186                 if (!ep->auth_enable)
2187                         goto fallthrough;
2188
2189                 /* SCTP-AUTH: Section 3.2
2190                  * The CHUNKS parameter MUST be included once in the INIT or
2191                  *  INIT-ACK chunk if the sender wants to receive authenticated
2192                  *  chunks.  Its maximum length is 260 bytes.
2193                  */
2194                 if (260 < ntohs(param.p->length)) {
2195                         sctp_process_inv_paramlength(asoc, param.p,
2196                                                      chunk, err_chunk);
2197                         retval = SCTP_IERROR_ABORT;
2198                 }
2199                 break;
2200
2201         case SCTP_PARAM_HMAC_ALGO:
2202                 if (!ep->auth_enable)
2203                         goto fallthrough;
2204
2205                 hmacs = (struct sctp_hmac_algo_param *)param.p;
2206                 n_elt = (ntohs(param.p->length) - sizeof(sctp_paramhdr_t)) >> 1;
2207
2208                 /* SCTP-AUTH: Section 6.1
2209                  * The HMAC algorithm based on SHA-1 MUST be supported and
2210                  * included in the HMAC-ALGO parameter.
2211                  */
2212                 for (i = 0; i < n_elt; i++) {
2213                         id = ntohs(hmacs->hmac_ids[i]);
2214
2215                         if (id == SCTP_AUTH_HMAC_ID_SHA1)
2216                                 break;
2217                 }
2218
2219                 if (id != SCTP_AUTH_HMAC_ID_SHA1) {
2220                         sctp_process_inv_paramlength(asoc, param.p, chunk,
2221                                                      err_chunk);
2222                         retval = SCTP_IERROR_ABORT;
2223                 }
2224                 break;
2225 fallthrough:
2226         default:
2227                 pr_debug("%s: unrecognized param:%d for chunk:%d\n",
2228                          __func__, ntohs(param.p->type), cid);
2229
2230                 retval = sctp_process_unk_param(asoc, param, chunk, err_chunk);
2231                 break;
2232         }
2233         return retval;
2234 }
2235
2236 /* Verify the INIT packet before we process it.  */
2237 int sctp_verify_init(struct net *net, const struct sctp_endpoint *ep,
2238                      const struct sctp_association *asoc, sctp_cid_t cid,
2239                      sctp_init_chunk_t *peer_init, struct sctp_chunk *chunk,
2240                      struct sctp_chunk **errp)
2241 {
2242         union sctp_params param;
2243         bool has_cookie = false;
2244         int result;
2245
2246         /* Check for missing mandatory parameters. Note: Initial TSN is
2247          * also mandatory, but is not checked here since the valid range
2248          * is 0..2**32-1. RFC4960, section 3.3.3.
2249          */
2250         if (peer_init->init_hdr.num_outbound_streams == 0 ||
2251             peer_init->init_hdr.num_inbound_streams == 0 ||
2252             peer_init->init_hdr.init_tag == 0 ||
2253             ntohl(peer_init->init_hdr.a_rwnd) < SCTP_DEFAULT_MINWINDOW)
2254                 return sctp_process_inv_mandatory(asoc, chunk, errp);
2255
2256         sctp_walk_params(param, peer_init, init_hdr.params) {
2257                 if (param.p->type == SCTP_PARAM_STATE_COOKIE)
2258                         has_cookie = true;
2259         }
2260
2261         /* There is a possibility that a parameter length was bad and
2262          * in that case we would have stoped walking the parameters.
2263          * The current param.p would point at the bad one.
2264          * Current consensus on the mailing list is to generate a PROTOCOL
2265          * VIOLATION error.  We build the ERROR chunk here and let the normal
2266          * error handling code build and send the packet.
2267          */
2268         if (param.v != (void *)chunk->chunk_end)
2269                 return sctp_process_inv_paramlength(asoc, param.p, chunk, errp);
2270
2271         /* The only missing mandatory param possible today is
2272          * the state cookie for an INIT-ACK chunk.
2273          */
2274         if ((SCTP_CID_INIT_ACK == cid) && !has_cookie)
2275                 return sctp_process_missing_param(asoc, SCTP_PARAM_STATE_COOKIE,
2276                                                   chunk, errp);
2277
2278         /* Verify all the variable length parameters */
2279         sctp_walk_params(param, peer_init, init_hdr.params) {
2280                 result = sctp_verify_param(net, ep, asoc, param, cid,
2281                                            chunk, errp);
2282                 switch (result) {
2283                 case SCTP_IERROR_ABORT:
2284                 case SCTP_IERROR_NOMEM:
2285                         return 0;
2286                 case SCTP_IERROR_ERROR:
2287                         return 1;
2288                 case SCTP_IERROR_NO_ERROR:
2289                 default:
2290                         break;
2291                 }
2292
2293         } /* for (loop through all parameters) */
2294
2295         return 1;
2296 }
2297
2298 /* Unpack the parameters in an INIT packet into an association.
2299  * Returns 0 on failure, else success.
2300  * FIXME:  This is an association method.
2301  */
2302 int sctp_process_init(struct sctp_association *asoc, struct sctp_chunk *chunk,
2303                       const union sctp_addr *peer_addr,
2304                       sctp_init_chunk_t *peer_init, gfp_t gfp)
2305 {
2306         struct net *net = sock_net(asoc->base.sk);
2307         union sctp_params param;
2308         struct sctp_transport *transport;
2309         struct list_head *pos, *temp;
2310         struct sctp_af *af;
2311         union sctp_addr addr;
2312         char *cookie;
2313         int src_match = 0;
2314
2315         /* We must include the address that the INIT packet came from.
2316          * This is the only address that matters for an INIT packet.
2317          * When processing a COOKIE ECHO, we retrieve the from address
2318          * of the INIT from the cookie.
2319          */
2320
2321         /* This implementation defaults to making the first transport
2322          * added as the primary transport.  The source address seems to
2323          * be a a better choice than any of the embedded addresses.
2324          */
2325         if (!sctp_assoc_add_peer(asoc, peer_addr, gfp, SCTP_ACTIVE))
2326                 goto nomem;
2327
2328         if (sctp_cmp_addr_exact(sctp_source(chunk), peer_addr))
2329                 src_match = 1;
2330
2331         /* Process the initialization parameters.  */
2332         sctp_walk_params(param, peer_init, init_hdr.params) {
2333                 if (!src_match && (param.p->type == SCTP_PARAM_IPV4_ADDRESS ||
2334                     param.p->type == SCTP_PARAM_IPV6_ADDRESS)) {
2335                         af = sctp_get_af_specific(param_type2af(param.p->type));
2336                         af->from_addr_param(&addr, param.addr,
2337                                             chunk->sctp_hdr->source, 0);
2338                         if (sctp_cmp_addr_exact(sctp_source(chunk), &addr))
2339                                 src_match = 1;
2340                 }
2341
2342                 if (!sctp_process_param(asoc, param, peer_addr, gfp))
2343                         goto clean_up;
2344         }
2345
2346         /* source address of chunk may not match any valid address */
2347         if (!src_match)
2348                 goto clean_up;
2349
2350         /* AUTH: After processing the parameters, make sure that we
2351          * have all the required info to potentially do authentications.
2352          */
2353         if (asoc->peer.auth_capable && (!asoc->peer.peer_random ||
2354                                         !asoc->peer.peer_hmacs))
2355                 asoc->peer.auth_capable = 0;
2356
2357         /* In a non-backward compatible mode, if the peer claims
2358          * support for ADD-IP but not AUTH,  the ADD-IP spec states
2359          * that we MUST ABORT the association. Section 6.  The section
2360          * also give us an option to silently ignore the packet, which
2361          * is what we'll do here.
2362          */
2363         if (!net->sctp.addip_noauth &&
2364              (asoc->peer.asconf_capable && !asoc->peer.auth_capable)) {
2365                 asoc->peer.addip_disabled_mask |= (SCTP_PARAM_ADD_IP |
2366                                                   SCTP_PARAM_DEL_IP |
2367                                                   SCTP_PARAM_SET_PRIMARY);
2368                 asoc->peer.asconf_capable = 0;
2369                 goto clean_up;
2370         }
2371
2372         /* Walk list of transports, removing transports in the UNKNOWN state. */
2373         list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
2374                 transport = list_entry(pos, struct sctp_transport, transports);
2375                 if (transport->state == SCTP_UNKNOWN) {
2376                         sctp_assoc_rm_peer(asoc, transport);
2377                 }
2378         }
2379
2380         /* The fixed INIT headers are always in network byte
2381          * order.
2382          */
2383         asoc->peer.i.init_tag =
2384                 ntohl(peer_init->init_hdr.init_tag);
2385         asoc->peer.i.a_rwnd =
2386                 ntohl(peer_init->init_hdr.a_rwnd);
2387         asoc->peer.i.num_outbound_streams =
2388                 ntohs(peer_init->init_hdr.num_outbound_streams);
2389         asoc->peer.i.num_inbound_streams =
2390                 ntohs(peer_init->init_hdr.num_inbound_streams);
2391         asoc->peer.i.initial_tsn =
2392                 ntohl(peer_init->init_hdr.initial_tsn);
2393
2394         /* Apply the upper bounds for output streams based on peer's
2395          * number of inbound streams.
2396          */
2397         if (asoc->c.sinit_num_ostreams  >
2398             ntohs(peer_init->init_hdr.num_inbound_streams)) {
2399                 asoc->c.sinit_num_ostreams =
2400                         ntohs(peer_init->init_hdr.num_inbound_streams);
2401         }
2402
2403         if (asoc->c.sinit_max_instreams >
2404             ntohs(peer_init->init_hdr.num_outbound_streams)) {
2405                 asoc->c.sinit_max_instreams =
2406                         ntohs(peer_init->init_hdr.num_outbound_streams);
2407         }
2408
2409         /* Copy Initiation tag from INIT to VT_peer in cookie.   */
2410         asoc->c.peer_vtag = asoc->peer.i.init_tag;
2411
2412         /* Peer Rwnd   : Current calculated value of the peer's rwnd.  */
2413         asoc->peer.rwnd = asoc->peer.i.a_rwnd;
2414
2415         /* Copy cookie in case we need to resend COOKIE-ECHO. */
2416         cookie = asoc->peer.cookie;
2417         if (cookie) {
2418                 asoc->peer.cookie = kmemdup(cookie, asoc->peer.cookie_len, gfp);
2419                 if (!asoc->peer.cookie)
2420                         goto clean_up;
2421         }
2422
2423         /* RFC 2960 7.2.1 The initial value of ssthresh MAY be arbitrarily
2424          * high (for example, implementations MAY use the size of the receiver
2425          * advertised window).
2426          */
2427         list_for_each_entry(transport, &asoc->peer.transport_addr_list,
2428                         transports) {
2429                 transport->ssthresh = asoc->peer.i.a_rwnd;
2430         }
2431
2432         /* Set up the TSN tracking pieces.  */
2433         if (!sctp_tsnmap_init(&asoc->peer.tsn_map, SCTP_TSN_MAP_INITIAL,
2434                                 asoc->peer.i.initial_tsn, gfp))
2435                 goto clean_up;
2436
2437         /* RFC 2960 6.5 Stream Identifier and Stream Sequence Number
2438          *
2439          * The stream sequence number in all the streams shall start
2440          * from 0 when the association is established.  Also, when the
2441          * stream sequence number reaches the value 65535 the next
2442          * stream sequence number shall be set to 0.
2443          */
2444
2445         /* Allocate storage for the negotiated streams if it is not a temporary
2446          * association.
2447          */
2448         if (!asoc->temp) {
2449                 int error;
2450
2451                 asoc->ssnmap = sctp_ssnmap_new(asoc->c.sinit_max_instreams,
2452                                                asoc->c.sinit_num_ostreams, gfp);
2453                 if (!asoc->ssnmap)
2454                         goto clean_up;
2455
2456                 error = sctp_assoc_set_id(asoc, gfp);
2457                 if (error)
2458                         goto clean_up;
2459         }
2460
2461         /* ADDIP Section 4.1 ASCONF Chunk Procedures
2462          *
2463          * When an endpoint has an ASCONF signaled change to be sent to the
2464          * remote endpoint it should do the following:
2465          * ...
2466          * A2) A serial number should be assigned to the Chunk. The serial
2467          * number should be a monotonically increasing number. All serial
2468          * numbers are defined to be initialized at the start of the
2469          * association to the same value as the Initial TSN.
2470          */
2471         asoc->peer.addip_serial = asoc->peer.i.initial_tsn - 1;
2472         return 1;
2473
2474 clean_up:
2475         /* Release the transport structures. */
2476         list_for_each_safe(pos, temp, &asoc->peer.transport_addr_list) {
2477                 transport = list_entry(pos, struct sctp_transport, transports);
2478                 if (transport->state != SCTP_ACTIVE)
2479                         sctp_assoc_rm_peer(asoc, transport);
2480         }
2481
2482 nomem:
2483         return 0;
2484 }
2485
2486
2487 /* Update asoc with the option described in param.
2488  *
2489  * RFC2960 3.3.2.1 Optional/Variable Length Parameters in INIT
2490  *
2491  * asoc is the association to update.
2492  * param is the variable length parameter to use for update.
2493  * cid tells us if this is an INIT, INIT ACK or COOKIE ECHO.
2494  * If the current packet is an INIT we want to minimize the amount of
2495  * work we do.  In particular, we should not build transport
2496  * structures for the addresses.
2497  */
2498 static int sctp_process_param(struct sctp_association *asoc,
2499                               union sctp_params param,
2500                               const union sctp_addr *peer_addr,
2501                               gfp_t gfp)
2502 {
2503         struct net *net = sock_net(asoc->base.sk);
2504         union sctp_addr addr;
2505         int i;
2506         __u16 sat;
2507         int retval = 1;
2508         sctp_scope_t scope;
2509         u32 stale;
2510         struct sctp_af *af;
2511         union sctp_addr_param *addr_param;
2512         struct sctp_transport *t;
2513         struct sctp_endpoint *ep = asoc->ep;
2514
2515         /* We maintain all INIT parameters in network byte order all the
2516          * time.  This allows us to not worry about whether the parameters
2517          * came from a fresh INIT, and INIT ACK, or were stored in a cookie.
2518          */
2519         switch (param.p->type) {
2520         case SCTP_PARAM_IPV6_ADDRESS:
2521                 if (PF_INET6 != asoc->base.sk->sk_family)
2522                         break;
2523                 goto do_addr_param;
2524
2525         case SCTP_PARAM_IPV4_ADDRESS:
2526                 /* v4 addresses are not allowed on v6-only socket */
2527                 if (ipv6_only_sock(asoc->base.sk))
2528                         break;
2529 do_addr_param:
2530                 af = sctp_get_af_specific(param_type2af(param.p->type));
2531                 af->from_addr_param(&addr, param.addr, htons(asoc->peer.port), 0);
2532                 scope = sctp_scope(peer_addr);
2533                 if (sctp_in_scope(net, &addr, scope))
2534                         if (!sctp_assoc_add_peer(asoc, &addr, gfp, SCTP_UNCONFIRMED))
2535                                 return 0;
2536                 break;
2537
2538         case SCTP_PARAM_COOKIE_PRESERVATIVE:
2539                 if (!net->sctp.cookie_preserve_enable)
2540                         break;
2541
2542                 stale = ntohl(param.life->lifespan_increment);
2543
2544                 /* Suggested Cookie Life span increment's unit is msec,
2545                  * (1/1000sec).
2546                  */
2547                 asoc->cookie_life = ktime_add_ms(asoc->cookie_life, stale);
2548                 break;
2549
2550         case SCTP_PARAM_HOST_NAME_ADDRESS:
2551                 pr_debug("%s: unimplemented SCTP_HOST_NAME_ADDRESS\n", __func__);
2552                 break;
2553
2554         case SCTP_PARAM_SUPPORTED_ADDRESS_TYPES:
2555                 /* Turn off the default values first so we'll know which
2556                  * ones are really set by the peer.
2557                  */
2558                 asoc->peer.ipv4_address = 0;
2559                 asoc->peer.ipv6_address = 0;
2560
2561                 /* Assume that peer supports the address family
2562                  * by which it sends a packet.
2563                  */
2564                 if (peer_addr->sa.sa_family == AF_INET6)
2565                         asoc->peer.ipv6_address = 1;
2566                 else if (peer_addr->sa.sa_family == AF_INET)
2567                         asoc->peer.ipv4_address = 1;
2568
2569                 /* Cycle through address types; avoid divide by 0. */
2570                 sat = ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
2571                 if (sat)
2572                         sat /= sizeof(__u16);
2573
2574                 for (i = 0; i < sat; ++i) {
2575                         switch (param.sat->types[i]) {
2576                         case SCTP_PARAM_IPV4_ADDRESS:
2577                                 asoc->peer.ipv4_address = 1;
2578                                 break;
2579
2580                         case SCTP_PARAM_IPV6_ADDRESS:
2581                                 if (PF_INET6 == asoc->base.sk->sk_family)
2582                                         asoc->peer.ipv6_address = 1;
2583                                 break;
2584
2585                         case SCTP_PARAM_HOST_NAME_ADDRESS:
2586                                 asoc->peer.hostname_address = 1;
2587                                 break;
2588
2589                         default: /* Just ignore anything else.  */
2590                                 break;
2591                         }
2592                 }
2593                 break;
2594
2595         case SCTP_PARAM_STATE_COOKIE:
2596                 asoc->peer.cookie_len =
2597                         ntohs(param.p->length) - sizeof(sctp_paramhdr_t);
2598                 asoc->peer.cookie = param.cookie->body;
2599                 break;
2600
2601         case SCTP_PARAM_HEARTBEAT_INFO:
2602                 /* Would be odd to receive, but it causes no problems. */
2603                 break;
2604
2605         case SCTP_PARAM_UNRECOGNIZED_PARAMETERS:
2606                 /* Rejected during verify stage. */
2607                 break;
2608
2609         case SCTP_PARAM_ECN_CAPABLE:
2610                 asoc->peer.ecn_capable = 1;
2611                 break;
2612
2613         case SCTP_PARAM_ADAPTATION_LAYER_IND:
2614                 asoc->peer.adaptation_ind = ntohl(param.aind->adaptation_ind);
2615                 break;
2616
2617         case SCTP_PARAM_SET_PRIMARY:
2618                 if (!net->sctp.addip_enable)
2619                         goto fall_through;
2620
2621                 addr_param = param.v + sizeof(sctp_addip_param_t);
2622
2623                 af = sctp_get_af_specific(param_type2af(addr_param->p.type));
2624                 if (af == NULL)
2625                         break;
2626
2627                 af->from_addr_param(&addr, addr_param,
2628                                     htons(asoc->peer.port), 0);
2629
2630                 /* if the address is invalid, we can't process it.
2631                  * XXX: see spec for what to do.
2632                  */
2633                 if (!af->addr_valid(&addr, NULL, NULL))
2634                         break;
2635
2636                 t = sctp_assoc_lookup_paddr(asoc, &addr);
2637                 if (!t)
2638                         break;
2639
2640                 sctp_assoc_set_primary(asoc, t);
2641                 break;
2642
2643         case SCTP_PARAM_SUPPORTED_EXT:
2644                 sctp_process_ext_param(asoc, param);
2645                 break;
2646
2647         case SCTP_PARAM_FWD_TSN_SUPPORT:
2648                 if (net->sctp.prsctp_enable) {
2649                         asoc->peer.prsctp_capable = 1;
2650                         break;
2651                 }
2652                 /* Fall Through */
2653                 goto fall_through;
2654
2655         case SCTP_PARAM_RANDOM:
2656                 if (!ep->auth_enable)
2657                         goto fall_through;
2658
2659                 /* Save peer's random parameter */
2660                 asoc->peer.peer_random = kmemdup(param.p,
2661                                             ntohs(param.p->length), gfp);
2662                 if (!asoc->peer.peer_random) {
2663                         retval = 0;
2664                         break;
2665                 }
2666                 break;
2667
2668         case SCTP_PARAM_HMAC_ALGO:
2669                 if (!ep->auth_enable)
2670                         goto fall_through;
2671
2672                 /* Save peer's HMAC list */
2673                 asoc->peer.peer_hmacs = kmemdup(param.p,
2674                                             ntohs(param.p->length), gfp);
2675                 if (!asoc->peer.peer_hmacs) {
2676                         retval = 0;
2677                         break;
2678                 }
2679
2680                 /* Set the default HMAC the peer requested*/
2681                 sctp_auth_asoc_set_default_hmac(asoc, param.hmac_algo);
2682                 break;
2683
2684         case SCTP_PARAM_CHUNKS:
2685                 if (!ep->auth_enable)
2686                         goto fall_through;
2687
2688                 asoc->peer.peer_chunks = kmemdup(param.p,
2689                                             ntohs(param.p->length), gfp);
2690                 if (!asoc->peer.peer_chunks)
2691                         retval = 0;
2692                 break;
2693 fall_through:
2694         default:
2695                 /* Any unrecognized parameters should have been caught
2696                  * and handled by sctp_verify_param() which should be
2697                  * called prior to this routine.  Simply log the error
2698                  * here.
2699                  */
2700                 pr_debug("%s: ignoring param:%d for association:%p.\n",
2701                          __func__, ntohs(param.p->type), asoc);
2702                 break;
2703         }
2704
2705         return retval;
2706 }
2707
2708 /* Select a new verification tag.  */
2709 __u32 sctp_generate_tag(const struct sctp_endpoint *ep)
2710 {
2711         /* I believe that this random number generator complies with RFC1750.
2712          * A tag of 0 is reserved for special cases (e.g. INIT).
2713          */
2714         __u32 x;
2715
2716         do {
2717                 get_random_bytes(&x, sizeof(__u32));
2718         } while (x == 0);
2719
2720         return x;
2721 }
2722
2723 /* Select an initial TSN to send during startup.  */
2724 __u32 sctp_generate_tsn(const struct sctp_endpoint *ep)
2725 {
2726         __u32 retval;
2727
2728         get_random_bytes(&retval, sizeof(__u32));
2729         return retval;
2730 }
2731
2732 /*
2733  * ADDIP 3.1.1 Address Configuration Change Chunk (ASCONF)
2734  *      0                   1                   2                   3
2735  *      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
2736  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2737  *     | Type = 0xC1   |  Chunk Flags  |      Chunk Length             |
2738  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2739  *     |                       Serial Number                           |
2740  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2741  *     |                    Address Parameter                          |
2742  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2743  *     |                     ASCONF Parameter #1                       |
2744  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2745  *     \                                                               \
2746  *     /                             ....                              /
2747  *     \                                                               \
2748  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2749  *     |                     ASCONF Parameter #N                       |
2750  *      +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2751  *
2752  * Address Parameter and other parameter will not be wrapped in this function
2753  */
2754 static struct sctp_chunk *sctp_make_asconf(struct sctp_association *asoc,
2755                                            union sctp_addr *addr,
2756                                            int vparam_len)
2757 {
2758         sctp_addiphdr_t asconf;
2759         struct sctp_chunk *retval;
2760         int length = sizeof(asconf) + vparam_len;
2761         union sctp_addr_param addrparam;
2762         int addrlen;
2763         struct sctp_af *af = sctp_get_af_specific(addr->v4.sin_family);
2764
2765         addrlen = af->to_addr_param(addr, &addrparam);
2766         if (!addrlen)
2767                 return NULL;
2768         length += addrlen;
2769
2770         /* Create the chunk.  */
2771         retval = sctp_make_control(asoc, SCTP_CID_ASCONF, 0, length,
2772                                    GFP_ATOMIC);
2773         if (!retval)
2774                 return NULL;
2775
2776         asconf.serial = htonl(asoc->addip_serial++);
2777
2778         retval->subh.addip_hdr =
2779                 sctp_addto_chunk(retval, sizeof(asconf), &asconf);
2780         retval->param_hdr.v =
2781                 sctp_addto_chunk(retval, addrlen, &addrparam);
2782
2783         return retval;
2784 }
2785
2786 /* ADDIP
2787  * 3.2.1 Add IP Address
2788  *      0                   1                   2                   3
2789  *      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
2790  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2791  *     |        Type = 0xC001          |    Length = Variable          |
2792  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2793  *     |               ASCONF-Request Correlation ID                   |
2794  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2795  *     |                       Address Parameter                       |
2796  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2797  *
2798  * 3.2.2 Delete IP Address
2799  *      0                   1                   2                   3
2800  *      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
2801  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2802  *     |        Type = 0xC002          |    Length = Variable          |
2803  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2804  *     |               ASCONF-Request Correlation ID                   |
2805  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2806  *     |                       Address Parameter                       |
2807  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2808  *
2809  */
2810 struct sctp_chunk *sctp_make_asconf_update_ip(struct sctp_association *asoc,
2811                                               union sctp_addr         *laddr,
2812                                               struct sockaddr         *addrs,
2813                                               int                     addrcnt,
2814                                               __be16                  flags)
2815 {
2816         sctp_addip_param_t      param;
2817         struct sctp_chunk       *retval;
2818         union sctp_addr_param   addr_param;
2819         union sctp_addr         *addr;
2820         void                    *addr_buf;
2821         struct sctp_af          *af;
2822         int                     paramlen = sizeof(param);
2823         int                     addr_param_len = 0;
2824         int                     totallen = 0;
2825         int                     i;
2826         int                     del_pickup = 0;
2827
2828         /* Get total length of all the address parameters. */
2829         addr_buf = addrs;
2830         for (i = 0; i < addrcnt; i++) {
2831                 addr = addr_buf;
2832                 af = sctp_get_af_specific(addr->v4.sin_family);
2833                 addr_param_len = af->to_addr_param(addr, &addr_param);
2834
2835                 totallen += paramlen;
2836                 totallen += addr_param_len;
2837
2838                 addr_buf += af->sockaddr_len;
2839                 if (asoc->asconf_addr_del_pending && !del_pickup) {
2840                         /* reuse the parameter length from the same scope one */
2841                         totallen += paramlen;
2842                         totallen += addr_param_len;
2843                         del_pickup = 1;
2844
2845                         pr_debug("%s: picked same-scope del_pending addr, "
2846                                  "totallen for all addresses is %d\n",
2847                                  __func__, totallen);
2848                 }
2849         }
2850
2851         /* Create an asconf chunk with the required length. */
2852         retval = sctp_make_asconf(asoc, laddr, totallen);
2853         if (!retval)
2854                 return NULL;
2855
2856         /* Add the address parameters to the asconf chunk. */
2857         addr_buf = addrs;
2858         for (i = 0; i < addrcnt; i++) {
2859                 addr = addr_buf;
2860                 af = sctp_get_af_specific(addr->v4.sin_family);
2861                 addr_param_len = af->to_addr_param(addr, &addr_param);
2862                 param.param_hdr.type = flags;
2863                 param.param_hdr.length = htons(paramlen + addr_param_len);
2864                 param.crr_id = i;
2865
2866                 sctp_addto_chunk(retval, paramlen, &param);
2867                 sctp_addto_chunk(retval, addr_param_len, &addr_param);
2868
2869                 addr_buf += af->sockaddr_len;
2870         }
2871         if (flags == SCTP_PARAM_ADD_IP && del_pickup) {
2872                 addr = asoc->asconf_addr_del_pending;
2873                 af = sctp_get_af_specific(addr->v4.sin_family);
2874                 addr_param_len = af->to_addr_param(addr, &addr_param);
2875                 param.param_hdr.type = SCTP_PARAM_DEL_IP;
2876                 param.param_hdr.length = htons(paramlen + addr_param_len);
2877                 param.crr_id = i;
2878
2879                 sctp_addto_chunk(retval, paramlen, &param);
2880                 sctp_addto_chunk(retval, addr_param_len, &addr_param);
2881         }
2882         return retval;
2883 }
2884
2885 /* ADDIP
2886  * 3.2.4 Set Primary IP Address
2887  *      0                   1                   2                   3
2888  *      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
2889  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2890  *     |        Type =0xC004           |    Length = Variable          |
2891  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2892  *     |               ASCONF-Request Correlation ID                   |
2893  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2894  *     |                       Address Parameter                       |
2895  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2896  *
2897  * Create an ASCONF chunk with Set Primary IP address parameter.
2898  */
2899 struct sctp_chunk *sctp_make_asconf_set_prim(struct sctp_association *asoc,
2900                                              union sctp_addr *addr)
2901 {
2902         sctp_addip_param_t      param;
2903         struct sctp_chunk       *retval;
2904         int                     len = sizeof(param);
2905         union sctp_addr_param   addrparam;
2906         int                     addrlen;
2907         struct sctp_af          *af = sctp_get_af_specific(addr->v4.sin_family);
2908
2909         addrlen = af->to_addr_param(addr, &addrparam);
2910         if (!addrlen)
2911                 return NULL;
2912         len += addrlen;
2913
2914         /* Create the chunk and make asconf header. */
2915         retval = sctp_make_asconf(asoc, addr, len);
2916         if (!retval)
2917                 return NULL;
2918
2919         param.param_hdr.type = SCTP_PARAM_SET_PRIMARY;
2920         param.param_hdr.length = htons(len);
2921         param.crr_id = 0;
2922
2923         sctp_addto_chunk(retval, sizeof(param), &param);
2924         sctp_addto_chunk(retval, addrlen, &addrparam);
2925
2926         return retval;
2927 }
2928
2929 /* ADDIP 3.1.2 Address Configuration Acknowledgement Chunk (ASCONF-ACK)
2930  *      0                   1                   2                   3
2931  *      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0 1
2932  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2933  *     | Type = 0x80   |  Chunk Flags  |      Chunk Length             |
2934  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2935  *     |                       Serial Number                           |
2936  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2937  *     |                 ASCONF Parameter Response#1                   |
2938  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2939  *     \                                                               \
2940  *     /                             ....                              /
2941  *     \                                                               \
2942  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2943  *     |                 ASCONF Parameter Response#N                   |
2944  *     +-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+-+
2945  *
2946  * Create an ASCONF_ACK chunk with enough space for the parameter responses.
2947  */
2948 static struct sctp_chunk *sctp_make_asconf_ack(const struct sctp_association *asoc,
2949                                                __u32 serial, int vparam_len)
2950 {
2951         sctp_addiphdr_t         asconf;
2952         struct sctp_chunk       *retval;
2953         int                     length = sizeof(asconf) + vparam_len;
2954
2955         /* Create the chunk.  */
2956         retval = sctp_make_control(asoc, SCTP_CID_ASCONF_ACK, 0, length,
2957                                    GFP_ATOMIC);
2958         if (!retval)
2959                 return NULL;
2960
2961         asconf.serial = htonl(serial);
2962
2963         retval->subh.addip_hdr =
2964                 sctp_addto_chunk(retval, sizeof(asconf), &asconf);
2965
2966         return retval;
2967 }
2968
2969 /* Add response parameters to an ASCONF_ACK chunk. */
2970 static void sctp_add_asconf_response(struct sctp_chunk *chunk, __be32 crr_id,
2971                               __be16 err_code, sctp_addip_param_t *asconf_param)
2972 {
2973         sctp_addip_param_t      ack_param;
2974         sctp_errhdr_t           err_param;
2975         int                     asconf_param_len = 0;
2976         int                     err_param_len = 0;
2977         __be16                  response_type;
2978
2979         if (SCTP_ERROR_NO_ERROR == err_code) {
2980                 response_type = SCTP_PARAM_SUCCESS_REPORT;
2981         } else {
2982                 response_type = SCTP_PARAM_ERR_CAUSE;
2983                 err_param_len = sizeof(err_param);
2984                 if (asconf_param)
2985                         asconf_param_len =
2986                                  ntohs(asconf_param->param_hdr.length);
2987         }
2988
2989         /* Add Success Indication or Error Cause Indication parameter. */
2990         ack_param.param_hdr.type = response_type;
2991         ack_param.param_hdr.length = htons(sizeof(ack_param) +
2992                                            err_param_len +
2993                                            asconf_param_len);
2994         ack_param.crr_id = crr_id;
2995         sctp_addto_chunk(chunk, sizeof(ack_param), &ack_param);
2996
2997         if (SCTP_ERROR_NO_ERROR == err_code)
2998                 return;
2999
3000         /* Add Error Cause parameter. */
3001         err_param.cause = err_code;
3002         err_param.length = htons(err_param_len + asconf_param_len);
3003         sctp_addto_chunk(chunk, err_param_len, &err_param);
3004
3005         /* Add the failed TLV copied from ASCONF chunk. */
3006         if (asconf_param)
3007                 sctp_addto_chunk(chunk, asconf_param_len, asconf_param);
3008 }
3009
3010 /* Process a asconf parameter. */
3011 static __be16 sctp_process_asconf_param(struct sctp_association *asoc,
3012                                        struct sctp_chunk *asconf,
3013                                        sctp_addip_param_t *asconf_param)
3014 {
3015         struct sctp_transport *peer;
3016         struct sctp_af *af;
3017         union sctp_addr addr;
3018         union sctp_addr_param *addr_param;
3019
3020         addr_param = (void *)asconf_param + sizeof(sctp_addip_param_t);
3021
3022         if (asconf_param->param_hdr.type != SCTP_PARAM_ADD_IP &&
3023             asconf_param->param_hdr.type != SCTP_PARAM_DEL_IP &&
3024             asconf_param->param_hdr.type != SCTP_PARAM_SET_PRIMARY)
3025                 return SCTP_ERROR_UNKNOWN_PARAM;
3026
3027         switch (addr_param->p.type) {
3028         case SCTP_PARAM_IPV6_ADDRESS:
3029                 if (!asoc->peer.ipv6_address)
3030                         return SCTP_ERROR_DNS_FAILED;
3031                 break;
3032         case SCTP_PARAM_IPV4_ADDRESS:
3033                 if (!asoc->peer.ipv4_address)
3034                         return SCTP_ERROR_DNS_FAILED;
3035                 break;
3036         default:
3037                 return SCTP_ERROR_DNS_FAILED;
3038         }
3039
3040         af = sctp_get_af_specific(param_type2af(addr_param->p.type));
3041         if (unlikely(!af))
3042                 return SCTP_ERROR_DNS_FAILED;
3043
3044         af->from_addr_param(&addr, addr_param, htons(asoc->peer.port), 0);
3045
3046         /* ADDIP 4.2.1  This parameter MUST NOT contain a broadcast
3047          * or multicast address.
3048          * (note: wildcard is permitted and requires special handling so
3049          *  make sure we check for that)
3050          */
3051         if (!af->is_any(&addr) && !af->addr_valid(&addr, NULL, asconf->skb))
3052                 return SCTP_ERROR_DNS_FAILED;
3053
3054         switch (asconf_param->param_hdr.type) {
3055         case SCTP_PARAM_ADD_IP:
3056                 /* Section 4.2.1:
3057                  * If the address 0.0.0.0 or ::0 is provided, the source
3058                  * address of the packet MUST be added.
3059                  */
3060                 if (af->is_any(&addr))
3061                         memcpy(&addr, &asconf->source, sizeof(addr));
3062
3063                 /* ADDIP 4.3 D9) If an endpoint receives an ADD IP address
3064                  * request and does not have the local resources to add this
3065                  * new address to the association, it MUST return an Error
3066                  * Cause TLV set to the new error code 'Operation Refused
3067                  * Due to Resource Shortage'.
3068                  */
3069
3070                 peer = sctp_assoc_add_peer(asoc, &addr, GFP_ATOMIC, SCTP_UNCONFIRMED);
3071                 if (!peer)
3072                         return SCTP_ERROR_RSRC_LOW;
3073
3074                 /* Start the heartbeat timer. */
3075                 if (!mod_timer(&peer->hb_timer, sctp_transport_timeout(peer)))
3076                         sctp_transport_hold(peer);
3077                 asoc->new_transport = peer;
3078                 break;
3079         case SCTP_PARAM_DEL_IP:
3080                 /* ADDIP 4.3 D7) If a request is received to delete the
3081                  * last remaining IP address of a peer endpoint, the receiver
3082                  * MUST send an Error Cause TLV with the error cause set to the
3083                  * new error code 'Request to Delete Last Remaining IP Address'.
3084                  */
3085                 if (asoc->peer.transport_count == 1)
3086                         return SCTP_ERROR_DEL_LAST_IP;
3087
3088                 /* ADDIP 4.3 D8) If a request is received to delete an IP
3089                  * address which is also the source address of the IP packet
3090                  * which contained the ASCONF chunk, the receiver MUST reject
3091                  * this request. To reject the request the receiver MUST send
3092                  * an Error Cause TLV set to the new error code 'Request to
3093                  * Delete Source IP Address'
3094                  */
3095                 if (sctp_cmp_addr_exact(&asconf->source, &addr))
3096                         return SCTP_ERROR_DEL_SRC_IP;
3097
3098                 /* Section 4.2.2
3099                  * If the address 0.0.0.0 or ::0 is provided, all
3100                  * addresses of the peer except the source address of the
3101                  * packet MUST be deleted.
3102                  */
3103                 if (af->is_any(&addr)) {
3104                         sctp_assoc_set_primary(asoc, asconf->transport);
3105                         sctp_assoc_del_nonprimary_peers(asoc,
3106                                                         asconf->transport);
3107                         return SCTP_ERROR_NO_ERROR;
3108                 }
3109
3110                 /* If the address is not part of the association, the
3111                  * ASCONF-ACK with Error Cause Indication Parameter
3112                  * which including cause of Unresolvable Address should
3113                  * be sent.
3114                  */
3115                 peer = sctp_assoc_lookup_paddr(asoc, &addr);
3116                 if (!peer)
3117                         return SCTP_ERROR_DNS_FAILED;
3118
3119                 sctp_assoc_rm_peer(asoc, peer);
3120                 break;
3121         case SCTP_PARAM_SET_PRIMARY:
3122                 /* ADDIP Section 4.2.4
3123                  * If the address 0.0.0.0 or ::0 is provided, the receiver
3124                  * MAY mark the source address of the packet as its
3125                  * primary.
3126                  */
3127                 if (af->is_any(&addr))
3128                         memcpy(&addr.v4, sctp_source(asconf), sizeof(addr));
3129
3130                 peer = sctp_assoc_lookup_paddr(asoc, &addr);
3131                 if (!peer)
3132                         return SCTP_ERROR_DNS_FAILED;
3133
3134                 sctp_assoc_set_primary(asoc, peer);
3135                 break;
3136         }
3137
3138         return SCTP_ERROR_NO_ERROR;
3139 }
3140
3141 /* Verify the ASCONF packet before we process it. */
3142 bool sctp_verify_asconf(const struct sctp_association *asoc,
3143                         struct sctp_chunk *chunk, bool addr_param_needed,
3144                         struct sctp_paramhdr **errp)
3145 {
3146         sctp_addip_chunk_t *addip = (sctp_addip_chunk_t *) chunk->chunk_hdr;
3147         union sctp_params param;
3148         bool addr_param_seen = false;
3149
3150         sctp_walk_params(param, addip, addip_hdr.params) {
3151                 size_t length = ntohs(param.p->length);
3152
3153                 *errp = param.p;
3154                 switch (param.p->type) {
3155                 case SCTP_PARAM_ERR_CAUSE:
3156                         break;
3157                 case SCTP_PARAM_IPV4_ADDRESS:
3158                         if (length != sizeof(sctp_ipv4addr_param_t))
3159                                 return false;
3160                         /* ensure there is only one addr param and it's in the
3161                          * beginning of addip_hdr params, or we reject it.
3162                          */
3163                         if (param.v != addip->addip_hdr.params)
3164                                 return false;
3165                         addr_param_seen = true;
3166                         break;
3167                 case SCTP_PARAM_IPV6_ADDRESS:
3168                         if (length != sizeof(sctp_ipv6addr_param_t))
3169                                 return false;
3170                         if (param.v != addip->addip_hdr.params)
3171                                 return false;
3172                         addr_param_seen = true;
3173                         break;
3174                 case SCTP_PARAM_ADD_IP:
3175                 case SCTP_PARAM_DEL_IP:
3176                 case SCTP_PARAM_SET_PRIMARY:
3177                         /* In ASCONF chunks, these need to be first. */
3178                         if (addr_param_needed && !addr_param_seen)
3179                                 return false;
3180                         length = ntohs(param.addip->param_hdr.length);
3181                         if (length < sizeof(sctp_addip_param_t) +
3182                                      sizeof(sctp_paramhdr_t))
3183                                 return false;
3184                         break;
3185                 case SCTP_PARAM_SUCCESS_REPORT:
3186                 case SCTP_PARAM_ADAPTATION_LAYER_IND:
3187                         if (length != sizeof(sctp_addip_param_t))
3188                                 return false;
3189                         break;
3190                 default:
3191                         /* This is unkown to us, reject! */
3192                         return false;
3193                 }
3194         }
3195
3196         /* Remaining sanity checks. */
3197         if (addr_param_needed && !addr_param_seen)
3198                 return false;
3199         if (!addr_param_needed && addr_param_seen)
3200                 return false;
3201         if (param.v != chunk->chunk_end)
3202                 return false;
3203
3204         return true;
3205 }
3206
3207 /* Process an incoming ASCONF chunk with the next expected serial no. and
3208  * return an ASCONF_ACK chunk to be sent in response.
3209  */
3210 struct sctp_chunk *sctp_process_asconf(struct sctp_association *asoc,
3211                                        struct sctp_chunk *asconf)
3212 {
3213         sctp_addip_chunk_t *addip = (sctp_addip_chunk_t *) asconf->chunk_hdr;
3214         bool all_param_pass = true;
3215         union sctp_params param;
3216         sctp_addiphdr_t         *hdr;
3217         union sctp_addr_param   *addr_param;
3218         sctp_addip_param_t      *asconf_param;
3219         struct sctp_chunk       *asconf_ack;
3220         __be16  err_code;
3221         int     length = 0;
3222         int     chunk_len;
3223         __u32   serial;
3224
3225         chunk_len = ntohs(asconf->chunk_hdr->length) - sizeof(sctp_chunkhdr_t);
3226         hdr = (sctp_addiphdr_t *)asconf->skb->data;
3227         serial = ntohl(hdr->serial);
3228
3229         /* Skip the addiphdr and store a pointer to address parameter.  */
3230         length = sizeof(sctp_addiphdr_t);
3231         addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
3232         chunk_len -= length;
3233
3234         /* Skip the address parameter and store a pointer to the first
3235          * asconf parameter.
3236          */
3237         length = ntohs(addr_param->p.length);
3238         asconf_param = (void *)addr_param + length;
3239         chunk_len -= length;
3240
3241         /* create an ASCONF_ACK chunk.
3242          * Based on the definitions of parameters, we know that the size of
3243          * ASCONF_ACK parameters are less than or equal to the fourfold of ASCONF
3244          * parameters.
3245          */
3246         asconf_ack = sctp_make_asconf_ack(asoc, serial, chunk_len * 4);
3247         if (!asconf_ack)
3248                 goto done;
3249
3250         /* Process the TLVs contained within the ASCONF chunk. */
3251         sctp_walk_params(param, addip, addip_hdr.params) {
3252                 /* Skip preceeding address parameters. */
3253                 if (param.p->type == SCTP_PARAM_IPV4_ADDRESS ||
3254                     param.p->type == SCTP_PARAM_IPV6_ADDRESS)
3255                         continue;
3256
3257                 err_code = sctp_process_asconf_param(asoc, asconf,
3258                                                      param.addip);
3259                 /* ADDIP 4.1 A7)
3260                  * If an error response is received for a TLV parameter,
3261                  * all TLVs with no response before the failed TLV are
3262                  * considered successful if not reported.  All TLVs after
3263                  * the failed response are considered unsuccessful unless
3264                  * a specific success indication is present for the parameter.
3265                  */
3266                 if (err_code != SCTP_ERROR_NO_ERROR)
3267                         all_param_pass = false;
3268                 if (!all_param_pass)
3269                         sctp_add_asconf_response(asconf_ack, param.addip->crr_id,
3270                                                  err_code, param.addip);
3271
3272                 /* ADDIP 4.3 D11) When an endpoint receiving an ASCONF to add
3273                  * an IP address sends an 'Out of Resource' in its response, it
3274                  * MUST also fail any subsequent add or delete requests bundled
3275                  * in the ASCONF.
3276                  */
3277                 if (err_code == SCTP_ERROR_RSRC_LOW)
3278                         goto done;
3279         }
3280 done:
3281         asoc->peer.addip_serial++;
3282
3283         /* If we are sending a new ASCONF_ACK hold a reference to it in assoc
3284          * after freeing the reference to old asconf ack if any.
3285          */
3286         if (asconf_ack) {
3287                 sctp_chunk_hold(asconf_ack);
3288                 list_add_tail(&asconf_ack->transmitted_list,
3289                               &asoc->asconf_ack_list);
3290         }
3291
3292         return asconf_ack;
3293 }
3294
3295 /* Process a asconf parameter that is successfully acked. */
3296 static void sctp_asconf_param_success(struct sctp_association *asoc,
3297                                      sctp_addip_param_t *asconf_param)
3298 {
3299         struct sctp_af *af;
3300         union sctp_addr addr;
3301         struct sctp_bind_addr *bp = &asoc->base.bind_addr;
3302         union sctp_addr_param *addr_param;
3303         struct sctp_transport *transport;
3304         struct sctp_sockaddr_entry *saddr;
3305
3306         addr_param = (void *)asconf_param + sizeof(sctp_addip_param_t);
3307
3308         /* We have checked the packet before, so we do not check again. */
3309         af = sctp_get_af_specific(param_type2af(addr_param->p.type));
3310         af->from_addr_param(&addr, addr_param, htons(bp->port), 0);
3311
3312         switch (asconf_param->param_hdr.type) {
3313         case SCTP_PARAM_ADD_IP:
3314                 /* This is always done in BH context with a socket lock
3315                  * held, so the list can not change.
3316                  */
3317                 local_bh_disable();
3318                 list_for_each_entry(saddr, &bp->address_list, list) {
3319                         if (sctp_cmp_addr_exact(&saddr->a, &addr))
3320                                 saddr->state = SCTP_ADDR_SRC;
3321                 }
3322                 local_bh_enable();
3323                 list_for_each_entry(transport, &asoc->peer.transport_addr_list,
3324                                 transports) {
3325                         dst_release(transport->dst);
3326                         transport->dst = NULL;
3327                 }
3328                 break;
3329         case SCTP_PARAM_DEL_IP:
3330                 local_bh_disable();
3331                 sctp_del_bind_addr(bp, &addr);
3332                 if (asoc->asconf_addr_del_pending != NULL &&
3333                     sctp_cmp_addr_exact(asoc->asconf_addr_del_pending, &addr)) {
3334                         kfree(asoc->asconf_addr_del_pending);
3335                         asoc->asconf_addr_del_pending = NULL;
3336                 }
3337                 local_bh_enable();
3338                 list_for_each_entry(transport, &asoc->peer.transport_addr_list,
3339                                 transports) {
3340                         dst_release(transport->dst);
3341                         transport->dst = NULL;
3342                 }
3343                 break;
3344         default:
3345                 break;
3346         }
3347 }
3348
3349 /* Get the corresponding ASCONF response error code from the ASCONF_ACK chunk
3350  * for the given asconf parameter.  If there is no response for this parameter,
3351  * return the error code based on the third argument 'no_err'.
3352  * ADDIP 4.1
3353  * A7) If an error response is received for a TLV parameter, all TLVs with no
3354  * response before the failed TLV are considered successful if not reported.
3355  * All TLVs after the failed response are considered unsuccessful unless a
3356  * specific success indication is present for the parameter.
3357  */
3358 static __be16 sctp_get_asconf_response(struct sctp_chunk *asconf_ack,
3359                                       sctp_addip_param_t *asconf_param,
3360                                       int no_err)
3361 {
3362         sctp_addip_param_t      *asconf_ack_param;
3363         sctp_errhdr_t           *err_param;
3364         int                     length;
3365         int                     asconf_ack_len;
3366         __be16                  err_code;
3367
3368         if (no_err)
3369                 err_code = SCTP_ERROR_NO_ERROR;
3370         else
3371                 err_code = SCTP_ERROR_REQ_REFUSED;
3372
3373         asconf_ack_len = ntohs(asconf_ack->chunk_hdr->length) -
3374                              sizeof(sctp_chunkhdr_t);
3375
3376         /* Skip the addiphdr from the asconf_ack chunk and store a pointer to
3377          * the first asconf_ack parameter.
3378          */
3379         length = sizeof(sctp_addiphdr_t);
3380         asconf_ack_param = (sctp_addip_param_t *)(asconf_ack->skb->data +
3381                                                   length);
3382         asconf_ack_len -= length;
3383
3384         while (asconf_ack_len > 0) {
3385                 if (asconf_ack_param->crr_id == asconf_param->crr_id) {
3386                         switch (asconf_ack_param->param_hdr.type) {
3387                         case SCTP_PARAM_SUCCESS_REPORT:
3388                                 return SCTP_ERROR_NO_ERROR;
3389                         case SCTP_PARAM_ERR_CAUSE:
3390                                 length = sizeof(sctp_addip_param_t);
3391                                 err_param = (void *)asconf_ack_param + length;
3392                                 asconf_ack_len -= length;
3393                                 if (asconf_ack_len > 0)
3394                                         return err_param->cause;
3395                                 else
3396                                         return SCTP_ERROR_INV_PARAM;
3397                                 break;
3398                         default:
3399                                 return SCTP_ERROR_INV_PARAM;
3400                         }
3401                 }
3402
3403                 length = ntohs(asconf_ack_param->param_hdr.length);
3404                 asconf_ack_param = (void *)asconf_ack_param + length;
3405                 asconf_ack_len -= length;
3406         }
3407
3408         return err_code;
3409 }
3410
3411 /* Process an incoming ASCONF_ACK chunk against the cached last ASCONF chunk. */
3412 int sctp_process_asconf_ack(struct sctp_association *asoc,
3413                             struct sctp_chunk *asconf_ack)
3414 {
3415         struct sctp_chunk       *asconf = asoc->addip_last_asconf;
3416         union sctp_addr_param   *addr_param;
3417         sctp_addip_param_t      *asconf_param;
3418         int     length = 0;
3419         int     asconf_len = asconf->skb->len;
3420         int     all_param_pass = 0;
3421         int     no_err = 1;
3422         int     retval = 0;
3423         __be16  err_code = SCTP_ERROR_NO_ERROR;
3424
3425         /* Skip the chunkhdr and addiphdr from the last asconf sent and store
3426          * a pointer to address parameter.
3427          */
3428         length = sizeof(sctp_addip_chunk_t);
3429         addr_param = (union sctp_addr_param *)(asconf->skb->data + length);
3430         asconf_len -= length;
3431
3432         /* Skip the address parameter in the last asconf sent and store a
3433          * pointer to the first asconf parameter.
3434          */
3435         length = ntohs(addr_param->p.length);
3436         asconf_param = (void *)addr_param + length;
3437         asconf_len -= length;
3438
3439         /* ADDIP 4.1
3440          * A8) If there is no response(s) to specific TLV parameter(s), and no
3441          * failures are indicated, then all request(s) are considered
3442          * successful.
3443          */
3444         if (asconf_ack->skb->len == sizeof(sctp_addiphdr_t))
3445                 all_param_pass = 1;
3446
3447         /* Process the TLVs contained in the last sent ASCONF chunk. */
3448         while (asconf_len > 0) {
3449                 if (all_param_pass)
3450                         err_code = SCTP_ERROR_NO_ERROR;
3451                 else {
3452                         err_code = sctp_get_asconf_response(asconf_ack,
3453                                                             asconf_param,
3454                                                             no_err);
3455                         if (no_err && (SCTP_ERROR_NO_ERROR != err_code))
3456                                 no_err = 0;
3457                 }
3458
3459                 switch (err_code) {
3460                 case SCTP_ERROR_NO_ERROR:
3461                         sctp_asconf_param_success(asoc, asconf_param);
3462                         break;
3463
3464                 case SCTP_ERROR_RSRC_LOW:
3465                         retval = 1;
3466                         break;
3467
3468                 case SCTP_ERROR_UNKNOWN_PARAM:
3469                         /* Disable sending this type of asconf parameter in
3470                          * future.
3471                          */
3472                         asoc->peer.addip_disabled_mask |=
3473                                 asconf_param->param_hdr.type;
3474                         break;
3475
3476                 case SCTP_ERROR_REQ_REFUSED:
3477                 case SCTP_ERROR_DEL_LAST_IP:
3478                 case SCTP_ERROR_DEL_SRC_IP:
3479                 default:
3480                          break;
3481                 }
3482
3483                 /* Skip the processed asconf parameter and move to the next
3484                  * one.
3485                  */
3486                 length = ntohs(asconf_param->param_hdr.length);
3487                 asconf_param = (void *)asconf_param + length;
3488                 asconf_len -= length;
3489         }
3490
3491         if (no_err && asoc->src_out_of_asoc_ok) {
3492                 asoc->src_out_of_asoc_ok = 0;
3493                 sctp_transport_immediate_rtx(asoc->peer.primary_path);
3494         }
3495
3496         /* Free the cached last sent asconf chunk. */
3497         list_del_init(&asconf->transmitted_list);
3498         sctp_chunk_free(asconf);
3499         asoc->addip_last_asconf = NULL;
3500
3501         return retval;
3502 }
3503
3504 /* Make a FWD TSN chunk. */
3505 struct sctp_chunk *sctp_make_fwdtsn(const struct sctp_association *asoc,
3506                                     __u32 new_cum_tsn, size_t nstreams,
3507                                     struct sctp_fwdtsn_skip *skiplist)
3508 {
3509         struct sctp_chunk *retval = NULL;
3510         struct sctp_fwdtsn_hdr ftsn_hdr;
3511         struct sctp_fwdtsn_skip skip;
3512         size_t hint;
3513         int i;
3514
3515         hint = (nstreams + 1) * sizeof(__u32);
3516
3517         retval = sctp_make_control(asoc, SCTP_CID_FWD_TSN, 0, hint, GFP_ATOMIC);
3518
3519         if (!retval)
3520                 return NULL;
3521
3522         ftsn_hdr.new_cum_tsn = htonl(new_cum_tsn);
3523         retval->subh.fwdtsn_hdr =
3524                 sctp_addto_chunk(retval, sizeof(ftsn_hdr), &ftsn_hdr);
3525
3526         for (i = 0; i < nstreams; i++) {
3527                 skip.stream = skiplist[i].stream;
3528                 skip.ssn = skiplist[i].ssn;
3529                 sctp_addto_chunk(retval, sizeof(skip), &skip);
3530         }
3531
3532         return retval;
3533 }