sctp: allow others to use sctp_input_cb
[cascardo/linux.git] / net / sctp / input.c
1 /* SCTP kernel implementation
2  * Copyright (c) 1999-2000 Cisco, Inc.
3  * Copyright (c) 1999-2001 Motorola, Inc.
4  * Copyright (c) 2001-2003 International Business Machines, Corp.
5  * Copyright (c) 2001 Intel Corp.
6  * Copyright (c) 2001 Nokia, Inc.
7  * Copyright (c) 2001 La Monte H.P. Yarroll
8  *
9  * This file is part of the SCTP kernel implementation
10  *
11  * These functions handle all input from the IP layer into SCTP.
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  *    Xingang Guo <xingang.guo@intel.com>
37  *    Jon Grimm <jgrimm@us.ibm.com>
38  *    Hui Huang <hui.huang@nokia.com>
39  *    Daisy Chang <daisyc@us.ibm.com>
40  *    Sridhar Samudrala <sri@us.ibm.com>
41  *    Ardelle Fan <ardelle.fan@intel.com>
42  */
43
44 #include <linux/types.h>
45 #include <linux/list.h> /* For struct list_head */
46 #include <linux/socket.h>
47 #include <linux/ip.h>
48 #include <linux/time.h> /* For struct timeval */
49 #include <linux/slab.h>
50 #include <net/ip.h>
51 #include <net/icmp.h>
52 #include <net/snmp.h>
53 #include <net/sock.h>
54 #include <net/xfrm.h>
55 #include <net/sctp/sctp.h>
56 #include <net/sctp/sm.h>
57 #include <net/sctp/checksum.h>
58 #include <net/net_namespace.h>
59
60 /* Forward declarations for internal helpers. */
61 static int sctp_rcv_ootb(struct sk_buff *);
62 static struct sctp_association *__sctp_rcv_lookup(struct net *net,
63                                       struct sk_buff *skb,
64                                       const union sctp_addr *paddr,
65                                       const union sctp_addr *laddr,
66                                       struct sctp_transport **transportp);
67 static struct sctp_endpoint *__sctp_rcv_lookup_endpoint(struct net *net,
68                                                 const union sctp_addr *laddr);
69 static struct sctp_association *__sctp_lookup_association(
70                                         struct net *net,
71                                         const union sctp_addr *local,
72                                         const union sctp_addr *peer,
73                                         struct sctp_transport **pt);
74
75 static int sctp_add_backlog(struct sock *sk, struct sk_buff *skb);
76
77
78 /* Calculate the SCTP checksum of an SCTP packet.  */
79 static inline int sctp_rcv_checksum(struct net *net, struct sk_buff *skb)
80 {
81         struct sctphdr *sh = sctp_hdr(skb);
82         __le32 cmp = sh->checksum;
83         __le32 val = sctp_compute_cksum(skb, 0);
84
85         if (val != cmp) {
86                 /* CRC failure, dump it. */
87                 __SCTP_INC_STATS(net, SCTP_MIB_CHECKSUMERRORS);
88                 return -1;
89         }
90         return 0;
91 }
92
93 /*
94  * This is the routine which IP calls when receiving an SCTP packet.
95  */
96 int sctp_rcv(struct sk_buff *skb)
97 {
98         struct sock *sk;
99         struct sctp_association *asoc;
100         struct sctp_endpoint *ep = NULL;
101         struct sctp_ep_common *rcvr;
102         struct sctp_transport *transport = NULL;
103         struct sctp_chunk *chunk;
104         union sctp_addr src;
105         union sctp_addr dest;
106         int family;
107         struct sctp_af *af;
108         struct net *net = dev_net(skb->dev);
109
110         if (skb->pkt_type != PACKET_HOST)
111                 goto discard_it;
112
113         __SCTP_INC_STATS(net, SCTP_MIB_INSCTPPACKS);
114
115         /* If packet is too small to contain a single chunk, let's not
116          * waste time on it anymore.
117          */
118         if (skb->len < sizeof(struct sctphdr) + sizeof(struct sctp_chunkhdr) +
119                        skb_transport_offset(skb))
120                 goto discard_it;
121
122         if (!pskb_may_pull(skb, sizeof(struct sctphdr)))
123                 goto discard_it;
124
125         /* Pull up the IP header. */
126         __skb_pull(skb, skb_transport_offset(skb));
127
128         skb->csum_valid = 0; /* Previous value not applicable */
129         if (skb_csum_unnecessary(skb))
130                 __skb_decr_checksum_unnecessary(skb);
131         else if (!sctp_checksum_disable &&
132                  !(skb_shinfo(skb)->gso_type & SKB_GSO_SCTP) &&
133                  sctp_rcv_checksum(net, skb) < 0)
134                 goto discard_it;
135         skb->csum_valid = 1;
136
137         __skb_pull(skb, sizeof(struct sctphdr));
138
139         family = ipver2af(ip_hdr(skb)->version);
140         af = sctp_get_af_specific(family);
141         if (unlikely(!af))
142                 goto discard_it;
143
144         /* Initialize local addresses for lookups. */
145         af->from_skb(&src, skb, 1);
146         af->from_skb(&dest, skb, 0);
147
148         /* If the packet is to or from a non-unicast address,
149          * silently discard the packet.
150          *
151          * This is not clearly defined in the RFC except in section
152          * 8.4 - OOTB handling.  However, based on the book "Stream Control
153          * Transmission Protocol" 2.1, "It is important to note that the
154          * IP address of an SCTP transport address must be a routable
155          * unicast address.  In other words, IP multicast addresses and
156          * IP broadcast addresses cannot be used in an SCTP transport
157          * address."
158          */
159         if (!af->addr_valid(&src, NULL, skb) ||
160             !af->addr_valid(&dest, NULL, skb))
161                 goto discard_it;
162
163         asoc = __sctp_rcv_lookup(net, skb, &src, &dest, &transport);
164
165         if (!asoc)
166                 ep = __sctp_rcv_lookup_endpoint(net, &dest);
167
168         /* Retrieve the common input handling substructure. */
169         rcvr = asoc ? &asoc->base : &ep->base;
170         sk = rcvr->sk;
171
172         /*
173          * If a frame arrives on an interface and the receiving socket is
174          * bound to another interface, via SO_BINDTODEVICE, treat it as OOTB
175          */
176         if (sk->sk_bound_dev_if && (sk->sk_bound_dev_if != af->skb_iif(skb))) {
177                 if (asoc) {
178                         sctp_association_put(asoc);
179                         asoc = NULL;
180                 } else {
181                         sctp_endpoint_put(ep);
182                         ep = NULL;
183                 }
184                 sk = net->sctp.ctl_sock;
185                 ep = sctp_sk(sk)->ep;
186                 sctp_endpoint_hold(ep);
187                 rcvr = &ep->base;
188         }
189
190         /*
191          * RFC 2960, 8.4 - Handle "Out of the blue" Packets.
192          * An SCTP packet is called an "out of the blue" (OOTB)
193          * packet if it is correctly formed, i.e., passed the
194          * receiver's checksum check, but the receiver is not
195          * able to identify the association to which this
196          * packet belongs.
197          */
198         if (!asoc) {
199                 if (sctp_rcv_ootb(skb)) {
200                         __SCTP_INC_STATS(net, SCTP_MIB_OUTOFBLUES);
201                         goto discard_release;
202                 }
203         }
204
205         if (!xfrm_policy_check(sk, XFRM_POLICY_IN, skb, family))
206                 goto discard_release;
207         nf_reset(skb);
208
209         if (sk_filter(sk, skb))
210                 goto discard_release;
211
212         /* Create an SCTP packet structure. */
213         chunk = sctp_chunkify(skb, asoc, sk, GFP_ATOMIC);
214         if (!chunk)
215                 goto discard_release;
216         SCTP_INPUT_CB(skb)->chunk = chunk;
217
218         /* Remember what endpoint is to handle this packet. */
219         chunk->rcvr = rcvr;
220
221         /* Remember the SCTP header. */
222         chunk->sctp_hdr = sctp_hdr(skb);
223
224         /* Set the source and destination addresses of the incoming chunk.  */
225         sctp_init_addrs(chunk, &src, &dest);
226
227         /* Remember where we came from.  */
228         chunk->transport = transport;
229
230         /* Acquire access to the sock lock. Note: We are safe from other
231          * bottom halves on this lock, but a user may be in the lock too,
232          * so check if it is busy.
233          */
234         bh_lock_sock(sk);
235
236         if (sk != rcvr->sk) {
237                 /* Our cached sk is different from the rcvr->sk.  This is
238                  * because migrate()/accept() may have moved the association
239                  * to a new socket and released all the sockets.  So now we
240                  * are holding a lock on the old socket while the user may
241                  * be doing something with the new socket.  Switch our veiw
242                  * of the current sk.
243                  */
244                 bh_unlock_sock(sk);
245                 sk = rcvr->sk;
246                 bh_lock_sock(sk);
247         }
248
249         if (sock_owned_by_user(sk)) {
250                 if (sctp_add_backlog(sk, skb)) {
251                         bh_unlock_sock(sk);
252                         sctp_chunk_free(chunk);
253                         skb = NULL; /* sctp_chunk_free already freed the skb */
254                         goto discard_release;
255                 }
256                 __SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_BACKLOG);
257         } else {
258                 __SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_SOFTIRQ);
259                 sctp_inq_push(&chunk->rcvr->inqueue, chunk);
260         }
261
262         bh_unlock_sock(sk);
263
264         /* Release the asoc/ep ref we took in the lookup calls. */
265         if (asoc)
266                 sctp_association_put(asoc);
267         else
268                 sctp_endpoint_put(ep);
269
270         return 0;
271
272 discard_it:
273         __SCTP_INC_STATS(net, SCTP_MIB_IN_PKT_DISCARDS);
274         kfree_skb(skb);
275         return 0;
276
277 discard_release:
278         /* Release the asoc/ep ref we took in the lookup calls. */
279         if (asoc)
280                 sctp_association_put(asoc);
281         else
282                 sctp_endpoint_put(ep);
283
284         goto discard_it;
285 }
286
287 /* Process the backlog queue of the socket.  Every skb on
288  * the backlog holds a ref on an association or endpoint.
289  * We hold this ref throughout the state machine to make
290  * sure that the structure we need is still around.
291  */
292 int sctp_backlog_rcv(struct sock *sk, struct sk_buff *skb)
293 {
294         struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk;
295         struct sctp_inq *inqueue = &chunk->rcvr->inqueue;
296         struct sctp_ep_common *rcvr = NULL;
297         int backloged = 0;
298
299         rcvr = chunk->rcvr;
300
301         /* If the rcvr is dead then the association or endpoint
302          * has been deleted and we can safely drop the chunk
303          * and refs that we are holding.
304          */
305         if (rcvr->dead) {
306                 sctp_chunk_free(chunk);
307                 goto done;
308         }
309
310         if (unlikely(rcvr->sk != sk)) {
311                 /* In this case, the association moved from one socket to
312                  * another.  We are currently sitting on the backlog of the
313                  * old socket, so we need to move.
314                  * However, since we are here in the process context we
315                  * need to take make sure that the user doesn't own
316                  * the new socket when we process the packet.
317                  * If the new socket is user-owned, queue the chunk to the
318                  * backlog of the new socket without dropping any refs.
319                  * Otherwise, we can safely push the chunk on the inqueue.
320                  */
321
322                 sk = rcvr->sk;
323                 bh_lock_sock(sk);
324
325                 if (sock_owned_by_user(sk)) {
326                         if (sk_add_backlog(sk, skb, sk->sk_rcvbuf))
327                                 sctp_chunk_free(chunk);
328                         else
329                                 backloged = 1;
330                 } else
331                         sctp_inq_push(inqueue, chunk);
332
333                 bh_unlock_sock(sk);
334
335                 /* If the chunk was backloged again, don't drop refs */
336                 if (backloged)
337                         return 0;
338         } else {
339                 sctp_inq_push(inqueue, chunk);
340         }
341
342 done:
343         /* Release the refs we took in sctp_add_backlog */
344         if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type)
345                 sctp_association_put(sctp_assoc(rcvr));
346         else if (SCTP_EP_TYPE_SOCKET == rcvr->type)
347                 sctp_endpoint_put(sctp_ep(rcvr));
348         else
349                 BUG();
350
351         return 0;
352 }
353
354 static int sctp_add_backlog(struct sock *sk, struct sk_buff *skb)
355 {
356         struct sctp_chunk *chunk = SCTP_INPUT_CB(skb)->chunk;
357         struct sctp_ep_common *rcvr = chunk->rcvr;
358         int ret;
359
360         ret = sk_add_backlog(sk, skb, sk->sk_rcvbuf);
361         if (!ret) {
362                 /* Hold the assoc/ep while hanging on the backlog queue.
363                  * This way, we know structures we need will not disappear
364                  * from us
365                  */
366                 if (SCTP_EP_TYPE_ASSOCIATION == rcvr->type)
367                         sctp_association_hold(sctp_assoc(rcvr));
368                 else if (SCTP_EP_TYPE_SOCKET == rcvr->type)
369                         sctp_endpoint_hold(sctp_ep(rcvr));
370                 else
371                         BUG();
372         }
373         return ret;
374
375 }
376
377 /* Handle icmp frag needed error. */
378 void sctp_icmp_frag_needed(struct sock *sk, struct sctp_association *asoc,
379                            struct sctp_transport *t, __u32 pmtu)
380 {
381         if (!t || (t->pathmtu <= pmtu))
382                 return;
383
384         if (sock_owned_by_user(sk)) {
385                 asoc->pmtu_pending = 1;
386                 t->pmtu_pending = 1;
387                 return;
388         }
389
390         if (t->param_flags & SPP_PMTUD_ENABLE) {
391                 /* Update transports view of the MTU */
392                 sctp_transport_update_pmtu(sk, t, pmtu);
393
394                 /* Update association pmtu. */
395                 sctp_assoc_sync_pmtu(sk, asoc);
396         }
397
398         /* Retransmit with the new pmtu setting.
399          * Normally, if PMTU discovery is disabled, an ICMP Fragmentation
400          * Needed will never be sent, but if a message was sent before
401          * PMTU discovery was disabled that was larger than the PMTU, it
402          * would not be fragmented, so it must be re-transmitted fragmented.
403          */
404         sctp_retransmit(&asoc->outqueue, t, SCTP_RTXR_PMTUD);
405 }
406
407 void sctp_icmp_redirect(struct sock *sk, struct sctp_transport *t,
408                         struct sk_buff *skb)
409 {
410         struct dst_entry *dst;
411
412         if (!t)
413                 return;
414         dst = sctp_transport_dst_check(t);
415         if (dst)
416                 dst->ops->redirect(dst, sk, skb);
417 }
418
419 /*
420  * SCTP Implementer's Guide, 2.37 ICMP handling procedures
421  *
422  * ICMP8) If the ICMP code is a "Unrecognized next header type encountered"
423  *        or a "Protocol Unreachable" treat this message as an abort
424  *        with the T bit set.
425  *
426  * This function sends an event to the state machine, which will abort the
427  * association.
428  *
429  */
430 void sctp_icmp_proto_unreachable(struct sock *sk,
431                            struct sctp_association *asoc,
432                            struct sctp_transport *t)
433 {
434         if (sock_owned_by_user(sk)) {
435                 if (timer_pending(&t->proto_unreach_timer))
436                         return;
437                 else {
438                         if (!mod_timer(&t->proto_unreach_timer,
439                                                 jiffies + (HZ/20)))
440                                 sctp_association_hold(asoc);
441                 }
442         } else {
443                 struct net *net = sock_net(sk);
444
445                 pr_debug("%s: unrecognized next header type "
446                          "encountered!\n", __func__);
447
448                 if (del_timer(&t->proto_unreach_timer))
449                         sctp_association_put(asoc);
450
451                 sctp_do_sm(net, SCTP_EVENT_T_OTHER,
452                            SCTP_ST_OTHER(SCTP_EVENT_ICMP_PROTO_UNREACH),
453                            asoc->state, asoc->ep, asoc, t,
454                            GFP_ATOMIC);
455         }
456 }
457
458 /* Common lookup code for icmp/icmpv6 error handler. */
459 struct sock *sctp_err_lookup(struct net *net, int family, struct sk_buff *skb,
460                              struct sctphdr *sctphdr,
461                              struct sctp_association **app,
462                              struct sctp_transport **tpp)
463 {
464         union sctp_addr saddr;
465         union sctp_addr daddr;
466         struct sctp_af *af;
467         struct sock *sk = NULL;
468         struct sctp_association *asoc;
469         struct sctp_transport *transport = NULL;
470         struct sctp_init_chunk *chunkhdr;
471         __u32 vtag = ntohl(sctphdr->vtag);
472         int len = skb->len - ((void *)sctphdr - (void *)skb->data);
473
474         *app = NULL; *tpp = NULL;
475
476         af = sctp_get_af_specific(family);
477         if (unlikely(!af)) {
478                 return NULL;
479         }
480
481         /* Initialize local addresses for lookups. */
482         af->from_skb(&saddr, skb, 1);
483         af->from_skb(&daddr, skb, 0);
484
485         /* Look for an association that matches the incoming ICMP error
486          * packet.
487          */
488         asoc = __sctp_lookup_association(net, &saddr, &daddr, &transport);
489         if (!asoc)
490                 return NULL;
491
492         sk = asoc->base.sk;
493
494         /* RFC 4960, Appendix C. ICMP Handling
495          *
496          * ICMP6) An implementation MUST validate that the Verification Tag
497          * contained in the ICMP message matches the Verification Tag of
498          * the peer.  If the Verification Tag is not 0 and does NOT
499          * match, discard the ICMP message.  If it is 0 and the ICMP
500          * message contains enough bytes to verify that the chunk type is
501          * an INIT chunk and that the Initiate Tag matches the tag of the
502          * peer, continue with ICMP7.  If the ICMP message is too short
503          * or the chunk type or the Initiate Tag does not match, silently
504          * discard the packet.
505          */
506         if (vtag == 0) {
507                 chunkhdr = (void *)sctphdr + sizeof(struct sctphdr);
508                 if (len < sizeof(struct sctphdr) + sizeof(sctp_chunkhdr_t)
509                           + sizeof(__be32) ||
510                     chunkhdr->chunk_hdr.type != SCTP_CID_INIT ||
511                     ntohl(chunkhdr->init_hdr.init_tag) != asoc->c.my_vtag) {
512                         goto out;
513                 }
514         } else if (vtag != asoc->c.peer_vtag) {
515                 goto out;
516         }
517
518         bh_lock_sock(sk);
519
520         /* If too many ICMPs get dropped on busy
521          * servers this needs to be solved differently.
522          */
523         if (sock_owned_by_user(sk))
524                 __NET_INC_STATS(net, LINUX_MIB_LOCKDROPPEDICMPS);
525
526         *app = asoc;
527         *tpp = transport;
528         return sk;
529
530 out:
531         sctp_association_put(asoc);
532         return NULL;
533 }
534
535 /* Common cleanup code for icmp/icmpv6 error handler. */
536 void sctp_err_finish(struct sock *sk, struct sctp_association *asoc)
537 {
538         bh_unlock_sock(sk);
539         sctp_association_put(asoc);
540 }
541
542 /*
543  * This routine is called by the ICMP module when it gets some
544  * sort of error condition.  If err < 0 then the socket should
545  * be closed and the error returned to the user.  If err > 0
546  * it's just the icmp type << 8 | icmp code.  After adjustment
547  * header points to the first 8 bytes of the sctp header.  We need
548  * to find the appropriate port.
549  *
550  * The locking strategy used here is very "optimistic". When
551  * someone else accesses the socket the ICMP is just dropped
552  * and for some paths there is no check at all.
553  * A more general error queue to queue errors for later handling
554  * is probably better.
555  *
556  */
557 void sctp_v4_err(struct sk_buff *skb, __u32 info)
558 {
559         const struct iphdr *iph = (const struct iphdr *)skb->data;
560         const int ihlen = iph->ihl * 4;
561         const int type = icmp_hdr(skb)->type;
562         const int code = icmp_hdr(skb)->code;
563         struct sock *sk;
564         struct sctp_association *asoc = NULL;
565         struct sctp_transport *transport;
566         struct inet_sock *inet;
567         __u16 saveip, savesctp;
568         int err;
569         struct net *net = dev_net(skb->dev);
570
571         /* Fix up skb to look at the embedded net header. */
572         saveip = skb->network_header;
573         savesctp = skb->transport_header;
574         skb_reset_network_header(skb);
575         skb_set_transport_header(skb, ihlen);
576         sk = sctp_err_lookup(net, AF_INET, skb, sctp_hdr(skb), &asoc, &transport);
577         /* Put back, the original values. */
578         skb->network_header = saveip;
579         skb->transport_header = savesctp;
580         if (!sk) {
581                 __ICMP_INC_STATS(net, ICMP_MIB_INERRORS);
582                 return;
583         }
584         /* Warning:  The sock lock is held.  Remember to call
585          * sctp_err_finish!
586          */
587
588         switch (type) {
589         case ICMP_PARAMETERPROB:
590                 err = EPROTO;
591                 break;
592         case ICMP_DEST_UNREACH:
593                 if (code > NR_ICMP_UNREACH)
594                         goto out_unlock;
595
596                 /* PMTU discovery (RFC1191) */
597                 if (ICMP_FRAG_NEEDED == code) {
598                         sctp_icmp_frag_needed(sk, asoc, transport,
599                                               WORD_TRUNC(info));
600                         goto out_unlock;
601                 } else {
602                         if (ICMP_PROT_UNREACH == code) {
603                                 sctp_icmp_proto_unreachable(sk, asoc,
604                                                             transport);
605                                 goto out_unlock;
606                         }
607                 }
608                 err = icmp_err_convert[code].errno;
609                 break;
610         case ICMP_TIME_EXCEEDED:
611                 /* Ignore any time exceeded errors due to fragment reassembly
612                  * timeouts.
613                  */
614                 if (ICMP_EXC_FRAGTIME == code)
615                         goto out_unlock;
616
617                 err = EHOSTUNREACH;
618                 break;
619         case ICMP_REDIRECT:
620                 sctp_icmp_redirect(sk, transport, skb);
621                 /* Fall through to out_unlock. */
622         default:
623                 goto out_unlock;
624         }
625
626         inet = inet_sk(sk);
627         if (!sock_owned_by_user(sk) && inet->recverr) {
628                 sk->sk_err = err;
629                 sk->sk_error_report(sk);
630         } else {  /* Only an error on timeout */
631                 sk->sk_err_soft = err;
632         }
633
634 out_unlock:
635         sctp_err_finish(sk, asoc);
636 }
637
638 /*
639  * RFC 2960, 8.4 - Handle "Out of the blue" Packets.
640  *
641  * This function scans all the chunks in the OOTB packet to determine if
642  * the packet should be discarded right away.  If a response might be needed
643  * for this packet, or, if further processing is possible, the packet will
644  * be queued to a proper inqueue for the next phase of handling.
645  *
646  * Output:
647  * Return 0 - If further processing is needed.
648  * Return 1 - If the packet can be discarded right away.
649  */
650 static int sctp_rcv_ootb(struct sk_buff *skb)
651 {
652         sctp_chunkhdr_t *ch, _ch;
653         int ch_end, offset = 0;
654
655         /* Scan through all the chunks in the packet.  */
656         do {
657                 /* Make sure we have at least the header there */
658                 if (offset + sizeof(sctp_chunkhdr_t) > skb->len)
659                         break;
660
661                 ch = skb_header_pointer(skb, offset, sizeof(*ch), &_ch);
662
663                 /* Break out if chunk length is less then minimal. */
664                 if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
665                         break;
666
667                 ch_end = offset + WORD_ROUND(ntohs(ch->length));
668                 if (ch_end > skb->len)
669                         break;
670
671                 /* RFC 8.4, 2) If the OOTB packet contains an ABORT chunk, the
672                  * receiver MUST silently discard the OOTB packet and take no
673                  * further action.
674                  */
675                 if (SCTP_CID_ABORT == ch->type)
676                         goto discard;
677
678                 /* RFC 8.4, 6) If the packet contains a SHUTDOWN COMPLETE
679                  * chunk, the receiver should silently discard the packet
680                  * and take no further action.
681                  */
682                 if (SCTP_CID_SHUTDOWN_COMPLETE == ch->type)
683                         goto discard;
684
685                 /* RFC 4460, 2.11.2
686                  * This will discard packets with INIT chunk bundled as
687                  * subsequent chunks in the packet.  When INIT is first,
688                  * the normal INIT processing will discard the chunk.
689                  */
690                 if (SCTP_CID_INIT == ch->type && (void *)ch != skb->data)
691                         goto discard;
692
693                 offset = ch_end;
694         } while (ch_end < skb->len);
695
696         return 0;
697
698 discard:
699         return 1;
700 }
701
702 /* Insert endpoint into the hash table.  */
703 static void __sctp_hash_endpoint(struct sctp_endpoint *ep)
704 {
705         struct net *net = sock_net(ep->base.sk);
706         struct sctp_ep_common *epb;
707         struct sctp_hashbucket *head;
708
709         epb = &ep->base;
710
711         epb->hashent = sctp_ep_hashfn(net, epb->bind_addr.port);
712         head = &sctp_ep_hashtable[epb->hashent];
713
714         write_lock(&head->lock);
715         hlist_add_head(&epb->node, &head->chain);
716         write_unlock(&head->lock);
717 }
718
719 /* Add an endpoint to the hash. Local BH-safe. */
720 void sctp_hash_endpoint(struct sctp_endpoint *ep)
721 {
722         local_bh_disable();
723         __sctp_hash_endpoint(ep);
724         local_bh_enable();
725 }
726
727 /* Remove endpoint from the hash table.  */
728 static void __sctp_unhash_endpoint(struct sctp_endpoint *ep)
729 {
730         struct net *net = sock_net(ep->base.sk);
731         struct sctp_hashbucket *head;
732         struct sctp_ep_common *epb;
733
734         epb = &ep->base;
735
736         epb->hashent = sctp_ep_hashfn(net, epb->bind_addr.port);
737
738         head = &sctp_ep_hashtable[epb->hashent];
739
740         write_lock(&head->lock);
741         hlist_del_init(&epb->node);
742         write_unlock(&head->lock);
743 }
744
745 /* Remove endpoint from the hash.  Local BH-safe. */
746 void sctp_unhash_endpoint(struct sctp_endpoint *ep)
747 {
748         local_bh_disable();
749         __sctp_unhash_endpoint(ep);
750         local_bh_enable();
751 }
752
753 /* Look up an endpoint. */
754 static struct sctp_endpoint *__sctp_rcv_lookup_endpoint(struct net *net,
755                                                 const union sctp_addr *laddr)
756 {
757         struct sctp_hashbucket *head;
758         struct sctp_ep_common *epb;
759         struct sctp_endpoint *ep;
760         int hash;
761
762         hash = sctp_ep_hashfn(net, ntohs(laddr->v4.sin_port));
763         head = &sctp_ep_hashtable[hash];
764         read_lock(&head->lock);
765         sctp_for_each_hentry(epb, &head->chain) {
766                 ep = sctp_ep(epb);
767                 if (sctp_endpoint_is_match(ep, net, laddr))
768                         goto hit;
769         }
770
771         ep = sctp_sk(net->sctp.ctl_sock)->ep;
772
773 hit:
774         sctp_endpoint_hold(ep);
775         read_unlock(&head->lock);
776         return ep;
777 }
778
779 /* rhashtable for transport */
780 struct sctp_hash_cmp_arg {
781         const struct sctp_endpoint      *ep;
782         const union sctp_addr           *laddr;
783         const union sctp_addr           *paddr;
784         const struct net                *net;
785 };
786
787 static inline int sctp_hash_cmp(struct rhashtable_compare_arg *arg,
788                                 const void *ptr)
789 {
790         const struct sctp_hash_cmp_arg *x = arg->key;
791         const struct sctp_transport *t = ptr;
792         struct sctp_association *asoc = t->asoc;
793         const struct net *net = x->net;
794
795         if (!sctp_cmp_addr_exact(&t->ipaddr, x->paddr))
796                 return 1;
797         if (!net_eq(sock_net(asoc->base.sk), net))
798                 return 1;
799         if (x->ep) {
800                 if (x->ep != asoc->ep)
801                         return 1;
802         } else {
803                 if (x->laddr->v4.sin_port != htons(asoc->base.bind_addr.port))
804                         return 1;
805                 if (!sctp_bind_addr_match(&asoc->base.bind_addr,
806                                           x->laddr, sctp_sk(asoc->base.sk)))
807                         return 1;
808         }
809
810         return 0;
811 }
812
813 static inline u32 sctp_hash_obj(const void *data, u32 len, u32 seed)
814 {
815         const struct sctp_transport *t = data;
816         const union sctp_addr *paddr = &t->ipaddr;
817         const struct net *net = sock_net(t->asoc->base.sk);
818         u16 lport = htons(t->asoc->base.bind_addr.port);
819         u32 addr;
820
821         if (paddr->sa.sa_family == AF_INET6)
822                 addr = jhash(&paddr->v6.sin6_addr, 16, seed);
823         else
824                 addr = paddr->v4.sin_addr.s_addr;
825
826         return  jhash_3words(addr, ((__u32)paddr->v4.sin_port) << 16 |
827                              (__force __u32)lport, net_hash_mix(net), seed);
828 }
829
830 static inline u32 sctp_hash_key(const void *data, u32 len, u32 seed)
831 {
832         const struct sctp_hash_cmp_arg *x = data;
833         const union sctp_addr *paddr = x->paddr;
834         const struct net *net = x->net;
835         u16 lport;
836         u32 addr;
837
838         lport = x->ep ? htons(x->ep->base.bind_addr.port) :
839                         x->laddr->v4.sin_port;
840         if (paddr->sa.sa_family == AF_INET6)
841                 addr = jhash(&paddr->v6.sin6_addr, 16, seed);
842         else
843                 addr = paddr->v4.sin_addr.s_addr;
844
845         return  jhash_3words(addr, ((__u32)paddr->v4.sin_port) << 16 |
846                              (__force __u32)lport, net_hash_mix(net), seed);
847 }
848
849 static const struct rhashtable_params sctp_hash_params = {
850         .head_offset            = offsetof(struct sctp_transport, node),
851         .hashfn                 = sctp_hash_key,
852         .obj_hashfn             = sctp_hash_obj,
853         .obj_cmpfn              = sctp_hash_cmp,
854         .automatic_shrinking    = true,
855 };
856
857 int sctp_transport_hashtable_init(void)
858 {
859         return rhashtable_init(&sctp_transport_hashtable, &sctp_hash_params);
860 }
861
862 void sctp_transport_hashtable_destroy(void)
863 {
864         rhashtable_destroy(&sctp_transport_hashtable);
865 }
866
867 void sctp_hash_transport(struct sctp_transport *t)
868 {
869         struct sctp_hash_cmp_arg arg;
870
871         if (t->asoc->temp)
872                 return;
873
874         arg.ep = t->asoc->ep;
875         arg.paddr = &t->ipaddr;
876         arg.net   = sock_net(t->asoc->base.sk);
877
878 reinsert:
879         if (rhashtable_lookup_insert_key(&sctp_transport_hashtable, &arg,
880                                          &t->node, sctp_hash_params) == -EBUSY)
881                 goto reinsert;
882 }
883
884 void sctp_unhash_transport(struct sctp_transport *t)
885 {
886         if (t->asoc->temp)
887                 return;
888
889         rhashtable_remove_fast(&sctp_transport_hashtable, &t->node,
890                                sctp_hash_params);
891 }
892
893 struct sctp_transport *sctp_addrs_lookup_transport(
894                                 struct net *net,
895                                 const union sctp_addr *laddr,
896                                 const union sctp_addr *paddr)
897 {
898         struct sctp_hash_cmp_arg arg = {
899                 .ep    = NULL,
900                 .laddr = laddr,
901                 .paddr = paddr,
902                 .net   = net,
903         };
904
905         return rhashtable_lookup_fast(&sctp_transport_hashtable, &arg,
906                                       sctp_hash_params);
907 }
908
909 struct sctp_transport *sctp_epaddr_lookup_transport(
910                                 const struct sctp_endpoint *ep,
911                                 const union sctp_addr *paddr)
912 {
913         struct net *net = sock_net(ep->base.sk);
914         struct sctp_hash_cmp_arg arg = {
915                 .ep    = ep,
916                 .paddr = paddr,
917                 .net   = net,
918         };
919
920         return rhashtable_lookup_fast(&sctp_transport_hashtable, &arg,
921                                       sctp_hash_params);
922 }
923
924 /* Look up an association. */
925 static struct sctp_association *__sctp_lookup_association(
926                                         struct net *net,
927                                         const union sctp_addr *local,
928                                         const union sctp_addr *peer,
929                                         struct sctp_transport **pt)
930 {
931         struct sctp_transport *t;
932         struct sctp_association *asoc = NULL;
933
934         t = sctp_addrs_lookup_transport(net, local, peer);
935         if (!t || !sctp_transport_hold(t))
936                 goto out;
937
938         asoc = t->asoc;
939         sctp_association_hold(asoc);
940         *pt = t;
941
942         sctp_transport_put(t);
943
944 out:
945         return asoc;
946 }
947
948 /* Look up an association. protected by RCU read lock */
949 static
950 struct sctp_association *sctp_lookup_association(struct net *net,
951                                                  const union sctp_addr *laddr,
952                                                  const union sctp_addr *paddr,
953                                                  struct sctp_transport **transportp)
954 {
955         struct sctp_association *asoc;
956
957         rcu_read_lock();
958         asoc = __sctp_lookup_association(net, laddr, paddr, transportp);
959         rcu_read_unlock();
960
961         return asoc;
962 }
963
964 /* Is there an association matching the given local and peer addresses? */
965 int sctp_has_association(struct net *net,
966                          const union sctp_addr *laddr,
967                          const union sctp_addr *paddr)
968 {
969         struct sctp_association *asoc;
970         struct sctp_transport *transport;
971
972         if ((asoc = sctp_lookup_association(net, laddr, paddr, &transport))) {
973                 sctp_association_put(asoc);
974                 return 1;
975         }
976
977         return 0;
978 }
979
980 /*
981  * SCTP Implementors Guide, 2.18 Handling of address
982  * parameters within the INIT or INIT-ACK.
983  *
984  * D) When searching for a matching TCB upon reception of an INIT
985  *    or INIT-ACK chunk the receiver SHOULD use not only the
986  *    source address of the packet (containing the INIT or
987  *    INIT-ACK) but the receiver SHOULD also use all valid
988  *    address parameters contained within the chunk.
989  *
990  * 2.18.3 Solution description
991  *
992  * This new text clearly specifies to an implementor the need
993  * to look within the INIT or INIT-ACK. Any implementation that
994  * does not do this, may not be able to establish associations
995  * in certain circumstances.
996  *
997  */
998 static struct sctp_association *__sctp_rcv_init_lookup(struct net *net,
999         struct sk_buff *skb,
1000         const union sctp_addr *laddr, struct sctp_transport **transportp)
1001 {
1002         struct sctp_association *asoc;
1003         union sctp_addr addr;
1004         union sctp_addr *paddr = &addr;
1005         struct sctphdr *sh = sctp_hdr(skb);
1006         union sctp_params params;
1007         sctp_init_chunk_t *init;
1008         struct sctp_transport *transport;
1009         struct sctp_af *af;
1010
1011         /*
1012          * This code will NOT touch anything inside the chunk--it is
1013          * strictly READ-ONLY.
1014          *
1015          * RFC 2960 3  SCTP packet Format
1016          *
1017          * Multiple chunks can be bundled into one SCTP packet up to
1018          * the MTU size, except for the INIT, INIT ACK, and SHUTDOWN
1019          * COMPLETE chunks.  These chunks MUST NOT be bundled with any
1020          * other chunk in a packet.  See Section 6.10 for more details
1021          * on chunk bundling.
1022          */
1023
1024         /* Find the start of the TLVs and the end of the chunk.  This is
1025          * the region we search for address parameters.
1026          */
1027         init = (sctp_init_chunk_t *)skb->data;
1028
1029         /* Walk the parameters looking for embedded addresses. */
1030         sctp_walk_params(params, init, init_hdr.params) {
1031
1032                 /* Note: Ignoring hostname addresses. */
1033                 af = sctp_get_af_specific(param_type2af(params.p->type));
1034                 if (!af)
1035                         continue;
1036
1037                 af->from_addr_param(paddr, params.addr, sh->source, 0);
1038
1039                 asoc = __sctp_lookup_association(net, laddr, paddr, &transport);
1040                 if (asoc)
1041                         return asoc;
1042         }
1043
1044         return NULL;
1045 }
1046
1047 /* ADD-IP, Section 5.2
1048  * When an endpoint receives an ASCONF Chunk from the remote peer
1049  * special procedures may be needed to identify the association the
1050  * ASCONF Chunk is associated with. To properly find the association
1051  * the following procedures SHOULD be followed:
1052  *
1053  * D2) If the association is not found, use the address found in the
1054  * Address Parameter TLV combined with the port number found in the
1055  * SCTP common header. If found proceed to rule D4.
1056  *
1057  * D2-ext) If more than one ASCONF Chunks are packed together, use the
1058  * address found in the ASCONF Address Parameter TLV of each of the
1059  * subsequent ASCONF Chunks. If found, proceed to rule D4.
1060  */
1061 static struct sctp_association *__sctp_rcv_asconf_lookup(
1062                                         struct net *net,
1063                                         sctp_chunkhdr_t *ch,
1064                                         const union sctp_addr *laddr,
1065                                         __be16 peer_port,
1066                                         struct sctp_transport **transportp)
1067 {
1068         sctp_addip_chunk_t *asconf = (struct sctp_addip_chunk *)ch;
1069         struct sctp_af *af;
1070         union sctp_addr_param *param;
1071         union sctp_addr paddr;
1072
1073         /* Skip over the ADDIP header and find the Address parameter */
1074         param = (union sctp_addr_param *)(asconf + 1);
1075
1076         af = sctp_get_af_specific(param_type2af(param->p.type));
1077         if (unlikely(!af))
1078                 return NULL;
1079
1080         af->from_addr_param(&paddr, param, peer_port, 0);
1081
1082         return __sctp_lookup_association(net, laddr, &paddr, transportp);
1083 }
1084
1085
1086 /* SCTP-AUTH, Section 6.3:
1087 *    If the receiver does not find a STCB for a packet containing an AUTH
1088 *    chunk as the first chunk and not a COOKIE-ECHO chunk as the second
1089 *    chunk, it MUST use the chunks after the AUTH chunk to look up an existing
1090 *    association.
1091 *
1092 * This means that any chunks that can help us identify the association need
1093 * to be looked at to find this association.
1094 */
1095 static struct sctp_association *__sctp_rcv_walk_lookup(struct net *net,
1096                                       struct sk_buff *skb,
1097                                       const union sctp_addr *laddr,
1098                                       struct sctp_transport **transportp)
1099 {
1100         struct sctp_association *asoc = NULL;
1101         sctp_chunkhdr_t *ch;
1102         int have_auth = 0;
1103         unsigned int chunk_num = 1;
1104         __u8 *ch_end;
1105
1106         /* Walk through the chunks looking for AUTH or ASCONF chunks
1107          * to help us find the association.
1108          */
1109         ch = (sctp_chunkhdr_t *) skb->data;
1110         do {
1111                 /* Break out if chunk length is less then minimal. */
1112                 if (ntohs(ch->length) < sizeof(sctp_chunkhdr_t))
1113                         break;
1114
1115                 ch_end = ((__u8 *)ch) + WORD_ROUND(ntohs(ch->length));
1116                 if (ch_end > skb_tail_pointer(skb))
1117                         break;
1118
1119                 switch (ch->type) {
1120                 case SCTP_CID_AUTH:
1121                         have_auth = chunk_num;
1122                         break;
1123
1124                 case SCTP_CID_COOKIE_ECHO:
1125                         /* If a packet arrives containing an AUTH chunk as
1126                          * a first chunk, a COOKIE-ECHO chunk as the second
1127                          * chunk, and possibly more chunks after them, and
1128                          * the receiver does not have an STCB for that
1129                          * packet, then authentication is based on
1130                          * the contents of the COOKIE- ECHO chunk.
1131                          */
1132                         if (have_auth == 1 && chunk_num == 2)
1133                                 return NULL;
1134                         break;
1135
1136                 case SCTP_CID_ASCONF:
1137                         if (have_auth || net->sctp.addip_noauth)
1138                                 asoc = __sctp_rcv_asconf_lookup(
1139                                                 net, ch, laddr,
1140                                                 sctp_hdr(skb)->source,
1141                                                 transportp);
1142                 default:
1143                         break;
1144                 }
1145
1146                 if (asoc)
1147                         break;
1148
1149                 ch = (sctp_chunkhdr_t *) ch_end;
1150                 chunk_num++;
1151         } while (ch_end < skb_tail_pointer(skb));
1152
1153         return asoc;
1154 }
1155
1156 /*
1157  * There are circumstances when we need to look inside the SCTP packet
1158  * for information to help us find the association.   Examples
1159  * include looking inside of INIT/INIT-ACK chunks or after the AUTH
1160  * chunks.
1161  */
1162 static struct sctp_association *__sctp_rcv_lookup_harder(struct net *net,
1163                                       struct sk_buff *skb,
1164                                       const union sctp_addr *laddr,
1165                                       struct sctp_transport **transportp)
1166 {
1167         sctp_chunkhdr_t *ch;
1168
1169         /* We do not allow GSO frames here as we need to linearize and
1170          * then cannot guarantee frame boundaries. This shouldn't be an
1171          * issue as packets hitting this are mostly INIT or INIT-ACK and
1172          * those cannot be on GSO-style anyway.
1173          */
1174         if ((skb_shinfo(skb)->gso_type & SKB_GSO_SCTP) == SKB_GSO_SCTP)
1175                 return NULL;
1176
1177         if (skb_linearize(skb))
1178                 return NULL;
1179
1180         ch = (sctp_chunkhdr_t *) skb->data;
1181
1182         /* The code below will attempt to walk the chunk and extract
1183          * parameter information.  Before we do that, we need to verify
1184          * that the chunk length doesn't cause overflow.  Otherwise, we'll
1185          * walk off the end.
1186          */
1187         if (WORD_ROUND(ntohs(ch->length)) > skb->len)
1188                 return NULL;
1189
1190         /* If this is INIT/INIT-ACK look inside the chunk too. */
1191         if (ch->type == SCTP_CID_INIT || ch->type == SCTP_CID_INIT_ACK)
1192                 return __sctp_rcv_init_lookup(net, skb, laddr, transportp);
1193
1194         return __sctp_rcv_walk_lookup(net, skb, laddr, transportp);
1195 }
1196
1197 /* Lookup an association for an inbound skb. */
1198 static struct sctp_association *__sctp_rcv_lookup(struct net *net,
1199                                       struct sk_buff *skb,
1200                                       const union sctp_addr *paddr,
1201                                       const union sctp_addr *laddr,
1202                                       struct sctp_transport **transportp)
1203 {
1204         struct sctp_association *asoc;
1205
1206         asoc = __sctp_lookup_association(net, laddr, paddr, transportp);
1207
1208         /* Further lookup for INIT/INIT-ACK packets.
1209          * SCTP Implementors Guide, 2.18 Handling of address
1210          * parameters within the INIT or INIT-ACK.
1211          */
1212         if (!asoc)
1213                 asoc = __sctp_rcv_lookup_harder(net, skb, laddr, transportp);
1214
1215         return asoc;
1216 }