3 // (c) Copyrigth 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd)
10 #include <linux/if_tun.h>
15 #include <net/route.h>
18 #include <netinet/in.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
29 #include <sys/resource.h>
30 #include <sys/types.h>
42 #include "constants.h"
47 struct configt
*config
= NULL
; // all configuration
48 int tapfd
= -1; // tap interface file handle
49 int udpfd
= -1; // UDP file handle
50 int controlfd
= -1; // Control signal handle
51 int snoopfd
= -1; // UDP file handle for sending out intercept data
52 int radfd
= -1; // RADIUS requests file handle
53 int ifrfd
= -1; // File descriptor for routing, etc
54 time_t basetime
= 0; // base clock
55 char hostname
[1000] = ""; // us.
56 ipt myip
= 0; // MY IP
57 u16 tapmac
[3]; // MAC of tap interface
58 int tapidx
; // ifr_ifindex of tap device
59 u32 sessionid
= 0; // session id for radius accounting
60 int syslog_log
= 0; // are we logging to syslog
61 FILE *log_stream
= NULL
;
62 struct sockaddr_in snoop_addr
= {0};
63 extern int cluster_sockfd
;
64 unsigned long last_sid
= 0;
65 int handle_interface
= 0;
67 sessionidt
*cli_session_kill
= NULL
;
68 tunnelidt
*cli_tunnel_kill
= NULL
;
69 static void *ip_hash
[256];
70 unsigned long udp_tx
= 0, udp_rx
= 0, udp_rx_pkt
= 0;
71 unsigned long eth_tx
= 0, eth_rx
= 0, eth_rx_pkt
= 0;
72 unsigned int ip_pool_size
= 0;
74 char time_now_string
[64] = {0};
76 char *_program_name
= NULL
;
77 linked_list
*loaded_plugins
;
78 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
80 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
81 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(struct configt, MEMBER), membersize(struct configt, MEMBER), TYPE }
83 struct config_descriptt config_values
[] = {
84 CONFIG("debug", debug
, INT
),
85 CONFIG("log_file", log_filename
, STRING
),
86 CONFIG("l2tp_secret", l2tpsecret
, STRING
),
87 CONFIG("primary_dns", default_dns1
, IP
),
88 CONFIG("secondary_dns", default_dns2
, IP
),
89 CONFIG("save_state", save_state
, BOOL
),
90 CONFIG("snoop_host", snoop_destination_host
, IP
),
91 CONFIG("snoop_port", snoop_destination_port
, SHORT
),
92 CONFIG("primary_radius", radiusserver
[0], IP
),
93 CONFIG("secondary_radius", radiusserver
[1], IP
),
94 CONFIG("radius_accounting", radius_accounting
, BOOL
),
95 CONFIG("radius_secret", radiussecret
, STRING
),
96 CONFIG("bind_address", bind_address
, IP
),
97 CONFIG("cluster_master", cluster_address
, IP
),
98 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
99 CONFIG("accounting_dir", accounting_dir
, STRING
),
100 CONFIG("setuid", target_uid
, INT
),
101 CONFIG("dump_speed", dump_speed
, BOOL
),
105 char *plugin_functions
[] = {
112 "plugin_new_session",
113 "plugin_kill_session",
115 "plugin_radius_response",
117 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
119 tunnelt
*tunnel
= NULL
; // 1000 * 45 = 45000 = 45k
120 sessiont
*session
= NULL
; // 5000 * 213 = 1065000 = 1 Mb
121 radiust
*radius
= NULL
;
122 ippoolt
*ip_address_pool
= NULL
;
123 controlt
*controlfree
= 0;
124 struct Tstats
*_statistics
= NULL
;
126 struct Tringbuffer
*ringbuffer
= NULL
;
128 tbft
*filter_buckets
= NULL
;
130 void sigalrm_handler(int);
131 void sighup_handler(int);
132 void sigterm_handler(int);
133 void sigquit_handler(int);
134 void sigchild_handler(int);
135 void sigsegv_handler(int);
136 void read_config_file();
140 tunnelidt
new_tunnel();
141 void update_config();
143 // return internal time (10ths since run)
148 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
151 // work out a retry time based on try number
152 clockt
backoff(u8
try)
154 if (try > 5) try = 5; // max backoff
155 return now() + 10 * (1 << try);
158 void _log(int level
, ipt address
, sessionidt s
, tunnelidt t
, const char *format
, ...)
160 static char message
[65535] = {0};
161 static char message2
[65535] = {0};
167 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
168 ringbuffer
->tail
= 0;
169 if (ringbuffer
->tail
== ringbuffer
->head
)
170 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
171 ringbuffer
->head
= 0;
173 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
174 ringbuffer
->buffer
[ringbuffer
->tail
].address
= address
;
175 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
176 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
177 va_start(ap
, format
);
178 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
183 if (config
->debug
< level
) return;
185 va_start(ap
, format
);
188 vsnprintf(message2
, 65535, format
, ap
);
189 snprintf(message
, 65535, "%s %02d/%02d %s", time_now_string
, t
, s
, message2
);
190 fprintf(log_stream
, message
);
194 vsnprintf(message2
, 65535, format
, ap
);
195 snprintf(message
, 65535, "%02d/%02d %s", t
, s
, message2
);
196 syslog(level
+ 2, message
); // We don't need LOG_EMERG or LOG_ALERT
201 void _log_hex(int level
, ipt address
, sessionidt s
, tunnelidt t
, const char *title
, const char *data
, int maxsize
)
204 unsigned const char *d
= (unsigned const char *)data
;
206 if (config
->debug
< level
) return;
208 // No support for log_hex to syslog
211 log(level
, address
, s
, t
, "%s (%d bytes):\n", title
, maxsize
);
212 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
214 for (i
= 0; i
< maxsize
; )
216 fprintf(log_stream
, "%4X: ", i
);
217 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
219 fprintf(log_stream
, "%02X ", d
[j
]);
221 fputs(": ", log_stream
);
224 for (; j
< i
+ 16; j
++)
226 fputs(" ", log_stream
);
228 fputs(": ", log_stream
);
231 fputs(" ", log_stream
);
232 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
234 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
235 fputc(d
[j
], log_stream
);
237 fputc('.', log_stream
);
240 fputs(" ", log_stream
);
244 fputs("\n", log_stream
);
248 setbuf(log_stream
, NULL
);
254 void routeset(ipt ip
, ipt mask
, ipt gw
, u8 add
)
257 memset(&r
, 0, sizeof(r
));
258 r
.rt_dev
= config
->tapdevice
;
259 r
.rt_dst
.sa_family
= AF_INET
;
260 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
261 r
.rt_gateway
.sa_family
= AF_INET
;
262 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
263 r
.rt_genmask
.sa_family
= AF_INET
;
264 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
? mask
: 0xFFFFFFF);
265 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
267 r
.rt_flags
|= RTF_GATEWAY
;
269 r
.rt_flags
|= RTF_HOST
;
270 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0) perror("routeset");
271 log(1, ip
, 0, 0, "Route %s %u.%u.%u.%u/%u.%u.%u.%u %u.%u.%u.%u\n", add
? "Add" : "Del", ip
>> 24, ip
>> 16 & 255, ip
>> 8 & 255, ip
& 255, mask
>> 24, mask
>> 16 & 255, mask
>> 8 & 255, mask
& 255, gw
>> 24, gw
>> 16 & 255, gw
>> 8 & 255, gw
& 255);
274 // Set up TAP interface
278 struct sockaddr_in sin
= {0};
279 memset(&ifr
, 0, sizeof(ifr
));
280 ifr
.ifr_flags
= IFF_TUN
;
282 tapfd
= open(TAPDEVICE
, O_RDWR
);
285 log(0, 0, 0, 0, "Can't open %s: %s\n", TAPDEVICE
, strerror(errno
));
288 if (ioctl(tapfd
, TUNSETIFF
, (void *) &ifr
) < 0)
290 log(0, 0, 0, 0, "Can't set tap interface: %s\n", strerror(errno
));
293 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tapdevice
));
294 strncpy(config
->tapdevice
, ifr
.ifr_name
, sizeof(config
->tapdevice
) - 1);
295 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
297 sin
.sin_family
= AF_INET
;
298 sin
.sin_addr
.s_addr
= handle_interface
? config
->bind_address
: 0x01010101; // 1.1.1.1
299 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
301 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
303 perror("set tap addr");
306 ifr
.ifr_flags
= IFF_UP
;
307 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
309 perror("set tap flags");
312 if (ioctl(ifrfd
, SIOCGIFHWADDR
, (void *) &ifr
) < 0)
314 perror("get tap hwaddr");
317 memcpy(&tapmac
, 2 + (u8
*) & ifr
.ifr_hwaddr
, 6);
318 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
320 perror("get tap ifindex");
323 tapidx
= ifr
.ifr_ifindex
;
330 struct sockaddr_in addr
;
333 memset(&addr
, 0, sizeof(addr
));
334 addr
.sin_family
= AF_INET
;
335 addr
.sin_port
= htons(L2TPPORT
);
336 addr
.sin_addr
.s_addr
= config
->bind_address
;
337 udpfd
= socket(AF_INET
, SOCK_DGRAM
, UDP
);
338 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
339 if (bind(udpfd
, (void *) &addr
, sizeof(addr
)) < 0)
344 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, UDP
);
347 memset(&addr
, 0, sizeof(addr
));
348 addr
.sin_family
= AF_INET
;
349 addr
.sin_port
= htons(1702);
350 controlfd
= socket(AF_INET
, SOCK_DGRAM
, 17);
351 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
352 if (bind(controlfd
, (void *) &addr
, sizeof(addr
)) < 0)
359 // Find session by IP, 0 for not found
360 sessionidt
sessionbyip(ipt ip
)
362 unsigned char *a
= (unsigned char *)&ip
;
363 char **d
= (char **) ip_hash
;
366 STAT(call_sessionbyip
);
369 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
370 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
371 if (!(d
= (char **) d
[(size_t) *a
++])) return 0;
373 return (ipt
) d
[(size_t) *a
];
376 void cache_sessionid(ipt ip
, sessionidt s
)
378 unsigned char *a
= (unsigned char *) &ip
;
379 char **d
= (char **) ip_hash
;
382 for (i
= 0; i
< 3; i
++)
384 if (!d
[(size_t) a
[i
]])
386 if (!(d
[(size_t) a
[i
]] = calloc(256, sizeof (void *))))
390 d
= (char **) d
[(size_t) a
[i
]];
393 log(4, ip
, s
, session
[s
].tunnel
, "Caching session ID %d for ip address\n", s
);
394 d
[(size_t) a
[3]] = (char *)((int)s
);
397 void uncache_sessionid(ipt ip
)
399 unsigned char *a
= (unsigned char *) &ip
;
400 char **d
= (char **) ip_hash
;
403 for (i
= 0; i
< 3; i
++)
405 if (!d
[(size_t) a
[i
]]) return;
406 d
= (char **) d
[(size_t) a
[i
]];
408 d
[(size_t) a
[3]] = NULL
;
411 // Find session by username, 0 for not found
412 // walled garden users aren't authenticated, so the username is
413 // reasonably useless. Ignore them to avoid incorrect actions
414 sessionidt
sessionbyuser(char *username
)
418 STAT(call_sessionbyuser
);
420 for (s
= 1; s
< MAXSESSION
&& (session
[s
].walled_garden
|| strncmp(session
[s
].user
, username
, 128)); s
++);
426 void send_garp(ipt ip
)
430 unsigned char mac
[6];
432 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
438 memset(&ifr
, 0, sizeof(ifr
));
439 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
440 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
442 perror("get eth0 hwaddr");
445 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
446 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
448 perror("get eth0 ifindex");
452 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
455 // Find session by username, 0 for not found
456 sessiont
*sessiontbysessionidt(sessionidt s
)
458 if (!s
|| s
> MAXSESSION
) return NULL
;
462 sessionidt
sessionidtbysessiont(sessiont
*s
)
464 sessionidt val
= s
-session
;
465 if (s
< session
|| val
> MAXSESSION
) return 0;
469 // send gratuitous ARP to set ARP table for newly allocated IP
470 void sessionsendarp(sessionidt s
)
472 unsigned char mac
[6];
476 *(u16
*) (mac
+ 0) = htons(tapmac
[0]); // set source address
477 *(u16
*) (mac
+ 2) = htons(tapmac
[1]);
478 *(u16
*) (mac
+ 4) = htons(tapmac
[2]);
479 sendarp(tapidx
, mac
, session
[s
].ip
);
483 // Handle ARP requests
484 void processarp(u8
* buf
, int len
)
490 STAT(call_processarp
);
495 log(0, 0, 0, 0, "Unexpected length ARP %d bytes\n", len
);
499 if (*(u16
*) (buf
+ 16) != htons(PKTARP
))
501 log(0, 0, 0, 0, "Unexpected ARP type %04X\n", ntohs(*(u16
*) (buf
+ 16)));
505 if (*(u16
*) (buf
+ 18) != htons(0x0001))
507 log(0, 0, 0, 0, "Unexpected ARP hard type %04X\n", ntohs(*(u16
*) (buf
+ 18)));
511 if (*(u16
*) (buf
+ 20) != htons(PKTIP
))
513 log(0, 0, 0, 0, "Unexpected ARP prot type %04X\n", ntohs(*(u16
*) (buf
+ 20)));
519 log(0, 0, 0, 0, "Unexpected ARP hard len %d\n", buf
[22]);
525 log(0, 0, 0, 0, "Unexpected ARP prot len %d\n", buf
[23]);
529 if (*(u16
*) (buf
+ 24) != htons(0x0001))
531 log(0, 0, 0, 0, "Unexpected ARP op %04X\n", ntohs(*(u16
*) (buf
+ 24)));
535 ip
= ntohl(*(u32
*) (buf
+ 42));
537 s
= sessionbyip(htonl(ip
));
540 log(3, ip
, s
, session
[s
].tunnel
, "ARP reply for %u.%u.%u.%u\n", ip
>> 24, ip
>> 16 & 255, ip
>> 8 & 255, ip
& 255, session
[s
].tunnel
, s
);
541 memcpy(buf
+ 4, buf
+ 10, 6); // set destination as source
542 *(u16
*) (buf
+ 10) = htons(tapmac
[0]); // set soucre address
543 *(u16
*) (buf
+ 12) = htons(tapmac
[1]);
544 *(u16
*) (buf
+ 14) = htons(tapmac
[2]);
545 *(u16
*) (buf
+ 24) = htons(0x0002); // ARP reply
546 memcpy(buf
+ 26, buf
+ 10, 6); // sender ethernet
547 memcpy(buf
+ 36, buf
+ 4, 6); // target ethernet
548 *(u32
*) (buf
+ 42) = *(u32
*) (buf
+ 32); // target IP
549 *(u32
*) (buf
+ 32) = htonl(ip
); // sender IP
550 write(tapfd
, buf
, len
);
555 log(3, ip
, 0, 0, "ARP request for unknown IP %u.%u.%u.%u\n", ip
>> 24, ip
>> 16 & 255, ip
>> 8 & 255, ip
& 255);
560 // actually send a control message for a specific tunnel
561 void tunnelsend(u8
* buf
, u16 l
, tunnelidt t
)
563 struct sockaddr_in addr
;
566 STAT(call_tunnelsend
);
570 log(1, 0, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
571 STAT(tunnel_tx_errors
);
574 memset(&addr
, 0, sizeof(addr
));
575 addr
.sin_family
= AF_INET
;
576 *(u32
*) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
577 addr
.sin_port
= htons(tunnel
[t
].port
);
579 // sequence expected, if sequence in message
580 if (*buf
& 0x08) *(u16
*) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
582 // If this is a control message, deal with retries
585 tunnel
[t
].last
= time_now
; // control message sent
586 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
587 if (tunnel
[t
].try > 1)
589 STAT(tunnel_retries
);
590 log(3, tunnel
[t
].ip
, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
594 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
596 log(0, tunnel
[t
].ip
, ntohs((*(u16
*) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
597 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
598 STAT(tunnel_tx_errors
);
602 log_hex(5, "Send Tunnel Data", buf
, l
);
603 STAT(tunnel_tx_packets
);
604 INC_STAT(tunnel_tx_bytes
, l
);
607 // process outgoing (to tunnel) IP
608 void processipout(u8
* buf
, int len
)
616 STAT(call_processipout
);
620 log(1, 0, 0, 0, "Short IP, %d bytes\n", len
);
621 STAT(tunnel_tx_errors
);
625 // Skip the tun header
629 // Got an IP header now
630 if (*(u8
*)(buf
) >> 4 != 4)
632 log(1, 0, 0, 0, "IP: Don't understand anything except IPv4\n");
636 ip
= *(u32
*)(buf
+ 16);
637 if (!(s
= sessionbyip(ip
)))
639 log(4, 0, 0, 0, "IP: Sending ICMP host unreachable to %s\n", inet_toa(*(u32
*)(buf
+ 12)));
640 host_unreachable(*(u32
*)(buf
+ 12), *(u16
*)(buf
+ 4), ip
, buf
, (len
< 64) ? 64 : len
);
643 t
= session
[s
].tunnel
;
646 // Snooping this session, send it to ASIO
647 if (sp
->snoop
) snoop_send_packet(buf
, len
);
649 log(5, session
[s
].ip
, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
653 struct param_packet_rx packet
= { &tunnel
[t
], &session
[s
], buf
, len
};
654 run_plugins(PLUGIN_PACKET_RX
, &packet
);
657 // Add on L2TP header
659 u8
*p
= makeppp(b
, buf
, len
, t
, s
, PPPIP
);
660 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
661 sp
->cout
+= len
; // byte count
662 sp
->total_cout
+= len
; // byte count
668 // add an AVP (16 bit)
669 void control16(controlt
* c
, u16 avp
, u16 val
, u8 m
)
671 u16 l
= (m
? 0x8008 : 0x0008);
672 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
673 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
674 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
675 *(u16
*) (c
->buf
+ c
->length
+ 6) = htons(val
);
679 // add an AVP (32 bit)
680 void control32(controlt
* c
, u16 avp
, u32 val
, u8 m
)
682 u16 l
= (m
? 0x800A : 0x000A);
683 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
684 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
685 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
686 *(u32
*) (c
->buf
+ c
->length
+ 6) = htonl(val
);
690 // add an AVP (32 bit)
691 void controls(controlt
* c
, u16 avp
, char *val
, u8 m
)
693 u16 l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
694 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
695 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
696 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
697 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
698 c
->length
+= 6 + strlen(val
);
702 void controlb(controlt
* c
, u16 avp
, char *val
, unsigned int len
, u8 m
)
704 u16 l
= ((m
? 0x8000 : 0) + len
+ 6);
705 *(u16
*) (c
->buf
+ c
->length
+ 0) = htons(l
);
706 *(u16
*) (c
->buf
+ c
->length
+ 2) = htons(0);
707 *(u16
*) (c
->buf
+ c
->length
+ 4) = htons(avp
);
708 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
709 c
->length
+= 6 + len
;
712 // new control connection
713 controlt
*controlnew(u16 mtype
)
717 c
= malloc(sizeof(controlt
));
721 controlfree
= c
->next
;
725 *(u16
*) (c
->buf
+ 0) = htons(0xC802); // flags/ver
727 control16(c
, 0, mtype
, 1);
731 // send zero block if nothing is waiting
732 void controlnull(tunnelidt t
)
735 if (tunnel
[t
].controlc
)
737 *(u16
*) (buf
+ 0) = htons(0xC802); // flags/ver
738 *(u16
*) (buf
+ 2) = htons(12); // length
739 *(u16
*) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
740 *(u16
*) (buf
+ 6) = htons(0); // session
741 *(u16
*) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
742 *(u16
*) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
743 tunnelsend(buf
, 12, t
);
746 // add a control message to a tunnel, and send if within window
747 void controladd(controlt
* c
, tunnelidt t
, sessionidt s
)
749 *(u16
*) (c
->buf
+ 2) = htons(c
->length
); // length
750 *(u16
*) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
751 *(u16
*) (c
->buf
+ 6) = htons(s
? session
[s
].far
: 0); // session
752 *(u16
*) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
753 tunnel
[t
].ns
++; // advance sequence
754 // link in message in to queue
755 if (tunnel
[t
].controlc
)
756 tunnel
[t
].controle
->next
= c
;
758 tunnel
[t
].controls
= c
;
759 tunnel
[t
].controle
= c
;
760 tunnel
[t
].controlc
++;
761 // send now if space in window
762 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
764 tunnel
[t
].try = 0; // first send
765 tunnelsend(c
->buf
, c
->length
, t
);
769 // start tidy shutdown of session
770 void sessionshutdown(sessionidt s
, char *reason
)
772 int dead
= session
[s
].die
;
773 int walled_garden
= session
[s
].walled_garden
;
776 STAT(call_sessionshutdown
);
778 if (!session
[s
].tunnel
)
779 return; // not a live session
782 log(2, 0, s
, session
[s
].tunnel
, "Shutting down session %d: %s\n", s
, reason
);
784 session
[s
].die
= now() + 150; // Clean up in 15 seconds
787 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
788 run_plugins(PLUGIN_KILL_SESSION
, &data
);
791 // RADIUS Stop message
792 if (session
[s
].opened
&& !walled_garden
&& !dead
) {
793 u8 r
= session
[s
].radius
;
796 if (!(r
= radiusnew(s
)))
798 log(1, 0, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
799 STAT(radius_overflow
);
804 for (n
= 0; n
< 15; n
++)
805 radius
[r
].auth
[n
] = rand();
808 if (r
&& radius
[r
].state
!= RADIUSSTOP
)
809 radiussend(r
, RADIUSSTOP
); // stop, if not already trying
813 { // IP allocated, clear and unroute
815 if (session
[s
].route
[0].ip
)
817 routeset(session
[s
].ip
, 0, 0, 0);
818 for (r
= 0; r
< MAXROUTE
; r
++)
820 if (session
[s
].route
[r
].ip
)
822 routeset(session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, session
[s
].ip
, 0);
823 session
[s
].route
[r
].ip
= 0;
827 if (session
[s
].throttle
) throttle_session(s
, 0); session
[s
].throttle
= 0;
831 controlt
*c
= controlnew(14); // sending CDN
832 control16(c
, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
833 control16(c
, 14, s
, 1); // assigned session (our end)
834 controladd(c
, session
[s
].tunnel
, s
); // send the message
836 cluster_send_session(s
);
839 void sendipcp(tunnelidt t
, sessionidt s
)
842 u8 r
= session
[s
].radius
;
849 if (radius
[r
].state
!= RADIUSIPCP
)
851 radius
[r
].state
= RADIUSIPCP
;
854 radius
[r
].retry
= backoff(radius
[r
].try++);
855 if (radius
[r
].try > 10)
857 sessionshutdown(s
, "No reply on IPCP");
860 q
= makeppp(buf
, 0, 0, t
, s
, PPPIPCP
);
862 q
[1] = r
; // ID, dont care, we only send one type of request
863 *(u16
*) (q
+ 2) = htons(10);
866 *(u32
*) (q
+ 6) = htonl(myip
? myip
: session
[s
].ip
); // send my IP (use theirs if I dont have one)
867 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
870 // kill a session now
871 void sessionkill(sessionidt s
, char *reason
)
874 STAT(call_sessionkill
);
876 sessionshutdown(s
, reason
); // close radius/routes, etc.
877 if (session
[s
].radius
)
878 radiusclear(session
[s
].radius
, 0); // cant send clean accounting data, session is killed
879 memset(&session
[s
], 0, sizeof(session
[s
]));
880 session
[s
].next
= sessionfree
;
882 log(2, 0, s
, session
[s
].tunnel
, "Kill session %d: %s\n", s
, reason
);
883 cluster_send_session(s
);
887 void tunnelkill(tunnelidt t
, char *reason
)
892 STAT(call_tunnelkill
);
895 tunnel
[t
].state
= TUNNELDIE
;
897 // free control messages
898 while ((c
= tunnel
[t
].controls
))
900 controlt
* n
= c
->next
;
901 tunnel
[t
].controls
= n
;
902 tunnel
[t
].controlc
--;
903 c
->next
= controlfree
;
907 for (s
= 1; s
< MAXSESSION
; s
++)
908 if (session
[s
].tunnel
== t
)
909 sessionkill(s
, reason
);
913 cluster_send_tunnel(t
);
914 log(1, 0, 0, t
, "Kill tunnel %d: %s\n", t
, reason
);
916 tunnel
[t
].state
= TUNNELFREE
;
919 // shut down a tunnel cleanly
920 void tunnelshutdown(tunnelidt t
, char *reason
)
924 STAT(call_tunnelshutdown
);
926 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
928 // never set up, can immediately kill
929 tunnelkill(t
, reason
);
932 log(1, 0, 0, t
, "Shutting down tunnel %d (%s)\n", t
, reason
);
935 for (s
= 1; s
< MAXSESSION
; s
++)
936 if (session
[s
].tunnel
== t
)
937 sessionkill(s
, reason
);
939 tunnel
[t
].state
= TUNNELDIE
;
940 tunnel
[t
].die
= now() + 700; // Clean up in 70 seconds
941 cluster_send_tunnel(t
);
942 // TBA - should we wait for sessions to stop?
944 controlt
*c
= controlnew(4); // sending StopCCN
945 control16(c
, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message
946 control16(c
, 9, t
, 1); // assigned tunnel (our end)
947 controladd(c
, t
, 0); // send the message
951 // read and process packet on tunnel (UDP)
952 void processudp(u8
* buf
, int len
, struct sockaddr_in
*addr
)
954 char *chapresponse
= NULL
;
955 u16 l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
959 STAT(call_processudp
);
963 log_hex(5, "UDP Data", buf
, len
);
964 STAT(tunnel_rx_packets
);
965 INC_STAT(tunnel_rx_bytes
, len
);
968 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Short UDP, %d bytes\n", len
);
969 STAT(tunnel_rx_errors
);
972 if ((buf
[1] & 0x0F) != 2)
974 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Bad L2TP ver %d\n", (buf
[1] & 0x0F) != 2);
975 STAT(tunnel_rx_errors
);
980 l
= ntohs(*(u16
*) p
);
983 t
= ntohs(*(u16
*) p
);
985 s
= ntohs(*(u16
*) p
);
989 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid session ID\n");
990 STAT(tunnel_rx_errors
);
995 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Received UDP packet with invalid tunnel ID\n");
996 STAT(tunnel_rx_errors
);
999 if (s
&& !session
[s
].tunnel
)
1001 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "UDP packet contains session %d but no session[%d].tunnel exists (LAC said tunnel = %d). Dropping packet.\n", s
, s
, t
);
1002 STAT(tunnel_rx_errors
);
1007 ns
= ntohs(*(u16
*) p
);
1009 nr
= ntohs(*(u16
*) p
);
1014 u16 o
= ntohs(*(u16
*) p
);
1019 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad length %d>%d\n", (p
- buf
), l
);
1020 STAT(tunnel_rx_errors
);
1026 u16 message
= 0xFFFF; // message type
1028 u8 mandatorymessage
= 0;
1029 u8 chap
= 0; // if CHAP being used
1030 u16 asession
= 0; // assigned session
1031 u32 amagic
= 0; // magic number
1032 u8 aflags
= 0; // flags from last LCF
1033 u16 version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1034 int requestchap
= 0; // do we request PAP instead of original CHAP request?
1035 char called
[MAXTEL
] = ""; // called number
1036 char calling
[MAXTEL
] = ""; // calling number
1037 if ((*buf
& 0xCA) != 0xC8)
1039 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Bad control header %02X\n", *buf
);
1040 STAT(tunnel_rx_errors
);
1043 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Control message (%d bytes): %d ns %d nr %d ns %d nr %d\n",
1044 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
1045 // if no tunnel specified, assign one
1048 if (!(t
= new_tunnel()))
1050 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "No more tunnels\n");
1051 STAT(tunnel_overflow
);
1055 tunnel
[t
].ip
= ntohl(*(ipt
*) & addr
->sin_addr
);
1056 tunnel
[t
].port
= ntohs(addr
->sin_port
);
1057 tunnel
[t
].window
= 4; // default window
1058 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, t
, " New tunnel from %u.%u.%u.%u/%u ID %d\n", tunnel
[t
].ip
>> 24, tunnel
[t
].ip
>> 16 & 255, tunnel
[t
].ip
>> 8 & 255, tunnel
[t
].ip
& 255, tunnel
[t
].port
, t
);
1059 STAT(tunnel_created
);
1062 // This is used to time out old tunnels
1063 tunnel
[t
].lastrec
= time_now
;
1065 // check sequence of this message
1067 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
1068 if (tunnel
[t
].controlc
)
1069 { // some to clear maybe
1070 while (tunnel
[t
].controlc
&& (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
1072 controlt
*c
= tunnel
[t
].controls
;
1073 tunnel
[t
].controls
= c
->next
;
1074 tunnel
[t
].controlc
--;
1075 c
->next
= controlfree
;
1078 tunnel
[t
].try = 0; // we have progress
1081 if (tunnel
[t
].nr
< ns
&& tunnel
[t
].nr
!= 0)
1083 // is this the sequence we were expecting?
1084 log(1, ntohl(addr
->sin_addr
.s_addr
), 0, t
, " Out of sequence tunnel %d, (%d not %d)\n", t
, ns
, tunnel
[t
].nr
);
1085 STAT(tunnel_rx_errors
);
1089 // receiver advance (do here so quoted correctly in any sends below)
1090 if (l
) tunnel
[t
].nr
++;
1091 if (skip
< 0) skip
= 0;
1092 if (skip
< tunnel
[t
].controlc
)
1094 // some control packets can now be sent that were previous stuck out of window
1095 int tosend
= tunnel
[t
].window
- skip
;
1096 controlt
*c
= tunnel
[t
].controls
;
1104 tunnel
[t
].try = 0; // first send
1105 tunnelsend(c
->buf
, c
->length
, t
);
1110 if (!tunnel
[t
].controlc
)
1111 tunnel
[t
].retry
= 0; // caught up
1114 { // if not a null message
1116 while (l
&& !(fatal
& 0x80))
1118 u16 n
= (ntohs(*(u16
*) p
) & 0x3FF);
1125 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Invalid length in AVP\n");
1126 STAT(tunnel_rx_errors
);
1133 // handle hidden AVPs
1134 if (!*config
->l2tpsecret
)
1136 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
1140 if (!session
[s
].random_vector_length
)
1142 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP requested, but no random vector.\n");
1146 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Hidden AVP\n");
1150 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unrecognised AVP flags %02X\n", *b
);
1157 log(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown AVP vendor %d\n", ntohs(*(u16
*) (b
)));
1162 mtype
= ntohs(*(u16
*) (b
));
1166 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " AVP %d (%s) len %d\n", mtype
, avpnames
[mtype
], n
);
1169 case 0: // message type
1170 message
= ntohs(*(u16
*) b
);
1171 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Message type = %d (%s)\n", *b
,
1172 l2tp_message_types
[message
]);
1173 mandatorymessage
= flags
;
1175 case 1: // result code
1177 u16 rescode
= ntohs(*(u16
*)(b
));
1178 const char* resdesc
= "(unknown)";
1179 if (message
== 4) { /* StopCCN */
1180 if (rescode
<= MAX_STOPCCN_RESULT_CODE
)
1181 resdesc
= stopccn_result_codes
[rescode
];
1182 } else if (message
== 14) { /* CDN */
1183 if (rescode
<= MAX_CDN_RESULT_CODE
)
1184 resdesc
= cdn_result_codes
[rescode
];
1187 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Result Code %d: %s\n",
1190 u16 errcode
= ntohs(*(u16
*)(b
+ 2));
1191 const char* errdesc
= "(unknown)";
1192 if (errcode
<= MAX_ERROR_CODE
)
1193 errdesc
= error_codes
[errcode
];
1194 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error Code %d: %s\n",
1198 /* %*s doesn't work?? */
1199 char *buf
= (char *)strndup(b
+4, n
-4);
1200 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Error String: %s\n",
1207 case 2: // protocol version
1209 version
= ntohs(*(u16
*) (b
));
1210 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Protocol version = %d\n", version
);
1211 if (version
&& version
!= 0x0100)
1212 { // allow 0.0 and 1.0
1213 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Bad protocol version %04X\n",
1220 case 3: // framing capabilities
1221 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Framing capabilities\n");
1223 case 4: // bearer capabilities
1224 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Bearer capabilities\n");
1226 case 5: // tie breaker
1227 // We never open tunnels, so we don't care about tie breakers
1228 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Tie breaker\n");
1230 case 6: // firmware revision
1231 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Firmware revision\n");
1233 case 7: // host name
1234 memset(tunnel
[t
].hostname
, 0, 128);
1235 memcpy(tunnel
[t
].hostname
, b
, (n
>= 127) ? 127 : n
);
1236 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
1237 // TBA - to send to RADIUS
1239 case 8: // vendor name
1240 memset(tunnel
[t
].vendor
, 0, 128);
1241 memcpy(tunnel
[t
].vendor
, b
, (n
>= 127) ? 127 : n
);
1242 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
1244 case 9: // assigned tunnel
1245 tunnel
[t
].far
= ntohs(*(u16
*) (b
));
1246 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Remote tunnel id = %d\n", tunnel
[t
].far
);
1248 case 10: // rx window
1249 tunnel
[t
].window
= ntohs(*(u16
*) (b
));
1250 if (!tunnel
[t
].window
)
1251 tunnel
[t
].window
= 1; // window of 0 is silly
1252 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " rx window = %d\n", tunnel
[t
].window
);
1254 case 11: // Challenge
1256 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " LAC requested CHAP authentication for tunnel\n");
1257 build_chap_response(b
, 2, n
, &chapresponse
);
1260 case 14: // assigned session
1261 asession
= session
[s
].far
= ntohs(*(u16
*) (b
));
1262 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " assigned session = %d\n", asession
);
1264 case 15: // call serial number
1265 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " call serial number = %d\n", ntohl(*(u32
*)b
));
1267 case 18: // bearer type
1268 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " bearer type = %d\n", ntohl(*(u32
*)b
));
1271 case 19: // framing type
1272 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " framing type = %d\n", ntohl(*(u32
*)b
));
1275 case 21: // called number
1276 memset(called
, 0, MAXTEL
);
1277 memcpy(called
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1278 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Called <%s>\n", called
);
1280 case 22: // calling number
1281 memset(calling
, 0, MAXTEL
);
1282 memcpy(calling
, b
, (n
>= MAXTEL
) ? (MAXTEL
-1) : n
);
1283 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Calling <%s>\n", calling
);
1285 case 24: // tx connect speed
1288 session
[s
].tx_connect_speed
= ntohl(*(u32
*)b
);
1292 // AS5300s send connect speed as a string
1294 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1295 session
[s
].tx_connect_speed
= atol(tmp
);
1297 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " TX connect speed <%d>\n",
1298 session
[s
].tx_connect_speed
);
1300 case 38: // rx connect speed
1303 session
[s
].rx_connect_speed
= ntohl(*(u32
*)b
);
1307 // AS5300s send connect speed as a string
1309 memcpy(tmp
, b
, (n
>= 30) ? 30 : n
);
1310 session
[s
].rx_connect_speed
= atol(tmp
);
1312 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " RX connect speed <%d>\n",
1313 session
[s
].rx_connect_speed
);
1315 case 25: // Physical Channel ID
1317 u32 tmp
= ntohl(*(u32
*)b
);
1318 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Physical Channel ID <%X>\n", tmp
);
1321 case 29: // Proxy Authentication Type
1323 u16 authtype
= ntohs(*(u16
*)b
);
1324 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Type %d (%s)\n",
1325 authtype
, authtypes
[authtype
]);
1326 requestchap
= (authtype
== 2);
1329 case 30: // Proxy Authentication Name
1331 char authname
[64] = {0};
1332 memcpy(authname
, b
, (n
> 63) ? 63 : n
);
1333 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Name (%s)\n",
1337 case 31: // Proxy Authentication Challenge
1339 memcpy(radius
[session
[s
].radius
].auth
, b
, 16);
1340 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Challenge (%X)\n", radius
[session
[s
].radius
].auth
);
1343 case 32: // Proxy Authentication ID
1345 u16 authid
= ntohs(*(u16
*)(b
));
1346 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth ID (%d)\n",
1348 if (session
[s
].radius
)
1349 radius
[session
[s
].radius
].id
= authid
;
1352 case 33: // Proxy Authentication Response
1354 char authresp
[64] = {0};
1355 memcpy(authresp
, b
, (n
> 63) ? 63 : n
);
1356 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Proxy Auth Response\n");
1359 case 27: // last send lcp
1360 { // find magic number
1361 u8
*p
= b
, *e
= p
+ n
;
1362 while (p
< e
&& p
[1])
1364 if (*p
== 5 && p
[1] == 6)
1365 amagic
= ntohl(*(u32
*) (p
+ 2));
1366 else if (*p
== 3 && p
[1] == 5 && *(u16
*) (p
+ 2) == htons(PPPCHAP
) && p
[4] == 5)
1369 aflags
|= SESSIONPFC
;
1371 aflags
|= SESSIONACFC
;
1376 char tmp
[500] = {0};
1378 memcpy((tmp
+ 1), b
, n
);
1382 case 28: // last recv lcp confreq
1384 char tmp
[500] = {0};
1386 memcpy((tmp
+ 1), b
, n
);
1389 case 26: // Initial Received LCP CONFREQ
1391 char tmp
[500] = {0};
1393 memcpy((tmp
+ 1), b
, n
);
1396 case 39: // seq required - we control it as an LNS anyway...
1398 case 36: // Random Vector
1399 log(4, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
1400 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
1401 memcpy(session
[s
].random_vector
, b
, n
);
1402 session
[s
].random_vector_length
= n
;
1405 log(2, ntohl(addr
->sin_addr
.s_addr
), s
, t
, " Unknown AVP type %d\n", mtype
);
1412 tunnelshutdown(t
, "Unknown Mandatory AVP");
1416 case 1: // SCCRQ - Start Control Connection Request
1418 controlt
*c
= controlnew(2); // sending SCCRP
1419 control16(c
, 2, version
, 1); // protocol version
1420 control32(c
, 3, 3, 1); // framing
1421 controls(c
, 7, tunnel
[t
].hostname
, 1); // host name (TBA)
1422 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
1423 control16(c
, 9, t
, 1); // assigned tunnel
1424 controladd(c
, t
, s
); // send the resply
1426 tunnel
[t
].state
= TUNNELOPENING
;
1429 tunnel
[t
].state
= TUNNELOPEN
;
1432 tunnel
[t
].state
= TUNNELOPEN
;
1433 controlnull(t
); // ack
1436 controlnull(t
); // ack
1437 tunnelshutdown(t
, "Stopped"); // Shut down cleanly
1438 tunnelkill(t
, "Stopped"); // Immediately force everything dead
1441 controlnull(t
); // simply ACK
1455 STAT(session_overflow
);
1456 tunnelshutdown(t
, "No free sessions");
1464 sessionfree
= session
[s
].next
;
1465 memset(&session
[s
], 0, sizeof(session
[s
]));
1467 // make a RADIUS session
1468 if (!(r
= radiusnew(s
)))
1470 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "No free RADIUS sessions for ICRQ\n");
1471 sessionkill(s
, "no free RADIUS sesions");
1475 c
= controlnew(11); // sending ICRP
1476 session
[s
].id
= sessionid
++;
1477 session
[s
].opened
= time(NULL
);
1478 session
[s
].tunnel
= t
;
1479 session
[s
].far
= asession
;
1480 session
[s
].last_packet
= time_now
;
1481 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "New session (%d/%d)\n", tunnel
[t
].far
, session
[s
].far
);
1482 control16(c
, 14, s
, 1); // assigned session
1483 controladd(c
, t
, s
); // send the reply
1485 // Generate a random challenge
1487 for (n
= 0; n
< 15; n
++)
1488 radius
[r
].auth
[n
] = rand();
1490 strncpy(radius
[r
].calling
, calling
, sizeof(radius
[r
].calling
) - 1);
1491 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
1492 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
1493 STAT(session_created
);
1500 session
[s
].magic
= amagic
; // set magic number
1501 session
[s
].flags
= aflags
; // set flags received
1502 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Magic %X Flags %X\n", amagic
, aflags
);
1503 controlnull(t
); // ack
1504 // In CHAP state, request PAP instead
1509 controlnull(t
); // ack
1510 sessionshutdown(s
, "Closed (Received CDN)");
1513 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Missing message type\n");
1516 STAT(tunnel_rx_errors
);
1517 if (mandatorymessage
& 0x80)
1518 tunnelshutdown(t
, "Unknown message");
1520 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown message type %d\n", message
);
1523 if (chapresponse
) free(chapresponse
);
1524 cluster_send_tunnel(t
);
1528 log(4, 0, s
, t
, " Got a ZLB ack\n");
1535 log_hex(5, "Receive Tunnel Data", p
, l
);
1538 log(3, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Session %d is closing. Don't process PPP packets\n", s
);
1539 return; // closing session, PPP not processed
1541 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
1542 { // HDLC address header, discard
1548 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Short ppp length %d\n", l
);
1549 STAT(tunnel_rx_errors
);
1559 prot
= ntohs(*(u16
*) p
);
1565 session
[s
].last_packet
= time_now
;
1566 processpap(t
, s
, p
, l
);
1568 else if (prot
== PPPCHAP
)
1570 session
[s
].last_packet
= time_now
;
1571 processchap(t
, s
, p
, l
);
1573 else if (prot
== PPPLCP
)
1575 session
[s
].last_packet
= time_now
;
1576 processlcp(t
, s
, p
, l
);
1578 else if (prot
== PPPIPCP
)
1580 session
[s
].last_packet
= time_now
;
1581 processipcp(t
, s
, p
, l
);
1583 else if (prot
== PPPCCP
)
1585 session
[s
].last_packet
= time_now
;
1586 processccp(t
, s
, p
, l
);
1588 else if (prot
== PPPIP
)
1590 session
[s
].last_packet
= time_now
;
1591 processipin(t
, s
, p
, l
);
1595 STAT(tunnel_rx_errors
);
1596 log(1, ntohl(addr
->sin_addr
.s_addr
), s
, t
, "Unknown PPP protocol %04X\n", prot
);
1601 // read and process packet on tap
1602 void processtap(u8
* buf
, int len
)
1604 log_hex(5, "Receive TAP Data", buf
, len
);
1605 STAT(tap_rx_packets
);
1606 INC_STAT(tap_rx_bytes
, len
);
1608 STAT(call_processtap
);
1614 log(1, 0, 0, 0, "Short tap packet %d bytes\n", len
);
1615 STAT(tap_rx_errors
);
1618 if (*(u16
*) (buf
+ 2) == htons(PKTARP
)) // ARP
1619 processarp(buf
, len
);
1620 else if (*(u16
*) (buf
+ 2) == htons(PKTIP
)) // ARP
1621 processipout(buf
, len
);
1624 log(1, 0, 0, 0, "Unexpected tap packet %04X, %d bytes\n", ntohs(*(u16
*) (buf
+ 2)), len
);
1628 // main loop - gets packets on tap or udp and processes them
1635 clockt slow
= now(); // occasional functions like session/tunnel expiry, tunnel hello, etc
1636 clockt next_acct
= slow
+ ACCT_TIME
;
1637 clockt next_cluster_ping
= slow
+ 50;
1640 log(4, 0, 0, 0, "Beginning of main loop. udpfd=%d, tapfd=%d, radfd=%d, cluster_sockfd=%d, controlfd=%d\n",
1641 udpfd
, tapfd
, radfd
, cluster_sockfd
, controlfd
);
1647 FD_SET(controlfd
, &cr
);
1649 if (cluster_sockfd
) FD_SET(cluster_sockfd
, &cr
);
1651 if (cn
< radfd
) cn
= radfd
;
1652 if (cn
< tapfd
) cn
= tapfd
;
1653 if (cn
< controlfd
) cn
= controlfd
;
1654 if (cn
< clifd
) cn
= clifd
;
1655 if (cn
< cluster_sockfd
) cn
= cluster_sockfd
;
1662 if (config
->reload_config
)
1664 // Update the config state based on config settings
1668 memcpy(&r
, &cr
, sizeof(fd_set
));
1669 n
= select(n
+ 1, &r
, 0, 0, &to
);
1680 struct sockaddr_in addr
;
1681 int alen
= sizeof(addr
);
1682 if (FD_ISSET(udpfd
, &r
))
1683 processudp(buf
, recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
), &addr
);
1684 else if (FD_ISSET(tapfd
, &r
))
1685 processtap(buf
, read(tapfd
, buf
, sizeof(buf
)));
1686 else if (FD_ISSET(radfd
, &r
))
1687 processrad(buf
, recv(radfd
, buf
, sizeof(buf
), 0));
1688 else if (FD_ISSET(cluster_sockfd
, &r
))
1689 processcluster(buf
, recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
));
1690 else if (FD_ISSET(controlfd
, &r
))
1691 processcontrol(buf
, recvfrom(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
), &addr
);
1692 else if (FD_ISSET(clifd
, &r
))
1694 struct sockaddr_in addr
;
1696 int len
= sizeof(addr
);
1698 if ((sockfd
= accept(clifd
, (struct sockaddr
*)&addr
, &len
)) <= 0)
1700 log(0, 0, 0, 0, "accept error: %s\n", strerror(errno
));
1711 log(1, 0, 0, 0, "Main select() loop returned %d, but no fds have data waiting\n", n
);
1715 else if (n
== 0) { // handle timeouts
1716 clockt when
= now();
1717 clockt best
= when
+ 100; // default timeout
1722 for (r
= 1; r
< MAXRADIUS
; r
++)
1723 if (radius
[r
].state
&& radius
[r
].retry
)
1725 if (radius
[r
].retry
<= when
)
1727 if (radius
[r
].retry
&& radius
[r
].retry
< best
)
1728 best
= radius
[r
].retry
;
1730 for (t
= 1; t
< MAXTUNNEL
; t
++)
1732 // check for expired tunnels
1733 if (tunnel
[t
].die
&& tunnel
[t
].die
<= when
)
1735 STAT(tunnel_timeout
);
1736 tunnelkill(t
, "Expired");
1739 // check for message resend
1740 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
1742 // resend pending messages as timeout on reply
1743 if (tunnel
[t
].retry
<= when
)
1745 controlt
*c
= tunnel
[t
].controls
;
1746 u8 w
= tunnel
[t
].window
;
1747 tunnel
[t
].try++; // another try
1748 if (tunnel
[t
].try > 5)
1749 tunnelkill(t
, "Timeout on control message"); // game over
1753 tunnelsend(c
->buf
, c
->length
, t
);
1757 if (tunnel
[t
].retry
&& tunnel
[t
].retry
< best
)
1758 best
= tunnel
[t
].retry
;
1761 if (tunnel
[t
].state
== TUNNELOPEN
&& tunnel
[t
].lastrec
< when
+ 600)
1763 controlt
*c
= controlnew(6); // sending HELLO
1764 controladd(c
, t
, 0); // send the message
1765 log(3, tunnel
[t
].ip
, 0, t
, "Sending HELLO message\n");
1769 // Check for sessions that have been killed from the CLI
1770 if (cli_session_kill
[0])
1773 for (i
= 1; i
< MAXSESSION
&& cli_session_kill
[i
]; i
++)
1775 log(2, 0, cli_session_kill
[i
], 0, "Dropping session by CLI\n");
1776 sessionshutdown(cli_session_kill
[i
], "Requested by administrator");
1777 cli_session_kill
[i
] = 0;
1780 // Check for tunnels that have been killed from the CLI
1781 if (cli_tunnel_kill
[0])
1784 for (i
= 1; i
< MAXTUNNEL
&& cli_tunnel_kill
[i
]; i
++)
1786 log(2, 0, cli_tunnel_kill
[i
], 0, "Dropping tunnel by CLI\n");
1787 tunnelshutdown(cli_tunnel_kill
[i
], "Requested by administrator");
1788 cli_tunnel_kill
[i
] = 0;
1792 for (s
= 1; s
< MAXSESSION
; s
++)
1794 // check for expired sessions
1795 if (session
[s
].die
&& session
[s
].die
<= when
)
1797 sessionkill(s
, "Expired");
1801 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
1802 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
1804 sessionkill(s
, "No response to LCP ECHO requests");
1805 STAT(session_timeout
);
1809 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
1810 if (session
[s
].user
[0] && (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
))
1812 u8 b
[MAXCONTROL
] = {0};
1813 u8
*q
= makeppp(b
, 0, 0, session
[s
].tunnel
, s
, PPPLCP
);
1816 *(u8
*)(q
+ 1) = (time_now
% 255); // ID
1817 *(u16
*)(q
+ 2) = htons(8); // Length
1818 *(u32
*)(q
+ 4) = 0; // Magic Number (not supported)
1820 log(4, session
[s
].ip
, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
1821 time_now
- session
[s
].last_packet
);
1822 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
1826 if (config
->accounting_dir
&& next_acct
<= when
)
1828 // Dump accounting data
1829 next_acct
= when
+ ACCT_TIME
;
1833 if (cluster_sockfd
&& next_cluster_ping
<= when
)
1835 // Dump accounting data
1836 next_cluster_ping
= when
+ 50;
1837 cluster_send_message(config
->cluster_address
, config
->bind_address
, C_PING
, hostname
, strlen(hostname
));
1841 best
= when
+ 1; // should not really happen
1842 to
.tv_sec
= (best
- when
) / 10;
1843 to
.tv_usec
= 100000 * ((best
- when
) % 10);
1844 log(5, 0, 0, 0, "Next time check in %d.%d seconds\n", (best
- when
) / 10, ((best
- when
) % 10));
1849 // Init data structures
1854 _statistics
= mmap(NULL
, sizeof(struct Tstats
), PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1855 if (_statistics
== MAP_FAILED
)
1857 log(0, 0, 0, 0, "Error doing mmap for _statistics: %s\n", strerror(errno
));
1860 config
= mmap(NULL
, sizeof(struct configt
), PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1861 if (config
== MAP_FAILED
)
1863 log(0, 0, 0, 0, "Error doing mmap for configuration: %s\n", strerror(errno
));
1866 memset(config
, 0, sizeof(struct configt
));
1867 time(&config
->start_time
);
1868 strncpy(config
->config_file
, CONFIGFILE
, sizeof(config
->config_file
) - 1);
1869 tunnel
= mmap(NULL
, sizeof(tunnelt
) * MAXTUNNEL
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1870 if (tunnel
== MAP_FAILED
)
1872 log(0, 0, 0, 0, "Error doing mmap for tunnels: %s\n", strerror(errno
));
1875 session
= mmap(NULL
, sizeof(sessiont
) * MAXSESSION
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1876 if (session
== MAP_FAILED
)
1878 log(0, 0, 0, 0, "Error doing mmap for sessions: %s\n", strerror(errno
));
1881 radius
= mmap(NULL
, sizeof(radiust
) * MAXRADIUS
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1882 if (radius
== MAP_FAILED
)
1884 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno
));
1887 ip_address_pool
= mmap(NULL
, sizeof(ippoolt
) * MAXIPPOOL
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1888 if (ip_address_pool
== MAP_FAILED
)
1890 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno
));
1894 ringbuffer
= mmap(NULL
, sizeof(struct Tringbuffer
), PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1895 if (ringbuffer
== MAP_FAILED
)
1897 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno
));
1900 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
1903 cli_session_kill
= mmap(NULL
, sizeof(sessionidt
) * MAXSESSION
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1904 if (cli_session_kill
== MAP_FAILED
)
1906 log(0, 0, 0, 0, "Error doing mmap for cli session kill: %s\n", strerror(errno
));
1909 memset(cli_session_kill
, 0, sizeof(sessionidt
) * MAXSESSION
);
1910 cli_tunnel_kill
= mmap(NULL
, sizeof(tunnelidt
) * MAXSESSION
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1911 if (cli_tunnel_kill
== MAP_FAILED
)
1913 log(0, 0, 0, 0, "Error doing mmap for cli tunnel kill: %s\n", strerror(errno
));
1916 memset(cli_tunnel_kill
, 0, sizeof(tunnelidt
) * MAXSESSION
);
1918 filter_buckets
= mmap(NULL
, sizeof(tbft
) * MAXSESSION
, PROT_READ
| PROT_WRITE
, MAP_SHARED
| MAP_ANONYMOUS
, 0, 0);
1919 if (filter_buckets
== MAP_FAILED
)
1921 log(0, 0, 0, 0, "Error doing mmap for filter buckets: %s\n", strerror(errno
));
1924 memset(filter_buckets
, 0, sizeof(tbft
) * MAXSESSION
);
1926 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
1927 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
1928 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
1929 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
1930 for (i
= 1; i
< MAXSESSION
- 1; i
++)
1931 session
[i
].next
= i
+ 1;
1932 session
[MAXSESSION
- 1].next
= 0;
1937 // Grab my hostname unless it's been specified
1938 gethostname(hostname
, sizeof(hostname
));
1940 struct hostent
*h
= gethostbyname(hostname
);
1942 myip
= ntohl(*(u32
*) h
->h_addr
);
1945 if ((p
= strstr(hostname
, ".optusnet.com.au"))) *p
= 0;
1947 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
1950 void initiptables(void)
1952 /* Flush the tables here so that we have a clean slate */
1953 system("iptables -t nat -F l2tpns");
1954 system("iptables -t mangle -F l2tpns");
1957 int assign_ip_address(sessionidt s
)
1961 clockt best_time
= time_now
;
1962 char *u
= session
[s
].user
;
1966 STAT(call_assign_ip_address
);
1968 for (i
= 0; i
< ip_pool_size
; i
++)
1970 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
1973 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
1980 if (ip_address_pool
[i
].last
< best_time
)
1983 if (!(best_time
= ip_address_pool
[i
].last
))
1984 break; // never used, grab this one
1990 log(0, 0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
1994 session
[s
].ip
= ntohl(ip_address_pool
[best
].address
);
1995 session
[s
].ip_pool_index
= best
;
1996 ip_address_pool
[best
].assigned
= 1;
1997 ip_address_pool
[best
].last
= time_now
;
1998 if (session
[s
].walled_garden
)
1999 /* Don't track addresses of users in walled garden (note: this
2000 means that their address isn't "sticky" even if they get
2002 ip_address_pool
[best
].user
[0] = 0;
2004 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
2007 log(4, ip_address_pool
[best
].address
, s
, session
[s
].tunnel
,
2008 "assign_ip_address(): %s ip address %lu from pool\n", reuse
? "Reusing" : "Allocating", best
);
2013 void free_ip_address(sessionidt s
)
2015 int i
= session
[s
].ip_pool_index
;
2018 STAT(call_free_ip_address
);
2022 return; // what the?
2025 uncache_sessionid(session
[s
].ip
);
2027 ip_address_pool
[i
].assigned
= 0;
2028 ip_address_pool
[i
].last
= time_now
;
2031 // Initialize the IP address pool
2037 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
2039 if (!(f
= fopen(IPPOOLFILE
, "r")))
2041 log(0, 0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
2045 buf
= (char *)malloc(4096);
2047 while (pi
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
2050 if (*buf
== '#' || *buf
== '\n')
2051 continue; // Skip comments / blank lines
2052 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
2053 if ((p
= (char *)strchr(buf
, ':')))
2057 src
= inet_addr(buf
);
2058 if (src
== INADDR_NONE
)
2060 log(0, 0, 0, 0, "Invalid address pool IP %s", buf
);
2063 // This entry is for a specific IP only
2064 if (src
!= config
->bind_address
)
2069 if ((p
= (char *)strchr(pool
, '/')))
2073 unsigned long start
= 0, end
= 0, mask
= 0, ip
;
2076 log(2, 0, 0, 0, "Adding IP address range %s\n", buf
);
2078 if (!*p
|| !(numbits
= atoi(p
)))
2080 log(0, 0, 0, 0, "Invalid pool range %s/\n", buf
, p
);
2083 start
= end
= ntohl(inet_addr(pool
));
2084 mask
= (unsigned long)(pow(2, numbits
) - 1) << (32 - numbits
);
2086 end
= start
+ (int)(pow(2, (32 - numbits
))) - 1;
2087 for (ip
= (start
+ 1); ip
< end
&& pi
< MAXIPPOOL
; ip
++)
2089 if ((ip
& 0xFF) == 0 || (ip
& 0xFF) == 255)
2091 ip_address_pool
[pi
++].address
= htonl(ip
);
2094 // Add a static route for this pool
2095 log(5, 0, 0, 0, "Adding route for address pool %s/%d\n", inet_toa(htonl(start
)), 32+mask
);
2096 memset(&r
, 0, sizeof(r
));
2097 r
.rt_dev
= config
->tapdevice
;
2098 r
.rt_dst
.sa_family
= AF_INET
;
2099 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(start
);
2100 r
.rt_genmask
.sa_family
= AF_INET
;
2101 *(u32
*) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
2102 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
2103 if (ioctl(ifrfd
, SIOCADDRT
, (void *) &r
) < 0)
2105 log(0, 0, 0, 0, "Error adding ip address pool route %s/%d: %s\n", inet_toa(start
), mask
, strerror(errno
));
2110 // It's a single ip address
2111 ip_address_pool
[pi
++].address
= inet_addr(pool
);
2117 log(1, 0, 0, 0, "IP address pool is %d addresses\n", pi
);
2121 void snoop_send_packet(char *packet
, u16 size
)
2123 if (!snoop_addr
.sin_port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
2126 log(5, 0, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n", packet
, size
, inet_toa(snoop_addr
.sin_addr
.s_addr
), htons(snoop_addr
.sin_port
));
2127 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
2128 log(0, 0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
2129 STAT(packets_snooped
);
2132 void dump_acct_info()
2134 char filename
[1024];
2136 time_t t
= time(NULL
);
2141 STAT(call_dump_acct_info
);
2143 strftime(timestr
, 64, "%Y%m%d%H%M%S", localtime(&t
));
2144 snprintf(filename
, 1024, "%s/%s", config
->accounting_dir
, timestr
);
2146 for (i
= 0; i
< MAXSESSION
; i
++)
2148 if (!session
[i
].opened
|| !session
[i
].cin
|| !session
[i
].cout
|| !*session
[i
].user
|| session
[i
].walled_garden
)
2152 time_t now
= time(NULL
);
2153 if (!(f
= fopen(filename
, "w")))
2155 log(0, 0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
2158 log(3, 0, 0, 0, "Dumping accounting information to %s\n", filename
);
2159 fprintf(f
, "# dslwatch.pl dump file V1.01\n"
2163 "# format: username ip qos uptxoctets downrxoctets\n",
2169 log(4, 0, 0, 0, "Dumping accounting information for %s\n", session
[i
].user
);
2170 fprintf(f
, "%s %s %d %lu %lu\n",
2171 session
[i
].user
, // username
2172 inet_toa(htonl(session
[i
].ip
)), // ip
2173 (session
[i
].throttle
) ? 2 : 1, // qos
2174 (unsigned long)session
[i
].cin
, // uptxoctets
2175 (unsigned long)session
[i
].cout
); // downrxoctets
2177 session
[i
].pin
= session
[i
].cin
= 0;
2178 session
[i
].pout
= session
[i
].cout
= 0;
2185 int main(int argc
, char *argv
[])
2189 _program_name
= strdup(argv
[0]);
2193 rlim
.rlim_cur
= RLIM_INFINITY
;
2194 rlim
.rlim_max
= RLIM_INFINITY
;
2195 // Remove the maximum core size
2196 setrlimit(RLIMIT_CORE
, &rlim
);
2197 // Make core dumps go to /tmp
2201 time(&basetime
); // start clock
2205 while ((o
= getopt(argc
, argv
, "vc:h:a:")) >= 0)
2213 strncpy(config
->config_file
, optarg
, sizeof(config
->config_file
) - 1);
2216 strncpy(hostname
, optarg
, 999);
2219 myip
= inet_addr(optarg
);
2220 if (myip
== INADDR_NONE
) {
2221 log(0, 0, 0, 0, "Invalid ip %s\n", optarg
);
2224 config
->bind_address
= myip
;
2225 handle_interface
= 1;
2229 printf("Args are:\n\t-c <file>\tConfig file\n\t-h <hostname>\tForce hostname\n\t-a <address>\tUse specific address\n\t-v\t\tDebug\n");
2235 // Start the timer routine off
2237 strftime(time_now_string
, 64, "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
2243 log(1, 0, 0, 0, "L2TPNS Version 1.1.0 - http://l2tpns.sourceforge.net/\n");
2244 log(1, 0, 0, 0, "Licensed under the GPL\n");
2246 /* Start up the cluster first, so that we don't have two machines with
2247 * the same IP at once.
2248 * This is still racy, but the second GARP should fix that
2250 cluster_init(config
->bind_address
, 0);
2251 cluster_send_message(config
->cluster_address
, config
->bind_address
, C_HELLO
, hostname
, strlen(hostname
));
2254 log(1, 0, 0, 0, "Set up on interface %s\n", config
->tapdevice
);
2260 if (handle_interface
) {
2261 send_garp(config
->bind_address
);
2264 // If NOSTATEFILE exists, we will ignore any updates from the cluster master for this execution
2265 if (!unlink(NOSTATEFILE
))
2266 config
->ignore_cluster_updates
= 1;
2270 signal(SIGALRM
, sigalrm_handler
);
2271 signal(SIGHUP
, sighup_handler
);
2272 signal(SIGTERM
, sigterm_handler
);
2273 signal(SIGINT
, sigterm_handler
);
2274 signal(SIGQUIT
, sigquit_handler
);
2275 signal(SIGCHLD
, sigchild_handler
);
2276 signal(SIGSEGV
, sigsegv_handler
);
2280 // Drop privileges here
2281 if (config
->target_uid
> 0 && geteuid() == 0)
2282 setuid(config
->target_uid
);
2288 void sighup_handler(int junk
)
2290 if (log_stream
&& log_stream
!= stderr
)
2299 void sigalrm_handler(int junk
)
2301 // Log current traffic stats
2303 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
2304 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%lu OUT:%lu",
2305 (udp_rx
/ 1024.0 / 1024.0 * 8),
2306 (eth_tx
/ 1024.0 / 1024.0 * 8),
2307 (eth_rx
/ 1024.0 / 1024.0 * 8),
2308 (udp_tx
/ 1024.0 / 1024.0 * 8),
2309 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / 1024.0 / 1024.0 * 8),
2310 udp_rx_pkt
, eth_rx_pkt
);
2312 udp_tx
= udp_rx
= 0;
2313 udp_rx_pkt
= eth_rx_pkt
= 0;
2314 eth_tx
= eth_rx
= 0;
2316 if (config
->dump_speed
)
2317 printf("%s\n", config
->bandwidth
);
2319 // Update the internal time counter
2321 strftime(time_now_string
, 64, "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
2326 struct param_timer p
= { time_now
};
2327 run_plugins(PLUGIN_TIMER
, &p
);
2332 void sigterm_handler(int junk
)
2334 log(1, 0, 0, 0, "Shutting down cleanly\n");
2335 if (config
->save_state
)
2340 void sigquit_handler(int junk
)
2345 log(1, 0, 0, 0, "Shutting down without saving sessions\n");
2346 for (i
= 1; i
< MAXSESSION
; i
++)
2348 if (session
[i
].opened
)
2349 sessionkill(i
, "L2TPNS Closing");
2351 for (i
= 1; i
< MAXTUNNEL
; i
++)
2353 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
2354 tunnelshutdown(i
, "L2TPNS Closing");
2357 cluster_send_goodbye();
2359 // Touch a file which says not to reload the state
2360 f
= fopen(NOSTATEFILE
, "w");
2366 void sigchild_handler(int signal
)
2368 while (waitpid(-1, NULL
, WNOHANG
) > 0)
2372 void sigsegv_handler(int signal
)
2374 log(0, 0, 0, 0, "----------------------------------------------\n");
2375 log(0, 0, 0, 0, "- SEGFAULT! -\n");
2376 log(0, 0, 0, 0, "----------------------------------------------\n");
2386 char magic
[sizeof(DUMP_MAGIC
)-1];
2389 if (!config
->save_state
)
2392 // Ignore saved state if NOSTATEFILE exists
2393 if (config
->ignore_cluster_updates
)
2399 if (stat(STATEFILE
, &sb
) < 0)
2402 if (sb
.st_mtime
< (time(NULL
) - 60))
2404 log(0, 0, 0, 0, "State file is too old to read, ignoring\n");
2409 f
= fopen(STATEFILE
, "r");
2414 log(0, 0, 0, 0, "Can't read state file: %s\n", strerror(errno
));
2418 if (fread(magic
, sizeof(magic
), 1, f
) != 1 || strncmp(magic
, DUMP_MAGIC
, sizeof(magic
)))
2420 log(0, 0, 0, 0, "Bad state file magic\n");
2424 log(1, 0, 0, 0, "Reading state information\n");
2425 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] > MAXIPPOOL
|| buf
[1] != sizeof(ippoolt
))
2427 log(0, 0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
2431 if (buf
[0] > ip_pool_size
)
2433 log(0, 0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf
[0], ip_pool_size
);
2437 log(2, 0, 0, 0, "Loading %u ip addresses\n", buf
[0]);
2438 for (i
= 0; i
< buf
[0]; i
++)
2440 if (fread(&itmp
, sizeof(itmp
), 1, f
) != 1)
2442 log(0, 0, 0, 0, "Error reading ip %d from state file: %s\n", i
, strerror(errno
));
2446 if (itmp
.address
!= ip_address_pool
[i
].address
)
2448 log(0, 0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i
);
2452 memcpy(&ip_address_pool
[i
], &itmp
, sizeof(itmp
));
2455 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXTUNNEL
|| buf
[1] != sizeof(tunnelt
))
2457 log(0, 0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
2461 log(2, 0, 0, 0, "Loading %u tunnels\n", MAXTUNNEL
);
2462 if (fread(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
)
2464 log(0, 0, 0, 0, "Error reading tunnel data from state file\n");
2468 for (i
= 0; i
< MAXTUNNEL
; i
++)
2470 tunnel
[i
].controlc
= 0;
2471 tunnel
[i
].controls
= NULL
;
2472 tunnel
[i
].controle
= NULL
;
2473 if (*tunnel
[i
].hostname
)
2474 log(3, 0, 0, 0, "Created tunnel for %s\n", tunnel
[i
].hostname
);
2477 if (fread(buf
, sizeof(buf
), 1, f
) != 1 || buf
[0] != MAXSESSION
|| buf
[1] != sizeof(sessiont
))
2479 log(0, 0, 0, 0, "Error/mismatch reading session header from state file\n");
2483 log(2, 0, 0, 0, "Loading %u sessions\n", MAXSESSION
);
2484 if (fread(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
)
2486 log(0, 0, 0, 0, "Error reading session data from state file\n");
2490 for (i
= 0; i
< MAXSESSION
; i
++)
2493 session
[i
].throttle
= 0;
2494 if (session
[i
].opened
)
2496 log(2, 0, i
, 0, "Loaded active session for user %s\n", session
[i
].user
);
2497 if (session
[i
].ip
&& session
[i
].ip
!= 0xFFFFFFFE)
2498 sessionsetup(session
[i
].tunnel
, i
, 0);
2503 log(0, 0, 0, 0, "Loaded saved state information\n");
2511 if (!config
->save_state
)
2515 if (!(f
= fopen(STATEFILE
, "w")))
2518 log(1, 0, 0, 0, "Dumping state information\n");
2520 if (fwrite(DUMP_MAGIC
, sizeof(DUMP_MAGIC
)-1, 1, f
) != 1) break;
2522 log(2, 0, 0, 0, "Dumping %u ip addresses\n", ip_pool_size
);
2523 buf
[0] = ip_pool_size
;
2524 buf
[1] = sizeof(ippoolt
);
2525 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1) break;
2526 if (fwrite(ip_address_pool
, sizeof(ippoolt
), ip_pool_size
, f
) != ip_pool_size
) break;
2528 log(2, 0, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL
);
2530 buf
[1] = sizeof(tunnelt
);
2531 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1) break;
2532 if (fwrite(tunnel
, sizeof(tunnelt
), MAXTUNNEL
, f
) != MAXTUNNEL
) break;
2534 log(2, 0, 0, 0, "Dumping %u sessions\n", MAXSESSION
);
2535 buf
[0] = MAXSESSION
;
2536 buf
[1] = sizeof(sessiont
);
2537 if (fwrite(buf
, sizeof(buf
), 1, f
) != 1) break;
2538 if (fwrite(session
, sizeof(sessiont
), MAXSESSION
, f
) != MAXSESSION
) break;
2540 if (fclose(f
) == 0) return; // OK
2543 log(0, 0, 0, 0, "Can't write state information: %s\n", strerror(errno
));
2547 void build_chap_response(char *challenge
, u8 id
, u16 challenge_length
, char **challenge_response
)
2550 *challenge_response
= NULL
;
2552 if (!*config
->l2tpsecret
)
2554 log(0, 0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
2558 log(4, 0, 0, 0, " Building challenge response for CHAP request\n");
2560 *challenge_response
= (char *)calloc(17, 1);
2563 MD5Update(&ctx
, &id
, 1);
2564 MD5Update(&ctx
, config
->l2tpsecret
, strlen(config
->l2tpsecret
));
2565 MD5Update(&ctx
, challenge
, challenge_length
);
2566 MD5Final(*challenge_response
, &ctx
);
2571 static int facility_value(char *name
)
2574 for (i
= 0; facilitynames
[i
].c_name
; i
++)
2576 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
2577 return facilitynames
[i
].c_val
;
2582 void update_config()
2586 snoop_addr
.sin_family
= AF_INET
;
2587 snoop_addr
.sin_addr
.s_addr
= config
->snoop_destination_host
;
2588 snoop_addr
.sin_port
= htons(config
->snoop_destination_port
);
2598 if (*config
->log_filename
)
2600 if (strstr(config
->log_filename
, "file:") == config
->log_filename
)
2602 if ((log_stream
= fopen((char *)(config
->log_filename
+ 5), "a")))
2604 fseek(log_stream
, 0, SEEK_END
);
2605 setbuf(log_stream
, NULL
);
2609 log_stream
= stderr
;
2610 setbuf(log_stream
, NULL
);
2613 else if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
2615 char *p
= config
->log_filename
+ 7;
2618 openlog("l2tpns", LOG_PID
, facility_value(p
));
2625 log_stream
= stderr
;
2626 setbuf(log_stream
, NULL
);
2631 config
->numradiusservers
= 0;
2632 for (i
= 0; i
< MAXRADSERVER
; i
++)
2633 if (config
->radiusserver
[i
]) config
->numradiusservers
++;
2635 if (!config
->numradiusservers
)
2637 log(0, 0, 0, 0, "No RADIUS servers defined!\n");
2641 for (i
= 0; i
< MAXPLUGINS
; i
++)
2643 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
2645 if (*config
->plugins
[i
])
2648 add_plugin(config
->plugins
[i
]);
2650 else if (*config
->old_plugins
[i
])
2653 remove_plugin(config
->old_plugins
[i
]);
2656 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
2657 config
->reload_config
= 0;
2660 void read_config_file()
2664 if (!config
->config_file
) return;
2665 if (!(f
= fopen(config
->config_file
, "r"))) {
2666 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
2670 log(3, 0, 0, 0, "Reading config file %s\n", config
->config_file
);
2672 log(3, 0, 0, 0, "Done reading config file\n");
2678 int sessionsetup(tunnelidt t
, sessionidt s
, u8 routes
)
2680 // A session now exists, set it up
2685 STAT(call_sessionsetup
);
2687 log(3, session
[s
].ip
, s
, t
, "Doing session setup for session\n");
2688 if (!session
[s
].ip
) {
2689 log(0, session
[s
].ip
, s
, t
, "VERY VERY BAD! sessionsetup() called with no session[s].ip\n");
2693 // Make sure this is right
2694 session
[s
].tunnel
= t
;
2695 // zap old sessions with same IP and/or username
2696 // Don't kill walled garden sessions - doing so leads to a DoS
2697 // from someone who doesn't need to know the password
2699 user
= session
[s
].user
;
2700 for (i
= 1; i
< MAXSESSION
; i
++)
2702 if (i
== s
) continue;
2703 if (ip
== session
[i
].ip
) sessionkill(i
, "Duplicate IP address");
2704 if (!session
[s
].walled_garden
&& !session
[i
].walled_garden
&& strcasecmp(user
, session
[i
].user
) == 0)
2705 sessionkill(i
, "Duplicate session for user");
2710 if (session
[s
].route
[routes
].ip
&& session
[s
].route
[routes
].mask
)
2712 log(2, session
[s
].ip
, s
, t
, "Routing session\n");
2713 routeset(session
[s
].ip
, 0, 0, 1);
2715 routeset(session
[s
].route
[routes
].ip
, session
[s
].route
[routes
].mask
,
2720 if (!session
[s
].sid
)
2723 // Force throttling on or off
2724 // This has the advantage of cleaning up after another throttled user who may have left
2725 // firewall rules lying around
2726 throttle_session(s
, session
[s
].throttle
);
2729 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
2730 run_plugins(PLUGIN_NEW_SESSION
, &data
);
2733 if (!session
[s
].sid
)
2734 session
[s
].sid
= ++last_sid
;
2736 cache_sessionid(htonl(session
[s
].ip
), s
);
2738 cluster_send_session(s
);
2739 session
[s
].last_packet
= time_now
;
2741 char *sessionip
, *tunnelip
;
2742 sessionip
= strdup(inet_toa(ntohl(session
[s
].ip
)));
2743 tunnelip
= strdup(inet_toa(ntohl(tunnel
[t
].ip
)));
2744 log(2, session
[s
].ip
, s
, t
, "Login by %s at %s from %s (%s)\n",
2745 session
[s
].user
, sessionip
, tunnelip
, tunnel
[t
].hostname
);
2746 if (sessionip
) free(sessionip
);
2747 if (tunnelip
) free(tunnelip
);
2750 return 1; // RADIUS OK and IP allocated, done...
2754 void ringbuffer_dump(FILE *stream
)
2756 int i
= ringbuffer
->head
;
2758 while (i
!= ringbuffer
->tail
)
2760 if (*ringbuffer
->buffer
[i
].message
)
2761 fprintf(stream
, "%d-%s", ringbuffer
->buffer
[i
].level
, ringbuffer
->buffer
[i
].message
);
2762 if (++i
== ringbuffer
->tail
) break;
2763 if (i
== RINGBUFFER_SIZE
) i
= 0;
2772 loaded_plugins
= ll_init();
2773 // Initialize the plugins to nothing
2774 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
2775 plugins
[i
] = ll_init();
2778 void add_plugin(char *plugin_name
)
2781 int (*initfunc
)(struct pluginfuncs
*);
2782 char path
[256] = {0};
2784 struct pluginfuncs funcs
;
2787 funcs
._log_hex
= _log_hex
;
2788 funcs
.inet_toa
= inet_toa
;
2789 funcs
.get_session_by_username
= sessionbyuser
;
2790 funcs
.get_session_by_id
= sessiontbysessionidt
;
2791 funcs
.get_id_by_session
= sessionidtbysessiont
;
2792 funcs
.sessionkill
= sessionkill
;
2793 funcs
.radiusnew
= radiusnew
;
2794 funcs
.radiussend
= radiussend
;
2796 snprintf(path
, 256, "%s/%s.so", LIBDIR
, plugin_name
);
2798 log(2, 0, 0, 0, "Loading plugin from %s\n", path
);
2799 p
= dlopen(path
, RTLD_NOW
);
2802 log(1, 0, 0, 0, " Plugin load failed: %s\n", dlerror());
2806 if (ll_contains(loaded_plugins
, p
))
2813 int *v
= dlsym(p
, "__plugin_api_version");
2814 if (!v
|| *v
!= PLUGIN_API_VERSION
)
2816 log(1, 0, 0, 0, " Plugin load failed: API version mismatch\n", dlerror());
2822 initfunc
= dlsym(p
, "plugin_init");
2825 log(1, 0, 0, 0, " Plugin load failed: function plugin_init() does not exist.\n", dlerror());
2830 if (!initfunc(&funcs
))
2832 log(1, 0, 0, 0, " Plugin load failed: plugin_init() returned FALSE.\n", dlerror());
2837 for (i
= 0; i
< max_plugin_functions
; i
++)
2840 if (!plugin_functions
[i
]) continue;
2841 if ((x
= dlsym(p
, plugin_functions
[i
])))
2843 log(3, 0, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
2844 ll_push(plugins
[i
], x
);
2847 log(2, 0, 0, 0, " Loaded plugin %s\n", plugin_name
);
2850 void remove_plugin(char *plugin_name
)
2854 char path
[256] = {0};
2857 snprintf(path
, 256, "%s/%s.so", LIBDIR
, plugin_name
);
2859 log(2, 0, 0, 0, "Removing plugin %s\n", plugin_name
);
2860 // Get the existing pointer
2861 p
= dlopen(path
, RTLD_LAZY
);
2864 for (i
= 0; i
< max_plugin_functions
; i
++)
2867 if (!plugin_functions
[i
]) continue;
2868 if ((x
= dlsym(p
, plugin_functions
[i
]))) ll_delete(plugins
[i
], x
);
2871 if (ll_contains(loaded_plugins
, p
))
2873 ll_delete(loaded_plugins
, p
);
2875 donefunc
= dlsym(p
, "plugin_done");
2876 if (donefunc
) donefunc();
2881 log(2, 0, 0, 0, "Removed plugin %s\n", plugin_name
);
2884 int run_plugins(int plugin_type
, void *data
)
2886 int (*func
)(void *data
);
2887 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
) return 1;
2889 ll_reset(plugins
[plugin_type
]);
2890 while ((func
= ll_next(plugins
[plugin_type
])))
2894 if (rc
== PLUGIN_RET_STOP
) return 1;
2895 if (rc
== PLUGIN_RET_ERROR
) return 0;
2900 void processcontrol(u8
* buf
, int len
, struct sockaddr_in
*addr
)
2904 struct param_control param
= { buf
, len
, ntohl(addr
->sin_addr
.s_addr
), ntohs(addr
->sin_port
), NULL
, 0, 0 };
2906 log(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Received ");
2908 dump_packet(buf
, log_stream
);
2910 resp
= calloc(1400, 1);
2911 l
= new_packet(PKT_RESP_ERROR
, resp
);
2912 *(int *)(resp
+ 6) = *(int *)(buf
+ 6);
2914 param
.type
= ntohs(*(short *)(buf
+ 2));
2915 param
.id
= ntohl(*(int *)(buf
+ 6));
2916 param
.data_length
= ntohs(*(short *)(buf
+ 4)) - 10;
2917 param
.data
= (param
.data_length
> 0) ? (char *)(buf
+ 10) : NULL
;
2918 param
.response
= resp
;
2919 param
.response_length
= l
;
2921 if (param
.type
== PKT_LOAD_PLUGIN
&& param
.data_length
)
2923 add_plugin(param
.data
);
2925 else if (param
.type
== PKT_UNLOAD_PLUGIN
&& param
.data_length
)
2927 remove_plugin(param
.data
);
2931 run_plugins(PLUGIN_CONTROL
, ¶m
);
2934 if (param
.send_response
)
2936 send_packet(controlfd
, ntohl(addr
->sin_addr
.s_addr
), ntohs(addr
->sin_port
), param
.response
, param
.response_length
);
2937 log(4, ntohl(addr
->sin_addr
.s_addr
), 0, 0, "Sent Control packet response\n");
2945 * Go through all of the tunnels and do some cleanups
2951 log(1, 0, 0, 0, "Cleaning tunnels array\n");
2953 for (i
= 1; i
< MAXTUNNEL
; i
++)
2956 || !*tunnel
[i
].hostname
2957 || (tunnel
[i
].state
== TUNNELDIE
&& tunnel
[i
].die
>= time_now
))
2964 void tunnelclear(tunnelidt t
)
2967 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2968 tunnel
[t
].state
= TUNNELFREE
;
2971 tunnelidt
new_tunnel()
2974 for (i
= 1; i
< MAXTUNNEL
; i
++)
2976 if (tunnel
[i
].state
== TUNNELFREE
)
2978 log(4, 0, 0, i
, "Assigning tunnel ID %d\n", i
);
2982 log(0, 0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");