[INET]: Generalise tcp_v4_hash_connect
[pandora-kernel.git] / net / dccp / ipv4.c
1 /*
2  *  net/dccp/ipv4.c
3  *
4  *  An implementation of the DCCP protocol
5  *  Arnaldo Carvalho de Melo <acme@conectiva.com.br>
6  *
7  *      This program is free software; you can redistribute it and/or
8  *      modify it under the terms of the GNU General Public License
9  *      as published by the Free Software Foundation; either version
10  *      2 of the License, or (at your option) any later version.
11  */
12
13 #include <linux/config.h>
14 #include <linux/dccp.h>
15 #include <linux/icmp.h>
16 #include <linux/module.h>
17 #include <linux/skbuff.h>
18 #include <linux/random.h>
19
20 #include <net/icmp.h>
21 #include <net/inet_hashtables.h>
22 #include <net/sock.h>
23 #include <net/timewait_sock.h>
24 #include <net/tcp_states.h>
25 #include <net/xfrm.h>
26
27 #include "ackvec.h"
28 #include "ccid.h"
29 #include "dccp.h"
30
31 struct inet_hashinfo __cacheline_aligned dccp_hashinfo = {
32         .lhash_lock     = RW_LOCK_UNLOCKED,
33         .lhash_users    = ATOMIC_INIT(0),
34         .lhash_wait = __WAIT_QUEUE_HEAD_INITIALIZER(dccp_hashinfo.lhash_wait),
35 };
36
37 EXPORT_SYMBOL_GPL(dccp_hashinfo);
38
39 static int dccp_v4_get_port(struct sock *sk, const unsigned short snum)
40 {
41         return inet_csk_get_port(&dccp_hashinfo, sk, snum,
42                                  inet_csk_bind_conflict);
43 }
44
45 static void dccp_v4_hash(struct sock *sk)
46 {
47         inet_hash(&dccp_hashinfo, sk);
48 }
49
50 void dccp_unhash(struct sock *sk)
51 {
52         inet_unhash(&dccp_hashinfo, sk);
53 }
54
55 EXPORT_SYMBOL_GPL(dccp_unhash);
56
57 int dccp_v4_connect(struct sock *sk, struct sockaddr *uaddr, int addr_len)
58 {
59         struct inet_sock *inet = inet_sk(sk);
60         struct dccp_sock *dp = dccp_sk(sk);
61         const struct sockaddr_in *usin = (struct sockaddr_in *)uaddr;
62         struct rtable *rt;
63         u32 daddr, nexthop;
64         int tmp;
65         int err;
66
67         dp->dccps_role = DCCP_ROLE_CLIENT;
68
69         if (dccp_service_not_initialized(sk))
70                 return -EPROTO;
71
72         if (addr_len < sizeof(struct sockaddr_in))
73                 return -EINVAL;
74
75         if (usin->sin_family != AF_INET)
76                 return -EAFNOSUPPORT;
77
78         nexthop = daddr = usin->sin_addr.s_addr;
79         if (inet->opt != NULL && inet->opt->srr) {
80                 if (daddr == 0)
81                         return -EINVAL;
82                 nexthop = inet->opt->faddr;
83         }
84
85         tmp = ip_route_connect(&rt, nexthop, inet->saddr,
86                                RT_CONN_FLAGS(sk), sk->sk_bound_dev_if,
87                                IPPROTO_DCCP,
88                                inet->sport, usin->sin_port, sk);
89         if (tmp < 0)
90                 return tmp;
91
92         if (rt->rt_flags & (RTCF_MULTICAST | RTCF_BROADCAST)) {
93                 ip_rt_put(rt);
94                 return -ENETUNREACH;
95         }
96
97         if (inet->opt == NULL || !inet->opt->srr)
98                 daddr = rt->rt_dst;
99
100         if (inet->saddr == 0)
101                 inet->saddr = rt->rt_src;
102         inet->rcv_saddr = inet->saddr;
103
104         inet->dport = usin->sin_port;
105         inet->daddr = daddr;
106
107         dp->dccps_ext_header_len = 0;
108         if (inet->opt != NULL)
109                 dp->dccps_ext_header_len = inet->opt->optlen;
110         /*
111          * Socket identity is still unknown (sport may be zero).
112          * However we set state to DCCP_REQUESTING and not releasing socket
113          * lock select source port, enter ourselves into the hash tables and
114          * complete initialization after this.
115          */
116         dccp_set_state(sk, DCCP_REQUESTING);
117         err = inet_hash_connect(&dccp_death_row, sk);
118         if (err != 0)
119                 goto failure;
120
121         err = ip_route_newports(&rt, inet->sport, inet->dport, sk);
122         if (err != 0)
123                 goto failure;
124
125         /* OK, now commit destination to socket.  */
126         sk_setup_caps(sk, &rt->u.dst);
127
128         dp->dccps_gar =
129                 dp->dccps_iss = secure_dccp_sequence_number(inet->saddr,
130                                                             inet->daddr,
131                                                             inet->sport,
132                                                             usin->sin_port);
133         dccp_update_gss(sk, dp->dccps_iss);
134
135         inet->id = dp->dccps_iss ^ jiffies;
136
137         err = dccp_connect(sk);
138         rt = NULL;
139         if (err != 0)
140                 goto failure;
141 out:
142         return err;
143 failure:
144         /*
145          * This unhashes the socket and releases the local port, if necessary.
146          */
147         dccp_set_state(sk, DCCP_CLOSED);
148         ip_rt_put(rt);
149         sk->sk_route_caps = 0;
150         inet->dport = 0;
151         goto out;
152 }
153
154 EXPORT_SYMBOL_GPL(dccp_v4_connect);
155
156 /*
157  * This routine does path mtu discovery as defined in RFC1191.
158  */
159 static inline void dccp_do_pmtu_discovery(struct sock *sk,
160                                           const struct iphdr *iph,
161                                           u32 mtu)
162 {
163         struct dst_entry *dst;
164         const struct inet_sock *inet = inet_sk(sk);
165         const struct dccp_sock *dp = dccp_sk(sk);
166
167         /* We are not interested in DCCP_LISTEN and request_socks (RESPONSEs
168          * send out by Linux are always < 576bytes so they should go through
169          * unfragmented).
170          */
171         if (sk->sk_state == DCCP_LISTEN)
172                 return;
173
174         /* We don't check in the destentry if pmtu discovery is forbidden
175          * on this route. We just assume that no packet_to_big packets
176          * are send back when pmtu discovery is not active.
177          * There is a small race when the user changes this flag in the
178          * route, but I think that's acceptable.
179          */
180         if ((dst = __sk_dst_check(sk, 0)) == NULL)
181                 return;
182
183         dst->ops->update_pmtu(dst, mtu);
184
185         /* Something is about to be wrong... Remember soft error
186          * for the case, if this connection will not able to recover.
187          */
188         if (mtu < dst_mtu(dst) && ip_dont_fragment(sk, dst))
189                 sk->sk_err_soft = EMSGSIZE;
190
191         mtu = dst_mtu(dst);
192
193         if (inet->pmtudisc != IP_PMTUDISC_DONT &&
194             dp->dccps_pmtu_cookie > mtu) {
195                 dccp_sync_mss(sk, mtu);
196
197                 /*
198                  * From: draft-ietf-dccp-spec-11.txt
199                  *
200                  *      DCCP-Sync packets are the best choice for upward
201                  *      probing, since DCCP-Sync probes do not risk application
202                  *      data loss.
203                  */
204                 dccp_send_sync(sk, dp->dccps_gsr, DCCP_PKT_SYNC);
205         } /* else let the usual retransmit timer handle it */
206 }
207
208 static void dccp_v4_ctl_send_ack(struct sk_buff *rxskb)
209 {
210         int err;
211         struct dccp_hdr *rxdh = dccp_hdr(rxskb), *dh;
212         const int dccp_hdr_ack_len = sizeof(struct dccp_hdr) +
213                                      sizeof(struct dccp_hdr_ext) +
214                                      sizeof(struct dccp_hdr_ack_bits);
215         struct sk_buff *skb;
216
217         if (((struct rtable *)rxskb->dst)->rt_type != RTN_LOCAL)
218                 return;
219
220         skb = alloc_skb(MAX_DCCP_HEADER + 15, GFP_ATOMIC);
221         if (skb == NULL)
222                 return;
223
224         /* Reserve space for headers. */
225         skb_reserve(skb, MAX_DCCP_HEADER);
226
227         skb->dst = dst_clone(rxskb->dst);
228
229         skb->h.raw = skb_push(skb, dccp_hdr_ack_len);
230         dh = dccp_hdr(skb);
231         memset(dh, 0, dccp_hdr_ack_len);
232
233         /* Build DCCP header and checksum it. */
234         dh->dccph_type     = DCCP_PKT_ACK;
235         dh->dccph_sport    = rxdh->dccph_dport;
236         dh->dccph_dport    = rxdh->dccph_sport;
237         dh->dccph_doff     = dccp_hdr_ack_len / 4;
238         dh->dccph_x        = 1;
239
240         dccp_hdr_set_seq(dh, DCCP_SKB_CB(rxskb)->dccpd_ack_seq);
241         dccp_hdr_set_ack(dccp_hdr_ack_bits(skb),
242                          DCCP_SKB_CB(rxskb)->dccpd_seq);
243
244         bh_lock_sock(dccp_ctl_socket->sk);
245         err = ip_build_and_send_pkt(skb, dccp_ctl_socket->sk,
246                                     rxskb->nh.iph->daddr,
247                                     rxskb->nh.iph->saddr, NULL);
248         bh_unlock_sock(dccp_ctl_socket->sk);
249
250         if (err == NET_XMIT_CN || err == 0) {
251                 DCCP_INC_STATS_BH(DCCP_MIB_OUTSEGS);
252                 DCCP_INC_STATS_BH(DCCP_MIB_OUTRSTS);
253         }
254 }
255
256 static void dccp_v4_reqsk_send_ack(struct sk_buff *skb,
257                                    struct request_sock *req)
258 {
259         dccp_v4_ctl_send_ack(skb);
260 }
261
262 static int dccp_v4_send_response(struct sock *sk, struct request_sock *req,
263                                  struct dst_entry *dst)
264 {
265         int err = -1;
266         struct sk_buff *skb;
267
268         /* First, grab a route. */
269         
270         if (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL)
271                 goto out;
272
273         skb = dccp_make_response(sk, dst, req);
274         if (skb != NULL) {
275                 const struct inet_request_sock *ireq = inet_rsk(req);
276
277                 memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
278                 err = ip_build_and_send_pkt(skb, sk, ireq->loc_addr,
279                                             ireq->rmt_addr,
280                                             ireq->opt);
281                 if (err == NET_XMIT_CN)
282                         err = 0;
283         }
284
285 out:
286         dst_release(dst);
287         return err;
288 }
289
290 /*
291  * This routine is called by the ICMP module when it gets some sort of error
292  * condition. If err < 0 then the socket should be closed and the error
293  * returned to the user. If err > 0 it's just the icmp type << 8 | icmp code.
294  * After adjustment header points to the first 8 bytes of the tcp header. We
295  * need to find the appropriate port.
296  *
297  * The locking strategy used here is very "optimistic". When someone else
298  * accesses the socket the ICMP is just dropped and for some paths there is no
299  * check at all. A more general error queue to queue errors for later handling
300  * is probably better.
301  */
302 void dccp_v4_err(struct sk_buff *skb, u32 info)
303 {
304         const struct iphdr *iph = (struct iphdr *)skb->data;
305         const struct dccp_hdr *dh = (struct dccp_hdr *)(skb->data +
306                                                         (iph->ihl << 2));
307         struct dccp_sock *dp;
308         struct inet_sock *inet;
309         const int type = skb->h.icmph->type;
310         const int code = skb->h.icmph->code;
311         struct sock *sk;
312         __u64 seq;
313         int err;
314
315         if (skb->len < (iph->ihl << 2) + 8) {
316                 ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
317                 return;
318         }
319
320         sk = inet_lookup(&dccp_hashinfo, iph->daddr, dh->dccph_dport,
321                          iph->saddr, dh->dccph_sport, inet_iif(skb));
322         if (sk == NULL) {
323                 ICMP_INC_STATS_BH(ICMP_MIB_INERRORS);
324                 return;
325         }
326
327         if (sk->sk_state == DCCP_TIME_WAIT) {
328                 inet_twsk_put((struct inet_timewait_sock *)sk);
329                 return;
330         }
331
332         bh_lock_sock(sk);
333         /* If too many ICMPs get dropped on busy
334          * servers this needs to be solved differently.
335          */
336         if (sock_owned_by_user(sk))
337                 NET_INC_STATS_BH(LINUX_MIB_LOCKDROPPEDICMPS);
338
339         if (sk->sk_state == DCCP_CLOSED)
340                 goto out;
341
342         dp = dccp_sk(sk);
343         seq = dccp_hdr_seq(skb);
344         if (sk->sk_state != DCCP_LISTEN &&
345             !between48(seq, dp->dccps_swl, dp->dccps_swh)) {
346                 NET_INC_STATS(LINUX_MIB_OUTOFWINDOWICMPS);
347                 goto out;
348         }
349
350         switch (type) {
351         case ICMP_SOURCE_QUENCH:
352                 /* Just silently ignore these. */
353                 goto out;
354         case ICMP_PARAMETERPROB:
355                 err = EPROTO;
356                 break;
357         case ICMP_DEST_UNREACH:
358                 if (code > NR_ICMP_UNREACH)
359                         goto out;
360
361                 if (code == ICMP_FRAG_NEEDED) { /* PMTU discovery (RFC1191) */
362                         if (!sock_owned_by_user(sk))
363                                 dccp_do_pmtu_discovery(sk, iph, info);
364                         goto out;
365                 }
366
367                 err = icmp_err_convert[code].errno;
368                 break;
369         case ICMP_TIME_EXCEEDED:
370                 err = EHOSTUNREACH;
371                 break;
372         default:
373                 goto out;
374         }
375
376         switch (sk->sk_state) {
377                 struct request_sock *req , **prev;
378         case DCCP_LISTEN:
379                 if (sock_owned_by_user(sk))
380                         goto out;
381                 req = inet_csk_search_req(sk, &prev, dh->dccph_dport,
382                                           iph->daddr, iph->saddr);
383                 if (!req)
384                         goto out;
385
386                 /*
387                  * ICMPs are not backlogged, hence we cannot get an established
388                  * socket here.
389                  */
390                 BUG_TRAP(!req->sk);
391
392                 if (seq != dccp_rsk(req)->dreq_iss) {
393                         NET_INC_STATS_BH(LINUX_MIB_OUTOFWINDOWICMPS);
394                         goto out;
395                 }
396                 /*
397                  * Still in RESPOND, just remove it silently.
398                  * There is no good way to pass the error to the newly
399                  * created socket, and POSIX does not want network
400                  * errors returned from accept().
401                  */
402                 inet_csk_reqsk_queue_drop(sk, req, prev);
403                 goto out;
404
405         case DCCP_REQUESTING:
406         case DCCP_RESPOND:
407                 if (!sock_owned_by_user(sk)) {
408                         DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS);
409                         sk->sk_err = err;
410
411                         sk->sk_error_report(sk);
412
413                         dccp_done(sk);
414                 } else
415                         sk->sk_err_soft = err;
416                 goto out;
417         }
418
419         /* If we've already connected we will keep trying
420          * until we time out, or the user gives up.
421          *
422          * rfc1122 4.2.3.9 allows to consider as hard errors
423          * only PROTO_UNREACH and PORT_UNREACH (well, FRAG_FAILED too,
424          * but it is obsoleted by pmtu discovery).
425          *
426          * Note, that in modern internet, where routing is unreliable
427          * and in each dark corner broken firewalls sit, sending random
428          * errors ordered by their masters even this two messages finally lose
429          * their original sense (even Linux sends invalid PORT_UNREACHs)
430          *
431          * Now we are in compliance with RFCs.
432          *                                                      --ANK (980905)
433          */
434
435         inet = inet_sk(sk);
436         if (!sock_owned_by_user(sk) && inet->recverr) {
437                 sk->sk_err = err;
438                 sk->sk_error_report(sk);
439         } else /* Only an error on timeout */
440                 sk->sk_err_soft = err;
441 out:
442         bh_unlock_sock(sk);
443         sock_put(sk);
444 }
445
446 /* This routine computes an IPv4 DCCP checksum. */
447 void dccp_v4_send_check(struct sock *sk, int len, struct sk_buff *skb)
448 {
449         const struct inet_sock *inet = inet_sk(sk);
450         struct dccp_hdr *dh = dccp_hdr(skb);
451
452         dh->dccph_checksum = dccp_v4_checksum(skb, inet->saddr, inet->daddr);
453 }
454
455 EXPORT_SYMBOL_GPL(dccp_v4_send_check);
456
457 int dccp_v4_send_reset(struct sock *sk, enum dccp_reset_codes code)
458 {
459         struct sk_buff *skb;
460         /*
461          * FIXME: what if rebuild_header fails?
462          * Should we be doing a rebuild_header here?
463          */
464         int err = inet_sk_rebuild_header(sk);
465
466         if (err != 0)
467                 return err;
468
469         skb = dccp_make_reset(sk, sk->sk_dst_cache, code);
470         if (skb != NULL) {
471                 const struct inet_sock *inet = inet_sk(sk);
472
473                 memset(&(IPCB(skb)->opt), 0, sizeof(IPCB(skb)->opt));
474                 err = ip_build_and_send_pkt(skb, sk,
475                                             inet->saddr, inet->daddr, NULL);
476                 if (err == NET_XMIT_CN)
477                         err = 0;
478         }
479
480         return err;
481 }
482
483 static inline u64 dccp_v4_init_sequence(const struct sock *sk,
484                                         const struct sk_buff *skb)
485 {
486         return secure_dccp_sequence_number(skb->nh.iph->daddr,
487                                            skb->nh.iph->saddr,
488                                            dccp_hdr(skb)->dccph_dport,
489                                            dccp_hdr(skb)->dccph_sport);
490 }
491
492 int dccp_v4_conn_request(struct sock *sk, struct sk_buff *skb)
493 {
494         struct inet_request_sock *ireq;
495         struct dccp_sock dp;
496         struct request_sock *req;
497         struct dccp_request_sock *dreq;
498         const __u32 saddr = skb->nh.iph->saddr;
499         const __u32 daddr = skb->nh.iph->daddr;
500         const __u32 service = dccp_hdr_request(skb)->dccph_req_service;
501         struct dccp_skb_cb *dcb = DCCP_SKB_CB(skb);
502         __u8 reset_code = DCCP_RESET_CODE_TOO_BUSY;
503
504         /* Never answer to DCCP_PKT_REQUESTs send to broadcast or multicast */
505         if (((struct rtable *)skb->dst)->rt_flags &
506             (RTCF_BROADCAST | RTCF_MULTICAST)) {
507                 reset_code = DCCP_RESET_CODE_NO_CONNECTION;
508                 goto drop;
509         }
510
511         if (dccp_bad_service_code(sk, service)) {
512                 reset_code = DCCP_RESET_CODE_BAD_SERVICE_CODE;
513                 goto drop;
514         }
515         /*
516          * TW buckets are converted to open requests without
517          * limitations, they conserve resources and peer is
518          * evidently real one.
519          */
520         if (inet_csk_reqsk_queue_is_full(sk))
521                 goto drop;
522
523         /*
524          * Accept backlog is full. If we have already queued enough
525          * of warm entries in syn queue, drop request. It is better than
526          * clogging syn queue with openreqs with exponentially increasing
527          * timeout.
528          */
529         if (sk_acceptq_is_full(sk) && inet_csk_reqsk_queue_young(sk) > 1)
530                 goto drop;
531
532         req = reqsk_alloc(sk->sk_prot->rsk_prot);
533         if (req == NULL)
534                 goto drop;
535
536         /* FIXME: process options */
537
538         dccp_openreq_init(req, &dp, skb);
539
540         ireq = inet_rsk(req);
541         ireq->loc_addr = daddr;
542         ireq->rmt_addr = saddr;
543         req->rcv_wnd    = 100; /* Fake, option parsing will get the
544                                   right value */
545         ireq->opt       = NULL;
546
547         /* 
548          * Step 3: Process LISTEN state
549          *
550          * Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookie
551          *
552          * In fact we defer setting S.GSR, S.SWL, S.SWH to
553          * dccp_create_openreq_child.
554          */
555         dreq = dccp_rsk(req);
556         dreq->dreq_isr     = dcb->dccpd_seq;
557         dreq->dreq_iss     = dccp_v4_init_sequence(sk, skb);
558         dreq->dreq_service = service;
559
560         if (dccp_v4_send_response(sk, req, NULL))
561                 goto drop_and_free;
562
563         inet_csk_reqsk_queue_hash_add(sk, req, DCCP_TIMEOUT_INIT);
564         return 0;
565
566 drop_and_free:
567         reqsk_free(req);
568 drop:
569         DCCP_INC_STATS_BH(DCCP_MIB_ATTEMPTFAILS);
570         dcb->dccpd_reset_code = reset_code;
571         return -1;
572 }
573
574 EXPORT_SYMBOL_GPL(dccp_v4_conn_request);
575
576 /*
577  * The three way handshake has completed - we got a valid ACK or DATAACK -
578  * now create the new socket.
579  *
580  * This is the equivalent of TCP's tcp_v4_syn_recv_sock
581  */
582 struct sock *dccp_v4_request_recv_sock(struct sock *sk, struct sk_buff *skb,
583                                        struct request_sock *req,
584                                        struct dst_entry *dst)
585 {
586         struct inet_request_sock *ireq;
587         struct inet_sock *newinet;
588         struct dccp_sock *newdp;
589         struct sock *newsk;
590
591         if (sk_acceptq_is_full(sk))
592                 goto exit_overflow;
593
594         if (dst == NULL && (dst = inet_csk_route_req(sk, req)) == NULL)
595                 goto exit;
596
597         newsk = dccp_create_openreq_child(sk, req, skb);
598         if (newsk == NULL)
599                 goto exit;
600
601         sk_setup_caps(newsk, dst);
602
603         newdp              = dccp_sk(newsk);
604         newinet            = inet_sk(newsk);
605         ireq               = inet_rsk(req);
606         newinet->daddr     = ireq->rmt_addr;
607         newinet->rcv_saddr = ireq->loc_addr;
608         newinet->saddr     = ireq->loc_addr;
609         newinet->opt       = ireq->opt;
610         ireq->opt          = NULL;
611         newinet->mc_index  = inet_iif(skb);
612         newinet->mc_ttl    = skb->nh.iph->ttl;
613         newinet->id        = jiffies;
614
615         dccp_sync_mss(newsk, dst_mtu(dst));
616
617         __inet_hash(&dccp_hashinfo, newsk, 0);
618         __inet_inherit_port(&dccp_hashinfo, sk, newsk);
619
620         return newsk;
621
622 exit_overflow:
623         NET_INC_STATS_BH(LINUX_MIB_LISTENOVERFLOWS);
624 exit:
625         NET_INC_STATS_BH(LINUX_MIB_LISTENDROPS);
626         dst_release(dst);
627         return NULL;
628 }
629
630 EXPORT_SYMBOL_GPL(dccp_v4_request_recv_sock);
631
632 static struct sock *dccp_v4_hnd_req(struct sock *sk, struct sk_buff *skb)
633 {
634         const struct dccp_hdr *dh = dccp_hdr(skb);
635         const struct iphdr *iph = skb->nh.iph;
636         struct sock *nsk;
637         struct request_sock **prev;
638         /* Find possible connection requests. */
639         struct request_sock *req = inet_csk_search_req(sk, &prev,
640                                                        dh->dccph_sport,
641                                                        iph->saddr, iph->daddr);
642         if (req != NULL)
643                 return dccp_check_req(sk, skb, req, prev);
644
645         nsk = __inet_lookup_established(&dccp_hashinfo,
646                                         iph->saddr, dh->dccph_sport,
647                                         iph->daddr, ntohs(dh->dccph_dport),
648                                         inet_iif(skb));
649         if (nsk != NULL) {
650                 if (nsk->sk_state != DCCP_TIME_WAIT) {
651                         bh_lock_sock(nsk);
652                         return nsk;
653                 }
654                 inet_twsk_put((struct inet_timewait_sock *)nsk);
655                 return NULL;
656         }
657
658         return sk;
659 }
660
661 int dccp_v4_checksum(const struct sk_buff *skb, const u32 saddr,
662                      const u32 daddr)
663 {
664         const struct dccp_hdr* dh = dccp_hdr(skb);
665         int checksum_len;
666         u32 tmp;
667
668         if (dh->dccph_cscov == 0)
669                 checksum_len = skb->len;
670         else {
671                 checksum_len = (dh->dccph_cscov + dh->dccph_x) * sizeof(u32);
672                 checksum_len = checksum_len < skb->len ? checksum_len :
673                                                          skb->len;
674         }
675
676         tmp = csum_partial((unsigned char *)dh, checksum_len, 0);
677         return csum_tcpudp_magic(saddr, daddr, checksum_len,
678                                  IPPROTO_DCCP, tmp);
679 }
680
681 static int dccp_v4_verify_checksum(struct sk_buff *skb,
682                                    const u32 saddr, const u32 daddr)
683 {
684         struct dccp_hdr *dh = dccp_hdr(skb);
685         int checksum_len;
686         u32 tmp;
687
688         if (dh->dccph_cscov == 0)
689                 checksum_len = skb->len;
690         else {
691                 checksum_len = (dh->dccph_cscov + dh->dccph_x) * sizeof(u32);
692                 checksum_len = checksum_len < skb->len ? checksum_len :
693                                                          skb->len;
694         }
695         tmp = csum_partial((unsigned char *)dh, checksum_len, 0);
696         return csum_tcpudp_magic(saddr, daddr, checksum_len,
697                                  IPPROTO_DCCP, tmp) == 0 ? 0 : -1;
698 }
699
700 static struct dst_entry* dccp_v4_route_skb(struct sock *sk,
701                                            struct sk_buff *skb)
702 {
703         struct rtable *rt;
704         struct flowi fl = { .oif = ((struct rtable *)skb->dst)->rt_iif,
705                             .nl_u = { .ip4_u =
706                                       { .daddr = skb->nh.iph->saddr,
707                                         .saddr = skb->nh.iph->daddr,
708                                         .tos = RT_CONN_FLAGS(sk) } },
709                             .proto = sk->sk_protocol,
710                             .uli_u = { .ports =
711                                        { .sport = dccp_hdr(skb)->dccph_dport,
712                                          .dport = dccp_hdr(skb)->dccph_sport }
713                                      }
714                           };
715
716         if (ip_route_output_flow(&rt, &fl, sk, 0)) {
717                 IP_INC_STATS_BH(IPSTATS_MIB_OUTNOROUTES);
718                 return NULL;
719         }
720
721         return &rt->u.dst;
722 }
723
724 static void dccp_v4_ctl_send_reset(struct sk_buff *rxskb)
725 {
726         int err;
727         struct dccp_hdr *rxdh = dccp_hdr(rxskb), *dh;
728         const int dccp_hdr_reset_len = sizeof(struct dccp_hdr) +
729                                        sizeof(struct dccp_hdr_ext) +
730                                        sizeof(struct dccp_hdr_reset);
731         struct sk_buff *skb;
732         struct dst_entry *dst;
733         u64 seqno;
734
735         /* Never send a reset in response to a reset. */
736         if (rxdh->dccph_type == DCCP_PKT_RESET)
737                 return;
738
739         if (((struct rtable *)rxskb->dst)->rt_type != RTN_LOCAL)
740                 return;
741
742         dst = dccp_v4_route_skb(dccp_ctl_socket->sk, rxskb);
743         if (dst == NULL)
744                 return;
745
746         skb = alloc_skb(MAX_DCCP_HEADER + 15, GFP_ATOMIC);
747         if (skb == NULL)
748                 goto out;
749
750         /* Reserve space for headers. */
751         skb_reserve(skb, MAX_DCCP_HEADER);
752         skb->dst = dst_clone(dst);
753
754         skb->h.raw = skb_push(skb, dccp_hdr_reset_len);
755         dh = dccp_hdr(skb);
756         memset(dh, 0, dccp_hdr_reset_len);
757
758         /* Build DCCP header and checksum it. */
759         dh->dccph_type     = DCCP_PKT_RESET;
760         dh->dccph_sport    = rxdh->dccph_dport;
761         dh->dccph_dport    = rxdh->dccph_sport;
762         dh->dccph_doff     = dccp_hdr_reset_len / 4;
763         dh->dccph_x        = 1;
764         dccp_hdr_reset(skb)->dccph_reset_code =
765                                 DCCP_SKB_CB(rxskb)->dccpd_reset_code;
766
767         /* See "8.3.1. Abnormal Termination" in draft-ietf-dccp-spec-11 */
768         seqno = 0;
769         if (DCCP_SKB_CB(rxskb)->dccpd_ack_seq != DCCP_PKT_WITHOUT_ACK_SEQ)
770                 dccp_set_seqno(&seqno, DCCP_SKB_CB(rxskb)->dccpd_ack_seq + 1);
771
772         dccp_hdr_set_seq(dh, seqno);
773         dccp_hdr_set_ack(dccp_hdr_ack_bits(skb),
774                          DCCP_SKB_CB(rxskb)->dccpd_seq);
775
776         dh->dccph_checksum = dccp_v4_checksum(skb, rxskb->nh.iph->saddr,
777                                               rxskb->nh.iph->daddr);
778
779         bh_lock_sock(dccp_ctl_socket->sk);
780         err = ip_build_and_send_pkt(skb, dccp_ctl_socket->sk,
781                                     rxskb->nh.iph->daddr,
782                                     rxskb->nh.iph->saddr, NULL);
783         bh_unlock_sock(dccp_ctl_socket->sk);
784
785         if (err == NET_XMIT_CN || err == 0) {
786                 DCCP_INC_STATS_BH(DCCP_MIB_OUTSEGS);
787                 DCCP_INC_STATS_BH(DCCP_MIB_OUTRSTS);
788         }
789 out:
790          dst_release(dst);
791 }
792
793 int dccp_v4_do_rcv(struct sock *sk, struct sk_buff *skb)
794 {
795         struct dccp_hdr *dh = dccp_hdr(skb);
796
797         if (sk->sk_state == DCCP_OPEN) { /* Fast path */
798                 if (dccp_rcv_established(sk, skb, dh, skb->len))
799                         goto reset;
800                 return 0;
801         }
802
803         /*
804          *  Step 3: Process LISTEN state
805          *     If S.state == LISTEN,
806          *        If P.type == Request or P contains a valid Init Cookie
807          *              option,
808          *           * Must scan the packet's options to check for an Init
809          *              Cookie.  Only the Init Cookie is processed here,
810          *              however; other options are processed in Step 8.  This
811          *              scan need only be performed if the endpoint uses Init
812          *              Cookies *
813          *           * Generate a new socket and switch to that socket *
814          *           Set S := new socket for this port pair
815          *           S.state = RESPOND
816          *           Choose S.ISS (initial seqno) or set from Init Cookie
817          *           Set S.ISR, S.GSR, S.SWL, S.SWH from packet or Init Cookie
818          *           Continue with S.state == RESPOND
819          *           * A Response packet will be generated in Step 11 *
820          *        Otherwise,
821          *           Generate Reset(No Connection) unless P.type == Reset
822          *           Drop packet and return
823          *
824          * NOTE: the check for the packet types is done in
825          *       dccp_rcv_state_process
826          */
827         if (sk->sk_state == DCCP_LISTEN) {
828                 struct sock *nsk = dccp_v4_hnd_req(sk, skb);
829
830                 if (nsk == NULL)
831                         goto discard;
832
833                 if (nsk != sk) {
834                         if (dccp_child_process(sk, nsk, skb))
835                                 goto reset;
836                         return 0;
837                 }
838         }
839
840         if (dccp_rcv_state_process(sk, skb, dh, skb->len))
841                 goto reset;
842         return 0;
843
844 reset:
845         dccp_v4_ctl_send_reset(skb);
846 discard:
847         kfree_skb(skb);
848         return 0;
849 }
850
851 EXPORT_SYMBOL_GPL(dccp_v4_do_rcv);
852
853 int dccp_invalid_packet(struct sk_buff *skb)
854 {
855         const struct dccp_hdr *dh;
856
857         if (skb->pkt_type != PACKET_HOST)
858                 return 1;
859
860         if (!pskb_may_pull(skb, sizeof(struct dccp_hdr))) {
861                 LIMIT_NETDEBUG(KERN_WARNING "DCCP: pskb_may_pull failed\n");
862                 return 1;
863         }
864
865         dh = dccp_hdr(skb);
866
867         /* If the packet type is not understood, drop packet and return */
868         if (dh->dccph_type >= DCCP_PKT_INVALID) {
869                 LIMIT_NETDEBUG(KERN_WARNING "DCCP: invalid packet type\n");
870                 return 1;
871         }
872
873         /*
874          * If P.Data Offset is too small for packet type, or too large for
875          * packet, drop packet and return
876          */
877         if (dh->dccph_doff < dccp_hdr_len(skb) / sizeof(u32)) {
878                 LIMIT_NETDEBUG(KERN_WARNING "DCCP: P.Data Offset(%u) "
879                                             "too small 1\n",
880                                dh->dccph_doff);
881                 return 1;
882         }
883
884         if (!pskb_may_pull(skb, dh->dccph_doff * sizeof(u32))) {
885                 LIMIT_NETDEBUG(KERN_WARNING "DCCP: P.Data Offset(%u) "
886                                             "too small 2\n",
887                                dh->dccph_doff);
888                 return 1;
889         }
890
891         dh = dccp_hdr(skb);
892
893         /*
894          * If P.type is not Data, Ack, or DataAck and P.X == 0 (the packet
895          * has short sequence numbers), drop packet and return
896          */
897         if (dh->dccph_x == 0 &&
898             dh->dccph_type != DCCP_PKT_DATA &&
899             dh->dccph_type != DCCP_PKT_ACK &&
900             dh->dccph_type != DCCP_PKT_DATAACK) {
901                 LIMIT_NETDEBUG(KERN_WARNING "DCCP: P.type (%s) not Data, Ack "
902                                             "nor DataAck and P.X == 0\n",
903                                dccp_packet_name(dh->dccph_type));
904                 return 1;
905         }
906
907         return 0;
908 }
909
910 EXPORT_SYMBOL_GPL(dccp_invalid_packet);
911
912 /* this is called when real data arrives */
913 int dccp_v4_rcv(struct sk_buff *skb)
914 {
915         const struct dccp_hdr *dh;
916         struct sock *sk;
917         int rc;
918
919         /* Step 1: Check header basics: */
920
921         if (dccp_invalid_packet(skb))
922                 goto discard_it;
923
924         /* If the header checksum is incorrect, drop packet and return */
925         if (dccp_v4_verify_checksum(skb, skb->nh.iph->saddr,
926                                     skb->nh.iph->daddr) < 0) {
927                 LIMIT_NETDEBUG(KERN_WARNING "%s: incorrect header checksum\n",
928                                __FUNCTION__);
929                 goto discard_it;
930         }
931
932         dh = dccp_hdr(skb);
933
934         DCCP_SKB_CB(skb)->dccpd_seq  = dccp_hdr_seq(skb);
935         DCCP_SKB_CB(skb)->dccpd_type = dh->dccph_type;
936
937         dccp_pr_debug("%8.8s "
938                       "src=%u.%u.%u.%u@%-5d "
939                       "dst=%u.%u.%u.%u@%-5d seq=%llu",
940                       dccp_packet_name(dh->dccph_type),
941                       NIPQUAD(skb->nh.iph->saddr), ntohs(dh->dccph_sport),
942                       NIPQUAD(skb->nh.iph->daddr), ntohs(dh->dccph_dport),
943                       (unsigned long long) DCCP_SKB_CB(skb)->dccpd_seq);
944
945         if (dccp_packet_without_ack(skb)) {
946                 DCCP_SKB_CB(skb)->dccpd_ack_seq = DCCP_PKT_WITHOUT_ACK_SEQ;
947                 dccp_pr_debug_cat("\n");
948         } else {
949                 DCCP_SKB_CB(skb)->dccpd_ack_seq = dccp_hdr_ack_seq(skb);
950                 dccp_pr_debug_cat(", ack=%llu\n",
951                                   (unsigned long long)
952                                   DCCP_SKB_CB(skb)->dccpd_ack_seq);
953         }
954
955         /* Step 2:
956          *      Look up flow ID in table and get corresponding socket */
957         sk = __inet_lookup(&dccp_hashinfo,
958                            skb->nh.iph->saddr, dh->dccph_sport,
959                            skb->nh.iph->daddr, ntohs(dh->dccph_dport),
960                            inet_iif(skb));
961
962         /* 
963          * Step 2:
964          *      If no socket ...
965          *              Generate Reset(No Connection) unless P.type == Reset
966          *              Drop packet and return
967          */
968         if (sk == NULL) {
969                 dccp_pr_debug("failed to look up flow ID in table and "
970                               "get corresponding socket\n");
971                 goto no_dccp_socket;
972         }
973
974         /* 
975          * Step 2:
976          *      ... or S.state == TIMEWAIT,
977          *              Generate Reset(No Connection) unless P.type == Reset
978          *              Drop packet and return
979          */
980                
981         if (sk->sk_state == DCCP_TIME_WAIT) {
982                 dccp_pr_debug("sk->sk_state == DCCP_TIME_WAIT: "
983                               "do_time_wait\n");
984                 goto do_time_wait;
985         }
986
987         if (!xfrm4_policy_check(sk, XFRM_POLICY_IN, skb)) {
988                 dccp_pr_debug("xfrm4_policy_check failed\n");
989                 goto discard_and_relse;
990         }
991
992         if (sk_filter(sk, skb, 0)) {
993                 dccp_pr_debug("sk_filter failed\n");
994                 goto discard_and_relse;
995         }
996
997         skb->dev = NULL;
998
999         bh_lock_sock(sk);
1000         rc = 0;
1001         if (!sock_owned_by_user(sk))
1002                 rc = dccp_v4_do_rcv(sk, skb);
1003         else
1004                 sk_add_backlog(sk, skb);
1005         bh_unlock_sock(sk);
1006
1007         sock_put(sk);
1008         return rc;
1009
1010 no_dccp_socket:
1011         if (!xfrm4_policy_check(NULL, XFRM_POLICY_IN, skb))
1012                 goto discard_it;
1013         /*
1014          * Step 2:
1015          *              Generate Reset(No Connection) unless P.type == Reset
1016          *              Drop packet and return
1017          */
1018         if (dh->dccph_type != DCCP_PKT_RESET) {
1019                 DCCP_SKB_CB(skb)->dccpd_reset_code =
1020                                         DCCP_RESET_CODE_NO_CONNECTION;
1021                 dccp_v4_ctl_send_reset(skb);
1022         }
1023
1024 discard_it:
1025         /* Discard frame. */
1026         kfree_skb(skb);
1027         return 0;
1028
1029 discard_and_relse:
1030         sock_put(sk);
1031         goto discard_it;
1032
1033 do_time_wait:
1034         inet_twsk_put((struct inet_timewait_sock *)sk);
1035         goto no_dccp_socket;
1036 }
1037
1038 struct inet_connection_sock_af_ops dccp_ipv4_af_ops = {
1039         .queue_xmit     = ip_queue_xmit,
1040         .send_check     = dccp_v4_send_check,
1041         .rebuild_header = inet_sk_rebuild_header,
1042         .conn_request   = dccp_v4_conn_request,
1043         .syn_recv_sock  = dccp_v4_request_recv_sock,
1044         .net_header_len = sizeof(struct iphdr),
1045         .setsockopt     = ip_setsockopt,
1046         .getsockopt     = ip_getsockopt,
1047         .addr2sockaddr  = inet_csk_addr2sockaddr,
1048         .sockaddr_len   = sizeof(struct sockaddr_in),
1049 };
1050
1051 int dccp_v4_init_sock(struct sock *sk)
1052 {
1053         struct dccp_sock *dp = dccp_sk(sk);
1054         static int dccp_ctl_socket_init = 1;
1055
1056         dccp_options_init(&dp->dccps_options);
1057         do_gettimeofday(&dp->dccps_epoch);
1058
1059         if (dp->dccps_options.dccpo_send_ack_vector) {
1060                 dp->dccps_hc_rx_ackvec = dccp_ackvec_alloc(DCCP_MAX_ACKVEC_LEN,
1061                                                            GFP_KERNEL);
1062                 if (dp->dccps_hc_rx_ackvec == NULL)
1063                         return -ENOMEM;
1064         }
1065
1066         /*
1067          * FIXME: We're hardcoding the CCID, and doing this at this point makes
1068          * the listening (master) sock get CCID control blocks, which is not
1069          * necessary, but for now, to not mess with the test userspace apps,
1070          * lets leave it here, later the real solution is to do this in a
1071          * setsockopt(CCIDs-I-want/accept). -acme
1072          */
1073         if (likely(!dccp_ctl_socket_init)) {
1074                 dp->dccps_hc_rx_ccid = ccid_init(dp->dccps_options.dccpo_rx_ccid,
1075                                                  sk);
1076                 dp->dccps_hc_tx_ccid = ccid_init(dp->dccps_options.dccpo_tx_ccid,
1077                                                  sk);
1078                 if (dp->dccps_hc_rx_ccid == NULL ||
1079                     dp->dccps_hc_tx_ccid == NULL) {
1080                         ccid_exit(dp->dccps_hc_rx_ccid, sk);
1081                         ccid_exit(dp->dccps_hc_tx_ccid, sk);
1082                         if (dp->dccps_options.dccpo_send_ack_vector) {
1083                                 dccp_ackvec_free(dp->dccps_hc_rx_ackvec);
1084                                 dp->dccps_hc_rx_ackvec = NULL;
1085                         }
1086                         dp->dccps_hc_rx_ccid = dp->dccps_hc_tx_ccid = NULL;
1087                         return -ENOMEM;
1088                 }
1089         } else
1090                 dccp_ctl_socket_init = 0;
1091
1092         dccp_init_xmit_timers(sk);
1093         inet_csk(sk)->icsk_rto = DCCP_TIMEOUT_INIT;
1094         sk->sk_state = DCCP_CLOSED;
1095         sk->sk_write_space = dccp_write_space;
1096         inet_csk(sk)->icsk_af_ops = &dccp_ipv4_af_ops;
1097         dp->dccps_mss_cache = 536;
1098         dp->dccps_role = DCCP_ROLE_UNDEFINED;
1099         dp->dccps_service = DCCP_SERVICE_INVALID_VALUE;
1100
1101         return 0;
1102 }
1103
1104 EXPORT_SYMBOL_GPL(dccp_v4_init_sock);
1105
1106 int dccp_v4_destroy_sock(struct sock *sk)
1107 {
1108         struct dccp_sock *dp = dccp_sk(sk);
1109
1110         /*
1111          * DCCP doesn't use sk_write_queue, just sk_send_head
1112          * for retransmissions
1113          */
1114         if (sk->sk_send_head != NULL) {
1115                 kfree_skb(sk->sk_send_head);
1116                 sk->sk_send_head = NULL;
1117         }
1118
1119         /* Clean up a referenced DCCP bind bucket. */
1120         if (inet_csk(sk)->icsk_bind_hash != NULL)
1121                 inet_put_port(&dccp_hashinfo, sk);
1122
1123         kfree(dp->dccps_service_list);
1124         dp->dccps_service_list = NULL;
1125
1126         ccid_hc_rx_exit(dp->dccps_hc_rx_ccid, sk);
1127         ccid_hc_tx_exit(dp->dccps_hc_tx_ccid, sk);
1128         if (dp->dccps_options.dccpo_send_ack_vector) {
1129                 dccp_ackvec_free(dp->dccps_hc_rx_ackvec);
1130                 dp->dccps_hc_rx_ackvec = NULL;
1131         }
1132         ccid_exit(dp->dccps_hc_rx_ccid, sk);
1133         ccid_exit(dp->dccps_hc_tx_ccid, sk);
1134         dp->dccps_hc_rx_ccid = dp->dccps_hc_tx_ccid = NULL;
1135
1136         return 0;
1137 }
1138
1139 EXPORT_SYMBOL_GPL(dccp_v4_destroy_sock);
1140
1141 static void dccp_v4_reqsk_destructor(struct request_sock *req)
1142 {
1143         kfree(inet_rsk(req)->opt);
1144 }
1145
1146 static struct request_sock_ops dccp_request_sock_ops = {
1147         .family         = PF_INET,
1148         .obj_size       = sizeof(struct dccp_request_sock),
1149         .rtx_syn_ack    = dccp_v4_send_response,
1150         .send_ack       = dccp_v4_reqsk_send_ack,
1151         .destructor     = dccp_v4_reqsk_destructor,
1152         .send_reset     = dccp_v4_ctl_send_reset,
1153 };
1154
1155 static struct timewait_sock_ops dccp_timewait_sock_ops = {
1156         .twsk_obj_size  = sizeof(struct inet_timewait_sock),
1157 };
1158
1159 struct proto dccp_prot = {
1160         .name                   = "DCCP",
1161         .owner                  = THIS_MODULE,
1162         .close                  = dccp_close,
1163         .connect                = dccp_v4_connect,
1164         .disconnect             = dccp_disconnect,
1165         .ioctl                  = dccp_ioctl,
1166         .init                   = dccp_v4_init_sock,
1167         .setsockopt             = dccp_setsockopt,
1168         .getsockopt             = dccp_getsockopt,
1169         .sendmsg                = dccp_sendmsg,
1170         .recvmsg                = dccp_recvmsg,
1171         .backlog_rcv            = dccp_v4_do_rcv,
1172         .hash                   = dccp_v4_hash,
1173         .unhash                 = dccp_unhash,
1174         .accept                 = inet_csk_accept,
1175         .get_port               = dccp_v4_get_port,
1176         .shutdown               = dccp_shutdown,
1177         .destroy                = dccp_v4_destroy_sock,
1178         .orphan_count           = &dccp_orphan_count,
1179         .max_header             = MAX_DCCP_HEADER,
1180         .obj_size               = sizeof(struct dccp_sock),
1181         .rsk_prot               = &dccp_request_sock_ops,
1182         .twsk_prot              = &dccp_timewait_sock_ops,
1183 };
1184
1185 EXPORT_SYMBOL_GPL(dccp_prot);