Correct PPTP server firewall rules chain.
[tomato/davidwu.git] / release / src / router / rp-l2tp / tunnel.c
blob15174a813fc8141a1f2e8958e1eff94bc5e39015
1 /***********************************************************************
3 * tunnel.c
5 * Functions for manipulating L2TP tunnel objects.
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
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.
14 * LIC: GPL
16 * 2008-5-30 Cybertan modify to fix error after several times of login
19 ***********************************************************************/
21 static char const RCSID[] =
22 "$Id: tunnel.c,v 1.2.40.1 2005/08/08 12:05:25 honor Exp $";
24 #include "l2tp.h"
25 #include <stddef.h>
26 #include <stdarg.h>
27 #include <stdio.h>
28 #include <string.h>
29 #include <errno.h>
30 #include <sys/ioctl.h>
31 #include <netdb.h>
32 #include <features.h>
33 #include <resolv.h>
34 #include <cyutils.h>
36 /* Hash tables of all tunnels */
37 static hash_table tunnels_by_my_id;
38 static hash_table tunnels_by_peer_address;
40 static uint16_t tunnel_make_tid(void);
41 static l2tp_tunnel *tunnel_new(EventSelector *es);
42 static void tunnel_free(l2tp_tunnel *tunnel);
43 static int tunnel_send_SCCRQ(l2tp_tunnel *tunnel);
44 static void tunnel_handle_SCCRQ(l2tp_dgram *dgram,
45 EventSelector *es,
46 struct sockaddr_in *from);
47 static void tunnel_handle_SCCRP(l2tp_tunnel *tunnel,
48 l2tp_dgram *dgram);
49 static void tunnel_handle_SCCCN(l2tp_tunnel *tunnel,
50 l2tp_dgram *dgram);
51 static void tunnel_handle_ICRQ(l2tp_tunnel *tunnel,
52 l2tp_dgram *dgram);
53 static void tunnel_process_received_datagram(l2tp_tunnel *tunnel,
54 l2tp_dgram *dgram);
55 static void tunnel_schedule_ack(l2tp_tunnel *tunnel);
56 static void tunnel_do_ack(EventSelector *es, int fd, unsigned int flags,
57 void *data);
58 static void tunnel_handle_timeout(EventSelector *es, int fd,
59 unsigned int flags, void *data);
60 static void tunnel_finally_cleanup(EventSelector *es, int fd,
61 unsigned int flags, void *data);
63 static void tunnel_do_hello(EventSelector *es, int fd,
64 unsigned int flags, void *data);
66 static void tunnel_dequeue_acked_packets(l2tp_tunnel *tunnel);
68 static void tunnel_send_StopCCN(l2tp_tunnel *tunnel,
69 int result_code,
70 int error_code,
71 char const *fmt, ...);
72 static void tunnel_schedule_destruction(l2tp_tunnel *tunnel);
73 static int tunnel_set_params(l2tp_tunnel *tunnel, l2tp_dgram *dgram);
75 static int tunnel_outstanding_frames(l2tp_tunnel *tunnel);
76 static void tunnel_setup_hello(l2tp_tunnel *tunnel);
77 static void tunnel_tell_sessions_tunnel_open(l2tp_tunnel *tunnel);
78 static l2tp_tunnel *tunnel_establish(l2tp_peer *peer, EventSelector *es);
79 static l2tp_tunnel *tunnel_find_bypeer(struct sockaddr_in addr);
81 static char *state_names[] = {
82 "idle", "wait-ctl-reply", "wait-ctl-conn", "established",
83 "received-stop-ccn", "sent-stop-ccn"
86 //#define VENDOR_STR "Roaring Penguin Software Inc."
87 #define VENDOR_STR L2TP_VENDOR
88 #define HOSTNAME_STR L2TP_HOSTNAME //2005-04-14 by kanki
90 /* Comparison of serial numbers according to RFC 1982 */
91 #define SERIAL_GT(a, b) \
92 (((a) > (b) && (a) - (b) < 32768) || ((a) < (b) && (b) - (a) > 32768))
94 #define SERIAL_LT(a, b) \
95 (((a) < (b) && (b) - (a) < 32768) || ((a) > (b) && (a) - (b) > 32768))
97 /* Route manipulation */
98 #define sin_addr(s) (((struct sockaddr_in *)(s))->sin_addr)
99 static int route_add(const struct in_addr inetaddr, struct rtentry *rt);
100 static int route_del(struct rtentry *rt);
102 /**********************************************************************
103 * %FUNCTION: tunnel_set_state
104 * %ARGUMENTS:
105 * tunnel -- the tunnel
106 * state -- new state
107 * %RETURNS:
108 * Nothing
109 ***********************************************************************/
110 static void
111 tunnel_set_state(l2tp_tunnel *tunnel, int state)
113 if (state == tunnel->state) return;
114 DBG(l2tp_db(DBG_TUNNEL, "tunnel(%s) state %s -> %s\n",
115 l2tp_debug_tunnel_to_str(tunnel),
116 state_names[tunnel->state],
117 state_names[state]));
118 tunnel->state = state;
121 /**********************************************************************
122 * %FUNCTION: tunnel_find_by_my_id
123 * %ARGUMENTS:
124 * id -- tunnel ID
125 * %RETURNS:
126 * A tunnel whose my_id field equals id, or NULL if no such tunnel
127 ***********************************************************************/
128 l2tp_tunnel *
129 l2tp_tunnel_find_by_my_id(uint16_t id)
131 l2tp_tunnel candidate;
132 candidate.my_id = id;
133 return hash_find(&tunnels_by_my_id, &candidate);
136 /**********************************************************************
137 * %FUNCTION: tunnel_find_bypeer
138 * %ARGUMENTS:
139 * addr -- peer address
140 * %RETURNS:
141 * A tunnel whose peer_addr field equals addr, or NULL if no such tunnel
142 ***********************************************************************/
143 static l2tp_tunnel *
144 tunnel_find_bypeer(struct sockaddr_in addr)
146 l2tp_tunnel candidate;
147 candidate.peer_addr = addr;
148 return hash_find(&tunnels_by_peer_address, &candidate);
151 /**********************************************************************
152 * %FUNCTION: tunnel_flow_control_stats
153 * %ARGUMENTS:
154 * tunnel -- a tunnel
155 * %RETURNS:
156 * A string representing flow-control info (used for debugging)
157 ***********************************************************************/
158 static char const *
159 tunnel_flow_control_stats(l2tp_tunnel *tunnel)
161 static char buf[256];
163 snprintf(buf, sizeof(buf), "rws=%d cwnd=%d ssthresh=%d outstanding=%d",
164 (int) tunnel->peer_rws,
165 tunnel->cwnd,
166 tunnel->ssthresh,
167 tunnel_outstanding_frames(tunnel));
168 return buf;
171 /**********************************************************************
172 * %FUNCTION: tunnel_outstanding_frames
173 * %ARGUMENTS:
174 * tunnel -- a tunnel
175 * %RETURNS:
176 * The number of outstanding (transmitted, but not ack'd) frames.
177 ***********************************************************************/
178 static int
179 tunnel_outstanding_frames(l2tp_tunnel *tunnel)
181 int Ns = (int) tunnel->Ns_on_wire;
182 int Nr = (int) tunnel->peer_Nr;
183 if (Ns >= Nr) return Ns - Nr;
184 return 65536 - Nr + Ns;
187 /**********************************************************************
188 * %FUNCTION: tunnel_make_tid
189 * %ARGUMENTS:
190 * None
191 * %RETURNS:
192 * An unused, random tunnel ID.
193 ***********************************************************************/
194 static uint16_t tunnel_make_tid(void)
196 uint16_t id;
197 for(;;) {
198 L2TP_RANDOM_FILL(id);
199 if (!id) continue;
200 if (!l2tp_tunnel_find_by_my_id(id)) return id;
204 /**********************************************************************
205 * %FUNCTION: tunnel_enqueue_dgram
206 * %ARGUMENTS:
207 * tunnel -- the tunnel
208 * dgram -- an L2TP datagram to place at the tail of the transmit queue
209 * %RETURNS:
210 * Nothing
211 * %DESCRIPTION:
212 * Adds datagram to end of transmit queue.
213 ***********************************************************************/
214 static void
215 tunnel_enqueue_dgram(l2tp_tunnel *tunnel,
216 l2tp_dgram *dgram)
218 dgram->next = NULL;
219 if (tunnel->xmit_queue_tail) {
220 tunnel->xmit_queue_tail->next = dgram;
221 tunnel->xmit_queue_tail = dgram;
222 } else {
223 tunnel->xmit_queue_head = dgram;
224 tunnel->xmit_queue_tail = dgram;
226 if (!tunnel->xmit_new_dgrams) {
227 tunnel->xmit_new_dgrams = dgram;
230 dgram->Ns = tunnel->Ns;
231 tunnel->Ns++;
232 DBG(l2tp_db(DBG_FLOW, "tunnel_enqueue_dgram(%s, %s) %s\n",
233 l2tp_debug_tunnel_to_str(tunnel),
234 l2tp_debug_message_type_to_str(dgram->msg_type),
235 tunnel_flow_control_stats(tunnel)));
239 /**********************************************************************
240 * %FUNCTION: tunnel_dequeue_head
241 * %ARGUMENTS:
242 * tunnel -- the tunnel
243 * %RETURNS:
244 * Nothing
245 * %DESCRIPTION:
246 * Dequeues datagram from head of transmit queue and frees it
247 ***********************************************************************/
248 static void
249 tunnel_dequeue_head(l2tp_tunnel *tunnel)
251 l2tp_dgram *dgram = tunnel->xmit_queue_head;
252 if (dgram) {
253 tunnel->xmit_queue_head = dgram->next;
254 if (tunnel->xmit_new_dgrams == dgram) {
255 tunnel->xmit_new_dgrams = dgram->next;
257 if (tunnel->xmit_queue_tail == dgram) {
258 tunnel->xmit_queue_tail = NULL;
260 l2tp_dgram_free(dgram);
264 /**********************************************************************
265 * %FUNCTION: tunnel_xmit_queued_messages
266 * %ARGUMENTS:
267 * tunnel -- the tunnel
268 * %RETURNS:
269 * Nothing
270 * %DESCRIPTION:
271 * Transmits as many control messages as possible from the queue.
272 ***********************************************************************/
273 static void
274 tunnel_xmit_queued_messages(l2tp_tunnel *tunnel)
276 l2tp_dgram *dgram;
277 struct timeval t;
279 dgram = tunnel->xmit_new_dgrams;
280 if (!dgram) return;
282 DBG(l2tp_db(DBG_FLOW, "xmit_queued(%s): %s\n",
283 l2tp_debug_tunnel_to_str(tunnel),
284 tunnel_flow_control_stats(tunnel)));
285 while (dgram) {
286 /* If window is closed, we can't transmit anything */
287 if (tunnel_outstanding_frames(tunnel) >= tunnel->cwnd) {
288 break;
291 /* Update Nr */
292 dgram->Nr = tunnel->Nr;
294 /* Tid might have changed if call was initiated before
295 tunnel establishment was complete */
296 dgram->tid = tunnel->assigned_id;
298 if (l2tp_dgram_send_to_wire(dgram, &tunnel->peer_addr) < 0) {
299 break;
302 /* Cancel any pending ack */
303 if (tunnel->ack_handler) {
304 Event_DelHandler(tunnel->es, tunnel->ack_handler);
305 tunnel->ack_handler = NULL;
308 tunnel->xmit_new_dgrams = dgram->next;
309 tunnel->Ns_on_wire = dgram->Ns + 1;
310 DBG(l2tp_db(DBG_FLOW, "loop in xmit_queued(%s): %s\n",
311 l2tp_debug_tunnel_to_str(tunnel),
312 tunnel_flow_control_stats(tunnel)));
313 dgram = dgram->next;
316 t.tv_sec = tunnel->timeout;
317 t.tv_usec = 0;
319 /* Set retransmission timer */
320 if (tunnel->timeout_handler) {
321 Event_ChangeTimeout(tunnel->timeout_handler, t);
322 } else {
323 tunnel->timeout_handler =
324 Event_AddTimerHandler(tunnel->es, t,
325 tunnel_handle_timeout, tunnel);
329 /**********************************************************************
330 * %FUNCTION: tunnel_xmit_control_message
331 * %ARGUMENTS:
332 * tunnel -- the tunnel
333 * dgram -- the datagram to transmit. After return from this
334 * function, the tunnel "owns" the dgram and the caller should
335 * no longer use it.
336 * %RETURNS:
337 * Nothing
338 * %DESCRIPTION:
339 * Transmits a control message. If there is no room in the transmit
340 * window, queues the message.
341 ***********************************************************************/
342 void
343 l2tp_tunnel_xmit_control_message(l2tp_tunnel *tunnel,
344 l2tp_dgram *dgram)
346 /* Queue the datagram in case we need to retransmit it */
347 tunnel_enqueue_dgram(tunnel, dgram);
349 /* Run the queue */
350 tunnel_xmit_queued_messages(tunnel);
353 static unsigned int
354 tunnel_compute_peerhash(void *data)
356 return (unsigned int) (((l2tp_tunnel *)data)->peer_addr.sin_addr.s_addr);
359 static int
360 tunnel_compare_peer(void *d1, void *d2)
362 return (((l2tp_tunnel *)d1)->peer_addr.sin_addr.s_addr) !=
363 (((l2tp_tunnel *)d2)->peer_addr.sin_addr.s_addr);
366 /**********************************************************************
367 * %FUNCTION: tunnel_compute_hash_my_id
368 * %ARGUMENTS:
369 * data -- a void pointer which is really a tunnel
370 * %RETURNS:
371 * My tunnel ID
372 ***********************************************************************/
373 static unsigned int
374 tunnel_compute_hash_my_id(void *data)
376 return (unsigned int) (((l2tp_tunnel *) data)->my_id);
379 /**********************************************************************
380 * %FUNCTION: tunnel_compare_my_id
381 * %ARGUMENTS:
382 * item1 -- first tunnel
383 * item2 -- second tunnel
384 * %RETURNS:
385 * 0 if both tunnels have same ID, non-zero otherwise
386 ***********************************************************************/
387 static int
388 tunnel_compare_my_id(void *item1, void *item2)
390 return ((l2tp_tunnel *) item1)->my_id != ((l2tp_tunnel *) item2)->my_id;
393 /**********************************************************************
394 * %FUNCTION: tunnel_cleanup
395 * %ARGUMENTS:
396 * data -- event selector
397 * %RETURNS:
398 * Nothing
399 * %DESCRIPTION:
400 * Shuts down all tunnels and waits for them to exit
401 ***********************************************************************/
402 static void
403 tunnel_cleanup(void *data)
405 EventSelector *es = (EventSelector *) data;
406 int i;
408 /* Stop all tunnels */
409 l2tp_tunnel_stop_all("Shutting down");
411 while (hash_num_entries(&tunnels_by_my_id)) {
412 i = Event_HandleEvent(es);
413 if (i < 0) {
414 exit(EXIT_FAILURE);
419 /**********************************************************************
420 * %FUNCTION: tunnel_init
421 * %ARGUMENTS:
422 * es -- event selector
423 * %RETURNS:
424 * Nothing
425 * %DESCRIPTION:
426 * Initializes static tunnel data structures.
427 ***********************************************************************/
428 void
429 l2tp_tunnel_init(EventSelector *es)
431 hash_init(&tunnels_by_my_id,
432 offsetof(l2tp_tunnel, hash_by_my_id),
433 tunnel_compute_hash_my_id,
434 tunnel_compare_my_id);
435 hash_init(&tunnels_by_peer_address,
436 offsetof(l2tp_tunnel, hash_by_peer),
437 tunnel_compute_peerhash,
438 tunnel_compare_peer);
440 l2tp_register_shutdown_handler(tunnel_cleanup, es);
443 /**********************************************************************
444 * %FUNCTION: tunnel_new
445 * %ARGUMENTS:
446 * es -- event selector
447 * %RETURNS:
448 * A newly-allocated and initialized l2tp_tunnel object
449 ***********************************************************************/
450 static l2tp_tunnel *
451 tunnel_new(EventSelector *es)
453 l2tp_tunnel *tunnel = malloc(sizeof(l2tp_tunnel));
454 if (!tunnel) return NULL;
456 memset(tunnel, 0, sizeof(l2tp_tunnel));
457 l2tp_session_hash_init(&tunnel->sessions_by_my_id);
458 tunnel->rws = 4;
459 tunnel->peer_rws = 1;
460 tunnel->es = es;
461 tunnel->timeout = 1;
462 tunnel->my_id = tunnel_make_tid();
463 tunnel->ssthresh = 1;
464 tunnel->cwnd = 1;
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;
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 ***********************************************************************/
480 static void
481 tunnel_free(l2tp_tunnel *tunnel)
483 void *cursor;
484 l2tp_session *ses;
485 EventSelector *es = tunnel->es;
487 DBG(l2tp_db(DBG_TUNNEL, "tunnel_free(%s)\n", l2tp_debug_tunnel_to_str(tunnel)));
489 hash_remove(&tunnels_by_my_id, tunnel);
490 hash_remove(&tunnels_by_peer_address, tunnel);
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);
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);
501 while(tunnel->xmit_queue_head) {
502 tunnel_dequeue_head(tunnel);
504 route_del(&tunnel->rt);
505 memset(tunnel, 0, sizeof(l2tp_tunnel));
506 free(tunnel);
509 /**********************************************************************
510 * %FUNCTION: tunnel_establish
511 * %ARGUMENTS:
512 * peer -- peer with which to establish tunnel
513 * es -- event selector for event loop
514 * %RETURNS:
515 * A newly-allocated tunnel, or NULL on error.
516 * %DESCRIPTION:
517 * Begins tunnel establishment to peer.
518 ***********************************************************************/
519 static l2tp_tunnel *
520 tunnel_establish(l2tp_peer *peer, EventSelector *es)
522 l2tp_tunnel *tunnel;
523 struct sockaddr_in peer_addr = peer->addr;
524 struct hostent *he;
526 /* check peer_addr and resolv it based on the peername if needed */
527 if (peer_addr.sin_addr.s_addr == INADDR_ANY) {
528 #if !defined(__UCLIBC__) \
529 || (__UCLIBC_MAJOR__ == 0 \
530 && (__UCLIBC_MINOR__ < 9 || (__UCLIBC_MINOR__ == 9 && __UCLIBC_SUBLEVEL__ < 31)))
531 /* force ns refresh from resolv.conf with uClibc pre-0.9.31 */
532 res_init();
533 #endif
534 he = gethostbyname(peer->peername);
535 if (!he) {
536 l2tp_set_errmsg("tunnel_establish: gethostbyname failed for '%s'", peer->peername);
537 if (peer->persist && (peer->maxfail == 0 || peer->fail++ < peer->maxfail))
539 struct timeval t;
541 t.tv_sec = peer->holdoff;
542 t.tv_usec = 0;
543 Event_AddTimerHandler(es, t, l2tp_tunnel_reestablish, peer);
545 return NULL;
547 memcpy(&peer_addr.sin_addr, he->h_addr, sizeof(peer_addr.sin_addr));
550 tunnel = tunnel_new(es);
551 if (!tunnel) return NULL;
553 tunnel->peer = peer;
554 tunnel->peer_addr = peer_addr;
556 memset(&tunnel->rt, 0, sizeof(tunnel->rt));
557 route_add(tunnel->peer_addr.sin_addr, &tunnel->rt);
559 hash_insert(&tunnels_by_peer_address, tunnel);
560 tunnel_send_SCCRQ(tunnel);
561 tunnel_set_state(tunnel, TUNNEL_WAIT_CTL_REPLY);
562 return tunnel;
565 /**********************************************************************
566 * %FUNCTION: tunnel_send_SCCRQ
567 * %ARGUMENTS:
568 * tunnel -- the tunnel we wish to establish
569 * %RETURNS:
570 * 0 if we handed the datagram off to control transport, -1 otherwise.
571 * %DESCRIPTION:
572 * Sends SCCRQ to establish a tunnel.
573 ***********************************************************************/
574 static int
575 tunnel_send_SCCRQ(l2tp_tunnel *tunnel)
577 uint16_t u16;
578 uint32_t u32;
579 unsigned char tie_breaker[8];
580 unsigned char challenge[16];
581 int old_hide;
582 // char *hostname;
584 l2tp_dgram *dgram = l2tp_dgram_new_control(MESSAGE_SCCRQ, 0, 0);
585 if (!dgram) return -1;
587 /* Add the AVP's */
588 /* HACK! Cisco equipment cannot handle hidden AVP's in SCCRQ.
589 So we temporarily disable AVP hiding */
590 old_hide = tunnel->peer->hide_avps;
591 tunnel->peer->hide_avps = 0;
593 /* Protocol version */
594 u16 = htons(0x0100);
595 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
596 sizeof(u16), VENDOR_IETF, AVP_PROTOCOL_VERSION, &u16);
598 /* Framing capabilities -- hard-coded as sync and async */
599 u32 = htonl(3);
600 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
601 sizeof(u32), VENDOR_IETF, AVP_FRAMING_CAPABILITIES, &u32);
603 //hostname = tunnel->peer->hostname[0] ? tunnel->peer->hostname : Hostname; //2005-04-14 by kanki
605 /* Host name */
606 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
607 //strlen(hostname), VENDOR_IETF, AVP_HOST_NAME, //2005-04-14 by kanki
608 //hostname);
609 strlen(HOSTNAME_STR), VENDOR_IETF, AVP_HOST_NAME,
610 HOSTNAME_STR);
612 /* Assigned ID */
613 u16 = htons(tunnel->my_id);
614 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
615 sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
617 /* Receive window size */
618 u16 = htons(tunnel->rws);
619 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
620 sizeof(u16), VENDOR_IETF, AVP_RECEIVE_WINDOW_SIZE, &u16);
622 /* Tie-breaker */
623 l2tp_random_fill(tie_breaker, sizeof(tie_breaker));
624 l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
625 sizeof(tie_breaker), VENDOR_IETF, AVP_TIE_BREAKER,
626 tie_breaker);
628 /* Vendor name */
629 l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
630 strlen(VENDOR_STR), VENDOR_IETF,
631 AVP_VENDOR_NAME, VENDOR_STR);
633 /* Challenge */
634 if (tunnel->peer->secret_len) {
635 l2tp_random_fill(challenge, sizeof(challenge));
636 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
637 sizeof(challenge), VENDOR_IETF,
638 AVP_CHALLENGE, challenge);
640 /* Compute and save expected response */
641 l2tp_auth_gen_response(MESSAGE_SCCRP, tunnel->peer->secret,
642 challenge, sizeof(challenge), tunnel->expected_response);
645 tunnel->peer->hide_avps = old_hide;
646 /* And ship it out */
647 l2tp_tunnel_xmit_control_message(tunnel, dgram);
648 return 1;
651 /**********************************************************************
652 * %FUNCTION: tunnel_handle_received_control_datagram
653 * %ARGUMENTS:
654 * dgram -- received datagram
655 * es -- event selector
656 * from -- address of sender
657 * %RETURNS:
658 * Nothing
659 * %DESCRIPTION:
660 * Handles a received control datagram
661 ***********************************************************************/
662 void
663 l2tp_tunnel_handle_received_control_datagram(l2tp_dgram *dgram,
664 EventSelector *es,
665 struct sockaddr_in *from)
667 l2tp_tunnel *tunnel;
669 /* If it's SCCRQ, then handle it */
670 if (dgram->msg_type == MESSAGE_SCCRQ) {
671 tunnel_handle_SCCRQ(dgram, es, from);
672 return;
675 /* Find the tunnel to which it refers */
676 if (dgram->tid == 0) {
677 l2tp_set_errmsg("Invalid control message - tunnel ID = 0");
678 return;
680 tunnel = l2tp_tunnel_find_by_my_id(dgram->tid);
682 if (!tunnel) {
683 /* TODO: Send error message back? */
684 DBG(l2tp_db(DBG_TUNNEL, "Invalid control message - unknown tunnel ID %d",
685 (int) dgram->tid));
686 return;
689 /* Verify that source address is the tunnel's peer */
690 if (tunnel->peer && tunnel->peer->validate_peer_ip) {
691 if (from->sin_addr.s_addr != tunnel->peer_addr.sin_addr.s_addr) {
692 l2tp_set_errmsg("Invalid control message for tunnel %s - not sent from peer",
693 l2tp_debug_tunnel_to_str(tunnel));
694 return;
698 /* Set port for replies */
699 tunnel->peer_addr.sin_port = from->sin_port;
701 /* Schedule an ACK for 100ms from now, but do not ack ZLB's */
702 if (dgram->msg_type != MESSAGE_ZLB) {
703 tunnel_schedule_ack(tunnel);
706 /* If it's an old datagram, ignore it */
707 if (dgram->Ns != tunnel->Nr) {
708 if (SERIAL_LT(dgram->Ns, tunnel->Nr)) {
709 /* Old packet: Drop it */
710 /* Throw away ack'd packets in our xmit queue */
711 tunnel_dequeue_acked_packets(tunnel);
712 return;
714 /* Out-of-order packet or intermediate dropped packets.
715 TODO: Look into handling this better */
716 return;
719 /* Do not increment if we got ZLB */
720 if (dgram->msg_type != MESSAGE_ZLB) {
721 tunnel->Nr++;
724 /* Update peer_Nr */
725 if (SERIAL_GT(dgram->Nr, tunnel->peer_Nr)) {
726 tunnel->peer_Nr = dgram->Nr;
729 /* Reschedule HELLO handler for 60 seconds in future */
730 if (tunnel->state != TUNNEL_RECEIVED_STOP_CCN &&
731 tunnel->state != TUNNEL_SENT_STOP_CCN &&
732 tunnel->hello_handler != NULL) {
733 struct timeval t;
734 //t.tv_sec = 60;
735 t.tv_sec = 30;
736 t.tv_usec = 0;
737 Event_ChangeTimeout(tunnel->hello_handler, t);
740 /* Reset retransmission stuff */
741 tunnel->retransmissions = 0;
742 tunnel->timeout = 1;
744 /* Throw away ack'd packets in our xmit queue */
745 tunnel_dequeue_acked_packets(tunnel);
747 /* Let the specific tunnel handle it */
748 tunnel_process_received_datagram(tunnel, dgram);
750 /* Run the xmit queue -- window may have opened */
751 tunnel_xmit_queued_messages(tunnel);
753 /* Destroy tunnel if required and if xmit queue empty */
754 if (!tunnel->xmit_queue_head) {
755 if (tunnel->timeout_handler) {
756 Event_DelHandler(tunnel->es, tunnel->timeout_handler);
757 tunnel->timeout_handler = NULL;
759 if (tunnel->state == TUNNEL_RECEIVED_STOP_CCN) {
760 tunnel_schedule_destruction(tunnel);
761 } else if (tunnel->state == TUNNEL_SENT_STOP_CCN) {
762 /* Our stop-CCN has been ack'd, destroy NOW */
763 tunnel_free(tunnel);
768 /**********************************************************************
769 * %FUNCTION: tunnel_handle_SCCRQ
770 * %ARGUMENTS:
771 * dgram -- the received datagram
772 * es -- event selector
773 * from -- address of sender
774 * %RETURNS:
775 * Nothing
776 * %DESCRIPTION:
777 * Handles an incoming SCCRQ
778 ***********************************************************************/
779 static void
780 tunnel_handle_SCCRQ(l2tp_dgram *dgram,
781 EventSelector *es,
782 struct sockaddr_in *from)
784 l2tp_tunnel *tunnel = NULL;
786 uint16_t u16;
787 uint32_t u32;
788 unsigned char challenge[16];
789 // char *hostname;
791 /* TODO: Check if this is a retransmitted SCCRQ */
792 /* Allocate a tunnel */
793 tunnel = tunnel_new(es);
794 if (!tunnel) {
795 l2tp_set_errmsg("Unable to allocate new tunnel");
796 return;
799 tunnel->peer_addr = *from;
801 hash_insert(&tunnels_by_peer_address, tunnel);
803 /* We've received our first control datagram (SCCRQ) */
804 tunnel->Nr = 1;
806 if (tunnel_set_params(tunnel, dgram) < 0) return;
808 /* Hunky-dory. Send SCCRP */
809 dgram = l2tp_dgram_new_control(MESSAGE_SCCRP, tunnel->assigned_id, 0);
810 if (!dgram) {
811 /* Doh! Out of resources. Not much chance of StopCCN working... */
812 tunnel_send_StopCCN(tunnel,
813 RESULT_GENERAL_ERROR, ERROR_OUT_OF_RESOURCES,
814 "Out of memory");
815 return;
818 /* Protocol version */
819 u16 = htons(0x0100);
820 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
821 sizeof(u16), VENDOR_IETF, AVP_PROTOCOL_VERSION, &u16);
823 /* Framing capabilities -- hard-coded as sync and async */
824 u32 = htonl(3);
825 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
826 sizeof(u32), VENDOR_IETF, AVP_FRAMING_CAPABILITIES, &u32);
828 //hostname = tunnel->peer->hostname[0] ? tunnel->peer->hostname : Hostname; //2005-04-14 by kanki
830 /* Host name */
831 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
832 //strlen(hostname), VENDOR_IETF, AVP_HOST_NAME, //2005-04-14 by kanki
833 //hostname);
834 strlen(HOSTNAME_STR), VENDOR_IETF, AVP_HOST_NAME,
835 HOSTNAME_STR);
837 /* Assigned ID */
838 u16 = htons(tunnel->my_id);
839 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
840 sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
842 /* Receive window size */
843 u16 = htons(tunnel->rws);
844 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
845 sizeof(u16), VENDOR_IETF, AVP_RECEIVE_WINDOW_SIZE, &u16);
847 /* Vendor name */
848 l2tp_dgram_add_avp(dgram, tunnel, NOT_MANDATORY,
849 strlen(VENDOR_STR), VENDOR_IETF,
850 AVP_VENDOR_NAME, VENDOR_STR);
852 if (tunnel->peer->secret_len) {
853 /* Response */
854 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
855 MD5LEN, VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
856 tunnel->response);
858 /* Challenge */
859 l2tp_random_fill(challenge, sizeof(challenge));
860 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
861 sizeof(challenge), VENDOR_IETF,
862 AVP_CHALLENGE, challenge);
864 /* Compute and save expected response */
865 l2tp_auth_gen_response(MESSAGE_SCCCN, tunnel->peer->secret,
866 challenge, sizeof(challenge), tunnel->expected_response);
869 tunnel_set_state(tunnel, TUNNEL_WAIT_CTL_CONN);
871 /* And ship it out */
872 l2tp_tunnel_xmit_control_message(tunnel, dgram);
875 /**********************************************************************
876 * %FUNCTION: tunnel_schedule_ack
877 * %ARGUMENTS:
878 * tunnel -- the tunnel
879 * %RETURNS:
880 * Nothing
881 * %DESCRIPTION:
882 * Schedules an ack for 100ms from now. The hope is we'll be able to
883 * piggy-back the ack on a packet in the queue; if not, we'll send a ZLB.
884 ***********************************************************************/
885 static void
886 tunnel_schedule_ack(l2tp_tunnel *tunnel)
888 struct timeval t;
890 DBG(l2tp_db(DBG_FLOW, "tunnel_schedule_ack(%s)\n",
891 l2tp_debug_tunnel_to_str(tunnel)));
892 /* Already scheduled? Do nothing */
893 if (tunnel->ack_handler) return;
895 t.tv_sec = 0;
896 t.tv_usec = 100000;
897 tunnel->ack_handler = Event_AddTimerHandler(tunnel->es,
898 t, tunnel_do_ack, tunnel);
901 /**********************************************************************
902 * %FUNCTION: tunnel_do_ack
903 * %ARGUMENTS:
904 * es -- event selector
905 * fd, flags -- not used
906 * data -- pointer to tunnel which needs ack
907 * %RETURNS:
908 * Nothing
909 * %DESCRIPTION:
910 * If there is a frame on our queue, update it's Nr and run queue; if not,
911 * send a ZLB immediately.
912 ***********************************************************************/
913 static void
914 tunnel_do_ack(EventSelector *es,
915 int fd,
916 unsigned int flags,
917 void *data)
919 l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
921 /* Ack handler has fired */
922 tunnel->ack_handler = NULL;
924 DBG(l2tp_db(DBG_FLOW, "tunnel_do_ack(%s)\n",
925 l2tp_debug_tunnel_to_str(tunnel)));
927 /* If nothing is on the queue, add a ZLB */
928 /* Or, if we cannot transmit because of flow-control, send ZLB */
929 if (!tunnel->xmit_new_dgrams ||
930 tunnel_outstanding_frames(tunnel) >= tunnel->cwnd) {
931 tunnel_send_ZLB(tunnel);
932 return;
935 /* Run the queue */
936 tunnel_xmit_queued_messages(tunnel);
939 /**********************************************************************
940 * %FUNCTION: tunnel_dequeue_acked_packets
941 * %ARGUMENTS:
942 * tunnel -- the tunnel
943 * %RETURNS:
944 * Nothing
945 * %DESCRIPTION:
946 * Discards all acknowledged packets from our xmit queue.
947 ***********************************************************************/
948 static void
949 tunnel_dequeue_acked_packets(l2tp_tunnel *tunnel)
951 l2tp_dgram *dgram = tunnel->xmit_queue_head;
952 DBG(l2tp_db(DBG_FLOW, "tunnel_dequeue_acked_packets(%s) %s\n",
953 l2tp_debug_tunnel_to_str(tunnel), tunnel_flow_control_stats(tunnel)));
954 while (dgram) {
955 if (SERIAL_LT(dgram->Ns, tunnel->peer_Nr)) {
956 tunnel_dequeue_head(tunnel);
957 if (tunnel->cwnd < tunnel->ssthresh) {
958 /* Slow start: increment CWND for each packet dequeued */
959 tunnel->cwnd++;
960 if (tunnel->cwnd > tunnel->peer_rws) {
961 tunnel->cwnd = tunnel->peer_rws;
963 } else {
964 /* Congestion avoidance: increment CWND for each CWND
965 packets dequeued */
966 tunnel->cwnd_counter++;
967 if (tunnel->cwnd_counter >= tunnel->cwnd) {
968 tunnel->cwnd_counter = 0;
969 tunnel->cwnd++;
970 if (tunnel->cwnd > tunnel->peer_rws) {
971 tunnel->cwnd = tunnel->peer_rws;
975 } else {
976 break;
978 dgram = tunnel->xmit_queue_head;
982 /**********************************************************************
983 * %FUNCTION: tunnel_handle_timeout
984 * %ARGUMENTS:
985 * es -- event selector
986 * fd, flags -- not used
987 * data -- pointer to tunnel which needs ack
988 * %RETURNS:
989 * Nothing
990 * %DESCRIPTION:
991 * Called when retransmission timer fires.
992 ***********************************************************************/
993 static void
994 tunnel_handle_timeout(EventSelector *es,
995 int fd,
996 unsigned int flags,
997 void *data)
999 l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
1001 /* Timeout handler has fired */
1002 tunnel->timeout_handler = NULL;
1004 /* Reset xmit_new_dgrams */
1005 tunnel->xmit_new_dgrams = tunnel->xmit_queue_head;
1007 /* Set Ns on wire to Ns of first frame in queue */
1008 if (tunnel->xmit_queue_head) {
1009 tunnel->Ns_on_wire = tunnel->xmit_queue_head->Ns;
1012 /* Go back to slow-start phase */
1013 tunnel->ssthresh = tunnel->cwnd / 2;
1014 if (!tunnel->ssthresh) tunnel->ssthresh = 1;
1015 tunnel->cwnd = 1;
1016 tunnel->cwnd_counter = 0;
1018 tunnel->retransmissions++;
1019 if (tunnel->retransmissions >= MAX_RETRANSMISSIONS) {
1020 l2tp_set_errmsg("Too many retransmissions on tunnel (%s); closing down",
1021 l2tp_debug_tunnel_to_str(tunnel));
1023 if (tunnel->state < TUNNEL_ESTABLISHED && tunnel->peer && tunnel->peer->persist &&
1024 (tunnel->peer->maxfail == 0 || tunnel->peer->fail++ < tunnel->peer->maxfail))
1026 struct timeval t;
1028 t.tv_sec = tunnel->peer->holdoff;
1029 t.tv_usec = 0;
1030 Event_AddTimerHandler(tunnel->es, t, l2tp_tunnel_reestablish, tunnel->peer);
1033 /* Close tunnel... */
1034 tunnel_free(tunnel);
1035 return;
1038 /* Double timeout, capping at 8 seconds */
1039 if (tunnel->timeout < 8) {
1040 tunnel->timeout *= 2;
1043 /* Run the queue */
1044 tunnel_xmit_queued_messages(tunnel);
1047 /**********************************************************************
1048 * %FUNCTION: tunnel_send_StopCCN
1049 * %ARGUMENTS:
1050 * tunnel -- the tunnel
1051 * result_code -- what to put in result-code AVP
1052 * error_code -- what to put in error-code field
1053 * fmt -- format string for error message
1054 * ... -- args for formatting error message
1055 * %RETURNS:
1056 * Nothing
1057 * %DESCRIPTION:
1058 * Sends a StopCCN control message.
1059 ***********************************************************************/
1060 static void
1061 tunnel_send_StopCCN(l2tp_tunnel *tunnel,
1062 int result_code,
1063 int error_code,
1064 char const *fmt, ...)
1066 char buf[256];
1067 va_list ap;
1068 uint16_t u16;
1069 uint16_t len;
1070 l2tp_dgram *dgram;
1072 /* Build the buffer for the result-code AVP */
1073 buf[0] = result_code / 256;
1074 buf[1] = result_code & 255;
1075 buf[2] = error_code / 256;
1076 buf[3] = error_code & 255;
1078 va_start(ap, fmt);
1079 vsnprintf(buf+4, 256-4, fmt, ap);
1080 buf[255] = 0;
1081 va_end(ap);
1083 DBG(l2tp_db(DBG_TUNNEL, "tunnel_send_StopCCN(%s, %d, %d, %s)\n",
1084 l2tp_debug_tunnel_to_str(tunnel), result_code, error_code, buf+4));
1086 len = 4 + strlen(buf+4);
1087 /* Build the datagram */
1088 dgram = l2tp_dgram_new_control(MESSAGE_StopCCN, tunnel->assigned_id, 0);
1089 if (!dgram) return;
1091 /* Add assigned tunnel ID */
1092 u16 = htons(tunnel->my_id);
1093 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1094 sizeof(u16), VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID, &u16);
1096 /* Add result code */
1097 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1098 len, VENDOR_IETF, AVP_RESULT_CODE, buf);
1100 /* TODO: Clean up */
1101 tunnel_set_state(tunnel, TUNNEL_SENT_STOP_CCN);
1103 /* Ship it out */
1104 l2tp_tunnel_xmit_control_message(tunnel, dgram);
1107 /**********************************************************************
1108 * %FUNCTION: tunnel_handle_StopCCN
1109 * %ARGUMENTS:
1110 * tunnel -- the tunnel
1111 * dgram -- received datagram
1112 * %RETURNS:
1113 * Nothing
1114 * %DESCRIPTION:
1115 * Processes a received StopCCN frame (shuts tunnel down)
1116 ***********************************************************************/
1117 static void
1118 tunnel_handle_StopCCN(l2tp_tunnel *tunnel,
1119 l2tp_dgram *dgram)
1121 unsigned char *val;
1122 int mandatory, hidden;
1123 uint16_t len, vendor, type;
1124 int err;
1125 l2tp_session *ses;
1126 void *cursor;
1128 /* Shut down all the sessions */
1129 for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1130 ses ;
1131 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1132 hash_remove(&tunnel->sessions_by_my_id, ses);
1133 l2tp_session_free(ses, "Tunnel closing down", 1);
1136 tunnel_set_state(tunnel, TUNNEL_RECEIVED_STOP_CCN);
1138 /* If there are any queued datagrams waiting for transmission,
1139 nuke them and adjust tunnel's Ns to whatever peer has ack'd */
1140 /* TODO: Is this correct? */
1141 if (tunnel->xmit_queue_head) {
1142 tunnel->Ns = tunnel->peer_Nr;
1143 while(tunnel->xmit_queue_head) {
1144 tunnel_dequeue_head(tunnel);
1148 /* Parse the AVP's */
1149 while(1) {
1150 val = l2tp_dgram_pull_avp(dgram, tunnel, &mandatory, &hidden,
1151 &len, &vendor, &type, &err);
1152 if (!val) {
1153 break;
1156 /* Only care about assigned tunnel ID. TODO: Fix this! */
1157 if (vendor != VENDOR_IETF || type != AVP_ASSIGNED_TUNNEL_ID) {
1158 continue;
1161 if (len == 2) {
1162 tunnel->assigned_id = ((unsigned int) val[0]) * 256 +
1163 (unsigned int) val[1];
1167 /* No point in delaying ack; there will never be a datagram for
1168 piggy-back. So cancel ack timer and shoot out a ZLB now */
1169 if (tunnel->ack_handler) {
1170 Event_DelHandler(tunnel->es, tunnel->ack_handler);
1171 tunnel->ack_handler = NULL;
1173 tunnel_send_ZLB(tunnel);
1174 /* We'll be scheduled for destruction after this function returns */
1177 /**********************************************************************
1178 * %FUNCTION: tunnel_process_received_datagram
1179 * %ARGUMENTS:
1180 * tunnel -- the tunnel
1181 * dgram -- the received datagram
1182 * %RETURNS:
1183 * Nothing
1184 * %DESCRIPTION:
1185 * Handles a received control message for this tunnel
1186 ***********************************************************************/
1187 static void
1188 tunnel_process_received_datagram(l2tp_tunnel *tunnel,
1189 l2tp_dgram *dgram)
1191 l2tp_session *ses = NULL;
1193 /* If message is associated with existing session, find session */
1195 DBG(l2tp_db(DBG_TUNNEL, "tunnel_process_received_datagram(%s, %s)\n",
1196 l2tp_debug_tunnel_to_str(tunnel),
1197 l2tp_debug_message_type_to_str(dgram->msg_type)));
1198 switch (dgram->msg_type) {
1199 case MESSAGE_OCRP:
1200 case MESSAGE_OCCN:
1201 case MESSAGE_ICRP:
1202 case MESSAGE_ICCN:
1203 case MESSAGE_CDN:
1204 ses = l2tp_tunnel_find_session(tunnel, dgram->sid);
1205 if (!ses) {
1206 l2tp_set_errmsg("Session-related message for unknown session %d",
1207 (int) dgram->sid);
1208 return;
1212 switch (dgram->msg_type) {
1213 case MESSAGE_StopCCN:
1214 tunnel_handle_StopCCN(tunnel, dgram);
1215 return;
1216 case MESSAGE_SCCRP:
1217 tunnel_handle_SCCRP(tunnel, dgram);
1218 return;
1219 case MESSAGE_SCCCN:
1220 tunnel_handle_SCCCN(tunnel, dgram);
1221 return;
1222 case MESSAGE_ICRQ:
1223 tunnel_handle_ICRQ(tunnel, dgram);
1224 return;
1225 case MESSAGE_CDN:
1226 l2tp_session_handle_CDN(ses, dgram);
1227 return;
1228 case MESSAGE_ICRP:
1229 l2tp_session_handle_ICRP(ses, dgram);
1230 return;
1231 case MESSAGE_ICCN:
1232 l2tp_session_handle_ICCN(ses, dgram);
1233 return;
1234 case MESSAGE_HELLO: //@.@ 20070806 When our reciver HELLO_MSG
1235 //tunnel_send_ZLB(tunnel);
1236 tunnel_setup_hello(tunnel); //every 60sec send hello to (Linux)L2TPD_Server
1237 return;
1241 /**********************************************************************
1242 * %FUNCTION: tunnel_finally_cleanup
1243 * %ARGUMENTS:
1244 * es -- event selector
1245 * fd, flags -- ignored
1246 * data -- the tunnel
1247 * %RETURNS:
1248 * Nothing
1249 * %DESCRIPTION:
1250 * Deallocates all tunnel state
1251 ***********************************************************************/
1252 static void
1253 tunnel_finally_cleanup(EventSelector *es,
1254 int fd,
1255 unsigned int flags,
1256 void *data)
1258 l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
1260 /* Hello handler has fired */
1261 tunnel->hello_handler = NULL;
1262 tunnel_free(tunnel);
1265 /**********************************************************************
1266 * %FUNCTION: tunnel_schedule_destruction
1267 * %ARGUMENTS:
1268 * tunnel -- tunnel which is to be destroyed
1269 * %RETURNS:
1270 * Nothing
1271 * %DESCRIPTION:
1272 * Schedules tunnel for destruction 31 seconds hence.
1273 ***********************************************************************/
1274 static void
1275 tunnel_schedule_destruction(l2tp_tunnel *tunnel)
1277 struct timeval t;
1278 void *cursor;
1279 l2tp_session *ses;
1281 t.tv_sec = 31;
1282 t.tv_usec = 0;
1284 DBG(l2tp_db(DBG_TUNNEL, "tunnel_schedule_destruction(%s)\n",
1285 l2tp_debug_tunnel_to_str(tunnel)));
1286 /* Shut down the tunnel in 31 seconds - (ab)use the hello handler */
1287 if (tunnel->hello_handler) {
1288 Event_DelHandler(tunnel->es, tunnel->hello_handler);
1290 tunnel->hello_handler =
1291 Event_AddTimerHandler(tunnel->es, t,
1292 tunnel_finally_cleanup, tunnel);
1294 /* Kill the sessions now */
1295 for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1296 ses ;
1297 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1298 l2tp_session_free(ses, "Tunnel closing down", 1);
1301 /* Clear hash table */
1302 l2tp_session_hash_init(&tunnel->sessions_by_my_id);
1305 /**********************************************************************
1306 * %FUNCTION: tunnel_send_ZLB
1307 * %ARGUMENTS:
1308 * tunnel -- the tunnel
1309 * %RETURNS:
1310 * Nothing
1311 * %DESCRIPTION:
1312 * Sends a ZLB ack packet.
1313 ***********************************************************************/
1314 void
1315 tunnel_send_ZLB(l2tp_tunnel *tunnel)
1317 l2tp_dgram *dgram =
1318 l2tp_dgram_new_control(MESSAGE_ZLB, tunnel->assigned_id, 0);
1319 if (!dgram) {
1320 l2tp_set_errmsg("tunnel_send_ZLB: Out of memory");
1321 return;
1323 dgram->Nr = tunnel->Nr;
1324 dgram->Ns = tunnel->Ns_on_wire;
1325 l2tp_dgram_send_to_wire(dgram, &tunnel->peer_addr);
1326 l2tp_dgram_free(dgram);
1329 /**********************************************************************
1330 * %FUNCTION: tunnel_handle_SCCRP
1331 * %ARGUMENTS:
1332 * tunnel -- the tunnel
1333 * dgram -- the incoming datagram
1334 * %RETURNS:
1335 * Nothing
1336 * %DESCRIPTION:
1337 * Handles an incoming SCCRP
1338 ***********************************************************************/
1339 static void
1340 tunnel_handle_SCCRP(l2tp_tunnel *tunnel,
1341 l2tp_dgram *dgram)
1344 /* TODO: If we don't get challenge response at all, barf */
1345 /* Are we expecing SCCRP? */
1346 if (tunnel->state != TUNNEL_WAIT_CTL_REPLY) {
1347 tunnel_send_StopCCN(tunnel, RESULT_FSM_ERROR, 0, "Not expecting SCCRP");
1348 return;
1351 /* Extract tunnel params */
1352 if (tunnel_set_params(tunnel, dgram) < 0) return;
1354 tunnel_set_state(tunnel, TUNNEL_ESTABLISHED);
1355 tunnel_setup_hello(tunnel);
1357 /* Hunky-dory. Send SCCCN */
1358 dgram = l2tp_dgram_new_control(MESSAGE_SCCCN, tunnel->assigned_id, 0);
1359 if (!dgram) {
1360 /* Doh! Out of resources. Not much chance of StopCCN working... */
1361 tunnel_send_StopCCN(tunnel,
1362 RESULT_GENERAL_ERROR, ERROR_OUT_OF_RESOURCES,
1363 "Out of memory");
1364 return;
1367 /* Add response */
1368 if (tunnel->peer->secret_len) {
1369 l2tp_dgram_add_avp(dgram, tunnel, MANDATORY,
1370 MD5LEN, VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
1371 tunnel->response);
1374 /* Ship it out */
1375 l2tp_tunnel_xmit_control_message(tunnel, dgram);
1377 /* Tell sessions tunnel has been established */
1378 tunnel_tell_sessions_tunnel_open(tunnel);
1381 /**********************************************************************
1382 * %FUNCTION: tunnel_set_params
1383 * %ARGUMENTS:
1384 * tunnel -- the tunnel
1385 * dgram -- incoming SCCRQ or SCCRP datagram
1386 * %RETURNS:
1387 * 0 if OK, non-zero on error
1388 * %DESCRIPTION:
1389 * Sets up initial tunnel parameters (assigned ID, etc.)
1390 ***********************************************************************/
1391 static int
1392 tunnel_set_params(l2tp_tunnel *tunnel,
1393 l2tp_dgram *dgram)
1395 unsigned char *val;
1396 int mandatory, hidden;
1397 uint16_t len, vendor, type;
1398 int err = 0;
1399 int found_response = 0;
1401 uint16_t u16;
1403 /* Get host name */
1404 val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1405 VENDOR_IETF, AVP_HOST_NAME);
1406 if (!val) {
1407 l2tp_set_errmsg("No host name AVP in SCCRQ");
1408 tunnel_free(tunnel);
1409 return -1;
1412 if (len >= MAX_HOSTNAME) len = MAX_HOSTNAME-1;
1413 memcpy(tunnel->peer_hostname, val, len);
1414 tunnel->peer_hostname[len+1] = 0;
1415 DBG(l2tp_db(DBG_TUNNEL, "%s: Peer host name is '%s'\n",
1416 l2tp_debug_tunnel_to_str(tunnel), tunnel->peer_hostname));
1418 /* Find peer */
1419 if (tunnel->peer == NULL || tunnel->peer->addr.sin_addr.s_addr != INADDR_ANY)
1420 tunnel->peer = l2tp_peer_find(&tunnel->peer_addr, tunnel->peer_hostname);
1422 /* Get assigned tunnel ID */
1423 val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1424 VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID);
1425 if (!val) {
1426 l2tp_set_errmsg("No assigned tunnel ID AVP in SCCRQ");
1427 tunnel_free(tunnel);
1428 return -1;
1431 if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_ASSIGNED_TUNNEL_ID,
1432 len, mandatory)) {
1433 tunnel_free(tunnel);
1434 return -1;
1437 /* Set tid */
1438 tunnel->assigned_id = ((unsigned int) val[0]) * 256 + (unsigned int) val[1];
1439 if (!tunnel->assigned_id) {
1440 l2tp_set_errmsg("Invalid assigned-tunnel-ID of zero");
1441 tunnel_free(tunnel);
1442 return -1;
1445 /* Validate peer */
1446 if (!tunnel->peer) {
1447 l2tp_set_errmsg("Peer %s is not authorized to create a tunnel",
1448 inet_ntoa(tunnel->peer_addr.sin_addr));
1449 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_OK, "%s", l2tp_get_errmsg());
1450 return -1;
1453 /* Pull out and examine AVP's */
1454 while(1) {
1455 val = l2tp_dgram_pull_avp(dgram, tunnel, &mandatory, &hidden,
1456 &len, &vendor, &type, &err);
1457 if (!val) {
1458 if (err) {
1459 tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1460 ERROR_BAD_VALUE, "%s", l2tp_get_errmsg());
1461 return -1;
1463 break;
1466 /* Unknown vendor? Ignore, unless mandatory */
1467 if (vendor != VENDOR_IETF) {
1468 if (!mandatory) continue;
1469 tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1470 ERROR_UNKNOWN_AVP_WITH_M_BIT,
1471 "Unknown mandatory attribute (vendor=%d, type=%d) in %s",
1472 (int) vendor, (int) type,
1473 l2tp_debug_avp_type_to_str(dgram->msg_type));
1474 return -1;
1477 /* Validate AVP, ignore invalid AVP's without M bit set */
1478 if (!l2tp_dgram_validate_avp(vendor, type, len, mandatory)) {
1479 if (!mandatory) continue;
1480 tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR,
1481 ERROR_BAD_LENGTH, "%s", l2tp_get_errmsg());
1482 return -1;
1485 switch(type) {
1486 case AVP_PROTOCOL_VERSION:
1487 u16 = ((uint16_t) val[0]) * 256 + val[1];
1488 if (u16 != 0x100) {
1489 tunnel_send_StopCCN(tunnel, RESULT_UNSUPPORTED_VERSION,
1490 0x100, "Unsupported protocol version");
1491 return -1;
1493 break;
1495 case AVP_HOST_NAME:
1496 /* Already been handled */
1497 break;
1499 case AVP_FRAMING_CAPABILITIES:
1500 /* TODO: Do we care about framing capabilities? */
1501 break;
1503 case AVP_ASSIGNED_TUNNEL_ID:
1504 /* Already been handled */
1505 break;
1507 case AVP_BEARER_CAPABILITIES:
1508 /* TODO: Do we care? */
1509 break;
1511 case AVP_RECEIVE_WINDOW_SIZE:
1512 u16 = ((uint16_t) val[0]) * 256 + val[1];
1513 /* Silently correct bogus rwin */
1514 if (u16 < 1) u16 = 1;
1515 tunnel->peer_rws = u16;
1516 tunnel->ssthresh = u16;
1517 break;
1519 case AVP_CHALLENGE:
1520 if (tunnel->peer->secret_len) {
1521 l2tp_auth_gen_response(
1522 ((dgram->msg_type == MESSAGE_SCCRQ) ? MESSAGE_SCCRP : MESSAGE_SCCCN),
1523 tunnel->peer->secret,
1524 val, len, tunnel->response);
1526 break;
1528 case AVP_CHALLENGE_RESPONSE:
1529 /* Length has been validated by l2tp_dgram_validate_avp */
1530 if (tunnel->peer->secret_len) {
1531 if (memcmp(val, tunnel->expected_response, MD5LEN)) {
1532 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_BAD_VALUE,
1533 "Incorrect challenge response");
1534 return -1;
1537 found_response = 1;
1538 break;
1540 case AVP_TIE_BREAKER:
1541 /* TODO: Handle tie-breaker */
1542 break;
1544 case AVP_FIRMWARE_REVISION:
1545 /* TODO: Do we care? */
1546 break;
1548 case AVP_VENDOR_NAME:
1549 /* TODO: Do we care? */
1550 break;
1552 default:
1553 /* TODO: Maybe print an error? */
1554 break;
1558 if (tunnel->peer->secret_len &&
1559 !found_response &&
1560 dgram->msg_type != MESSAGE_SCCRQ) {
1561 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, 0,
1562 "Missing challenge-response");
1563 return -1;
1565 return 0;
1568 /**********************************************************************
1569 * %FUNCTION: tunnel_setup_hello
1570 * %ARGUMENTS:
1571 * tunnel -- the tunnel
1572 * %RETURNS:
1573 * Nothing
1574 * %DESCRIPTION:
1575 * Sets up timer for sending HELLO messages
1576 ***********************************************************************/
1577 static void
1578 tunnel_setup_hello(l2tp_tunnel *tunnel)
1580 struct timeval t;
1582 //t.tv_sec = 60;
1583 t.tv_sec = 30;
1584 t.tv_usec = 0;
1586 if (tunnel->hello_handler) {
1587 Event_DelHandler(tunnel->es, tunnel->hello_handler);
1589 tunnel->hello_handler = Event_AddTimerHandler(tunnel->es, t,
1590 tunnel_do_hello, tunnel);
1593 /**********************************************************************
1594 * %FUNCTION: tunnel_do_hello
1595 * %ARGUMENTS:
1596 * es -- event selector
1597 * fd, flags -- ignored
1598 * data -- the tunnel
1599 * %RETURNS:
1600 * Nothing
1601 * %DESCRIPTION:
1602 * Deallocates all tunnel state
1603 ***********************************************************************/
1604 static void
1605 tunnel_do_hello(EventSelector *es,
1606 int fd,
1607 unsigned int flags,
1608 void *data)
1610 l2tp_tunnel *tunnel = (l2tp_tunnel *) data;
1611 l2tp_dgram *dgram;
1613 /* Hello handler has fired */
1614 tunnel->hello_handler = NULL;
1616 /* Reschedule HELLO timer */
1617 tunnel_setup_hello(tunnel);
1619 /* Send a HELLO message */
1620 dgram = l2tp_dgram_new_control(MESSAGE_HELLO, tunnel->assigned_id, 0);
1621 if (dgram) l2tp_tunnel_xmit_control_message(tunnel, dgram);
1624 /**********************************************************************
1625 * %FUNCTION: tunnel_handle_SCCCN
1626 * %ARGUMENTS:
1627 * tunnel -- the tunnel
1628 * dgram -- the incoming datagram
1629 * %RETURNS:
1630 * Nothing
1631 * %DESCRIPTION:
1632 * Handles an incoming SCCCN
1633 ***********************************************************************/
1634 static void
1635 tunnel_handle_SCCCN(l2tp_tunnel *tunnel,
1636 l2tp_dgram *dgram)
1638 unsigned char *val;
1639 uint16_t len;
1640 int hidden, mandatory;
1642 /* Are we expecing SCCCN? */
1643 if (tunnel->state != TUNNEL_WAIT_CTL_CONN) {
1644 tunnel_send_StopCCN(tunnel, RESULT_FSM_ERROR, 0, "Not expecting SCCCN");
1645 return;
1648 /* Check challenge response */
1649 if (tunnel->peer->secret_len) {
1650 val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1651 VENDOR_IETF, AVP_CHALLENGE_RESPONSE);
1652 if (!val) {
1653 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, 0,
1654 "Missing challenge-response");
1655 return;
1658 if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_CHALLENGE_RESPONSE,
1659 len, mandatory)) {
1660 tunnel_send_StopCCN(tunnel, RESULT_GENERAL_ERROR, ERROR_BAD_LENGTH,
1661 "Invalid challenge-response");
1662 return;
1664 if (memcmp(val, tunnel->expected_response, MD5LEN)) {
1665 tunnel_send_StopCCN(tunnel, RESULT_NOAUTH, ERROR_BAD_VALUE,
1666 "Incorrect challenge response");
1667 return;
1671 tunnel_set_state(tunnel, TUNNEL_ESTABLISHED);
1672 tunnel_setup_hello(tunnel);
1674 /* Tell sessions tunnel has been established */
1675 tunnel_tell_sessions_tunnel_open(tunnel);
1678 /**********************************************************************
1679 * %FUNCTION: tunnel_find_for_peer
1680 * %ARGUMENTS:
1681 * peer -- an L2TP peer
1682 * es -- an event selector
1683 * %RETURNS:
1684 * An existing tunnel to peer (if one exists) or a new one (if one does not),
1685 * or NULL if no tunnel could be established. If the existing tunnel
1686 * is in the state RECEIVED_STOP_CCN or SENT_STOP_CCN, make a new one.
1687 ***********************************************************************/
1688 l2tp_tunnel *
1689 l2tp_tunnel_find_for_peer(l2tp_peer *peer,
1690 EventSelector *es)
1692 l2tp_tunnel *tunnel;
1693 void *cursor;
1695 if (peer->addr.sin_addr.s_addr == INADDR_ANY)
1697 for (tunnel = hash_start(&tunnels_by_my_id, &cursor);
1698 tunnel && tunnel->peer != peer;
1699 tunnel = hash_next(&tunnels_by_my_id, &cursor));
1700 } else {
1701 tunnel = tunnel_find_bypeer(peer->addr);
1704 if (tunnel) {
1705 if (tunnel->state == TUNNEL_WAIT_CTL_REPLY ||
1706 tunnel->state == TUNNEL_WAIT_CTL_CONN ||
1707 tunnel->state == TUNNEL_ESTABLISHED) {
1708 return tunnel;
1712 /* No tunnel, or tunnel in wrong state */
1713 return tunnel_establish(peer, es);
1716 /**********************************************************************
1717 * %FUNCTION: tunnel_find_session
1718 * %ARGUMENTS:
1719 * sid -- session ID
1720 * %RETURNS:
1721 * The session with specified ID, or NULL if no such session
1722 ***********************************************************************/
1723 l2tp_session *
1724 l2tp_tunnel_find_session(l2tp_tunnel *tunnel,
1725 uint16_t sid)
1727 l2tp_session candidate;
1728 candidate.my_id = sid;
1729 return hash_find(&tunnel->sessions_by_my_id, &candidate);
1732 /**********************************************************************
1733 * %FUNCTION: tunnel_tell_sessions_tunnel_open
1734 * %ARGUMENTS:
1735 * tunnel -- the tunnel
1736 * %RETURNS:
1737 * Nothing
1738 * %DESCRIPTION:
1739 * Informs all waiting sessions that tunnel has moved into ESTABLISHED state.
1740 ***********************************************************************/
1741 static void
1742 tunnel_tell_sessions_tunnel_open(l2tp_tunnel *tunnel)
1744 l2tp_session *ses;
1745 void *cursor;
1747 for (ses = hash_start(&tunnel->sessions_by_my_id, &cursor);
1748 ses ;
1749 ses = hash_next(&tunnel->sessions_by_my_id, &cursor)) {
1750 l2tp_session_notify_tunnel_open(ses);
1754 /**********************************************************************
1755 * %FUNCTION: tunnel_add_session
1756 * %ARGUMENTS:
1757 * ses -- session to add
1758 * %RETURNS:
1759 * Nothing
1760 * %DESCRIPTION:
1761 * Adds session to tunnel's hash table. If tunnel is up, calls
1762 * l2tp_session_notify_tunnel_open
1763 ***********************************************************************/
1764 void
1765 l2tp_tunnel_add_session(l2tp_session *ses)
1767 l2tp_tunnel *tunnel = ses->tunnel;
1769 hash_insert(&tunnel->sessions_by_my_id, ses);
1770 if (tunnel->state == TUNNEL_ESTABLISHED) {
1771 l2tp_session_notify_tunnel_open(ses);
1775 void
1776 l2tp_tunnel_reestablish(EventSelector *es,
1777 int fd,
1778 unsigned int flags,
1779 void *data)
1781 l2tp_peer *peer = (l2tp_peer*) data;
1782 l2tp_session *ses;
1784 ses = l2tp_session_call_lns(peer, "foobar", es, NULL);
1785 if (!ses) {
1786 DBG(l2tp_db(DBG_TUNNEL, "l2tp_tunnel_reestablish() failed\n"));
1787 return;
1791 /**********************************************************************
1792 * %FUNCTION: tunnel_delete_session
1793 * %ARGUMENTS:
1794 * ses -- session to delete
1795 * %RETURNS:
1796 * Nothing
1797 * %DESCRIPTION:
1798 * Deletes session from tunnel's hash table and frees it.
1799 ***********************************************************************/
1800 void
1801 l2tp_tunnel_delete_session(l2tp_session *ses, char const *reason, int may_reestablish)
1803 l2tp_tunnel *tunnel = ses->tunnel;
1805 hash_remove(&tunnel->sessions_by_my_id, ses);
1806 l2tp_session_free(ses, reason, may_reestablish);
1808 /* Tear down tunnel if so indicated */
1809 if (!hash_num_entries(&tunnel->sessions_by_my_id)) {
1810 if (!tunnel->peer->retain_tunnel) {
1811 tunnel_send_StopCCN(tunnel,
1812 RESULT_GENERAL_REQUEST, 0,
1813 "Last session has closed");
1818 /**********************************************************************
1819 * %FUNCTION: tunnel_handle_ICRQ
1820 * %ARGUMENTS:
1821 * tunnel -- the tunnel
1822 * dgram -- the datagram
1823 * %RETURNS:
1824 * Nothing
1825 * %DESCRIPTION:
1826 * Handles ICRQ (Incoming Call ReQuest)
1827 ***********************************************************************/
1828 static void
1829 tunnel_handle_ICRQ(l2tp_tunnel *tunnel,
1830 l2tp_dgram *dgram)
1832 uint16_t u16;
1833 unsigned char *val;
1834 uint16_t len;
1835 int mandatory, hidden;
1837 /* Get assigned session ID */
1838 val = l2tp_dgram_search_avp(dgram, tunnel, &mandatory, &hidden, &len,
1839 VENDOR_IETF, AVP_ASSIGNED_SESSION_ID);
1840 if (!val) {
1841 l2tp_set_errmsg("No assigned tunnel ID AVP in ICRQ");
1842 return;
1844 if (!l2tp_dgram_validate_avp(VENDOR_IETF, AVP_ASSIGNED_SESSION_ID,
1845 len, mandatory)) {
1846 /* TODO: send CDN */
1847 return;
1850 /* Set assigned session ID */
1851 u16 = ((uint16_t) val[0]) * 256 + (uint16_t) val[1];
1853 if (!u16) {
1854 /* TODO: send CDN */
1855 return;
1858 /* Tunnel in wrong state? */
1859 if (tunnel->state != TUNNEL_ESTABLISHED) {
1860 /* TODO: Send CDN */
1861 return;
1864 /* Set up new incoming call */
1865 /* TODO: Include calling number */
1866 l2tp_session_lns_handle_incoming_call(tunnel, u16, dgram, "");
1869 /**********************************************************************
1870 * %FUNCTION: l2tp_tunnel_stop_all
1871 * %ARGUMENTS:
1872 * reason -- reason for stopping tunnels
1873 * %RETURNS:
1874 * Nothing
1875 * %DESCRIPTION:
1876 * Stops all tunnels
1877 ***********************************************************************/
1878 void
1879 l2tp_tunnel_stop_all(char const *reason)
1881 l2tp_tunnel *tunnel;
1882 void *cursor;
1884 /* Send StopCCN on all tunnels except those which are scheduled for
1885 destruction */
1886 for (tunnel = hash_start(&tunnels_by_my_id, &cursor);
1887 tunnel;
1888 tunnel = hash_next(&tunnels_by_my_id, &cursor)) {
1889 l2tp_tunnel_stop_tunnel(tunnel, reason);
1894 /**********************************************************************
1895 * %FUNCTION: l2tp_tunnel_stop_tunnel
1896 * %ARGUMENTS:
1897 * tunnel -- tunnel to stop
1898 * reason -- reason for stopping tunnel
1899 * %RETURNS:
1900 * Nothing
1901 * %DESCRIPTION:
1902 * Stops a tunnels (sends StopCCN)
1903 ***********************************************************************/
1904 void
1905 l2tp_tunnel_stop_tunnel(l2tp_tunnel *tunnel,
1906 char const *reason)
1908 /* Do not send StopCCN if we've received one already */
1909 if (tunnel->state != TUNNEL_RECEIVED_STOP_CCN &&
1910 tunnel->state != TUNNEL_SENT_STOP_CCN) {
1911 tunnel_send_StopCCN(tunnel, RESULT_SHUTTING_DOWN, 0, reason);
1915 /**********************************************************************
1916 * %FUNCTION: l2tp_num_tunnels
1917 * %ARGUMENTS:
1918 * None
1919 * %RETURNS:
1920 * The number of L2TP tunnels
1921 ***********************************************************************/
1923 l2tp_num_tunnels(void)
1925 return hash_num_entries(&tunnels_by_my_id);
1928 /**********************************************************************
1929 * %FUNCTION: l2tp_first_tunnel
1930 * %ARGUMENTS:
1931 * cursor -- cursor for keeping track of where we are in interation
1932 * %RETURNS:
1933 * First L2TP tunnel
1934 ***********************************************************************/
1935 l2tp_tunnel *
1936 l2tp_first_tunnel(void **cursor)
1938 return hash_start(&tunnels_by_my_id, cursor);
1942 /**********************************************************************
1943 * %FUNCTION: l2tp_next_tunnel
1944 * %ARGUMENTS:
1945 * cursor -- cursor for keeping track of where we are in interation
1946 * %RETURNS:
1947 * Next L2TP tunnel
1948 ***********************************************************************/
1949 l2tp_tunnel *
1950 l2tp_next_tunnel(void **cursor)
1952 return hash_next(&tunnels_by_my_id, cursor);
1955 /**********************************************************************
1956 * %FUNCTION: l2tp_tunnel_state_name
1957 * %ARGUMENTS:
1958 * tunnel -- the tunnel
1959 * %RETURNS:
1960 * The name of the tunnel's state
1961 ***********************************************************************/
1962 char const *
1963 l2tp_tunnel_state_name(l2tp_tunnel *tunnel)
1965 return state_names[tunnel->state];
1968 /**********************************************************************
1969 * %FUNCTION: l2tp_tunnel_first_session
1970 * %ARGUMENTS:
1971 * tunnel -- the tunnel
1972 * cursor -- cursor for hash table iteration
1973 * %RETURNS:
1974 * First session in tunnel
1975 ***********************************************************************/
1976 l2tp_session *
1977 l2tp_tunnel_first_session(l2tp_tunnel *tunnel, void **cursor)
1979 return hash_start(&tunnel->sessions_by_my_id, cursor);
1982 /**********************************************************************
1983 * %FUNCTION: l2tp_tunnel_next_session
1984 * %ARGUMENTS:
1985 * tunnel -- the tunnel
1986 * cursor -- cursor for hash table iteration
1987 * %RETURNS:
1988 * Next session in tunnel
1989 ***********************************************************************/
1990 l2tp_session *
1991 l2tp_tunnel_next_session(l2tp_tunnel *tunnel, void **cursor)
1993 return hash_next(&tunnel->sessions_by_my_id, cursor);
1996 /*** route manipulation ************************************************/
1998 static int
1999 route_ctrl(int ctrl, struct rtentry *rt)
2001 int s;
2003 /* Open a raw socket to the kernel */
2004 if ((s = socket(AF_INET, SOCK_DGRAM, 0)) < 0 || ioctl(s, ctrl, rt) < 0)
2005 l2tp_set_errmsg("route_ctrl: %s", strerror(errno));
2006 else errno = 0;
2008 close(s);
2009 return errno;
2012 static int
2013 route_del(struct rtentry *rt)
2015 if (rt->rt_dev) {
2016 route_ctrl(SIOCDELRT, rt);
2017 free(rt->rt_dev), rt->rt_dev = NULL;
2020 return 0;
2023 static int
2024 route_add(const struct in_addr inetaddr, struct rtentry *rt)
2026 char buf[256], dev[64];
2027 int metric, flags;
2028 u_int32_t dest, mask;
2030 FILE *f = fopen("/proc/net/route", "r");
2031 if (f == NULL) {
2032 l2tp_set_errmsg("/proc/net/route: %s", strerror(errno));
2033 return -1;
2036 while (fgets(buf, sizeof(buf), f))
2038 if (sscanf(buf, "%63s %x %x %X %*s %*s %d %x", dev, &dest,
2039 &sin_addr(&rt->rt_gateway).s_addr, &flags, &metric, &mask) != 6)
2040 continue;
2041 if ((flags & RTF_UP) == (RTF_UP) && (inetaddr.s_addr & mask) == dest &&
2042 (dest || strncmp(dev, "ppp", 3)) /* avoid default via pppX to avoid on-demand loops*/)
2044 rt->rt_metric = metric + 1;
2045 rt->rt_gateway.sa_family = AF_INET;
2046 break;
2050 fclose(f);
2052 /* check for no route */
2053 if (rt->rt_gateway.sa_family != AF_INET)
2055 /*l2tp_set_errmsg("route_add: no route to host");*/
2056 return -1;
2059 /* check for existing route to this host,
2060 add if missing based on the existing routes */
2061 if (flags & RTF_HOST) {
2062 /*l2tp_set_errmsg("route_add: not adding existing route");*/
2063 return -1;
2066 sin_addr(&rt->rt_dst) = inetaddr;
2067 rt->rt_dst.sa_family = AF_INET;
2069 sin_addr(&rt->rt_genmask).s_addr = INADDR_BROADCAST;
2070 rt->rt_genmask.sa_family = AF_INET;
2072 rt->rt_flags = RTF_UP | RTF_HOST;
2073 if (flags & RTF_GATEWAY)
2074 rt->rt_flags |= RTF_GATEWAY;
2076 rt->rt_metric++;
2077 rt->rt_dev = strdup(dev);
2079 if (!rt->rt_dev)
2081 l2tp_set_errmsg("route_add: no memory");
2082 return -1;
2085 if (!route_ctrl(SIOCADDRT, rt))
2086 return 0;
2088 free(rt->rt_dev), rt->rt_dev = NULL;
2090 return -1;