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