1/***********************************************************************
2*
3* tunnel.c
4*
5* Functions for manipulating L2TP tunnel objects.
6*
7* Copyright (C) 2002 Roaring Penguin Software Inc.
8* Copyright (C) 2005-2007 Oleg I. Vdovikin (oleg@cs.msu.su)
9*	Persist fixes, route manipulation
10*
11* This software may be distributed under the terms of the GNU General
12* Public License, Version 2, or (at your option) any later version.
13*
14* LIC: GPL
15*
16***********************************************************************/
17
18static char const RCSID[] =
19"$Id: tunnel.c 3323 2011-09-21 18:45:48Z lly.dev $";
20
21#include "l2tp.h"
22#include <stddef.h>
23#include <stdarg.h>
24#include <stdio.h>
25#include <string.h>
26#include <errno.h>
27#include <sys/ioctl.h>
28#include <netdb.h>
29#include <features.h>
30#include <resolv.h>
31
32/* Hash tables of all tunnels */
33static hash_table tunnels_by_my_id;
34static hash_table tunnels_by_peer_address;
35
36static uint16_t tunnel_make_tid(void);
37static l2tp_tunnel *tunnel_new(EventSelector *es);
38static void tunnel_free(l2tp_tunnel *tunnel);
39static int tunnel_send_SCCRQ(l2tp_tunnel *tunnel);
40static void tunnel_handle_SCCRQ(l2tp_dgram *dgram,
41					 EventSelector *es,
42					 struct sockaddr_in *from);
43static void tunnel_handle_SCCRP(l2tp_tunnel *tunnel,
44				l2tp_dgram *dgram);
45static void tunnel_handle_SCCCN(l2tp_tunnel *tunnel,
46				l2tp_dgram *dgram);
47static void tunnel_handle_ICRQ(l2tp_tunnel *tunnel,
48			       l2tp_dgram *dgram);
49static void tunnel_process_received_datagram(l2tp_tunnel *tunnel,
50					     l2tp_dgram *dgram);
51static void tunnel_schedule_ack(l2tp_tunnel *tunnel);
52static void tunnel_do_ack(EventSelector *es, int fd, unsigned int flags,
53			  void *data);
54static void tunnel_handle_timeout(EventSelector *es, int fd,
55				  unsigned int flags, void *data);
56static void tunnel_finally_cleanup(EventSelector *es, int fd,
57				   unsigned int flags, void *data);
58
59static void tunnel_do_hello(EventSelector *es, int fd,
60			    unsigned int flags, void *data);
61
62static void tunnel_dequeue_acked_packets(l2tp_tunnel *tunnel);
63
64static void tunnel_send_StopCCN(l2tp_tunnel *tunnel,
65				int result_code,
66				int error_code,
67				char const *fmt, ...);
68static void tunnel_schedule_destruction(l2tp_tunnel *tunnel);
69static int tunnel_set_params(l2tp_tunnel *tunnel, l2tp_dgram *dgram);
70
71static int tunnel_outstanding_frames(l2tp_tunnel *tunnel);
72static void tunnel_setup_hello(l2tp_tunnel *tunnel);
73static void tunnel_tell_sessions_tunnel_open(l2tp_tunnel *tunnel);
74static l2tp_tunnel *tunnel_establish(l2tp_peer *peer, EventSelector *es);
75static l2tp_tunnel *tunnel_find_bypeer(struct sockaddr_in addr);
76
77static char *state_names[] = {
78    "idle", "wait-ctl-reply", "wait-ctl-conn", "established",
79    "received-stop-ccn", "sent-stop-ccn"
80};
81
82#ifdef RTCONFIG_VPNC
83int vpnc = 0;
84#endif
85
86#define VENDOR_STR "Roaring Penguin Software Inc."
87
88/* Comparison of serial numbers according to RFC 1982 */
89#define SERIAL_GT(a, b) \
90(((a) > (b) && (a) - (b) < 32768) || ((a) < (b) && (b) - (a) > 32768))
91
92#define SERIAL_LT(a, b) \
93(((a) < (b) && (b) - (a) < 32768) || ((a) > (b) && (a) - (b) > 32768))
94
95/* Route manipulation */
96#define sin_addr(s) (((struct sockaddr_in *)(s))->sin_addr)
97#define route_msg l2tp_set_errmsg
98static int route_add(const struct in_addr inetaddr, struct rtentry *rt);
99static int route_del(struct rtentry *rt);
100
101/**********************************************************************
102* %FUNCTION: tunnel_set_state
103* %ARGUMENTS:
104*  tunnel -- the tunnel
105*  state -- new state
106* %RETURNS:
107*  Nothing
108***********************************************************************/
109static void
110tunnel_set_state(l2tp_tunnel *tunnel, int state)
111{
112    if (state == tunnel->state) return;
113    DBG(l2tp_db(DBG_TUNNEL, "tunnel(%s) state %s -> %s\n",
114	   l2tp_debug_tunnel_to_str(tunnel),
115	   state_names[tunnel->state],
116	   state_names[state]));
117    tunnel->state = state;
118}
119
120/**********************************************************************
121* %FUNCTION: tunnel_find_by_my_id
122* %ARGUMENTS:
123*  id -- tunnel ID
124* %RETURNS:
125*  A tunnel whose my_id field equals id, or NULL if no such tunnel
126***********************************************************************/
127l2tp_tunnel *
128l2tp_tunnel_find_by_my_id(uint16_t id)
129{
130    l2tp_tunnel candidate;
131    candidate.my_id = id;
132    return hash_find(&tunnels_by_my_id, &candidate);
133}
134
135/**********************************************************************
136* %FUNCTION: tunnel_find_bypeer
137* %ARGUMENTS:
138*  addr -- peer address
139* %RETURNS:
140*  A tunnel whose peer_addr field equals addr, or NULL if no such tunnel
141***********************************************************************/
142static l2tp_tunnel *
143tunnel_find_bypeer(struct sockaddr_in addr)
144{
145    l2tp_tunnel candidate;
146    candidate.peer_addr = addr;
147    return hash_find(&tunnels_by_peer_address, &candidate);
148}
149
150/**********************************************************************
151* %FUNCTION: tunnel_flow_control_stats
152* %ARGUMENTS:
153*  tunnel -- a tunnel
154* %RETURNS:
155*  A string representing flow-control info (used for debugging)
156***********************************************************************/
157static char const *
158tunnel_flow_control_stats(l2tp_tunnel *tunnel)
159{
160    static char buf[256];
161
162    snprintf(buf, sizeof(buf), "rws=%d cwnd=%d ssthresh=%d outstanding=%d",
163	     (int) tunnel->peer_rws,
164	     tunnel->cwnd,
165	     tunnel->ssthresh,
166	     tunnel_outstanding_frames(tunnel));
167    return buf;
168}
169
170/**********************************************************************
171* %FUNCTION: tunnel_outstanding_frames
172* %ARGUMENTS:
173*  tunnel -- a tunnel
174* %RETURNS:
175*  The number of outstanding (transmitted, but not ack'd) frames.
176***********************************************************************/
177static int
178tunnel_outstanding_frames(l2tp_tunnel *tunnel)
179{
180    int Ns = (int) tunnel->Ns_on_wire;
181    int Nr = (int) tunnel->peer_Nr;
182    if (Ns >= Nr) return Ns - Nr;
183    return 65536 - Nr + Ns;
184}
185
186/**********************************************************************
187* %FUNCTION: tunnel_make_tid
188* %ARGUMENTS:
189*  None
190* %RETURNS:
191*  An unused, random tunnel ID.
192***********************************************************************/
193static uint16_t tunnel_make_tid(void)
194{
195    uint16_t id;
196    for(;;) {
197	L2TP_RANDOM_FILL(id);
198	if (!id) continue;
199	if (!l2tp_tunnel_find_by_my_id(id)) return id;
200    }
201}
202
203/**********************************************************************
204* %FUNCTION: tunnel_enqueue_dgram
205* %ARGUMENTS:
206*  tunnel -- the tunnel
207*  dgram -- an L2TP datagram to place at the tail of the transmit queue
208* %RETURNS:
209*  Nothing
210* %DESCRIPTION:
211*  Adds datagram to end of transmit queue.
212***********************************************************************/
213static void
214tunnel_enqueue_dgram(l2tp_tunnel *tunnel,
215		     l2tp_dgram  *dgram)
216{
217    dgram->next = NULL;
218    if (tunnel->xmit_queue_tail) {
219	tunnel->xmit_queue_tail->next = dgram;
220	tunnel->xmit_queue_tail = dgram;
221    } else {
222	tunnel->xmit_queue_head = dgram;
223	tunnel->xmit_queue_tail = dgram;
224    }
225    if (!tunnel->xmit_new_dgrams) {
226	tunnel->xmit_new_dgrams = dgram;
227    }
228
229    dgram->Ns = tunnel->Ns;
230    tunnel->Ns++;
231    DBG(l2tp_db(DBG_FLOW, "tunnel_enqueue_dgram(%s, %s) %s\n",
232	   l2tp_debug_tunnel_to_str(tunnel),
233	   l2tp_debug_message_type_to_str(dgram->msg_type),
234	   tunnel_flow_control_stats(tunnel)));
235
236}
237
238/**********************************************************************
239* %FUNCTION: tunnel_dequeue_head
240* %ARGUMENTS:
241*  tunnel -- the tunnel
242* %RETURNS:
243*  Nothing
244* %DESCRIPTION:
245*  Dequeues datagram from head of transmit queue and frees it
246***********************************************************************/
247static void
248tunnel_dequeue_head(l2tp_tunnel *tunnel)
249{
250    l2tp_dgram *dgram = tunnel->xmit_queue_head;
251    if (dgram) {
252	tunnel->xmit_queue_head = dgram->next;
253	if (tunnel->xmit_new_dgrams == dgram) {
254	    tunnel->xmit_new_dgrams = dgram->next;
255	}
256	if (tunnel->xmit_queue_tail == dgram) {
257	    tunnel->xmit_queue_tail = NULL;
258	}
259	l2tp_dgram_free(dgram);
260    }
261}
262
263/**********************************************************************
264* %FUNCTION: tunnel_xmit_queued_messages
265* %ARGUMENTS:
266*  tunnel -- the tunnel
267* %RETURNS:
268*  Nothing
269* %DESCRIPTION:
270*  Transmits as many control messages as possible from the queue.
271***********************************************************************/
272static void
273tunnel_xmit_queued_messages(l2tp_tunnel *tunnel)
274{
275    l2tp_dgram *dgram;
276    struct timeval t;
277
278    dgram = tunnel->xmit_new_dgrams;
279    if (!dgram) return;
280
281    DBG(l2tp_db(DBG_FLOW, "xmit_queued(%s): %s\n",
282	   l2tp_debug_tunnel_to_str(tunnel),
283	   tunnel_flow_control_stats(tunnel)));
284    while (dgram) {
285	/* If window is closed, we can't transmit anything */
286	if (tunnel_outstanding_frames(tunnel) >= tunnel->cwnd) {
287	    break;
288	}
289
290	/* Update Nr */
291	dgram->Nr = tunnel->Nr;
292
293	/* Tid might have changed if call was initiated before
294	   tunnel establishment was complete */
295	dgram->tid = tunnel->assigned_id;
296
297	if (l2tp_dgram_send_to_wire(dgram, &tunnel->peer_addr) < 0) {
298	    break;
299	}
300
301	/* Cancel any pending ack */
302	if (tunnel->ack_handler) {
303	    Event_DelHandler(tunnel->es, tunnel->ack_handler);
304	    tunnel->ack_handler = NULL;
305	}
306
307	tunnel->xmit_new_dgrams = dgram->next;
308	tunnel->Ns_on_wire = dgram->Ns + 1;
309	DBG(l2tp_db(DBG_FLOW, "loop in xmit_queued(%s): %s\n",
310	       l2tp_debug_tunnel_to_str(tunnel),
311	       tunnel_flow_control_stats(tunnel)));
312	dgram = dgram->next;
313    }
314
315    t.tv_sec = tunnel->timeout;
316    t.tv_usec = 0;
317
318    /* Set retransmission timer */
319    if (tunnel->timeout_handler) {
320	Event_ChangeTimeout(tunnel->timeout_handler, t);
321    } else {
322	tunnel->timeout_handler =
323	    Event_AddTimerHandler(tunnel->es, t,
324				  tunnel_handle_timeout, tunnel);
325    }
326}
327
328/**********************************************************************
329* %FUNCTION: tunnel_xmit_control_message
330* %ARGUMENTS:
331*  tunnel -- the tunnel
332*  dgram -- the datagram to transmit.  After return from this
333*           function, the tunnel "owns" the dgram and the caller should
334*           no longer use it.
335* %RETURNS:
336*  Nothing
337* %DESCRIPTION:
338*  Transmits a control message.  If there is no room in the transmit
339*  window, queues the message.
340***********************************************************************/
341void
342l2tp_tunnel_xmit_control_message(l2tp_tunnel *tunnel,
343				 l2tp_dgram  *dgram)
344{
345    /* Queue the datagram in case we need to retransmit it */
346    tunnel_enqueue_dgram(tunnel, dgram);
347
348    /* Run the queue */
349    tunnel_xmit_queued_messages(tunnel);
350}
351
352static unsigned int
353tunnel_compute_peerhash(void *data)
354{
355    return (unsigned int) (((l2tp_tunnel *)data)->peer_addr.sin_addr.s_addr);
356}
357
358static int
359tunnel_compare_peer(void *d1, void *d2)
360{
361    return (((l2tp_tunnel *)d1)->peer_addr.sin_addr.s_addr) !=
362	(((l2tp_tunnel *)d2)->peer_addr.sin_addr.s_addr);
363}
364
365/**********************************************************************
366* %FUNCTION: tunnel_compute_hash_my_id
367* %ARGUMENTS:
368*  data -- a void pointer which is really a tunnel
369* %RETURNS:
370*  My tunnel ID
371***********************************************************************/
372static unsigned int
373tunnel_compute_hash_my_id(void *data)
374{
375    return (unsigned int) (((l2tp_tunnel *) data)->my_id);
376}
377
378/**********************************************************************
379* %FUNCTION: tunnel_compare_my_id
380* %ARGUMENTS:
381*  item1 -- first tunnel
382*  item2 -- second tunnel
383* %RETURNS:
384*  0 if both tunnels have same ID, non-zero otherwise
385***********************************************************************/
386static int
387tunnel_compare_my_id(void *item1, void *item2)
388{
389    return ((l2tp_tunnel *) item1)->my_id != ((l2tp_tunnel *) item2)->my_id;
390}
391
392/**********************************************************************
393* %FUNCTION: tunnel_cleanup
394* %ARGUMENTS:
395*  data -- event selector
396* %RETURNS:
397*  Nothing
398* %DESCRIPTION:
399*  Shuts down all tunnels and waits for them to exit
400***********************************************************************/
401static void
402tunnel_cleanup(void *data)
403{
404    EventSelector *es = (EventSelector *) data;
405    int i;
406
407    /* Stop all tunnels */
408    l2tp_tunnel_stop_all("Shutting down");
409
410    while (hash_num_entries(&tunnels_by_my_id)) {
411	i = Event_HandleEvent(es);
412	if (i < 0) {
413	    exit(EXIT_FAILURE);
414	}
415    }
416}
417
418/**********************************************************************
419* %FUNCTION: tunnel_init
420* %ARGUMENTS:
421*  es -- event selector
422* %RETURNS:
423*  Nothing
424* %DESCRIPTION:
425*  Initializes static tunnel data structures.
426***********************************************************************/
427void
428l2tp_tunnel_init(EventSelector *es)
429{
430    hash_init(&tunnels_by_my_id,
431	      offsetof(l2tp_tunnel, hash_by_my_id),
432	      tunnel_compute_hash_my_id,
433	      tunnel_compare_my_id);
434    hash_init(&tunnels_by_peer_address,
435	      offsetof(l2tp_tunnel, hash_by_peer),
436	      tunnel_compute_peerhash,
437	      tunnel_compare_peer);
438
439    l2tp_register_shutdown_handler(tunnel_cleanup, es);
440}
441
442/**********************************************************************
443* %FUNCTION: tunnel_new
444* %ARGUMENTS:
445*  es -- event selector
446* %RETURNS:
447*  A newly-allocated and initialized l2tp_tunnel object
448***********************************************************************/
449static l2tp_tunnel *
450tunnel_new(EventSelector *es)
451{
452    l2tp_tunnel *tunnel = malloc(sizeof(l2tp_tunnel));
453    if (!tunnel) return NULL;
454
455    memset(tunnel, 0, sizeof(l2tp_tunnel));
456    l2tp_session_hash_init(&tunnel->sessions_by_my_id);
457    tunnel->rws = 8;
458    tunnel->peer_rws = 1;
459    tunnel->es = es;
460    tunnel->timeout = 1;
461    tunnel->my_id = tunnel_make_tid();
462    tunnel->ssthresh = 1;
463    tunnel->cwnd = 1;
464    tunnel->private = NULL;
465
466    hash_insert(&tunnels_by_my_id, tunnel);
467    DBG(l2tp_db(DBG_TUNNEL, "tunnel_new() -> %s\n", l2tp_debug_tunnel_to_str(tunnel)));
468    return tunnel;
469}
470
471/**********************************************************************
472* %FUNCTION: tunnel_free
473* %ARGUMENTS:
474*  tunnel -- tunnel to free
475* %RETURNS:
476*  Nothing
477* %DESCRIPTION:
478*  Frees all memory used by tunnel
479***********************************************************************/
480static void
481tunnel_free(l2tp_tunnel *tunnel)
482{
483    void *cursor;
484    l2tp_session *ses;
485    EventSelector *es = tunnel->es;
486
487    DBG(l2tp_db(DBG_TUNNEL, "tunnel_free(%s)\n", l2tp_debug_tunnel_to_str(tunnel)));
488
489    hash_remove(&tunnels_by_my_id, tunnel);
490    hash_remove(&tunnels_by_peer_address, tunnel);
491
492    for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
493	 ses ;
494	 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
495	l2tp_session_free(ses, "Tunnel closing down", 1);
496    }
497    if (tunnel->hello_handler) Event_DelHandler(es, tunnel->hello_handler);
498    if (tunnel->timeout_handler) Event_DelHandler(es, tunnel->timeout_handler);
499    if (tunnel->ack_handler) Event_DelHandler(es, tunnel->ack_handler);
500
501    while(tunnel->xmit_queue_head) {
502	tunnel_dequeue_head(tunnel);
503    }
504
505    DBG(l2tp_db(DBG_TUNNEL, "tunnel_close(%s) ops: %p\n",
506	l2tp_debug_tunnel_to_str(tunnel), tunnel->call_ops));
507    if (tunnel->call_ops && tunnel->call_ops->tunnel_close) {
508	tunnel->call_ops->tunnel_close(tunnel);
509    }
510
511    route_del(&tunnel->rt);
512    memset(tunnel, 0, sizeof(l2tp_tunnel));
513    free(tunnel);
514}
515
516/**********************************************************************
517* %FUNCTION: tunnel_establish
518* %ARGUMENTS:
519*  peer -- peer with which to establish tunnel
520*  es -- event selector for event loop
521* %RETURNS:
522*  A newly-allocated tunnel, or NULL on error.
523* %DESCRIPTION:
524*  Begins tunnel establishment to peer.
525***********************************************************************/
526static l2tp_tunnel *
527tunnel_establish(l2tp_peer *peer, EventSelector *es)
528{
529    l2tp_tunnel *tunnel;
530    struct sockaddr_in peer_addr = peer->addr;
531    struct hostent *he;
532
533    /* check peer_addr and resolv it based on the peername if needed */
534    if (peer_addr.sin_addr.s_addr == INADDR_ANY) {
535#if !defined(__UCLIBC__) \
536 || (__UCLIBC_MAJOR__ == 0 \
537 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ < 31)))
538	/* force ns refresh from resolv.conf with uClibc pre-0.9.31 */
539	res_init();
540#endif
541	he = gethostbyname(peer->peername);
542	if (!he) {
543            l2tp_set_errmsg("tunnel_establish: gethostbyname failed for '%s'", peer->peername);
544	    if (peer->persist && (peer->maxfail == 0 || peer->fail++ < peer->maxfail))
545	    {
546		struct timeval t;
547
548		t.tv_sec = peer->holdoff;
549		t.tv_usec = 0;
550		Event_AddTimerHandler(es, t, l2tp_tunnel_reestablish, peer);
551	    }
552	    return NULL;
553	}
554	memcpy(&peer_addr.sin_addr, he->h_addr, sizeof(peer_addr.sin_addr));
555    }
556
557    tunnel = tunnel_new(es);
558    if (!tunnel) return NULL;
559
560    tunnel->peer = peer;
561    tunnel->peer_addr = peer_addr;
562    tunnel->call_ops = tunnel->peer->lac_ops;
563
564    DBG(l2tp_db(DBG_TUNNEL, "tunnel_establish(%s) -> %s (%s)\n",
565	    l2tp_debug_tunnel_to_str(tunnel),
566	    inet_ntoa(peer_addr.sin_addr), peer->peername));
567
568    memset(&tunnel->rt, 0, sizeof(tunnel->rt));
569    route_add(tunnel->peer_addr.sin_addr, &tunnel->rt);
570
571    hash_insert(&tunnels_by_peer_address, tunnel);
572    tunnel_send_SCCRQ(tunnel);
573    tunnel_set_state(tunnel, TUNNEL_WAIT_CTL_REPLY);
574    return tunnel;
575}
576
577/**********************************************************************
578* %FUNCTION: tunnel_send_SCCRQ
579* %ARGUMENTS:
580*  tunnel -- the tunnel we wish to establish
581* %RETURNS:
582*  0 if we handed the datagram off to control transport, -1 otherwise.
583* %DESCRIPTION:
584*  Sends SCCRQ to establish a tunnel.
585***********************************************************************/
586static int
587tunnel_send_SCCRQ(l2tp_tunnel *tunnel)
588{
589    uint16_t u16;
590    uint32_t u32;
591    unsigned char tie_breaker[8];
592    unsigned char challenge[16];
593    int old_hide;
594    char *hostname;
595
596    l2tp_dgram *dgram = l2tp_dgram_new_control(MESSAGE_SCCRQ, 0, 0);
597    if (!dgram) return -1;
598
599    /* Add the AVP's */
600    /* HACK!  Cisco equipment cannot handle hidden AVP's in SCCRQ.
601       So we temporarily disable AVP hiding */
602    old_hide = tunnel->peer->hide_avps;
603    tunnel->peer->hide_avps = 0;
604
605    /* Protocol version */
606    u16 = htons(0x0100);
607    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
608		  sizeof(u16), VENDOR_IETF, AVP_PROTOCOL_VERSION, &u16);
609
610    /* Framing capabilities -- hard-coded as sync and async */
611    u32 = htonl(3);
612    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
613		  sizeof(u32), VENDOR_IETF, AVP_FRAMING_CAPABILITIES, &u32);
614
615    hostname = tunnel->peer->hostname[0] ? tunnel->peer->hostname : Hostname;
616
617    /* Host name */
618    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
619		  strlen(hostname), VENDOR_IETF, AVP_HOST_NAME,
620		  hostname);
621
622    /* Assigned ID */
623    u16 = htons(tunnel->my_id);
624    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
625		  sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
626
627    /* Receive window size */
628    u16 = htons(tunnel->rws);
629    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
630		  sizeof(u16), VENDOR_IETF, AVP_RECEIVE_WINDOW_SIZE, &u16);
631
632    /* Tie-breaker */
633    l2tp_random_fill(tie_breaker, sizeof(tie_breaker));
634    l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
635		  sizeof(tie_breaker), VENDOR_IETF, AVP_TIE_BREAKER,
636		  tie_breaker);
637
638    /* Vendor name */
639    l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
640		  strlen(VENDOR_STR), VENDOR_IETF,
641		  AVP_VENDOR_NAME, VENDOR_STR);
642
643    /* Challenge */
644    if (tunnel->peer->secret_len) {
645	l2tp_random_fill(challenge, sizeof(challenge));
646	l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
647			   sizeof(challenge), VENDOR_IETF,
648			   AVP_CHALLENGE, challenge);
649
650	/* Compute and save expected response */
651	l2tp_auth_gen_response(MESSAGE_SCCRP, tunnel->peer->secret,
652			       challenge, sizeof(challenge), tunnel->expected_response);
653    }
654
655    tunnel->peer->hide_avps = old_hide;
656    /* And ship it out */
657    l2tp_tunnel_xmit_control_message(tunnel, dgram);
658    return 1;
659}
660
661/**********************************************************************
662* %FUNCTION: tunnel_handle_received_control_datagram
663* %ARGUMENTS:
664*  dgram -- received datagram
665*  es -- event selector
666*  from -- address of sender
667* %RETURNS:
668*  Nothing
669* %DESCRIPTION:
670*  Handles a received control datagram
671***********************************************************************/
672void
673l2tp_tunnel_handle_received_control_datagram(l2tp_dgram *dgram,
674					     EventSelector *es,
675					     struct sockaddr_in *from)
676{
677    l2tp_tunnel *tunnel;
678
679    /* If it's SCCRQ, then handle it */
680    if (dgram->msg_type == MESSAGE_SCCRQ) {
681	tunnel_handle_SCCRQ(dgram, es, from);
682	return;
683    }
684
685    /* Find the tunnel to which it refers */
686    if (dgram->tid == 0) {
687	l2tp_set_errmsg("Invalid control message - tunnel ID = 0");
688	return;
689    }
690    tunnel = l2tp_tunnel_find_by_my_id(dgram->tid);
691
692    if (!tunnel) {
693	/* TODO: Send error message back? */
694	DBG(l2tp_db(DBG_TUNNEL, "Invalid control message - unknown tunnel ID %d\n",
695		   (int) dgram->tid));
696	return;
697    }
698
699    /* Verify that source address is the tunnel's peer */
700    if (tunnel->peer && tunnel->peer->validate_peer_ip) {
701	if (from->sin_addr.s_addr != tunnel->peer_addr.sin_addr.s_addr) {
702	    l2tp_set_errmsg("Invalid control message for tunnel %s - not sent from peer",
703			    l2tp_debug_tunnel_to_str(tunnel));
704	    return;
705	}
706    }
707
708    /* Set port for replies */
709    tunnel->peer_addr.sin_port = from->sin_port;
710
711    /* Schedule an ACK for 100ms from now, but do not ack ZLB's */
712    if (dgram->msg_type != MESSAGE_ZLB) {
713	tunnel_schedule_ack(tunnel);
714    }
715
716    /* If it's an old datagram, ignore it */
717    if (dgram->Ns != tunnel->Nr) {
718	if (SERIAL_LT(dgram->Ns, tunnel->Nr)) {
719	    /* Old packet: Drop it */
720	    /* Throw away ack'd packets in our xmit queue */
721	    tunnel_dequeue_acked_packets(tunnel);
722	    return;
723	}
724	/* Out-of-order packet or intermediate dropped packets.
725	   TODO: Look into handling this better */
726	return;
727    }
728
729    /* Do not increment if we got ZLB */
730    if (dgram->msg_type != MESSAGE_ZLB) {
731	tunnel->Nr++;
732    }
733
734    /* Update peer_Nr */
735    if (SERIAL_GT(dgram->Nr, tunnel->peer_Nr)) {
736	tunnel->peer_Nr = dgram->Nr;
737    }
738
739    /* Reschedule HELLO handler for 60 seconds in future */
740    if (tunnel->state != TUNNEL_RECEIVED_STOP_CCN &&
741	tunnel->state != TUNNEL_SENT_STOP_CCN &&
742	tunnel->hello_handler != NULL) {
743	struct timeval t;
744	t.tv_sec = 60;
745	t.tv_usec = 0;
746	Event_ChangeTimeout(tunnel->hello_handler, t);
747    }
748
749    /* Reset retransmission stuff */
750    tunnel->retransmissions = 0;
751    tunnel->timeout = 1;
752
753    /* Throw away ack'd packets in our xmit queue */
754    tunnel_dequeue_acked_packets(tunnel);
755
756    /* Let the specific tunnel handle it */
757    tunnel_process_received_datagram(tunnel, dgram);
758
759    /* Run the xmit queue -- window may have opened */
760    tunnel_xmit_queued_messages(tunnel);
761
762    /* Destroy tunnel if required and if xmit queue empty */
763    if (!tunnel->xmit_queue_head) {
764	if (tunnel->timeout_handler) {
765	    Event_DelHandler(tunnel->es, tunnel->timeout_handler);
766	    tunnel->timeout_handler = NULL;
767	}
768	if (tunnel->state == TUNNEL_RECEIVED_STOP_CCN) {
769	    tunnel_schedule_destruction(tunnel);
770	} else if (tunnel->state == TUNNEL_SENT_STOP_CCN) {
771	    /* Our stop-CCN has been ack'd, destroy NOW */
772	    tunnel_free(tunnel);
773	}
774    }
775}
776
777/**********************************************************************
778* %FUNCTION: tunnel_handle_SCCRQ
779* %ARGUMENTS:
780*  dgram -- the received datagram
781*  es -- event selector
782*  from -- address of sender
783* %RETURNS:
784*  Nothing
785* %DESCRIPTION:
786*  Handles an incoming SCCRQ
787***********************************************************************/
788static void
789tunnel_handle_SCCRQ(l2tp_dgram *dgram,
790		    EventSelector *es,
791		    struct sockaddr_in *from)
792{
793    l2tp_tunnel *tunnel = NULL;
794
795    uint16_t u16;
796    uint32_t u32;
797    unsigned char challenge[16];
798    char *hostname;
799
800    /* TODO: Check if this is a retransmitted SCCRQ */
801    /* Allocate a tunnel */
802    tunnel = tunnel_new(es);
803    if (!tunnel) {
804	l2tp_set_errmsg("Unable to allocate new tunnel");
805	return;
806    }
807
808    tunnel->peer_addr = *from;
809
810    hash_insert(&tunnels_by_peer_address, tunnel);
811
812    /* We've received our first control datagram (SCCRQ) */
813    tunnel->Nr = 1;
814
815    if (tunnel_set_params(tunnel, dgram) < 0) return;
816
817    /* Hunky-dory.  Send SCCRP */
818    dgram = l2tp_dgram_new_control(MESSAGE_SCCRP, tunnel->assigned_id, 0);
819    if (!dgram) {
820	/* Doh! Out of resources.  Not much chance of StopCCN working... */
821	tunnel_send_StopCCN(tunnel,
822			    RESULT_GENERAL_ERROR, ERROR_OUT_OF_RESOURCES,
823			    "Out of memory");
824	return;
825    }
826
827    /* Protocol version */
828    u16 = htons(0x0100);
829    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
830		  sizeof(u16), VENDOR_IETF, AVP_PROTOCOL_VERSION, &u16);
831
832    /* Framing capabilities -- hard-coded as sync and async */
833    u32 = htonl(3);
834    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
835		  sizeof(u32), VENDOR_IETF, AVP_FRAMING_CAPABILITIES, &u32);
836
837    hostname = tunnel->peer->hostname[0] ? tunnel->peer->hostname : Hostname;
838
839    /* Host name */
840    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
841		  strlen(hostname), VENDOR_IETF, AVP_HOST_NAME,
842		  hostname);
843
844    /* Assigned ID */
845    u16 = htons(tunnel->my_id);
846    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
847		  sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
848
849    /* Receive window size */
850    u16 = htons(tunnel->rws);
851    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
852		  sizeof(u16), VENDOR_IETF, AVP_RECEIVE_WINDOW_SIZE, &u16);
853
854    /* Vendor name */
855    l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
856		  strlen(VENDOR_STR), VENDOR_IETF,
857		  AVP_VENDOR_NAME, VENDOR_STR);
858
859    if (tunnel->peer->secret_len) {
860	/* Response */
861	l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
862			   MD5LEN, VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
863			   tunnel->response);
864
865	/* Challenge */
866	l2tp_random_fill(challenge, sizeof(challenge));
867	l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
868			   sizeof(challenge), VENDOR_IETF,
869			   AVP_CHALLENGE, challenge);
870
871	/* Compute and save expected response */
872	l2tp_auth_gen_response(MESSAGE_SCCCN, tunnel->peer->secret,
873			       challenge, sizeof(challenge), tunnel->expected_response);
874    }
875
876    tunnel_set_state(tunnel, TUNNEL_WAIT_CTL_CONN);
877
878    /* And ship it out */
879    l2tp_tunnel_xmit_control_message(tunnel, dgram);
880}
881
882/**********************************************************************
883* %FUNCTION: tunnel_schedule_ack
884* %ARGUMENTS:
885*  tunnel -- the tunnel
886* %RETURNS:
887*  Nothing
888* %DESCRIPTION:
889*  Schedules an ack for 100ms from now.  The hope is we'll be able to
890*  piggy-back the ack on a packet in the queue; if not, we'll send a ZLB.
891***********************************************************************/
892static void
893tunnel_schedule_ack(l2tp_tunnel *tunnel)
894{
895    struct timeval t;
896
897    DBG(l2tp_db(DBG_FLOW, "tunnel_schedule_ack(%s)\n",
898	   l2tp_debug_tunnel_to_str(tunnel)));
899    /* Already scheduled?  Do nothing */
900    if (tunnel->ack_handler) return;
901
902    t.tv_sec = 0;
903    t.tv_usec = 100000;
904    tunnel->ack_handler = Event_AddTimerHandler(tunnel->es,
905						t, tunnel_do_ack, tunnel);
906}
907
908/**********************************************************************
909* %FUNCTION: tunnel_do_ack
910* %ARGUMENTS:
911*  es -- event selector
912*  fd, flags -- not used
913*  data -- pointer to tunnel which needs ack
914* %RETURNS:
915*  Nothing
916* %DESCRIPTION:
917*  If there is a frame on our queue, update it's Nr and run queue; if not,
918*  send a ZLB immediately.
919***********************************************************************/
920static void
921tunnel_do_ack(EventSelector *es,
922	      int fd,
923	      unsigned int flags,
924	      void *data)
925{
926    l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
927
928    /* Ack handler has fired */
929    tunnel->ack_handler = NULL;
930
931    DBG(l2tp_db(DBG_FLOW, "tunnel_do_ack(%s)\n",
932	   l2tp_debug_tunnel_to_str(tunnel)));
933
934    /* If nothing is on the queue, add a ZLB */
935    /* Or, if we cannot transmit because of flow-control, send ZLB */
936    if (!tunnel->xmit_new_dgrams ||
937	tunnel_outstanding_frames(tunnel) >= tunnel->cwnd) {
938	tunnel_send_ZLB(tunnel);
939	return;
940    }
941
942    /* Run the queue */
943    tunnel_xmit_queued_messages(tunnel);
944}
945
946/**********************************************************************
947* %FUNCTION: tunnel_dequeue_acked_packets
948* %ARGUMENTS:
949*  tunnel -- the tunnel
950* %RETURNS:
951*  Nothing
952* %DESCRIPTION:
953*  Discards all acknowledged packets from our xmit queue.
954***********************************************************************/
955static void
956tunnel_dequeue_acked_packets(l2tp_tunnel *tunnel)
957{
958    l2tp_dgram *dgram = tunnel->xmit_queue_head;
959    DBG(l2tp_db(DBG_FLOW, "tunnel_dequeue_acked_packets(%s) %s\n",
960       l2tp_debug_tunnel_to_str(tunnel), tunnel_flow_control_stats(tunnel)));
961    while (dgram) {
962	if (SERIAL_LT(dgram->Ns, tunnel->peer_Nr)) {
963	    tunnel_dequeue_head(tunnel);
964	    if (tunnel->cwnd < tunnel->ssthresh) {
965		/* Slow start: increment CWND for each packet dequeued */
966		tunnel->cwnd++;
967		if (tunnel->cwnd > tunnel->peer_rws) {
968		    tunnel->cwnd = tunnel->peer_rws;
969		}
970	    } else {
971		/* Congestion avoidance: increment CWND for each CWND
972		   packets dequeued */
973		tunnel->cwnd_counter++;
974		if (tunnel->cwnd_counter >= tunnel->cwnd) {
975		    tunnel->cwnd_counter = 0;
976		    tunnel->cwnd++;
977		    if (tunnel->cwnd > tunnel->peer_rws) {
978			tunnel->cwnd = tunnel->peer_rws;
979		    }
980		}
981	    }
982	} else {
983	    break;
984	}
985	dgram = tunnel->xmit_queue_head;
986    }
987}
988
989/**********************************************************************
990* %FUNCTION: tunnel_handle_timeout
991* %ARGUMENTS:
992*  es -- event selector
993*  fd, flags -- not used
994*  data -- pointer to tunnel which needs ack
995* %RETURNS:
996*  Nothing
997* %DESCRIPTION:
998*  Called when retransmission timer fires.
999***********************************************************************/
1000static void
1001tunnel_handle_timeout(EventSelector *es,
1002		      int fd,
1003		      unsigned int flags,
1004		      void *data)
1005{
1006    l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
1007
1008    /* Timeout handler has fired */
1009    tunnel->timeout_handler = NULL;
1010    DBG(l2tp_db(DBG_FLOW, "tunnel_handle_timeout(%s)\n",
1011	   l2tp_debug_tunnel_to_str(tunnel)));
1012
1013    /* Reset xmit_new_dgrams */
1014    tunnel->xmit_new_dgrams = tunnel->xmit_queue_head;
1015
1016    /* Set Ns on wire to Ns of first frame in queue */
1017    if (tunnel->xmit_queue_head) {
1018	tunnel->Ns_on_wire = tunnel->xmit_queue_head->Ns;
1019    }
1020
1021    /* Go back to slow-start phase */
1022    tunnel->ssthresh = tunnel->cwnd / 2;
1023    if (!tunnel->ssthresh) tunnel->ssthresh = 1;
1024    tunnel->cwnd = 1;
1025    tunnel->cwnd_counter = 0;
1026
1027    tunnel->retransmissions++;
1028    if (tunnel->retransmissions >= MAX_RETRANSMISSIONS) {
1029	l2tp_set_errmsg("Too many retransmissions on tunnel (%s); closing down",
1030		   l2tp_debug_tunnel_to_str(tunnel));
1031
1032	if (tunnel->state < TUNNEL_ESTABLISHED && tunnel->peer && tunnel->peer->persist &&
1033	    (tunnel->peer->maxfail == 0 || tunnel->peer->fail++ < tunnel->peer->maxfail))
1034	{
1035	    struct timeval t;
1036
1037	    t.tv_sec = tunnel->peer->holdoff;
1038	    t.tv_usec = 0;
1039	    Event_AddTimerHandler(tunnel->es, t, l2tp_tunnel_reestablish, tunnel->peer);
1040	}
1041
1042	/* Close tunnel... */
1043	tunnel_free(tunnel);
1044	return;
1045    }
1046
1047    /* Double timeout, capping at 8 seconds */
1048    if (tunnel->timeout < 8) {
1049	tunnel->timeout *= 2;
1050    }
1051
1052    /* Run the queue */
1053    tunnel_xmit_queued_messages(tunnel);
1054}
1055
1056/**********************************************************************
1057* %FUNCTION: tunnel_send_StopCCN
1058* %ARGUMENTS:
1059*  tunnel -- the tunnel
1060*  result_code -- what to put in result-code AVP
1061*  error_code -- what to put in error-code field
1062*  fmt -- format string for error message
1063*  ... -- args for formatting error message
1064* %RETURNS:
1065*  Nothing
1066* %DESCRIPTION:
1067*  Sends a StopCCN control message.
1068***********************************************************************/
1069static void
1070tunnel_send_StopCCN(l2tp_tunnel *tunnel,
1071		    int result_code,
1072		    int error_code,
1073		    char const *fmt, ...)
1074{
1075    char buf[256];
1076    va_list ap;
1077    uint16_t u16;
1078    uint16_t len;
1079    l2tp_dgram *dgram;
1080
1081    /* Build the buffer for the result-code AVP */
1082    buf[0] = result_code / 256;
1083    buf[1] = result_code & 255;
1084    buf[2] = error_code / 256;
1085    buf[3] = error_code & 255;
1086
1087    va_start(ap, fmt);
1088    vsnprintf(buf+4, 256-4, fmt, ap);
1089    buf[255] = 0;
1090    va_end(ap);
1091
1092    DBG(l2tp_db(DBG_TUNNEL, "tunnel_send_StopCCN(%s, %d, %d, %s)\n",
1093	   l2tp_debug_tunnel_to_str(tunnel), result_code, error_code, buf+4));
1094
1095    len = 4 + strlen(buf+4);
1096    /* Build the datagram */
1097    dgram = l2tp_dgram_new_control(MESSAGE_StopCCN, tunnel->assigned_id, 0);
1098    if (!dgram) return;
1099
1100    /* Add assigned tunnel ID */
1101    u16 = htons(tunnel->my_id);
1102    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1103		  sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
1104
1105    /* Add result code */
1106    l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1107		  len, VENDOR_IETF, AVP_RESULT_CODE, buf);
1108
1109    /* TODO: Clean up */
1110    tunnel_set_state(tunnel, TUNNEL_SENT_STOP_CCN);
1111
1112    /* Ship it out */
1113    l2tp_tunnel_xmit_control_message(tunnel, dgram);
1114}
1115
1116/**********************************************************************
1117* %FUNCTION: tunnel_handle_StopCCN
1118* %ARGUMENTS:
1119*  tunnel -- the tunnel
1120*  dgram -- received datagram
1121* %RETURNS:
1122*  Nothing
1123* %DESCRIPTION:
1124*  Processes a received StopCCN frame (shuts tunnel down)
1125***********************************************************************/
1126static void
1127tunnel_handle_StopCCN(l2tp_tunnel *tunnel,
1128		       l2tp_dgram *dgram)
1129{
1130    unsigned char *val;
1131    int mandatory, hidden;
1132    uint16_t len, vendor, type;
1133    int err;
1134    l2tp_session *ses;
1135    void *cursor;
1136
1137    /* Shut down all the sessions */
1138    for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1139	 ses ;
1140	 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1141	hash_remove(&tunnel->sessions_by_my_id, ses);
1142	l2tp_session_free(ses, "Tunnel closing down", 1);
1143    }
1144
1145    tunnel_set_state(tunnel, TUNNEL_RECEIVED_STOP_CCN);
1146
1147    /* If there are any queued datagrams waiting for transmission,
1148       nuke them and adjust tunnel's Ns to whatever peer has ack'd */
1149    /* TODO: Is this correct? */
1150    if (tunnel->xmit_queue_head) {
1151	tunnel->Ns = tunnel->peer_Nr;
1152	while(tunnel->xmit_queue_head) {
1153	    tunnel_dequeue_head(tunnel);
1154	}
1155    }
1156
1157    /* Parse the AVP's */
1158    while(1) {
1159	val = l2tp_dgram_pull_avp(dgram, tunnel, &mandatory, &hidden,
1160			     &len, &vendor, &type, &err);
1161	if (!val) {
1162	    break;
1163	}
1164
1165	/* Only care about assigned tunnel ID.  TODO: Fix this! */
1166	if (vendor != VENDOR_IETF || type != AVP_ASSIGNED_TUNNEL_ID) {
1167	    continue;
1168	}
1169
1170	if (len == 2) {
1171	    tunnel->assigned_id = ((unsigned int) val[0]) * 256 +
1172		(unsigned int) val[1];
1173	}
1174    }
1175
1176    /* No point in delaying ack; there will never be a datagram for
1177       piggy-back.  So cancel ack timer and shoot out a ZLB now */
1178    if (tunnel->ack_handler) {
1179	Event_DelHandler(tunnel->es, tunnel->ack_handler);
1180	tunnel->ack_handler = NULL;
1181    }
1182    tunnel_send_ZLB(tunnel);
1183    /* We'll be scheduled for destruction after this function returns */
1184}
1185
1186/**********************************************************************
1187* %FUNCTION: tunnel_process_received_datagram
1188* %ARGUMENTS:
1189*  tunnel -- the tunnel
1190*  dgram -- the received datagram
1191* %RETURNS:
1192*  Nothing
1193* %DESCRIPTION:
1194*  Handles a received control message for this tunnel
1195***********************************************************************/
1196static void
1197tunnel_process_received_datagram(l2tp_tunnel *tunnel,
1198				 l2tp_dgram *dgram)
1199{
1200    l2tp_session *ses = NULL;
1201
1202    /* If message is associated with existing session, find session */
1203
1204    DBG(l2tp_db(DBG_TUNNEL, "tunnel_process_received_datagram(%s, %s)\n",
1205	   l2tp_debug_tunnel_to_str(tunnel),
1206	   l2tp_debug_message_type_to_str(dgram->msg_type)));
1207    switch (dgram->msg_type) {
1208    case MESSAGE_OCRP:
1209    case MESSAGE_OCCN:
1210    case MESSAGE_ICRP:
1211    case MESSAGE_ICCN:
1212    case MESSAGE_CDN:
1213	ses = l2tp_tunnel_find_session(tunnel, dgram->sid);
1214	if (!ses) {
1215	    l2tp_set_errmsg("Session-related message for unknown session %d",
1216		       (int) dgram->sid);
1217	    return;
1218	}
1219    }
1220
1221    switch (dgram->msg_type) {
1222    case MESSAGE_StopCCN:
1223	tunnel_handle_StopCCN(tunnel, dgram);
1224	return;
1225    case MESSAGE_SCCRP:
1226	tunnel_handle_SCCRP(tunnel, dgram);
1227	return;
1228    case MESSAGE_SCCCN:
1229	tunnel_handle_SCCCN(tunnel, dgram);
1230	return;
1231    case MESSAGE_ICRQ:
1232	tunnel_handle_ICRQ(tunnel, dgram);
1233	return;
1234    case MESSAGE_CDN:
1235	l2tp_session_handle_CDN(ses, dgram);
1236	return;
1237    case MESSAGE_ICRP:
1238	l2tp_session_handle_ICRP(ses, dgram);
1239	return;
1240    case MESSAGE_ICCN:
1241	l2tp_session_handle_ICCN(ses, dgram);
1242	return;
1243    case MESSAGE_HELLO:
1244	tunnel_setup_hello(tunnel);
1245	return;
1246    }
1247}
1248
1249/**********************************************************************
1250* %FUNCTION: tunnel_finally_cleanup
1251* %ARGUMENTS:
1252*  es -- event selector
1253*  fd, flags -- ignored
1254*  data -- the tunnel
1255* %RETURNS:
1256*  Nothing
1257* %DESCRIPTION:
1258*  Deallocates all tunnel state
1259***********************************************************************/
1260static void
1261tunnel_finally_cleanup(EventSelector *es,
1262		       int fd,
1263		       unsigned int flags,
1264		       void *data)
1265{
1266    l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
1267
1268    /* Hello handler has fired */
1269    tunnel->hello_handler = NULL;
1270    tunnel_free(tunnel);
1271}
1272
1273/**********************************************************************
1274* %FUNCTION: tunnel_schedule_destruction
1275* %ARGUMENTS:
1276*  tunnel -- tunnel which is to be destroyed
1277* %RETURNS:
1278*  Nothing
1279* %DESCRIPTION:
1280*  Schedules tunnel for destruction 31 seconds hence.
1281***********************************************************************/
1282static void
1283tunnel_schedule_destruction(l2tp_tunnel *tunnel)
1284{
1285    struct timeval t;
1286    void *cursor;
1287    l2tp_session *ses;
1288
1289    t.tv_sec = 31;
1290    t.tv_usec = 0;
1291
1292    DBG(l2tp_db(DBG_TUNNEL, "tunnel_schedule_destruction(%s)\n",
1293	   l2tp_debug_tunnel_to_str(tunnel)));
1294    /* Shut down the tunnel in 31 seconds - (ab)use the hello handler */
1295    if (tunnel->hello_handler) {
1296	Event_DelHandler(tunnel->es, tunnel->hello_handler);
1297    }
1298    tunnel->hello_handler =
1299	Event_AddTimerHandler(tunnel->es, t,
1300			      tunnel_finally_cleanup, tunnel);
1301
1302    /* Kill the sessions now */
1303    for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1304	 ses ;
1305	 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1306	l2tp_session_free(ses, "Tunnel closing down", 1);
1307    }
1308
1309    /* Clear hash table */
1310    l2tp_session_hash_init(&tunnel->sessions_by_my_id);
1311}
1312
1313/**********************************************************************
1314* %FUNCTION: tunnel_send_ZLB
1315* %ARGUMENTS:
1316*  tunnel -- the tunnel
1317* %RETURNS:
1318*  Nothing
1319* %DESCRIPTION:
1320*  Sends a ZLB ack packet.
1321***********************************************************************/
1322void
1323tunnel_send_ZLB(l2tp_tunnel *tunnel)
1324{
1325    l2tp_dgram *dgram =
1326	l2tp_dgram_new_control(MESSAGE_ZLB, tunnel->assigned_id, 0);
1327    if (!dgram) {
1328	l2tp_set_errmsg("tunnel_send_ZLB: Out of memory");
1329	return;
1330    }
1331    dgram->Nr = tunnel->Nr;
1332    dgram->Ns = tunnel->Ns_on_wire;
1333    l2tp_dgram_send_to_wire(dgram, &tunnel->peer_addr);
1334    l2tp_dgram_free(dgram);
1335}
1336
1337/**********************************************************************
1338* %FUNCTION: tunnel_handle_SCCRP
1339* %ARGUMENTS:
1340*  tunnel -- the tunnel
1341*  dgram -- the incoming datagram
1342* %RETURNS:
1343*  Nothing
1344* %DESCRIPTION:
1345*  Handles an incoming SCCRP
1346***********************************************************************/
1347static void
1348tunnel_handle_SCCRP(l2tp_tunnel *tunnel,
1349		    l2tp_dgram *dgram)
1350{
1351
1352    /* TODO: If we don't get challenge response at all, barf */
1353    /* Are we expecing SCCRP? */
1354    if (tunnel->state != TUNNEL_WAIT_CTL_REPLY) {
1355	tunnel_send_StopCCN(tunnel, RESULT_FSM_ERROR, 0, "Not expecting SCCRP");
1356	return;
1357    }
1358
1359    /* Extract tunnel params */
1360    if (tunnel_set_params(tunnel, dgram) < 0) return;
1361
1362    DBG(l2tp_db(DBG_TUNNEL, "tunnel_establish(%s) ops: %p\n",
1363	l2tp_debug_tunnel_to_str(tunnel), tunnel->call_ops));
1364    if (tunnel->call_ops && tunnel->call_ops->tunnel_establish &&
1365	tunnel->call_ops->tunnel_establish(tunnel) < 0) {
1366	tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR, ERROR_VENDOR_SPECIFIC,
1367			    "%s", l2tp_get_errmsg());
1368	return;
1369    }
1370
1371    tunnel_set_state(tunnel, TUNNEL_ESTABLISHED);
1372    tunnel_setup_hello(tunnel);
1373
1374    /* Hunky-dory.  Send SCCCN */
1375    dgram = l2tp_dgram_new_control(MESSAGE_SCCCN, tunnel->assigned_id, 0);
1376    if (!dgram) {
1377	/* Doh! Out of resources.  Not much chance of StopCCN working... */
1378	tunnel_send_StopCCN(tunnel,
1379			    RESULT_GENERAL_ERROR, ERROR_OUT_OF_RESOURCES,
1380			    "Out of memory");
1381	return;
1382    }
1383
1384    /* Add response */
1385    if (tunnel->peer->secret_len) {
1386	l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1387			   MD5LEN, VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
1388			   tunnel->response);
1389    }
1390
1391    /* Ship it out */
1392    l2tp_tunnel_xmit_control_message(tunnel, dgram);
1393
1394    /* Tell sessions tunnel has been established */
1395    tunnel_tell_sessions_tunnel_open(tunnel);
1396}
1397
1398/**********************************************************************
1399* %FUNCTION: tunnel_set_params
1400* %ARGUMENTS:
1401*  tunnel -- the tunnel
1402*  dgram -- incoming SCCRQ or SCCRP datagram
1403* %RETURNS:
1404*  0 if OK, non-zero on error
1405* %DESCRIPTION:
1406*  Sets up initial tunnel parameters (assigned ID, etc.)
1407***********************************************************************/
1408static int
1409tunnel_set_params(l2tp_tunnel *tunnel,
1410		  l2tp_dgram *dgram)
1411{
1412    unsigned char *val;
1413    int mandatory, hidden;
1414    uint16_t len, vendor, type;
1415    int err = 0;
1416    int found_response = 0;
1417
1418    uint16_t u16;
1419
1420    /* Get host name */
1421    val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1422                           VENDOR_IETF, AVP_HOST_NAME);
1423    if (!val) {
1424	l2tp_set_errmsg("No host name AVP in SCCRQ");
1425	tunnel_free(tunnel);
1426	return -1;
1427    }
1428
1429    if (len >= MAX_HOSTNAME) len = MAX_HOSTNAME-1;
1430    memcpy(tunnel->peer_hostname, val, len);
1431    tunnel->peer_hostname[len+1] = 0;
1432    DBG(l2tp_db(DBG_TUNNEL, "%s: Peer host name is '%s'\n",
1433                           l2tp_debug_tunnel_to_str(tunnel), tunnel->peer_hostname));
1434
1435    /* Find peer */
1436    if (tunnel->peer == NULL || tunnel->peer->addr.sin_addr.s_addr != INADDR_ANY)
1437	tunnel->peer = l2tp_peer_find(&tunnel->peer_addr, tunnel->peer_hostname);
1438
1439    /* Get assigned tunnel ID */
1440    val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1441			   VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID);
1442    if (!val) {
1443	l2tp_set_errmsg("No assigned tunnel ID AVP in SCCRQ");
1444	tunnel_free(tunnel);
1445	return -1;
1446    }
1447
1448    if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID,
1449			    len, mandatory)) {
1450	tunnel_free(tunnel);
1451	return -1;
1452    }
1453
1454    /* Set tid */
1455    tunnel->assigned_id = ((unsigned int) val[0]) * 256 + (unsigned int) val[1];
1456    if (!tunnel->assigned_id) {
1457	l2tp_set_errmsg("Invalid assigned-tunnel-ID of zero");
1458	tunnel_free(tunnel);
1459	return -1;
1460    }
1461
1462    /* Validate peer */
1463    if (!tunnel->peer) {
1464	l2tp_set_errmsg("Peer %s is not authorized to create a tunnel",
1465		   inet_ntoa(tunnel->peer_addr.sin_addr));
1466	tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_OK, "%s", l2tp_get_errmsg());
1467	return -1;
1468    }
1469
1470    /* Setup LNS call ops if LAC wasn't set before */
1471    if (!tunnel->call_ops)
1472	tunnel->call_ops = tunnel->peer->lns_ops;
1473
1474    /* Pull out and examine AVP's */
1475    while(1) {
1476	val = l2tp_dgram_pull_avp(dgram, tunnel, &mandatory, &hidden,
1477			     &len, &vendor, &type, &err);
1478	if (!val) {
1479	    if (err) {
1480		tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1481				    ERROR_BAD_VALUE, "%s", l2tp_get_errmsg());
1482		return -1;
1483	    }
1484	    break;
1485	}
1486
1487	/* Unknown vendor?  Ignore, unless mandatory */
1488	if (vendor != VENDOR_IETF) {
1489	    if (!mandatory) continue;
1490	    tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1491				ERROR_UNKNOWN_AVP_WITH_M_BIT,
1492				"Unknown mandatory attribute (vendor=%d, type=%d) in %s",
1493				(int) vendor, (int) type,
1494				l2tp_debug_avp_type_to_str(dgram->msg_type));
1495	    return -1;
1496	}
1497
1498	/* Validate AVP, ignore invalid AVP's without M bit set */
1499	if (!l2tp_dgram_validate_avp(vendor, type, len, mandatory)) {
1500	    if (!mandatory) continue;
1501	    tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1502				ERROR_BAD_LENGTH, "%s", l2tp_get_errmsg());
1503	    return -1;
1504	}
1505
1506	switch(type) {
1507	case AVP_PROTOCOL_VERSION:
1508	    u16 = ((uint16_t) val[0]) * 256 + val[1];
1509	    if (u16 != 0x100) {
1510		tunnel_send_StopCCN(tunnel, RESULT_UNSUPPORTED_VERSION,
1511				    0x100, "Unsupported protocol version");
1512		return -1;
1513	    }
1514	    break;
1515
1516	case AVP_HOST_NAME:
1517	    /* Already been handled */
1518	    break;
1519
1520	case AVP_FRAMING_CAPABILITIES:
1521	    /* TODO: Do we care about framing capabilities? */
1522	    break;
1523
1524	case AVP_ASSIGNED_TUNNEL_ID:
1525	    /* Already been handled */
1526	    break;
1527
1528	case AVP_BEARER_CAPABILITIES:
1529	    /* TODO: Do we care? */
1530	    break;
1531
1532	case AVP_RECEIVE_WINDOW_SIZE:
1533	    u16 = ((uint16_t) val[0]) * 256 + val[1];
1534	    /* Silently correct bogus rwin */
1535	    if (u16 < 1) u16 = 1;
1536	    tunnel->peer_rws = u16;
1537	    tunnel->ssthresh = u16;
1538	    break;
1539
1540	case AVP_CHALLENGE:
1541	    if (tunnel->peer->secret_len) {
1542		l2tp_auth_gen_response(
1543		    ((dgram->msg_type == MESSAGE_SCCRQ) ? MESSAGE_SCCRP : MESSAGE_SCCCN),
1544		    tunnel->peer->secret,
1545		    val, len, tunnel->response);
1546	    }
1547	    break;
1548
1549	case AVP_CHALLENGE_RESPONSE:
1550	    /* Length has been validated by l2tp_dgram_validate_avp */
1551	    if (tunnel->peer->secret_len) {
1552		if (memcmp(val, tunnel->expected_response, MD5LEN)) {
1553		    tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_BAD_VALUE,
1554					"Incorrect challenge response");
1555		    return -1;
1556		}
1557	    }
1558	    found_response = 1;
1559	    break;
1560
1561	case AVP_TIE_BREAKER:
1562	    /* TODO: Handle tie-breaker */
1563	    break;
1564
1565	case AVP_FIRMWARE_REVISION:
1566	    /* TODO: Do we care? */
1567	    break;
1568
1569	case AVP_VENDOR_NAME:
1570	    /* TODO: Do we care? */
1571	    break;
1572
1573	default:
1574	    /* TODO: Maybe print an error? */
1575	    break;
1576	}
1577    }
1578
1579    if (tunnel->peer->secret_len &&
1580	!found_response &&
1581	dgram->msg_type != MESSAGE_SCCRQ) {
1582	tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, 0,
1583			    "Missing challenge-response");
1584	return -1;
1585    }
1586    return 0;
1587}
1588
1589/**********************************************************************
1590* %FUNCTION: tunnel_setup_hello
1591* %ARGUMENTS:
1592*  tunnel -- the tunnel
1593* %RETURNS:
1594*  Nothing
1595* %DESCRIPTION:
1596*  Sets up timer for sending HELLO messages
1597***********************************************************************/
1598static void
1599tunnel_setup_hello(l2tp_tunnel *tunnel)
1600{
1601    struct timeval t;
1602
1603    t.tv_sec = 60;
1604    t.tv_usec = 0;
1605
1606    if (tunnel->hello_handler) {
1607	Event_DelHandler(tunnel->es, tunnel->hello_handler);
1608    }
1609    tunnel->hello_handler = Event_AddTimerHandler(tunnel->es, t,
1610						  tunnel_do_hello, tunnel);
1611}
1612
1613/**********************************************************************
1614* %FUNCTION: tunnel_do_hello
1615* %ARGUMENTS:
1616*  es -- event selector
1617*  fd, flags -- ignored
1618*  data -- the tunnel
1619* %RETURNS:
1620*  Nothing
1621* %DESCRIPTION:
1622*  Deallocates all tunnel state
1623***********************************************************************/
1624static void
1625tunnel_do_hello(EventSelector *es,
1626		int fd,
1627		unsigned int flags,
1628		void *data)
1629{
1630    l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
1631    l2tp_dgram *dgram;
1632
1633    /* Hello handler has fired */
1634    tunnel->hello_handler = NULL;
1635
1636    /* Reschedule HELLO timer */
1637    tunnel_setup_hello(tunnel);
1638
1639    /* Send a HELLO message */
1640    dgram = l2tp_dgram_new_control(MESSAGE_HELLO, tunnel->assigned_id, 0);
1641    if (dgram) l2tp_tunnel_xmit_control_message(tunnel, dgram);
1642}
1643
1644/**********************************************************************
1645* %FUNCTION: tunnel_handle_SCCCN
1646* %ARGUMENTS:
1647*  tunnel -- the tunnel
1648*  dgram -- the incoming datagram
1649* %RETURNS:
1650*  Nothing
1651* %DESCRIPTION:
1652*  Handles an incoming SCCCN
1653***********************************************************************/
1654static void
1655tunnel_handle_SCCCN(l2tp_tunnel *tunnel,
1656		    l2tp_dgram *dgram)
1657{
1658    unsigned char *val;
1659    uint16_t len;
1660    int hidden, mandatory;
1661
1662    /* Are we expecing SCCCN? */
1663    if (tunnel->state != TUNNEL_WAIT_CTL_CONN) {
1664	tunnel_send_StopCCN(tunnel, RESULT_FSM_ERROR, 0, "Not expecting SCCCN");
1665	return;
1666    }
1667
1668    /* Check challenge response */
1669    if (tunnel->peer->secret_len) {
1670	val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1671				    VENDOR_IETF, AVP_CHALLENGE_RESPONSE);
1672	if (!val) {
1673	    tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, 0,
1674				"Missing challenge-response");
1675	    return;
1676	}
1677
1678	if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
1679				     len, mandatory)) {
1680	    tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR, ERROR_BAD_LENGTH,
1681				"Invalid challenge-response");
1682	    return;
1683	}
1684	if (memcmp(val, tunnel->expected_response, MD5LEN)) {
1685	    tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_BAD_VALUE,
1686				"Incorrect challenge response");
1687	    return;
1688	}
1689    }
1690
1691    DBG(l2tp_db(DBG_TUNNEL, "tunnel_establish(%s) ops: %p\n",
1692	l2tp_debug_tunnel_to_str(tunnel), tunnel->call_ops));
1693    if (tunnel->call_ops && tunnel->call_ops->tunnel_establish &&
1694	tunnel->call_ops->tunnel_establish(tunnel) < 0) {
1695	tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR, ERROR_VENDOR_SPECIFIC,
1696			    "%s", l2tp_get_errmsg());
1697	return;
1698    }
1699
1700    tunnel_set_state(tunnel, TUNNEL_ESTABLISHED);
1701    tunnel_setup_hello(tunnel);
1702
1703    /* Tell sessions tunnel has been established */
1704    tunnel_tell_sessions_tunnel_open(tunnel);
1705}
1706
1707/**********************************************************************
1708* %FUNCTION: tunnel_find_for_peer
1709* %ARGUMENTS:
1710*  peer -- an L2TP peer
1711*  es -- an event selector
1712* %RETURNS:
1713*  An existing tunnel to peer (if one exists) or a new one (if one does not),
1714*  or NULL if no tunnel could be established.  If the existing tunnel
1715*  is in the state RECEIVED_STOP_CCN or SENT_STOP_CCN, make a new one.
1716***********************************************************************/
1717l2tp_tunnel *
1718l2tp_tunnel_find_for_peer(l2tp_peer *peer,
1719		     EventSelector *es)
1720{
1721    l2tp_tunnel *tunnel;
1722    void *cursor;
1723
1724    if (peer->addr.sin_addr.s_addr == INADDR_ANY)
1725    {
1726	for (tunnel = hash_start(&tunnels_by_my_id, &cursor);
1727	    tunnel && tunnel->peer != peer;
1728	    tunnel = hash_next(&tunnels_by_my_id, &cursor));
1729    } else {
1730	tunnel = tunnel_find_bypeer(peer->addr);
1731    }
1732
1733    if (tunnel) {
1734	if (tunnel->state == TUNNEL_WAIT_CTL_REPLY ||
1735	    tunnel->state == TUNNEL_WAIT_CTL_CONN ||
1736	    tunnel->state == TUNNEL_ESTABLISHED) {
1737	    return tunnel;
1738	}
1739    }
1740
1741    /* No tunnel, or tunnel in wrong state */
1742    return tunnel_establish(peer, es);
1743}
1744
1745/**********************************************************************
1746* %FUNCTION: tunnel_find_session
1747* %ARGUMENTS:
1748*  sid -- session ID
1749* %RETURNS:
1750*  The session with specified ID, or NULL if no such session
1751***********************************************************************/
1752l2tp_session *
1753l2tp_tunnel_find_session(l2tp_tunnel *tunnel,
1754		    uint16_t sid)
1755{
1756    l2tp_session candidate;
1757    candidate.my_id = sid;
1758    return hash_find(&tunnel->sessions_by_my_id, &candidate);
1759}
1760
1761/**********************************************************************
1762* %FUNCTION: tunnel_tell_sessions_tunnel_open
1763* %ARGUMENTS:
1764*  tunnel -- the tunnel
1765* %RETURNS:
1766*  Nothing
1767* %DESCRIPTION:
1768*  Informs all waiting sessions that tunnel has moved into ESTABLISHED state.
1769***********************************************************************/
1770static void
1771tunnel_tell_sessions_tunnel_open(l2tp_tunnel *tunnel)
1772{
1773    l2tp_session *ses;
1774    void *cursor;
1775
1776    for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1777	 ses ;
1778	 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1779	l2tp_session_notify_tunnel_open(ses);
1780    }
1781}
1782
1783/**********************************************************************
1784* %FUNCTION: tunnel_add_session
1785* %ARGUMENTS:
1786*  ses -- session to add
1787* %RETURNS:
1788*  Nothing
1789* %DESCRIPTION:
1790*  Adds session to tunnel's hash table.  If tunnel is up, calls
1791*  l2tp_session_notify_tunnel_open
1792***********************************************************************/
1793void
1794l2tp_tunnel_add_session(l2tp_session *ses)
1795{
1796    l2tp_tunnel *tunnel = ses->tunnel;
1797
1798    hash_insert(&tunnel->sessions_by_my_id, ses);
1799    if (tunnel->state == TUNNEL_ESTABLISHED) {
1800	l2tp_session_notify_tunnel_open(ses);
1801    }
1802}
1803
1804void
1805l2tp_tunnel_reestablish(EventSelector *es,
1806		      int fd,
1807		      unsigned int flags,
1808		      void *data)
1809{
1810    l2tp_peer *peer = (l2tp_peer*) data;
1811    l2tp_session *ses;
1812
1813    ses = l2tp_session_call_lns(peer, "foobar", es, NULL);
1814    if (!ses) {
1815        DBG(l2tp_db(DBG_TUNNEL, "l2tp_tunnel_reestablish() failed\n"));
1816        return;
1817    }
1818}
1819
1820/**********************************************************************
1821* %FUNCTION: tunnel_delete_session
1822* %ARGUMENTS:
1823*  ses -- session to delete
1824* %RETURNS:
1825*  Nothing
1826* %DESCRIPTION:
1827*  Deletes session from tunnel's hash table and frees it.
1828***********************************************************************/
1829void
1830l2tp_tunnel_delete_session(l2tp_session *ses, char const *reason, int may_reestablish)
1831{
1832    l2tp_tunnel *tunnel = ses->tunnel;
1833
1834    if (may_reestablish && ses->state < SESSION_ESTABLISHED &&
1835	tunnel->peer && tunnel->peer->persist &&
1836	(tunnel->peer->maxfail == 0 || tunnel->peer->fail++ < tunnel->peer->maxfail))
1837    {
1838	struct timeval t;
1839
1840	t.tv_sec = tunnel->peer->holdoff;
1841	t.tv_usec = 0;
1842	Event_AddTimerHandler(tunnel->es, t, l2tp_tunnel_reestablish, tunnel->peer);
1843    }
1844
1845    hash_remove(&tunnel->sessions_by_my_id, ses);
1846    l2tp_session_free(ses, reason, may_reestablish);
1847
1848    /* Tear down tunnel if so indicated */
1849    if (!hash_num_entries(&tunnel->sessions_by_my_id)) {
1850	if (!tunnel->peer->retain_tunnel) {
1851	    tunnel_send_StopCCN(tunnel,
1852				RESULT_GENERAL_REQUEST, 0,
1853				"Last session has closed");
1854	}
1855    }
1856}
1857
1858/**********************************************************************
1859* %FUNCTION: tunnel_handle_ICRQ
1860* %ARGUMENTS:
1861*  tunnel -- the tunnel
1862*  dgram -- the datagram
1863* %RETURNS:
1864*  Nothing
1865* %DESCRIPTION:
1866*  Handles ICRQ (Incoming Call ReQuest)
1867***********************************************************************/
1868static void
1869tunnel_handle_ICRQ(l2tp_tunnel *tunnel,
1870		   l2tp_dgram *dgram)
1871{
1872    uint16_t u16;
1873    unsigned char *val;
1874    uint16_t len;
1875    int mandatory, hidden;
1876
1877    /* Get assigned session ID */
1878    val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1879			   VENDOR_IETF, AVP_ASSIGNED_SESSION_ID);
1880    if (!val) {
1881	l2tp_set_errmsg("No assigned tunnel ID AVP in ICRQ");
1882	return;
1883    }
1884    if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_ASSIGNED_SESSION_ID,
1885			    len, mandatory)) {
1886	/* TODO: send CDN */
1887	return;
1888    }
1889
1890    /* Set assigned session ID */
1891    u16 = ((uint16_t) val[0]) * 256 + (uint16_t) val[1];
1892
1893    if (!u16) {
1894	/* TODO: send CDN */
1895	return;
1896    }
1897
1898    /* Tunnel in wrong state? */
1899    if (tunnel->state != TUNNEL_ESTABLISHED) {
1900	/* TODO: Send CDN */
1901	return;
1902    }
1903
1904    /* Set up new incoming call */
1905    /* TODO: Include calling number */
1906    l2tp_session_lns_handle_incoming_call(tunnel, u16, dgram, "");
1907}
1908
1909/**********************************************************************
1910* %FUNCTION: l2tp_tunnel_stop_all
1911* %ARGUMENTS:
1912*  reason -- reason for stopping tunnels
1913* %RETURNS:
1914*  Nothing
1915* %DESCRIPTION:
1916*  Stops all tunnels
1917***********************************************************************/
1918void
1919l2tp_tunnel_stop_all(char const *reason)
1920{
1921    l2tp_tunnel *tunnel;
1922    void *cursor;
1923
1924    /* Send StopCCN on all tunnels except those which are scheduled for
1925       destruction */
1926    for (tunnel = hash_start(&tunnels_by_my_id, &cursor);
1927	 tunnel;
1928	 tunnel = hash_next(&tunnels_by_my_id, &cursor)) {
1929	l2tp_tunnel_stop_tunnel(tunnel, reason);
1930    }
1931
1932}
1933
1934/**********************************************************************
1935* %FUNCTION: l2tp_tunnel_stop_tunnel
1936* %ARGUMENTS:
1937*  tunnel -- tunnel to stop
1938*  reason -- reason for stopping tunnel
1939* %RETURNS:
1940*  Nothing
1941* %DESCRIPTION:
1942*  Stops a tunnels (sends StopCCN)
1943***********************************************************************/
1944void
1945l2tp_tunnel_stop_tunnel(l2tp_tunnel *tunnel,
1946			char const *reason)
1947{
1948    /* Do not send StopCCN if we've received one already */
1949    if (tunnel->state != TUNNEL_RECEIVED_STOP_CCN &&
1950	tunnel->state != TUNNEL_SENT_STOP_CCN) {
1951	tunnel_send_StopCCN(tunnel, RESULT_SHUTTING_DOWN, 0, reason);
1952    }
1953}
1954
1955/**********************************************************************
1956* %FUNCTION: l2tp_num_tunnels
1957* %ARGUMENTS:
1958*  None
1959* %RETURNS:
1960*  The number of L2TP tunnels
1961***********************************************************************/
1962int
1963l2tp_num_tunnels(void)
1964{
1965    return hash_num_entries(&tunnels_by_my_id);
1966}
1967
1968/**********************************************************************
1969* %FUNCTION: l2tp_first_tunnel
1970* %ARGUMENTS:
1971*  cursor -- cursor for keeping track of where we are in interation
1972* %RETURNS:
1973*  First L2TP tunnel
1974***********************************************************************/
1975l2tp_tunnel *
1976l2tp_first_tunnel(void **cursor)
1977{
1978    return hash_start(&tunnels_by_my_id, cursor);
1979}
1980
1981
1982/**********************************************************************
1983* %FUNCTION: l2tp_next_tunnel
1984* %ARGUMENTS:
1985*  cursor -- cursor for keeping track of where we are in interation
1986* %RETURNS:
1987*  Next L2TP tunnel
1988***********************************************************************/
1989l2tp_tunnel *
1990l2tp_next_tunnel(void **cursor)
1991{
1992    return hash_next(&tunnels_by_my_id, cursor);
1993}
1994
1995/**********************************************************************
1996* %FUNCTION: l2tp_tunnel_state_name
1997* %ARGUMENTS:
1998*  tunnel -- the tunnel
1999* %RETURNS:
2000*  The name of the tunnel's state
2001***********************************************************************/
2002char const *
2003l2tp_tunnel_state_name(l2tp_tunnel *tunnel)
2004{
2005    return state_names[tunnel->state];
2006}
2007
2008/**********************************************************************
2009* %FUNCTION: l2tp_tunnel_first_session
2010* %ARGUMENTS:
2011*  tunnel -- the tunnel
2012*  cursor -- cursor for hash table iteration
2013* %RETURNS:
2014*  First session in tunnel
2015***********************************************************************/
2016l2tp_session *
2017l2tp_tunnel_first_session(l2tp_tunnel *tunnel, void **cursor)
2018{
2019    return hash_start(&tunnel->sessions_by_my_id, cursor);
2020}
2021
2022/**********************************************************************
2023* %FUNCTION: l2tp_tunnel_next_session
2024* %ARGUMENTS:
2025*  tunnel -- the tunnel
2026*  cursor -- cursor for hash table iteration
2027* %RETURNS:
2028*  Next session in tunnel
2029***********************************************************************/
2030l2tp_session *
2031l2tp_tunnel_next_session(l2tp_tunnel *tunnel, void **cursor)
2032{
2033    return hash_next(&tunnel->sessions_by_my_id, cursor);
2034}
2035
2036/* Route manipulation */
2037static int
2038route_ctrl(int ctrl, struct rtentry *rt)
2039{
2040	int s;
2041
2042	/* Open a raw socket to the kernel */
2043	if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0 || ioctl(s, ctrl, rt) < 0)
2044		route_msg("%s: %s", __FUNCTION__, strerror(errno));
2045	else errno = 0;
2046
2047	close(s);
2048	return errno;
2049}
2050
2051static int
2052route_del(struct rtentry *rt)
2053{
2054	if (rt->rt_dev) {
2055		route_ctrl(SIOCDELRT, rt);
2056		free(rt->rt_dev), rt->rt_dev = NULL;
2057	}
2058
2059	return 0;
2060}
2061
2062static int
2063route_add(const struct in_addr inetaddr, struct rtentry *rt)
2064{
2065	char buf[256], dev[64], rdev[64];
2066	u_int32_t dest, mask, gateway, flags, bestmask = 0;
2067	int metric;
2068
2069	FILE *f = fopen("/proc/net/route", "r");
2070	if (f == NULL) {
2071		route_msg("%s: /proc/net/route: %s", strerror(errno), __FUNCTION__);
2072		return -1;
2073	}
2074
2075	rt->rt_gateway.sa_family = 0;
2076
2077	while (fgets(buf, sizeof(buf), f))
2078	{
2079		if (sscanf(buf, "%63s %x %x %x %*s %*s %d %x", dev, &dest,
2080			&gateway, &flags, &metric, &mask) != 6)
2081			continue;
2082		if ((flags & RTF_UP) == (RTF_UP) && (inetaddr.s_addr & mask) == dest &&
2083#ifdef RTCONFIG_VPNC
2084		    (dest || strncmp(dev, "ppp", 3) || vpnc) /* avoid default via pppX to avoid on-demand loops*/)
2085#else
2086		    (dest || strncmp(dev, "ppp", 3)) /* avoid default via pppX to avoid on-demand loops*/)
2087#endif
2088		{
2089			if ((mask | bestmask) == bestmask && rt->rt_gateway.sa_family)
2090				continue;
2091			bestmask = mask;
2092
2093			sin_addr(&rt->rt_gateway).s_addr = gateway;
2094			rt->rt_gateway.sa_family = AF_INET;
2095			rt->rt_flags = flags;
2096			rt->rt_metric = metric;
2097			strncpy(rdev, dev, sizeof(rdev));
2098
2099			if (mask == INADDR_BROADCAST)
2100				break;
2101		}
2102	}
2103
2104	fclose(f);
2105
2106	/* check for no route */
2107	if (rt->rt_gateway.sa_family != AF_INET)
2108	{
2109		/* route_msg("%s: no route to host", __FUNCTION__); */
2110		return -1;
2111	}
2112
2113	/* check for existing route to this host,
2114	 * add if missing based on the existing routes */
2115	if (rt->rt_flags & RTF_HOST)
2116	{
2117		/* route_msg("%s: not adding existing route", __FUNCTION__); */
2118		return -1;
2119	}
2120
2121	sin_addr(&rt->rt_dst) = inetaddr;
2122	rt->rt_dst.sa_family = AF_INET;
2123
2124	sin_addr(&rt->rt_genmask).s_addr = INADDR_BROADCAST;
2125	rt->rt_genmask.sa_family = AF_INET;
2126
2127	rt->rt_flags &= RTF_GATEWAY;
2128	rt->rt_flags |= RTF_UP | RTF_HOST;
2129
2130	rt->rt_metric++;
2131	rt->rt_dev = strdup(rdev);
2132
2133	if (!rt->rt_dev)
2134	{
2135		/* route_msg("%s: no memory", __FUNCTION__); */
2136		return -1;
2137	}
2138
2139	if (!route_ctrl(SIOCADDRT, rt))
2140		return 0;
2141
2142	free(rt->rt_dev), rt->rt_dev = NULL;
2143
2144	return -1;
2145}
2146