Tomato 1.26 beta(1766)
[tomato/tomato-null.git] / release / src / router / rp-l2tp / tunnel.c
blobd0123d3617a6ba3ec797d58855968e1004cdaf7c
1 /***********************************************************************
3 * tunnel.c
5 * Functions for manipulating L2TP tunnel objects.
7 * Copyright (C) 2002 Roaring Penguin Software Inc.
9 * This software may be distributed under the terms of the GNU General
10 * Public License, Version 2, or (at your option) any later version.
12 * LIC: GPL
14 ***********************************************************************/
16 static char const RCSID[] =
17 "$Id: tunnel.c,v 1.2.40.1 2005/08/08 12:05:25 honor Exp $";
19 #include "l2tp.h"
20 #include <stddef.h>
21 #include <stdarg.h>
22 #include <stdio.h>
23 #include <string.h>
24 #include <cyutils.h>
26 /* Hash tables of all tunnels */
27 static hash_table tunnels_by_my_id;
28 static hash_table tunnels_by_peer_address;
30 static uint16_t tunnel_make_tid(void);
31 static l2tp_tunnel *tunnel_new(EventSelector *es);
32 static void tunnel_free(l2tp_tunnel *tunnel);
33 static int tunnel_send_SCCRQ(l2tp_tunnel *tunnel);
34 static void tunnel_handle_SCCRQ(l2tp_dgram *dgram,
35 EventSelector *es,
36 struct sockaddr_in *from);
37 static void tunnel_handle_SCCRP(l2tp_tunnel *tunnel,
38 l2tp_dgram *dgram);
39 static void tunnel_handle_SCCCN(l2tp_tunnel *tunnel,
40 l2tp_dgram *dgram);
41 static void tunnel_handle_ICRQ(l2tp_tunnel *tunnel,
42 l2tp_dgram *dgram);
43 static void tunnel_process_received_datagram(l2tp_tunnel *tunnel,
44 l2tp_dgram *dgram);
45 static void tunnel_schedule_ack(l2tp_tunnel *tunnel);
46 static void tunnel_do_ack(EventSelector *es, int fd, unsigned int flags,
47 void *data);
48 static void tunnel_handle_timeout(EventSelector *es, int fd,
49 unsigned int flags, void *data);
50 static void tunnel_finally_cleanup(EventSelector *es, int fd,
51 unsigned int flags, void *data);
53 static void tunnel_do_hello(EventSelector *es, int fd,
54 unsigned int flags, void *data);
56 static void tunnel_dequeue_acked_packets(l2tp_tunnel *tunnel);
58 static void tunnel_send_StopCCN(l2tp_tunnel *tunnel,
59 int result_code,
60 int error_code,
61 char const *fmt, ...);
62 static void tunnel_schedule_destruction(l2tp_tunnel *tunnel);
63 static int tunnel_set_params(l2tp_tunnel *tunnel, l2tp_dgram *dgram);
65 static int tunnel_outstanding_frames(l2tp_tunnel *tunnel);
66 static void tunnel_setup_hello(l2tp_tunnel *tunnel);
67 static void tunnel_tell_sessions_tunnel_open(l2tp_tunnel *tunnel);
68 static l2tp_tunnel *tunnel_establish(l2tp_peer *peer, EventSelector *es);
69 static l2tp_tunnel *tunnel_find_bypeer(struct sockaddr_in addr);
71 static char *state_names[] = {
72 "idle", "wait-ctl-reply", "wait-ctl-conn", "established",
73 "received-stop-ccn", "sent-stop-ccn"
76 //#define VENDOR_STR "Roaring Penguin Software Inc."
77 #define VENDOR_STR L2TP_VENDOR
78 #define HOSTNAME_STR L2TP_HOSTNAME //2005-04-14 by kanki
80 /* Comparison of serial numbers according to RFC 1982 */
81 #define SERIAL_GT(a, b) \
82 (((a) > (b) && (a) - (b) < 32768) || ((a) < (b) && (b) - (a) > 32768))
84 #define SERIAL_LT(a, b) \
85 (((a) < (b) && (b) - (a) < 32768) || ((a) > (b) && (a) - (b) > 32768))
87 /**********************************************************************
88 * %FUNCTION: tunnel_set_state
89 * %ARGUMENTS:
90 * tunnel -- the tunnel
91 * state -- new state
92 * %RETURNS:
93 * Nothing
94 ***********************************************************************/
95 static void
96 tunnel_set_state(l2tp_tunnel *tunnel, int state)
98 if (state == tunnel->state) return;
99 DBG(l2tp_db(DBG_TUNNEL, "tunnel(%s) state %s -> %s\n",
100 l2tp_debug_tunnel_to_str(tunnel),
101 state_names[tunnel->state],
102 state_names[state]));
103 tunnel->state = state;
106 /**********************************************************************
107 * %FUNCTION: tunnel_find_by_my_id
108 * %ARGUMENTS:
109 * id -- tunnel ID
110 * %RETURNS:
111 * A tunnel whose my_id field equals id, or NULL if no such tunnel
112 ***********************************************************************/
113 l2tp_tunnel *
114 l2tp_tunnel_find_by_my_id(uint16_t id)
116 l2tp_tunnel candidate;
117 candidate.my_id = id;
118 return hash_find(&tunnels_by_my_id, &candidate);
121 /**********************************************************************
122 * %FUNCTION: tunnel_find_bypeer
123 * %ARGUMENTS:
124 * addr -- peer address
125 * %RETURNS:
126 * A tunnel whose peer_addr field equals addr, or NULL if no such tunnel
127 ***********************************************************************/
128 static l2tp_tunnel *
129 tunnel_find_bypeer(struct sockaddr_in addr)
131 l2tp_tunnel candidate;
132 candidate.peer_addr = addr;
133 return hash_find(&tunnels_by_peer_address, &candidate);
136 /**********************************************************************
137 * %FUNCTION: tunnel_flow_control_stats
138 * %ARGUMENTS:
139 * tunnel -- a tunnel
140 * %RETURNS:
141 * A string representing flow-control info (used for debugging)
142 ***********************************************************************/
143 static char const *
144 tunnel_flow_control_stats(l2tp_tunnel *tunnel)
146 static char buf[256];
148 snprintf(buf, sizeof(buf), "rws=%d cwnd=%d ssthresh=%d outstanding=%d",
149 (int) tunnel->peer_rws,
150 tunnel->cwnd,
151 tunnel->ssthresh,
152 tunnel_outstanding_frames(tunnel));
153 return buf;
156 /**********************************************************************
157 * %FUNCTION: tunnel_outstanding_frames
158 * %ARGUMENTS:
159 * tunnel -- a tunnel
160 * %RETURNS:
161 * The number of outstanding (transmitted, but not ack'd) frames.
162 ***********************************************************************/
163 static int
164 tunnel_outstanding_frames(l2tp_tunnel *tunnel)
166 int Ns = (int) tunnel->Ns_on_wire;
167 int Nr = (int) tunnel->peer_Nr;
168 if (Ns >= Nr) return Ns - Nr;
169 return 65536 - Nr + Ns;
172 /**********************************************************************
173 * %FUNCTION: tunnel_make_tid
174 * %ARGUMENTS:
175 * None
176 * %RETURNS:
177 * An unused, random tunnel ID.
178 ***********************************************************************/
179 static uint16_t tunnel_make_tid(void)
181 uint16_t id;
182 for(;;) {
183 L2TP_RANDOM_FILL(id);
184 if (!id) continue;
185 if (!l2tp_tunnel_find_by_my_id(id)) return id;
189 /**********************************************************************
190 * %FUNCTION: tunnel_enqueue_dgram
191 * %ARGUMENTS:
192 * tunnel -- the tunnel
193 * dgram -- an L2TP datagram to place at the tail of the transmit queue
194 * %RETURNS:
195 * Nothing
196 * %DESCRIPTION:
197 * Adds datagram to end of transmit queue.
198 ***********************************************************************/
199 static void
200 tunnel_enqueue_dgram(l2tp_tunnel *tunnel,
201 l2tp_dgram *dgram)
203 dgram->next = NULL;
204 if (tunnel->xmit_queue_tail) {
205 tunnel->xmit_queue_tail->next = dgram;
206 tunnel->xmit_queue_tail = dgram;
207 } else {
208 tunnel->xmit_queue_head = dgram;
209 tunnel->xmit_queue_tail = dgram;
211 if (!tunnel->xmit_new_dgrams) {
212 tunnel->xmit_new_dgrams = dgram;
215 dgram->Ns = tunnel->Ns;
216 tunnel->Ns++;
217 DBG(l2tp_db(DBG_FLOW, "tunnel_enqueue_dgram(%s, %s) %s\n",
218 l2tp_debug_tunnel_to_str(tunnel),
219 l2tp_debug_message_type_to_str(dgram->msg_type),
220 tunnel_flow_control_stats(tunnel)));
224 /**********************************************************************
225 * %FUNCTION: tunnel_dequeue_head
226 * %ARGUMENTS:
227 * tunnel -- the tunnel
228 * %RETURNS:
229 * Nothing
230 * %DESCRIPTION:
231 * Dequeues datagram from head of transmit queue and frees it
232 ***********************************************************************/
233 static void
234 tunnel_dequeue_head(l2tp_tunnel *tunnel)
236 l2tp_dgram *dgram = tunnel->xmit_queue_head;
237 if (dgram) {
238 tunnel->xmit_queue_head = dgram->next;
239 if (tunnel->xmit_new_dgrams == dgram) {
240 tunnel->xmit_new_dgrams = dgram->next;
242 if (tunnel->xmit_queue_tail == dgram) {
243 tunnel->xmit_queue_tail = NULL;
245 l2tp_dgram_free(dgram);
249 /**********************************************************************
250 * %FUNCTION: tunnel_xmit_queued_messages
251 * %ARGUMENTS:
252 * tunnel -- the tunnel
253 * %RETURNS:
254 * Nothing
255 * %DESCRIPTION:
256 * Transmits as many control messages as possible from the queue.
257 ***********************************************************************/
258 static void
259 tunnel_xmit_queued_messages(l2tp_tunnel *tunnel)
261 l2tp_dgram *dgram;
262 struct timeval t;
264 dgram = tunnel->xmit_new_dgrams;
265 if (!dgram) return;
267 DBG(l2tp_db(DBG_FLOW, "xmit_queued(%s): %s\n",
268 l2tp_debug_tunnel_to_str(tunnel),
269 tunnel_flow_control_stats(tunnel)));
270 while (dgram) {
271 /* If window is closed, we can't transmit anything */
272 if (tunnel_outstanding_frames(tunnel) >= tunnel->cwnd) {
273 break;
276 /* Update Nr */
277 dgram->Nr = tunnel->Nr;
279 /* Tid might have changed if call was initiated before
280 tunnel establishment was complete */
281 dgram->tid = tunnel->assigned_id;
283 if (l2tp_dgram_send_to_wire(dgram, &tunnel->peer_addr) < 0) {
284 break;
287 /* Cancel any pending ack */
288 if (tunnel->ack_handler) {
289 Event_DelHandler(tunnel->es, tunnel->ack_handler);
290 tunnel->ack_handler = NULL;
293 tunnel->xmit_new_dgrams = dgram->next;
294 tunnel->Ns_on_wire = dgram->Ns + 1;
295 DBG(l2tp_db(DBG_FLOW, "loop in xmit_queued(%s): %s\n",
296 l2tp_debug_tunnel_to_str(tunnel),
297 tunnel_flow_control_stats(tunnel)));
298 dgram = dgram->next;
301 t.tv_sec = tunnel->timeout;
302 t.tv_usec = 0;
304 /* Set retransmission timer */
305 if (tunnel->timeout_handler) {
306 Event_ChangeTimeout(tunnel->timeout_handler, t);
307 } else {
308 tunnel->timeout_handler =
309 Event_AddTimerHandler(tunnel->es, t,
310 tunnel_handle_timeout, tunnel);
314 /**********************************************************************
315 * %FUNCTION: tunnel_xmit_control_message
316 * %ARGUMENTS:
317 * tunnel -- the tunnel
318 * dgram -- the datagram to transmit. After return from this
319 * function, the tunnel "owns" the dgram and the caller should
320 * no longer use it.
321 * %RETURNS:
322 * Nothing
323 * %DESCRIPTION:
324 * Transmits a control message. If there is no room in the transmit
325 * window, queues the message.
326 ***********************************************************************/
327 void
328 l2tp_tunnel_xmit_control_message(l2tp_tunnel *tunnel,
329 l2tp_dgram *dgram)
331 /* Queue the datagram in case we need to retransmit it */
332 tunnel_enqueue_dgram(tunnel, dgram);
334 /* Run the queue */
335 tunnel_xmit_queued_messages(tunnel);
338 static unsigned int
339 tunnel_compute_peerhash(void *data)
341 return (unsigned int) (((l2tp_tunnel *)data)->peer_addr.sin_addr.s_addr);
344 static int
345 tunnel_compare_peer(void *d1, void *d2)
347 return (((l2tp_tunnel *)d1)->peer_addr.sin_addr.s_addr) !=
348 (((l2tp_tunnel *)d2)->peer_addr.sin_addr.s_addr);
351 /**********************************************************************
352 * %FUNCTION: tunnel_compute_hash_my_id
353 * %ARGUMENTS:
354 * data -- a void pointer which is really a tunnel
355 * %RETURNS:
356 * My tunnel ID
357 ***********************************************************************/
358 static unsigned int
359 tunnel_compute_hash_my_id(void *data)
361 return (unsigned int) (((l2tp_tunnel *) data)->my_id);
364 /**********************************************************************
365 * %FUNCTION: tunnel_compare_my_id
366 * %ARGUMENTS:
367 * item1 -- first tunnel
368 * item2 -- second tunnel
369 * %RETURNS:
370 * 0 if both tunnels have same ID, non-zero otherwise
371 ***********************************************************************/
372 static int
373 tunnel_compare_my_id(void *item1, void *item2)
375 return ((l2tp_tunnel *) item1)->my_id != ((l2tp_tunnel *) item2)->my_id;
378 /**********************************************************************
379 * %FUNCTION: tunnel_cleanup
380 * %ARGUMENTS:
381 * data -- event selector
382 * %RETURNS:
383 * Nothing
384 * %DESCRIPTION:
385 * Shuts down all tunnels and waits for them to exit
386 ***********************************************************************/
387 static void
388 tunnel_cleanup(void *data)
390 EventSelector *es = (EventSelector *) data;
391 int i;
393 /* Stop all tunnels */
394 l2tp_tunnel_stop_all("Shutting down");
396 while (hash_num_entries(&tunnels_by_my_id)) {
397 i = Event_HandleEvent(es);
398 if (i < 0) {
399 exit(EXIT_FAILURE);
404 /**********************************************************************
405 * %FUNCTION: tunnel_init
406 * %ARGUMENTS:
407 * es -- event selector
408 * %RETURNS:
409 * Nothing
410 * %DESCRIPTION:
411 * Initializes static tunnel data structures.
412 ***********************************************************************/
413 void
414 l2tp_tunnel_init(EventSelector *es)
416 hash_init(&tunnels_by_my_id,
417 offsetof(l2tp_tunnel, hash_by_my_id),
418 tunnel_compute_hash_my_id,
419 tunnel_compare_my_id);
420 hash_init(&tunnels_by_peer_address,
421 offsetof(l2tp_tunnel, hash_by_peer),
422 tunnel_compute_peerhash,
423 tunnel_compare_peer);
425 l2tp_register_shutdown_handler(tunnel_cleanup, es);
428 /**********************************************************************
429 * %FUNCTION: tunnel_new
430 * %ARGUMENTS:
431 * es -- event selector
432 * %RETURNS:
433 * A newly-allocated and initialized l2tp_tunnel object
434 ***********************************************************************/
435 static l2tp_tunnel *
436 tunnel_new(EventSelector *es)
438 l2tp_tunnel *tunnel = malloc(sizeof(l2tp_tunnel));
439 if (!tunnel) return NULL;
441 memset(tunnel, 0, sizeof(l2tp_tunnel));
442 l2tp_session_hash_init(&tunnel->sessions_by_my_id);
443 tunnel->rws = 4;
444 tunnel->peer_rws = 1;
445 tunnel->es = es;
446 tunnel->timeout = 1;
447 tunnel->my_id = tunnel_make_tid();
448 tunnel->ssthresh = 1;
449 tunnel->cwnd = 1;
451 hash_insert(&tunnels_by_my_id, tunnel);
452 DBG(l2tp_db(DBG_TUNNEL, "tunnel_new() -> %s\n", l2tp_debug_tunnel_to_str(tunnel)));
453 return tunnel;
456 /**********************************************************************
457 * %FUNCTION: tunnel_free
458 * %ARGUMENTS:
459 * tunnel -- tunnel to free
460 * %RETURNS:
461 * Nothing
462 * %DESCRIPTION:
463 * Frees all memory used by tunnel
464 ***********************************************************************/
465 static void
466 tunnel_free(l2tp_tunnel *tunnel)
468 void *cursor;
469 l2tp_session *ses;
470 EventSelector *es = tunnel->es;
472 DBG(l2tp_db(DBG_TUNNEL, "tunnel_free(%s)\n", l2tp_debug_tunnel_to_str(tunnel)));
474 hash_remove(&tunnels_by_my_id, tunnel);
475 hash_remove(&tunnels_by_peer_address, tunnel);
477 for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
478 ses ;
479 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
480 l2tp_session_free(ses, "Tunnel closing down", 1);
482 if (tunnel->hello_handler) Event_DelHandler(es, tunnel->hello_handler);
483 if (tunnel->timeout_handler) Event_DelHandler(es, tunnel->timeout_handler);
484 if (tunnel->ack_handler) Event_DelHandler(es, tunnel->ack_handler);
486 while(tunnel->xmit_queue_head) {
487 tunnel_dequeue_head(tunnel);
489 memset(tunnel, 0, sizeof(l2tp_tunnel));
490 free(tunnel);
493 /**********************************************************************
494 * %FUNCTION: tunnel_establish
495 * %ARGUMENTS:
496 * peer -- peer with which to establish tunnel
497 * es -- event selector for event loop
498 * %RETURNS:
499 * A newly-allocated tunnel, or NULL on error.
500 * %DESCRIPTION:
501 * Begins tunnel establishment to peer.
502 ***********************************************************************/
503 static l2tp_tunnel *
504 tunnel_establish(l2tp_peer *peer, EventSelector *es)
506 l2tp_tunnel *tunnel;
508 tunnel = tunnel_new(es);
509 if (!tunnel) return NULL;
511 tunnel->peer = peer;
512 tunnel->peer_addr = peer->addr;
514 hash_insert(&tunnels_by_peer_address, tunnel);
515 tunnel_send_SCCRQ(tunnel);
516 tunnel_set_state(tunnel, TUNNEL_WAIT_CTL_REPLY);
517 return tunnel;
520 /**********************************************************************
521 * %FUNCTION: tunnel_send_SCCRQ
522 * %ARGUMENTS:
523 * tunnel -- the tunnel we wish to establish
524 * %RETURNS:
525 * 0 if we handed the datagram off to control transport, -1 otherwise.
526 * %DESCRIPTION:
527 * Sends SCCRQ to establish a tunnel.
528 ***********************************************************************/
529 static int
530 tunnel_send_SCCRQ(l2tp_tunnel *tunnel)
532 uint16_t u16;
533 uint32_t u32;
534 unsigned char tie_breaker[8];
535 unsigned char challenge[16];
536 int old_hide;
537 // char *hostname;
539 l2tp_dgram *dgram = l2tp_dgram_new_control(MESSAGE_SCCRQ, 0, 0);
540 if (!dgram) return -1;
542 /* Add the AVP's */
543 /* HACK! Cisco equipment cannot handle hidden AVP's in SCCRQ.
544 So we temporarily disable AVP hiding */
545 old_hide = tunnel->peer->hide_avps;
546 tunnel->peer->hide_avps = 0;
548 /* Protocol version */
549 u16 = htons(0x0100);
550 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
551 sizeof(u16), VENDOR_IETF, AVP_PROTOCOL_VERSION, &u16);
553 /* Framing capabilities -- hard-coded as sync and async */
554 u32 = htonl(3);
555 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
556 sizeof(u32), VENDOR_IETF, AVP_FRAMING_CAPABILITIES, &u32);
558 //hostname = tunnel->peer->hostname ? tunnel->peer->hostname : Hostname; //2005-04-14 by kanki
560 /* Host name */
561 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
562 //strlen(hostname), VENDOR_IETF, AVP_HOST_NAME, //2005-04-14 by kanki
563 //hostname);
564 strlen(HOSTNAME_STR), VENDOR_IETF, AVP_HOST_NAME,
565 HOSTNAME_STR);
567 /* Assigned ID */
568 u16 = htons(tunnel->my_id);
569 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
570 sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
572 /* Receive window size */
573 u16 = htons(tunnel->rws);
574 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
575 sizeof(u16), VENDOR_IETF, AVP_RECEIVE_WINDOW_SIZE, &u16);
577 /* Tie-breaker */
578 l2tp_random_fill(tie_breaker, sizeof(tie_breaker));
579 l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
580 sizeof(tie_breaker), VENDOR_IETF, AVP_TIE_BREAKER,
581 tie_breaker);
583 /* Vendor name */
584 l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
585 strlen(VENDOR_STR), VENDOR_IETF,
586 AVP_VENDOR_NAME, VENDOR_STR);
588 /* Challenge */
589 if (tunnel->peer->secret_len) {
590 l2tp_random_fill(challenge, sizeof(challenge));
591 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
592 sizeof(challenge), VENDOR_IETF,
593 AVP_CHALLENGE, challenge);
595 /* Compute and save expected response */
596 l2tp_auth_gen_response(MESSAGE_SCCRP, tunnel->peer->secret,
597 challenge, sizeof(challenge), tunnel->expected_response);
600 tunnel->peer->hide_avps = old_hide;
601 /* And ship it out */
602 l2tp_tunnel_xmit_control_message(tunnel, dgram);
603 return 1;
606 /**********************************************************************
607 * %FUNCTION: tunnel_handle_received_control_datagram
608 * %ARGUMENTS:
609 * dgram -- received datagram
610 * es -- event selector
611 * from -- address of sender
612 * %RETURNS:
613 * Nothing
614 * %DESCRIPTION:
615 * Handles a received control datagram
616 ***********************************************************************/
617 void
618 l2tp_tunnel_handle_received_control_datagram(l2tp_dgram *dgram,
619 EventSelector *es,
620 struct sockaddr_in *from)
622 l2tp_tunnel *tunnel;
624 /* If it's SCCRQ, then handle it */
625 if (dgram->msg_type == MESSAGE_SCCRQ) {
626 tunnel_handle_SCCRQ(dgram, es, from);
627 return;
630 /* Find the tunnel to which it refers */
631 if (dgram->tid == 0) {
632 l2tp_set_errmsg("Invalid control message - tunnel ID = 0");
633 return;
635 tunnel = l2tp_tunnel_find_by_my_id(dgram->tid);
637 if (!tunnel) {
638 /* TODO: Send error message back? */
639 l2tp_set_errmsg("Invalid control message - unknown tunnel ID %d",
640 (int) dgram->tid);
641 return;
644 /* Verify that source address is the tunnel's peer */
645 if (tunnel->peer && tunnel->peer->validate_peer_ip) {
646 if (from->sin_addr.s_addr != tunnel->peer_addr.sin_addr.s_addr) {
647 l2tp_set_errmsg("Invalid control message for tunnel %s - not sent from peer",
648 l2tp_debug_tunnel_to_str(tunnel));
649 return;
653 /* Set port for replies */
654 tunnel->peer_addr.sin_port = from->sin_port;
656 /* Schedule an ACK for 100ms from now, but do not ack ZLB's */
657 if (dgram->msg_type != MESSAGE_ZLB) {
658 tunnel_schedule_ack(tunnel);
661 /* If it's an old datagram, ignore it */
662 if (dgram->Ns != tunnel->Nr) {
663 if (SERIAL_LT(dgram->Ns, tunnel->Nr)) {
664 /* Old packet: Drop it */
665 /* Throw away ack'd packets in our xmit queue */
666 tunnel_dequeue_acked_packets(tunnel);
667 return;
669 /* Out-of-order packet or intermediate dropped packets.
670 TODO: Look into handling this better */
671 return;
674 /* Do not increment if we got ZLB */
675 if (dgram->msg_type != MESSAGE_ZLB) {
676 tunnel->Nr++;
679 /* Update peer_Nr */
680 if (SERIAL_GT(dgram->Nr, tunnel->peer_Nr)) {
681 tunnel->peer_Nr = dgram->Nr;
684 /* Reschedule HELLO handler for 60 seconds in future */
685 if (tunnel->state != TUNNEL_RECEIVED_STOP_CCN &&
686 tunnel->state != TUNNEL_SENT_STOP_CCN &&
687 tunnel->hello_handler != NULL) {
688 struct timeval t;
689 t.tv_sec = 60;
690 t.tv_usec = 0;
691 Event_ChangeTimeout(tunnel->hello_handler, t);
694 /* Reset retransmission stuff */
695 tunnel->retransmissions = 0;
696 tunnel->timeout = 1;
698 /* Throw away ack'd packets in our xmit queue */
699 tunnel_dequeue_acked_packets(tunnel);
701 /* Let the specific tunnel handle it */
702 tunnel_process_received_datagram(tunnel, dgram);
704 /* Run the xmit queue -- window may have opened */
705 tunnel_xmit_queued_messages(tunnel);
707 /* Destroy tunnel if required and if xmit queue empty */
708 if (!tunnel->xmit_queue_head) {
709 if (tunnel->timeout_handler) {
710 Event_DelHandler(tunnel->es, tunnel->timeout_handler);
711 tunnel->timeout_handler = NULL;
713 if (tunnel->state == TUNNEL_RECEIVED_STOP_CCN) {
714 tunnel_schedule_destruction(tunnel);
715 } else if (tunnel->state == TUNNEL_SENT_STOP_CCN) {
716 /* Our stop-CCN has been ack'd, destroy NOW */
717 tunnel_free(tunnel);
722 /**********************************************************************
723 * %FUNCTION: tunnel_handle_SCCRQ
724 * %ARGUMENTS:
725 * dgram -- the received datagram
726 * es -- event selector
727 * from -- address of sender
728 * %RETURNS:
729 * Nothing
730 * %DESCRIPTION:
731 * Handles an incoming SCCRQ
732 ***********************************************************************/
733 static void
734 tunnel_handle_SCCRQ(l2tp_dgram *dgram,
735 EventSelector *es,
736 struct sockaddr_in *from)
738 l2tp_tunnel *tunnel = NULL;
740 uint16_t u16;
741 uint32_t u32;
742 unsigned char challenge[16];
743 // char *hostname;
745 /* TODO: Check if this is a retransmitted SCCRQ */
746 /* Allocate a tunnel */
747 tunnel = tunnel_new(es);
748 if (!tunnel) {
749 l2tp_set_errmsg("Unable to allocate new tunnel");
750 return;
753 tunnel->peer_addr = *from;
755 hash_insert(&tunnels_by_peer_address, tunnel);
757 /* We've received our first control datagram (SCCRQ) */
758 tunnel->Nr = 1;
760 if (tunnel_set_params(tunnel, dgram) < 0) return;
762 /* Hunky-dory. Send SCCRP */
763 dgram = l2tp_dgram_new_control(MESSAGE_SCCRP, tunnel->assigned_id, 0);
764 if (!dgram) {
765 /* Doh! Out of resources. Not much chance of StopCCN working... */
766 tunnel_send_StopCCN(tunnel,
767 RESULT_GENERAL_ERROR, ERROR_OUT_OF_RESOURCES,
768 "Out of memory");
769 return;
772 /* Protocol version */
773 u16 = htons(0x0100);
774 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
775 sizeof(u16), VENDOR_IETF, AVP_PROTOCOL_VERSION, &u16);
777 /* Framing capabilities -- hard-coded as sync and async */
778 u32 = htonl(3);
779 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
780 sizeof(u32), VENDOR_IETF, AVP_FRAMING_CAPABILITIES, &u32);
782 //hostname = tunnel->peer->hostname ? tunnel->peer->hostname : Hostname; //2005-04-14 by kanki
784 /* Host name */
785 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
786 //strlen(hostname), VENDOR_IETF, AVP_HOST_NAME, //2005-04-14 by kanki
787 //hostname);
788 strlen(HOSTNAME_STR), VENDOR_IETF, AVP_HOST_NAME,
789 HOSTNAME_STR);
791 /* Assigned ID */
792 u16 = htons(tunnel->my_id);
793 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
794 sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
796 /* Receive window size */
797 u16 = htons(tunnel->rws);
798 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
799 sizeof(u16), VENDOR_IETF, AVP_RECEIVE_WINDOW_SIZE, &u16);
801 /* Vendor name */
802 l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
803 strlen(VENDOR_STR), VENDOR_IETF,
804 AVP_VENDOR_NAME, VENDOR_STR);
806 if (tunnel->peer->secret_len) {
807 /* Response */
808 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
809 MD5LEN, VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
810 tunnel->response);
812 /* Challenge */
813 l2tp_random_fill(challenge, sizeof(challenge));
814 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
815 sizeof(challenge), VENDOR_IETF,
816 AVP_CHALLENGE, challenge);
818 /* Compute and save expected response */
819 l2tp_auth_gen_response(MESSAGE_SCCCN, tunnel->peer->secret,
820 challenge, sizeof(challenge), tunnel->expected_response);
823 tunnel_set_state(tunnel, TUNNEL_WAIT_CTL_CONN);
825 /* And ship it out */
826 l2tp_tunnel_xmit_control_message(tunnel, dgram);
829 /**********************************************************************
830 * %FUNCTION: tunnel_schedule_ack
831 * %ARGUMENTS:
832 * tunnel -- the tunnel
833 * %RETURNS:
834 * Nothing
835 * %DESCRIPTION:
836 * Schedules an ack for 100ms from now. The hope is we'll be able to
837 * piggy-back the ack on a packet in the queue; if not, we'll send a ZLB.
838 ***********************************************************************/
839 static void
840 tunnel_schedule_ack(l2tp_tunnel *tunnel)
842 struct timeval t;
844 DBG(l2tp_db(DBG_FLOW, "tunnel_schedule_ack(%s)\n",
845 l2tp_debug_tunnel_to_str(tunnel)));
846 /* Already scheduled? Do nothing */
847 if (tunnel->ack_handler) return;
849 t.tv_sec = 0;
850 t.tv_usec = 100000;
851 tunnel->ack_handler = Event_AddTimerHandler(tunnel->es,
852 t, tunnel_do_ack, tunnel);
855 /**********************************************************************
856 * %FUNCTION: tunnel_do_ack
857 * %ARGUMENTS:
858 * es -- event selector
859 * fd, flags -- not used
860 * data -- pointer to tunnel which needs ack
861 * %RETURNS:
862 * Nothing
863 * %DESCRIPTION:
864 * If there is a frame on our queue, update it's Nr and run queue; if not,
865 * send a ZLB immediately.
866 ***********************************************************************/
867 static void
868 tunnel_do_ack(EventSelector *es,
869 int fd,
870 unsigned int flags,
871 void *data)
873 l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
875 /* Ack handler has fired */
876 tunnel->ack_handler = NULL;
878 DBG(l2tp_db(DBG_FLOW, "tunnel_do_ack(%s)\n",
879 l2tp_debug_tunnel_to_str(tunnel)));
881 /* If nothing is on the queue, add a ZLB */
882 /* Or, if we cannot transmit because of flow-control, send ZLB */
883 if (!tunnel->xmit_new_dgrams ||
884 tunnel_outstanding_frames(tunnel) >= tunnel->cwnd) {
885 tunnel_send_ZLB(tunnel);
886 return;
889 /* Run the queue */
890 tunnel_xmit_queued_messages(tunnel);
893 /**********************************************************************
894 * %FUNCTION: tunnel_dequeue_acked_packets
895 * %ARGUMENTS:
896 * tunnel -- the tunnel
897 * %RETURNS:
898 * Nothing
899 * %DESCRIPTION:
900 * Discards all acknowledged packets from our xmit queue.
901 ***********************************************************************/
902 static void
903 tunnel_dequeue_acked_packets(l2tp_tunnel *tunnel)
905 l2tp_dgram *dgram = tunnel->xmit_queue_head;
906 DBG(l2tp_db(DBG_FLOW, "tunnel_dequeue_acked_packets(%s) %s\n",
907 l2tp_debug_tunnel_to_str(tunnel), tunnel_flow_control_stats(tunnel)));
908 while (dgram) {
909 if (SERIAL_LT(dgram->Ns, tunnel->peer_Nr)) {
910 tunnel_dequeue_head(tunnel);
911 if (tunnel->cwnd < tunnel->ssthresh) {
912 /* Slow start: increment CWND for each packet dequeued */
913 tunnel->cwnd++;
914 if (tunnel->cwnd > tunnel->peer_rws) {
915 tunnel->cwnd = tunnel->peer_rws;
917 } else {
918 /* Congestion avoidance: increment CWND for each CWND
919 packets dequeued */
920 tunnel->cwnd_counter++;
921 if (tunnel->cwnd_counter >= tunnel->cwnd) {
922 tunnel->cwnd_counter = 0;
923 tunnel->cwnd++;
924 if (tunnel->cwnd > tunnel->peer_rws) {
925 tunnel->cwnd = tunnel->peer_rws;
929 } else {
930 break;
932 dgram = tunnel->xmit_queue_head;
936 /**********************************************************************
937 * %FUNCTION: tunnel_handle_timeout
938 * %ARGUMENTS:
939 * es -- event selector
940 * fd, flags -- not used
941 * data -- pointer to tunnel which needs ack
942 * %RETURNS:
943 * Nothing
944 * %DESCRIPTION:
945 * Called when retransmission timer fires.
946 ***********************************************************************/
947 static void
948 tunnel_handle_timeout(EventSelector *es,
949 int fd,
950 unsigned int flags,
951 void *data)
953 l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
955 /* Timeout handler has fired */
956 tunnel->timeout_handler = NULL;
958 /* Reset xmit_new_dgrams */
959 tunnel->xmit_new_dgrams = tunnel->xmit_queue_head;
961 /* Set Ns on wire to Ns of first frame in queue */
962 if (tunnel->xmit_queue_head) {
963 tunnel->Ns_on_wire = tunnel->xmit_queue_head->Ns;
966 /* Go back to slow-start phase */
967 tunnel->ssthresh = tunnel->cwnd / 2;
968 if (!tunnel->ssthresh) tunnel->ssthresh = 1;
969 tunnel->cwnd = 1;
970 tunnel->cwnd_counter = 0;
972 tunnel->retransmissions++;
973 if (tunnel->retransmissions >= MAX_RETRANSMISSIONS) {
974 l2tp_set_errmsg("Too many retransmissions on tunnel (%s); closing down",
975 l2tp_debug_tunnel_to_str(tunnel));
976 /* Close tunnel... */
977 tunnel_free(tunnel);
978 return;
981 /* Double timeout, capping at 8 seconds */
982 if (tunnel->timeout < 8) {
983 tunnel->timeout *= 2;
986 /* Run the queue */
987 tunnel_xmit_queued_messages(tunnel);
990 /**********************************************************************
991 * %FUNCTION: tunnel_send_StopCCN
992 * %ARGUMENTS:
993 * tunnel -- the tunnel
994 * result_code -- what to put in result-code AVP
995 * error_code -- what to put in error-code field
996 * fmt -- format string for error message
997 * ... -- args for formatting error message
998 * %RETURNS:
999 * Nothing
1000 * %DESCRIPTION:
1001 * Sends a StopCCN control message.
1002 ***********************************************************************/
1003 static void
1004 tunnel_send_StopCCN(l2tp_tunnel *tunnel,
1005 int result_code,
1006 int error_code,
1007 char const *fmt, ...)
1009 char buf[256];
1010 va_list ap;
1011 uint16_t u16;
1012 uint16_t len;
1013 l2tp_dgram *dgram;
1015 /* Build the buffer for the result-code AVP */
1016 buf[0] = result_code / 256;
1017 buf[1] = result_code & 255;
1018 buf[2] = error_code / 256;
1019 buf[3] = error_code & 255;
1021 va_start(ap, fmt);
1022 vsnprintf(buf+4, 256-4, fmt, ap);
1023 buf[255] = 0;
1024 va_end(ap);
1026 DBG(l2tp_db(DBG_TUNNEL, "tunnel_send_StopCCN(%s, %d, %d, %s)\n",
1027 l2tp_debug_tunnel_to_str(tunnel), result_code, error_code, buf+4));
1029 len = 4 + strlen(buf+4);
1030 /* Build the datagram */
1031 dgram = l2tp_dgram_new_control(MESSAGE_StopCCN, tunnel->assigned_id, 0);
1032 if (!dgram) return;
1034 /* Add assigned tunnel ID */
1035 u16 = htons(tunnel->my_id);
1036 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1037 sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
1039 /* Add result code */
1040 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1041 len, VENDOR_IETF, AVP_RESULT_CODE, buf);
1043 /* TODO: Clean up */
1044 tunnel_set_state(tunnel, TUNNEL_SENT_STOP_CCN);
1046 /* Ship it out */
1047 l2tp_tunnel_xmit_control_message(tunnel, dgram);
1050 /**********************************************************************
1051 * %FUNCTION: tunnel_handle_StopCCN
1052 * %ARGUMENTS:
1053 * tunnel -- the tunnel
1054 * dgram -- received datagram
1055 * %RETURNS:
1056 * Nothing
1057 * %DESCRIPTION:
1058 * Processes a received StopCCN frame (shuts tunnel down)
1059 ***********************************************************************/
1060 static void
1061 tunnel_handle_StopCCN(l2tp_tunnel *tunnel,
1062 l2tp_dgram *dgram)
1064 unsigned char *val;
1065 int mandatory, hidden;
1066 uint16_t len, vendor, type;
1067 int err;
1068 l2tp_session *ses;
1069 void *cursor;
1071 /* Shut down all the sessions */
1072 for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1073 ses ;
1074 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1075 hash_remove(&tunnel->sessions_by_my_id, ses);
1076 l2tp_session_free(ses, "Tunnel closing down", 1);
1079 tunnel_set_state(tunnel, TUNNEL_RECEIVED_STOP_CCN);
1081 /* If there are any queued datagrams waiting for transmission,
1082 nuke them and adjust tunnel's Ns to whatever peer has ack'd */
1083 /* TODO: Is this correct? */
1084 if (tunnel->xmit_queue_head) {
1085 tunnel->Ns = tunnel->peer_Nr;
1086 while(tunnel->xmit_queue_head) {
1087 tunnel_dequeue_head(tunnel);
1091 /* Parse the AVP's */
1092 while(1) {
1093 val = l2tp_dgram_pull_avp(dgram, tunnel, &mandatory, &hidden,
1094 &len, &vendor, &type, &err);
1095 if (!val) {
1096 break;
1099 /* Only care about assigned tunnel ID. TODO: Fix this! */
1100 if (vendor != VENDOR_IETF || type != AVP_ASSIGNED_TUNNEL_ID) {
1101 continue;
1104 if (len == 2) {
1105 tunnel->assigned_id = ((unsigned int) val[0]) * 256 +
1106 (unsigned int) val[1];
1110 /* No point in delaying ack; there will never be a datagram for
1111 piggy-back. So cancel ack timer and shoot out a ZLB now */
1112 if (tunnel->ack_handler) {
1113 Event_DelHandler(tunnel->es, tunnel->ack_handler);
1114 tunnel->ack_handler = NULL;
1116 tunnel_send_ZLB(tunnel);
1117 /* We'll be scheduled for destruction after this function returns */
1120 /**********************************************************************
1121 * %FUNCTION: tunnel_process_received_datagram
1122 * %ARGUMENTS:
1123 * tunnel -- the tunnel
1124 * dgram -- the received datagram
1125 * %RETURNS:
1126 * Nothing
1127 * %DESCRIPTION:
1128 * Handles a received control message for this tunnel
1129 ***********************************************************************/
1130 static void
1131 tunnel_process_received_datagram(l2tp_tunnel *tunnel,
1132 l2tp_dgram *dgram)
1134 l2tp_session *ses = NULL;
1136 /* If message is associated with existing session, find session */
1138 DBG(l2tp_db(DBG_TUNNEL, "tunnel_process_received_datagram(%s, %s)\n",
1139 l2tp_debug_tunnel_to_str(tunnel),
1140 l2tp_debug_message_type_to_str(dgram->msg_type)));
1141 switch (dgram->msg_type) {
1142 case MESSAGE_OCRP:
1143 case MESSAGE_OCCN:
1144 case MESSAGE_ICRP:
1145 case MESSAGE_ICCN:
1146 case MESSAGE_CDN:
1147 ses = l2tp_tunnel_find_session(tunnel, dgram->sid);
1148 if (!ses) {
1149 l2tp_set_errmsg("Session-related message for unknown session %d",
1150 (int) dgram->sid);
1151 return;
1155 switch (dgram->msg_type) {
1156 case MESSAGE_StopCCN:
1157 tunnel_handle_StopCCN(tunnel, dgram);
1158 return;
1159 case MESSAGE_SCCRP:
1160 tunnel_handle_SCCRP(tunnel, dgram);
1161 return;
1162 case MESSAGE_SCCCN:
1163 tunnel_handle_SCCCN(tunnel, dgram);
1164 return;
1165 case MESSAGE_ICRQ:
1166 tunnel_handle_ICRQ(tunnel, dgram);
1167 return;
1168 case MESSAGE_CDN:
1169 l2tp_session_handle_CDN(ses, dgram);
1170 return;
1171 case MESSAGE_ICRP:
1172 l2tp_session_handle_ICRP(ses, dgram);
1173 return;
1174 case MESSAGE_ICCN:
1175 l2tp_session_handle_ICCN(ses, dgram);
1176 return;
1177 case MESSAGE_HELLO: //@.@ 20070806 When our reciver HELLO_MSG
1178 //tunnel_send_ZLB(tunnel);
1179 tunnel_setup_hello(tunnel); //every 60sec send hello to (Linux)L2TPD_Server
1180 return;
1184 /**********************************************************************
1185 * %FUNCTION: tunnel_finally_cleanup
1186 * %ARGUMENTS:
1187 * es -- event selector
1188 * fd, flags -- ignored
1189 * data -- the tunnel
1190 * %RETURNS:
1191 * Nothing
1192 * %DESCRIPTION:
1193 * Deallocates all tunnel state
1194 ***********************************************************************/
1195 static void
1196 tunnel_finally_cleanup(EventSelector *es,
1197 int fd,
1198 unsigned int flags,
1199 void *data)
1201 l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
1203 /* Hello handler has fired */
1204 tunnel->hello_handler = NULL;
1205 tunnel_free(tunnel);
1208 /**********************************************************************
1209 * %FUNCTION: tunnel_schedule_destruction
1210 * %ARGUMENTS:
1211 * tunnel -- tunnel which is to be destroyed
1212 * %RETURNS:
1213 * Nothing
1214 * %DESCRIPTION:
1215 * Schedules tunnel for destruction 31 seconds hence.
1216 ***********************************************************************/
1217 static void
1218 tunnel_schedule_destruction(l2tp_tunnel *tunnel)
1220 struct timeval t;
1221 void *cursor;
1222 l2tp_session *ses;
1224 t.tv_sec = 31;
1225 t.tv_usec = 0;
1227 DBG(l2tp_db(DBG_TUNNEL, "tunnel_schedule_destruction(%s)\n",
1228 l2tp_debug_tunnel_to_str(tunnel)));
1229 /* Shut down the tunnel in 31 seconds - (ab)use the hello handler */
1230 if (tunnel->hello_handler) {
1231 Event_DelHandler(tunnel->es, tunnel->hello_handler);
1233 tunnel->hello_handler =
1234 Event_AddTimerHandler(tunnel->es, t,
1235 tunnel_finally_cleanup, tunnel);
1237 /* Kill the sessions now */
1238 for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1239 ses ;
1240 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1241 l2tp_session_free(ses, "Tunnel closing down", 1);
1244 /* Clear hash table */
1245 l2tp_session_hash_init(&tunnel->sessions_by_my_id);
1248 /**********************************************************************
1249 * %FUNCTION: tunnel_send_ZLB
1250 * %ARGUMENTS:
1251 * tunnel -- the tunnel
1252 * %RETURNS:
1253 * Nothing
1254 * %DESCRIPTION:
1255 * Sends a ZLB ack packet.
1256 ***********************************************************************/
1257 void
1258 tunnel_send_ZLB(l2tp_tunnel *tunnel)
1260 l2tp_dgram *dgram =
1261 l2tp_dgram_new_control(MESSAGE_ZLB, tunnel->assigned_id, 0);
1262 if (!dgram) {
1263 l2tp_set_errmsg("tunnel_send_ZLB: Out of memory");
1264 return;
1266 dgram->Nr = tunnel->Nr;
1267 dgram->Ns = tunnel->Ns;
1268 l2tp_dgram_send_to_wire(dgram, &tunnel->peer_addr);
1269 l2tp_dgram_free(dgram);
1272 /**********************************************************************
1273 * %FUNCTION: tunnel_handle_SCCRP
1274 * %ARGUMENTS:
1275 * tunnel -- the tunnel
1276 * dgram -- the incoming datagram
1277 * %RETURNS:
1278 * Nothing
1279 * %DESCRIPTION:
1280 * Handles an incoming SCCRP
1281 ***********************************************************************/
1282 static void
1283 tunnel_handle_SCCRP(l2tp_tunnel *tunnel,
1284 l2tp_dgram *dgram)
1287 /* TODO: If we don't get challenge response at all, barf */
1288 /* Are we expecing SCCRP? */
1289 if (tunnel->state != TUNNEL_WAIT_CTL_REPLY) {
1290 tunnel_send_StopCCN(tunnel, RESULT_FSM_ERROR, 0, "Not expecting SCCRP");
1291 return;
1294 /* Extract tunnel params */
1295 if (tunnel_set_params(tunnel, dgram) < 0) return;
1297 tunnel_set_state(tunnel, TUNNEL_ESTABLISHED);
1298 tunnel_setup_hello(tunnel);
1300 /* Hunky-dory. Send SCCCN */
1301 dgram = l2tp_dgram_new_control(MESSAGE_SCCCN, tunnel->assigned_id, 0);
1302 if (!dgram) {
1303 /* Doh! Out of resources. Not much chance of StopCCN working... */
1304 tunnel_send_StopCCN(tunnel,
1305 RESULT_GENERAL_ERROR, ERROR_OUT_OF_RESOURCES,
1306 "Out of memory");
1307 return;
1310 /* Add response */
1311 if (tunnel->peer->secret_len) {
1312 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1313 MD5LEN, VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
1314 tunnel->response);
1317 /* Ship it out */
1318 l2tp_tunnel_xmit_control_message(tunnel, dgram);
1320 /* Tell sessions tunnel has been established */
1321 tunnel_tell_sessions_tunnel_open(tunnel);
1324 /**********************************************************************
1325 * %FUNCTION: tunnel_set_params
1326 * %ARGUMENTS:
1327 * tunnel -- the tunnel
1328 * dgram -- incoming SCCRQ or SCCRP datagram
1329 * %RETURNS:
1330 * 0 if OK, non-zero on error
1331 * %DESCRIPTION:
1332 * Sets up initial tunnel parameters (assigned ID, etc.)
1333 ***********************************************************************/
1334 static int
1335 tunnel_set_params(l2tp_tunnel *tunnel,
1336 l2tp_dgram *dgram)
1338 unsigned char *val;
1339 int mandatory, hidden;
1340 uint16_t len, vendor, type;
1341 int err = 0;
1342 int found_response = 0;
1344 uint16_t u16;
1346 /* Get host name */
1347 val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1348 VENDOR_IETF, AVP_HOST_NAME);
1349 if (!val) {
1350 l2tp_set_errmsg("No host name AVP in SCCRQ");
1351 tunnel_free(tunnel);
1352 return -1;
1355 if (len >= MAX_HOSTNAME) len = MAX_HOSTNAME-1;
1356 memcpy(tunnel->peer_hostname, val, len);
1357 tunnel->peer_hostname[len+1] = 0;
1358 DBG(l2tp_db(DBG_TUNNEL, "%s: Peer host name is '%s'\n",
1359 l2tp_debug_tunnel_to_str(tunnel), tunnel->peer_hostname));
1361 /* Find peer */
1362 tunnel->peer = l2tp_peer_find(&tunnel->peer_addr, tunnel->peer_hostname);
1364 /* Get assigned tunnel ID */
1365 val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1366 VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID);
1367 if (!val) {
1368 l2tp_set_errmsg("No assigned tunnel ID AVP in SCCRQ");
1369 tunnel_free(tunnel);
1370 return -1;
1373 if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID,
1374 len, mandatory)) {
1375 tunnel_free(tunnel);
1376 return -1;
1379 /* Set tid */
1380 tunnel->assigned_id = ((unsigned int) val[0]) * 256 + (unsigned int) val[1];
1381 if (!tunnel->assigned_id) {
1382 l2tp_set_errmsg("Invalid assigned-tunnel-ID of zero");
1383 tunnel_free(tunnel);
1384 return -1;
1387 /* Validate peer */
1388 if (!tunnel->peer) {
1389 l2tp_set_errmsg("Peer %s is not authorized to create a tunnel",
1390 inet_ntoa(tunnel->peer_addr.sin_addr));
1391 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_OK, "%s", l2tp_get_errmsg());
1392 return -1;
1395 /* Pull out and examine AVP's */
1396 while(1) {
1397 val = l2tp_dgram_pull_avp(dgram, tunnel, &mandatory, &hidden,
1398 &len, &vendor, &type, &err);
1399 if (!val) {
1400 if (err) {
1401 tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1402 ERROR_BAD_VALUE, "%s", l2tp_get_errmsg());
1403 return -1;
1405 break;
1408 /* Unknown vendor? Ignore, unless mandatory */
1409 if (vendor != VENDOR_IETF) {
1410 if (!mandatory) continue;
1411 tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1412 ERROR_UNKNOWN_AVP_WITH_M_BIT,
1413 "Unknown mandatory attribute (vendor=%d, type=%d) in %s",
1414 (int) vendor, (int) type,
1415 l2tp_debug_avp_type_to_str(dgram->msg_type));
1416 return -1;
1419 /* Validate AVP, ignore invalid AVP's without M bit set */
1420 if (!l2tp_dgram_validate_avp(vendor, type, len, mandatory)) {
1421 if (!mandatory) continue;
1422 tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1423 ERROR_BAD_LENGTH, "%s", l2tp_get_errmsg());
1424 return -1;
1427 switch(type) {
1428 case AVP_PROTOCOL_VERSION:
1429 u16 = ((uint16_t) val[0]) * 256 + val[1];
1430 if (u16 != 0x100) {
1431 tunnel_send_StopCCN(tunnel, RESULT_UNSUPPORTED_VERSION,
1432 0x100, "Unsupported protocol version");
1433 return -1;
1435 break;
1437 case AVP_HOST_NAME:
1438 /* Already been handled */
1439 break;
1441 case AVP_FRAMING_CAPABILITIES:
1442 /* TODO: Do we care about framing capabilities? */
1443 break;
1445 case AVP_ASSIGNED_TUNNEL_ID:
1446 /* Already been handled */
1447 break;
1449 case AVP_BEARER_CAPABILITIES:
1450 /* TODO: Do we care? */
1451 break;
1453 case AVP_RECEIVE_WINDOW_SIZE:
1454 u16 = ((uint16_t) val[0]) * 256 + val[1];
1455 /* Silently correct bogus rwin */
1456 if (u16 < 1) u16 = 1;
1457 tunnel->peer_rws = u16;
1458 tunnel->ssthresh = u16;
1459 break;
1461 case AVP_CHALLENGE:
1462 if (tunnel->peer->secret_len) {
1463 l2tp_auth_gen_response(
1464 ((dgram->msg_type == MESSAGE_SCCRQ) ? MESSAGE_SCCRP : MESSAGE_SCCCN),
1465 tunnel->peer->secret,
1466 val, len, tunnel->response);
1468 break;
1470 case AVP_CHALLENGE_RESPONSE:
1471 /* Length has been validated by l2tp_dgram_validate_avp */
1472 if (tunnel->peer->secret_len) {
1473 if (memcmp(val, tunnel->expected_response, MD5LEN)) {
1474 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_BAD_VALUE,
1475 "Incorrect challenge response");
1476 return -1;
1479 found_response = 1;
1480 break;
1482 case AVP_TIE_BREAKER:
1483 /* TODO: Handle tie-breaker */
1484 break;
1486 case AVP_FIRMWARE_REVISION:
1487 /* TODO: Do we care? */
1488 break;
1490 case AVP_VENDOR_NAME:
1491 /* TODO: Do we care? */
1492 break;
1494 default:
1495 /* TODO: Maybe print an error? */
1496 break;
1500 if (tunnel->peer->secret_len &&
1501 !found_response &&
1502 dgram->msg_type != MESSAGE_SCCRQ) {
1503 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, 0,
1504 "Missing challenge-response");
1505 return -1;
1507 return 0;
1510 /**********************************************************************
1511 * %FUNCTION: tunnel_setup_hello
1512 * %ARGUMENTS:
1513 * tunnel -- the tunnel
1514 * %RETURNS:
1515 * Nothing
1516 * %DESCRIPTION:
1517 * Sets up timer for sending HELLO messages
1518 ***********************************************************************/
1519 static void
1520 tunnel_setup_hello(l2tp_tunnel *tunnel)
1522 struct timeval t;
1524 t.tv_sec = 60;
1525 t.tv_usec = 0;
1527 if (tunnel->hello_handler) {
1528 Event_DelHandler(tunnel->es, tunnel->hello_handler);
1530 tunnel->hello_handler = Event_AddTimerHandler(tunnel->es, t,
1531 tunnel_do_hello, tunnel);
1534 /**********************************************************************
1535 * %FUNCTION: tunnel_do_hello
1536 * %ARGUMENTS:
1537 * es -- event selector
1538 * fd, flags -- ignored
1539 * data -- the tunnel
1540 * %RETURNS:
1541 * Nothing
1542 * %DESCRIPTION:
1543 * Deallocates all tunnel state
1544 ***********************************************************************/
1545 static void
1546 tunnel_do_hello(EventSelector *es,
1547 int fd,
1548 unsigned int flags,
1549 void *data)
1551 l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
1552 l2tp_dgram *dgram;
1554 /* Hello handler has fired */
1555 tunnel->hello_handler = NULL;
1557 /* Reschedule HELLO timer */
1558 tunnel_setup_hello(tunnel);
1560 /* Send a HELLO message */
1561 dgram = l2tp_dgram_new_control(MESSAGE_HELLO, tunnel->assigned_id, 0);
1562 if (dgram) l2tp_tunnel_xmit_control_message(tunnel, dgram);
1565 /**********************************************************************
1566 * %FUNCTION: tunnel_handle_SCCCN
1567 * %ARGUMENTS:
1568 * tunnel -- the tunnel
1569 * dgram -- the incoming datagram
1570 * %RETURNS:
1571 * Nothing
1572 * %DESCRIPTION:
1573 * Handles an incoming SCCCN
1574 ***********************************************************************/
1575 static void
1576 tunnel_handle_SCCCN(l2tp_tunnel *tunnel,
1577 l2tp_dgram *dgram)
1579 unsigned char *val;
1580 uint16_t len;
1581 int hidden, mandatory;
1583 /* Are we expecing SCCCN? */
1584 if (tunnel->state != TUNNEL_WAIT_CTL_CONN) {
1585 tunnel_send_StopCCN(tunnel, RESULT_FSM_ERROR, 0, "Not expecting SCCCN");
1586 return;
1589 /* Check challenge response */
1590 if (tunnel->peer->secret_len) {
1591 val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1592 VENDOR_IETF, AVP_CHALLENGE_RESPONSE);
1593 if (!val) {
1594 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, 0,
1595 "Missing challenge-response");
1596 return;
1599 if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
1600 len, mandatory)) {
1601 tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR, ERROR_BAD_LENGTH,
1602 "Invalid challenge-response");
1603 return;
1605 if (memcmp(val, tunnel->expected_response, MD5LEN)) {
1606 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_BAD_VALUE,
1607 "Incorrect challenge response");
1608 return;
1612 tunnel_set_state(tunnel, TUNNEL_ESTABLISHED);
1613 tunnel_setup_hello(tunnel);
1615 /* Tell sessions tunnel has been established */
1616 tunnel_tell_sessions_tunnel_open(tunnel);
1619 /**********************************************************************
1620 * %FUNCTION: tunnel_find_for_peer
1621 * %ARGUMENTS:
1622 * peer -- an L2TP peer
1623 * es -- an event selector
1624 * %RETURNS:
1625 * An existing tunnel to peer (if one exists) or a new one (if one does not),
1626 * or NULL if no tunnel could be established. If the existing tunnel
1627 * is in the state RECEIVED_STOP_CCN or SENT_STOP_CCN, make a new one.
1628 ***********************************************************************/
1629 l2tp_tunnel *
1630 l2tp_tunnel_find_for_peer(l2tp_peer *peer,
1631 EventSelector *es)
1633 l2tp_tunnel *tunnel = tunnel_find_bypeer(peer->addr);
1634 if (tunnel) {
1635 if (tunnel->state == TUNNEL_WAIT_CTL_REPLY ||
1636 tunnel->state == TUNNEL_WAIT_CTL_CONN ||
1637 tunnel->state == TUNNEL_ESTABLISHED) {
1638 return tunnel;
1642 /* No tunnel, or tunnel in wrong state */
1643 return tunnel_establish(peer, es);
1646 /**********************************************************************
1647 * %FUNCTION: tunnel_find_session
1648 * %ARGUMENTS:
1649 * sid -- session ID
1650 * %RETURNS:
1651 * The session with specified ID, or NULL if no such session
1652 ***********************************************************************/
1653 l2tp_session *
1654 l2tp_tunnel_find_session(l2tp_tunnel *tunnel,
1655 uint16_t sid)
1657 l2tp_session candidate;
1658 candidate.my_id = sid;
1659 return hash_find(&tunnel->sessions_by_my_id, &candidate);
1662 /**********************************************************************
1663 * %FUNCTION: tunnel_tell_sessions_tunnel_open
1664 * %ARGUMENTS:
1665 * tunnel -- the tunnel
1666 * %RETURNS:
1667 * Nothing
1668 * %DESCRIPTION:
1669 * Informs all waiting sessions that tunnel has moved into ESTABLISHED state.
1670 ***********************************************************************/
1671 static void
1672 tunnel_tell_sessions_tunnel_open(l2tp_tunnel *tunnel)
1674 l2tp_session *ses;
1675 void *cursor;
1677 for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1678 ses ;
1679 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1680 l2tp_session_notify_tunnel_open(ses);
1684 /**********************************************************************
1685 * %FUNCTION: tunnel_add_session
1686 * %ARGUMENTS:
1687 * ses -- session to add
1688 * %RETURNS:
1689 * Nothing
1690 * %DESCRIPTION:
1691 * Adds session to tunnel's hash table. If tunnel is up, calls
1692 * l2tp_session_notify_tunnel_open
1693 ***********************************************************************/
1694 void
1695 l2tp_tunnel_add_session(l2tp_session *ses)
1697 l2tp_tunnel *tunnel = ses->tunnel;
1699 hash_insert(&tunnel->sessions_by_my_id, ses);
1700 if (tunnel->state == TUNNEL_ESTABLISHED) {
1701 l2tp_session_notify_tunnel_open(ses);
1705 void
1706 l2tp_tunnel_reestablish(EventSelector *es,
1707 int fd,
1708 unsigned int flags,
1709 void *data)
1711 l2tp_peer *peer = (l2tp_peer*) data;
1712 l2tp_session *ses;
1714 ses = l2tp_session_call_lns(peer, "foobar", es, NULL);
1715 if (!ses) {
1716 DBG(l2tp_db(DBG_TUNNEL, "l2tp_tunnel_reestablish() failed\n"));
1717 return;
1721 /**********************************************************************
1722 * %FUNCTION: tunnel_delete_session
1723 * %ARGUMENTS:
1724 * ses -- session to delete
1725 * %RETURNS:
1726 * Nothing
1727 * %DESCRIPTION:
1728 * Deletes session from tunnel's hash table and frees it.
1729 ***********************************************************************/
1730 void
1731 l2tp_tunnel_delete_session(l2tp_session *ses, char const *reason, int may_reestablish)
1733 l2tp_tunnel *tunnel = ses->tunnel;
1735 hash_remove(&tunnel->sessions_by_my_id, ses);
1736 l2tp_session_free(ses, reason, may_reestablish);
1738 /* Tear down tunnel if so indicated */
1739 if (!hash_num_entries(&tunnel->sessions_by_my_id)) {
1740 if (!tunnel->peer->retain_tunnel) {
1741 tunnel_send_StopCCN(tunnel,
1742 RESULT_GENERAL_REQUEST, 0,
1743 "Last session has closed");
1748 /**********************************************************************
1749 * %FUNCTION: tunnel_handle_ICRQ
1750 * %ARGUMENTS:
1751 * tunnel -- the tunnel
1752 * dgram -- the datagram
1753 * %RETURNS:
1754 * Nothing
1755 * %DESCRIPTION:
1756 * Handles ICRQ (Incoming Call ReQuest)
1757 ***********************************************************************/
1758 static void
1759 tunnel_handle_ICRQ(l2tp_tunnel *tunnel,
1760 l2tp_dgram *dgram)
1762 uint16_t u16;
1763 unsigned char *val;
1764 uint16_t len;
1765 int mandatory, hidden;
1767 /* Get assigned session ID */
1768 val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1769 VENDOR_IETF, AVP_ASSIGNED_SESSION_ID);
1770 if (!val) {
1771 l2tp_set_errmsg("No assigned tunnel ID AVP in ICRQ");
1772 return;
1774 if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_ASSIGNED_SESSION_ID,
1775 len, mandatory)) {
1776 /* TODO: send CDN */
1777 return;
1780 /* Set assigned session ID */
1781 u16 = ((uint16_t) val[0]) * 256 + (uint16_t) val[1];
1783 if (!u16) {
1784 /* TODO: send CDN */
1785 return;
1788 /* Tunnel in wrong state? */
1789 if (tunnel->state != TUNNEL_ESTABLISHED) {
1790 /* TODO: Send CDN */
1791 return;
1794 /* Set up new incoming call */
1795 /* TODO: Include calling number */
1796 l2tp_session_lns_handle_incoming_call(tunnel, u16, dgram, "");
1799 /**********************************************************************
1800 * %FUNCTION: l2tp_tunnel_stop_all
1801 * %ARGUMENTS:
1802 * reason -- reason for stopping tunnels
1803 * %RETURNS:
1804 * Nothing
1805 * %DESCRIPTION:
1806 * Stops all tunnels
1807 ***********************************************************************/
1808 void
1809 l2tp_tunnel_stop_all(char const *reason)
1811 l2tp_tunnel *tunnel;
1812 void *cursor;
1814 /* Send StopCCN on all tunnels except those which are scheduled for
1815 destruction */
1816 for (tunnel = hash_start(&tunnels_by_my_id, &cursor);
1817 tunnel;
1818 tunnel = hash_next(&tunnels_by_my_id, &cursor)) {
1819 l2tp_tunnel_stop_tunnel(tunnel, reason);
1824 /**********************************************************************
1825 * %FUNCTION: l2tp_tunnel_stop_tunnel
1826 * %ARGUMENTS:
1827 * tunnel -- tunnel to stop
1828 * reason -- reason for stopping tunnel
1829 * %RETURNS:
1830 * Nothing
1831 * %DESCRIPTION:
1832 * Stops a tunnels (sends StopCCN)
1833 ***********************************************************************/
1834 void
1835 l2tp_tunnel_stop_tunnel(l2tp_tunnel *tunnel,
1836 char const *reason)
1838 /* Do not send StopCCN if we've received one already */
1839 if (tunnel->state != TUNNEL_RECEIVED_STOP_CCN &&
1840 tunnel->state != TUNNEL_SENT_STOP_CCN) {
1841 tunnel_send_StopCCN(tunnel, RESULT_SHUTTING_DOWN, 0, reason);
1845 /**********************************************************************
1846 * %FUNCTION: l2tp_num_tunnels
1847 * %ARGUMENTS:
1848 * None
1849 * %RETURNS:
1850 * The number of L2TP tunnels
1851 ***********************************************************************/
1853 l2tp_num_tunnels(void)
1855 return hash_num_entries(&tunnels_by_my_id);
1858 /**********************************************************************
1859 * %FUNCTION: l2tp_first_tunnel
1860 * %ARGUMENTS:
1861 * cursor -- cursor for keeping track of where we are in interation
1862 * %RETURNS:
1863 * First L2TP tunnel
1864 ***********************************************************************/
1865 l2tp_tunnel *
1866 l2tp_first_tunnel(void **cursor)
1868 return hash_start(&tunnels_by_my_id, cursor);
1872 /**********************************************************************
1873 * %FUNCTION: l2tp_next_tunnel
1874 * %ARGUMENTS:
1875 * cursor -- cursor for keeping track of where we are in interation
1876 * %RETURNS:
1877 * Next L2TP tunnel
1878 ***********************************************************************/
1879 l2tp_tunnel *
1880 l2tp_next_tunnel(void **cursor)
1882 return hash_next(&tunnels_by_my_id, cursor);
1885 /**********************************************************************
1886 * %FUNCTION: l2tp_tunnel_state_name
1887 * %ARGUMENTS:
1888 * tunnel -- the tunnel
1889 * %RETURNS:
1890 * The name of the tunnel's state
1891 ***********************************************************************/
1892 char const *
1893 l2tp_tunnel_state_name(l2tp_tunnel *tunnel)
1895 return state_names[tunnel->state];
1898 /**********************************************************************
1899 * %FUNCTION: l2tp_tunnel_first_session
1900 * %ARGUMENTS:
1901 * tunnel -- the tunnel
1902 * cursor -- cursor for hash table iteration
1903 * %RETURNS:
1904 * First session in tunnel
1905 ***********************************************************************/
1906 l2tp_session *
1907 l2tp_tunnel_first_session(l2tp_tunnel *tunnel, void **cursor)
1909 return hash_start(&tunnel->sessions_by_my_id, cursor);
1912 /**********************************************************************
1913 * %FUNCTION: l2tp_tunnel_next_session
1914 * %ARGUMENTS:
1915 * tunnel -- the tunnel
1916 * cursor -- cursor for hash table iteration
1917 * %RETURNS:
1918 * Next session in tunnel
1919 ***********************************************************************/
1920 l2tp_session *
1921 l2tp_tunnel_next_session(l2tp_tunnel *tunnel, void **cursor)
1923 return hash_next(&tunnel->sessions_by_my_id, cursor);