ac6c8e9619c69e2e174d2014b78005fa5003fe83
[l2tpns.git] / l2tpns.c
1 // L2TP Network Server
2 // Adrian Kennard 2002
3 // Copyright (c) 2003, 2004 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
5 // vim: sw=8 ts=8
6
7 char const *cvs_id_l2tpns = "$Id: l2tpns.c,v 1.11 2004/07/07 09:09:53 bodea Exp $";
8
9 #include <arpa/inet.h>
10 #include <assert.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <linux/if_tun.h>
14 #define SYSLOG_NAMES
15 #include <syslog.h>
16 #include <malloc.h>
17 #include <math.h>
18 #include <net/route.h>
19 #include <sys/mman.h>
20 #include <netdb.h>
21 #include <netinet/in.h>
22 #include <stdarg.h>
23 #include <stdlib.h>
24 #include <stdio.h>
25 #define __USE_GNU
26 #include <string.h>
27 #include <sys/ioctl.h>
28 #include <sys/socket.h>
29 #include <sys/stat.h>
30 #include <sys/time.h>
31 #include <sys/resource.h>
32 #include <sys/wait.h>
33 #include <linux/if.h>
34 #include <stddef.h>
35 #include <time.h>
36 #include <dlfcn.h>
37 #include <unistd.h>
38 #include <sched.h>
39 #include <sys/sysinfo.h>
40 #include <libcli.h>
41
42 #include "md5.h"
43 #include "l2tpns.h"
44 #include "cluster.h"
45 #include "plugin.h"
46 #include "ll.h"
47 #include "constants.h"
48 #include "control.h"
49 #include "util.h"
50 #include "tbf.h"
51
52 // Globals
53 struct configt *config = NULL; // all configuration
54 int tapfd = -1; // tap interface file handle
55 int udpfd = -1; // UDP file handle
56 int controlfd = -1; // Control signal handle
57 int snoopfd = -1; // UDP file handle for sending out intercept data
58 int *radfds = NULL; // RADIUS requests file handles
59 int ifrfd = -1; // File descriptor for routing, etc
60 time_t basetime = 0; // base clock
61 char hostname[1000] = ""; // us.
62 u16 tapmac[3]; // MAC of tap interface
63 int tapidx; // ifr_ifindex of tap device
64 u32 sessionid = 0; // session id for radius accounting
65 int syslog_log = 0; // are we logging to syslog
66 FILE *log_stream = NULL;
67 struct sockaddr_in snoop_addr = {0};
68 extern int cluster_sockfd;
69 u32 last_sid = 0;
70 int clifd = 0;
71 sessionidt *cli_session_kill = NULL;
72 tunnelidt *cli_tunnel_kill = NULL;
73 static void *ip_hash[256];
74 u32 udp_tx = 0, udp_rx = 0, udp_rx_pkt = 0;
75 u32 eth_tx = 0, eth_rx = 0, eth_rx_pkt = 0;
76 u32 ip_pool_size = 1;
77 time_t time_now = 0;
78 char time_now_string[64] = {0};
79 char main_quit = 0;
80 char *_program_name = NULL;
81 linked_list *loaded_plugins;
82 linked_list *plugins[MAX_PLUGIN_TYPES];
83
84 #ifdef BGP
85 #include "bgp.h"
86 struct bgp_peer *bgp_peers = 0;
87 struct bgp_route_list *bgp_routes = 0;
88 int bgp_configured = 0;
89 #endif /* BGP */
90
91 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
92 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(struct configt, MEMBER), membersize(struct configt, MEMBER), TYPE }
93
94 struct config_descriptt config_values[] = {
95 CONFIG("debug", debug, INT),
96 CONFIG("log_file", log_filename, STRING),
97 CONFIG("l2tp_secret", l2tpsecret, STRING),
98 CONFIG("primary_dns", default_dns1, IP),
99 CONFIG("secondary_dns", default_dns2, IP),
100 CONFIG("save_state", save_state, BOOL),
101 CONFIG("primary_radius", radiusserver[0], IP),
102 CONFIG("secondary_radius", radiusserver[1], IP),
103 CONFIG("radius_accounting", radius_accounting, BOOL),
104 CONFIG("radius_secret", radiussecret, STRING),
105 CONFIG("bind_address", bind_address, IP),
106 CONFIG("send_garp", send_garp, BOOL),
107 CONFIG("throttle_speed", rl_rate, UNSIGNED_LONG),
108 CONFIG("accounting_dir", accounting_dir, STRING),
109 CONFIG("setuid", target_uid, INT),
110 CONFIG("dump_speed", dump_speed, BOOL),
111 CONFIG("cleanup_interval", cleanup_interval, INT),
112 CONFIG("multi_read_count", multi_read_count, INT),
113 CONFIG("scheduler_fifo", scheduler_fifo, BOOL),
114 CONFIG("icmp_rate", icmp_rate, INT),
115 CONFIG("cluster_address", cluster_address, IP),
116 CONFIG("cluster_interface", cluster_interface, STRING),
117 CONFIG("cluster_hb_interval", cluster_hb_interval, INT),
118 CONFIG("cluster_hb_timeout", cluster_hb_timeout, INT),
119 #ifdef BGP
120 CONFIG("as_number", as_number, SHORT),
121 CONFIG("bgp_peer1", bgp_peer[0], STRING),
122 CONFIG("bgp_peer1_as", bgp_peer_as[0], SHORT),
123 CONFIG("bgp_peer2", bgp_peer[1], STRING),
124 CONFIG("bgp_peer2_as", bgp_peer_as[1], SHORT),
125 #endif /* BGP */
126 { NULL, 0, 0, 0 },
127 };
128
129 char *plugin_functions[] = {
130 NULL,
131 "plugin_pre_auth",
132 "plugin_post_auth",
133 "plugin_packet_rx",
134 "plugin_packet_tx",
135 "plugin_timer",
136 "plugin_new_session",
137 "plugin_kill_session",
138 "plugin_control",
139 "plugin_radius_response",
140 "plugin_become_master",
141 "plugin_new_session_master",
142 };
143
144 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
145
146 tunnelt *tunnel = NULL; // 1000 * 45 = 45000 = 45k
147 sessiont *session = NULL; // 5000 * 213 = 1065000 = 1 Mb
148 sessioncountt *sess_count = NULL;
149 radiust *radius = NULL;
150 ippoolt *ip_address_pool = NULL;
151 controlt *controlfree = 0;
152 struct Tstats *_statistics = NULL;
153 #ifdef RINGBUFFER
154 struct Tringbuffer *ringbuffer = NULL;
155 #endif
156
157 void sigalrm_handler(int);
158 void sighup_handler(int);
159 void sigterm_handler(int);
160 void sigquit_handler(int);
161 void sigchild_handler(int);
162 void read_config_file();
163 void read_state();
164 void dump_state();
165 void tunnel_clean();
166 tunnelidt new_tunnel();
167 void update_config();
168
169 static void cache_ipmap(ipt ip, int s);
170 static void uncache_ipmap(ipt ip);
171
172 // return internal time (10ths since run)
173 clockt now(void)
174 {
175 struct timeval t;
176 gettimeofday(&t, 0);
177 return (t.tv_sec - basetime) * 10 + t.tv_usec / 100000 + 1;
178 }
179
180 // work out a retry time based on try number
181 clockt backoff(u8 try)
182 {
183 if (try > 5) try = 5; // max backoff
184 return now() + 10 * (1 << try);
185 }
186
187 void _log(int level, ipt address, sessionidt s, tunnelidt t, const char *format, ...)
188 {
189 static char message[65536] = {0};
190 static char message2[65536] = {0};
191 va_list ap;
192
193 #ifdef RINGBUFFER
194 if (ringbuffer)
195 {
196 if (++ringbuffer->tail >= RINGBUFFER_SIZE)
197 ringbuffer->tail = 0;
198 if (ringbuffer->tail == ringbuffer->head)
199 if (++ringbuffer->head >= RINGBUFFER_SIZE)
200 ringbuffer->head = 0;
201
202 ringbuffer->buffer[ringbuffer->tail].level = level;
203 ringbuffer->buffer[ringbuffer->tail].address = address;
204 ringbuffer->buffer[ringbuffer->tail].session = s;
205 ringbuffer->buffer[ringbuffer->tail].tunnel = t;
206 va_start(ap, format);
207 vsnprintf(ringbuffer->buffer[ringbuffer->tail].message, 4095, format, ap);
208 va_end(ap);
209 }
210 #endif
211
212 if (config->debug < level) return;
213
214 va_start(ap, format);
215 if (log_stream)
216 {
217 vsnprintf(message2, 65535, format, ap);
218 snprintf(message, 65535, "%s %02d/%02d %s", time_now_string, t, s, message2);
219 fprintf(log_stream, "%s", message);
220 }
221 else if (syslog_log)
222 {
223 vsnprintf(message2, 65535, format, ap);
224 snprintf(message, 65535, "%02d/%02d %s", t, s, message2);
225 syslog(level + 2, message); // We don't need LOG_EMERG or LOG_ALERT
226 }
227 va_end(ap);
228 }
229
230 void _log_hex(int level, ipt address, sessionidt s, tunnelidt t, const char *title, const char *data, int maxsize)
231 {
232 int i, j;
233 const u8 *d = (const u8 *)data;
234
235 if (config->debug < level) return;
236
237 // No support for log_hex to syslog
238 if (log_stream)
239 {
240 log(level, address, s, t, "%s (%d bytes):\n", title, maxsize);
241 setvbuf(log_stream, NULL, _IOFBF, 16384);
242
243 for (i = 0; i < maxsize; )
244 {
245 fprintf(log_stream, "%4X: ", i);
246 for (j = i; j < maxsize && j < (i + 16); j++)
247 {
248 fprintf(log_stream, "%02X ", d[j]);
249 if (j == i + 7)
250 fputs(": ", log_stream);
251 }
252
253 for (; j < i + 16; j++)
254 {
255 fputs(" ", log_stream);
256 if (j == i + 7)
257 fputs(": ", log_stream);
258 }
259
260 fputs(" ", log_stream);
261 for (j = i; j < maxsize && j < (i + 16); j++)
262 {
263 if (d[j] >= 0x20 && d[j] < 0x7f && d[j] != 0x20)
264 fputc(d[j], log_stream);
265 else
266 fputc('.', log_stream);
267
268 if (j == i + 7)
269 fputs(" ", log_stream);
270 }
271
272 i = j;
273 fputs("\n", log_stream);
274 }
275
276 fflush(log_stream);
277 setbuf(log_stream, NULL);
278 }
279 }
280
281
282 // Add a route
283 //
284 // This adds it to the routing table, advertises it
285 // via iBGP if enabled, and stuffs it into the
286 // 'sessionbyip' cache.
287 //
288 // 'ip' and 'mask' must be in _host_ order.
289 //
290 void routeset(sessionidt s, ipt ip, ipt mask, ipt gw, u8 add)
291 {
292 struct rtentry r;
293 int i;
294
295 if (!mask) mask = 0xffffffff;
296
297 ip &= mask; // Force the ip to be the first one in the route.
298
299 memset(&r, 0, sizeof(r));
300 r.rt_dev = config->tapdevice;
301 r.rt_dst.sa_family = AF_INET;
302 *(u32 *) & (((struct sockaddr_in *) &r.rt_dst)->sin_addr.s_addr) = htonl(ip);
303 r.rt_gateway.sa_family = AF_INET;
304 *(u32 *) & (((struct sockaddr_in *) &r.rt_gateway)->sin_addr.s_addr) = htonl(gw);
305 r.rt_genmask.sa_family = AF_INET;
306 *(u32 *) & (((struct sockaddr_in *) &r.rt_genmask)->sin_addr.s_addr) = htonl(mask);
307 r.rt_flags = (RTF_UP | RTF_STATIC);
308 if (gw)
309 r.rt_flags |= RTF_GATEWAY;
310 else if (mask == 0xffffffff)
311 r.rt_flags |= RTF_HOST;
312
313 log(1, ip, 0, 0, "Route %s %u.%u.%u.%u/%u.%u.%u.%u %u.%u.%u.%u\n",
314 add ? "add" : "del",
315 ip >> 24, ip >> 16 & 0xff, ip >> 8 & 0xff, ip & 0xff,
316 mask >> 24, mask >> 16 & 0xff, mask >> 8 & 0xff, mask & 0xff,
317 gw >> 24, gw >> 16 & 0xff, gw >> 8 & 0xff, gw & 0xff);
318
319 if (ioctl(ifrfd, add ? SIOCADDRT : SIOCDELRT, (void *) &r) < 0)
320 log(0, 0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno));
321
322 #ifdef BGP
323 if (add)
324 bgp_add_route(htonl(ip), htonl(mask));
325 else
326 bgp_del_route(htonl(ip), htonl(mask));
327 #endif /* BGP */
328
329 // Add/Remove the IPs to the 'sessionbyip' cache.
330 // Note that we add the zero address in the case of
331 // a network route. Roll on CIDR.
332
333 // Note that 's == 0' implies this is the address pool.
334 // We still cache it here, because it will pre-fill
335 // the malloc'ed tree.
336
337 if (s)
338 {
339 if (!add) // Are we deleting a route?
340 s = 0; // Caching the session as '0' is the same as uncaching.
341
342 for (i = ip; (i&mask) == (ip&mask) ; ++i)
343 cache_ipmap(i, s);
344 }
345 }
346
347 // Set up TAP interface
348 void inittap(void)
349 {
350 struct ifreq ifr;
351 struct sockaddr_in sin = {0};
352 memset(&ifr, 0, sizeof(ifr));
353 ifr.ifr_flags = IFF_TUN;
354
355 tapfd = open(TAPDEVICE, O_RDWR);
356 if (tapfd < 0)
357 { // fatal
358 log(0, 0, 0, 0, "Can't open %s: %s\n", TAPDEVICE, strerror(errno));
359 exit(1);
360 }
361 {
362 int flags = fcntl(tapfd, F_GETFL, 0);
363 fcntl(tapfd, F_SETFL, flags | O_NONBLOCK);
364 }
365 if (ioctl(tapfd, TUNSETIFF, (void *) &ifr) < 0)
366 {
367 log(0, 0, 0, 0, "Can't set tap interface: %s\n", strerror(errno));
368 exit(1);
369 }
370 assert(strlen(ifr.ifr_name) < sizeof(config->tapdevice));
371 strncpy(config->tapdevice, ifr.ifr_name, sizeof(config->tapdevice) - 1);
372 ifrfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
373
374 sin.sin_family = AF_INET;
375 sin.sin_addr.s_addr = config->bind_address ? config->bind_address : 0x01010101; // 1.1.1.1
376 memcpy(&ifr.ifr_addr, &sin, sizeof(struct sockaddr));
377
378 if (ioctl(ifrfd, SIOCSIFADDR, (void *) &ifr) < 0)
379 {
380 log(0, 0, 0, 0, "Error setting tun address: %s\n", strerror(errno));
381 exit(1);
382 }
383 /* Bump up the qlen to deal with bursts from the network */
384 ifr.ifr_qlen = 1000;
385 if (ioctl(ifrfd, SIOCSIFTXQLEN, (void *) &ifr) < 0)
386 {
387 log(0, 0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno));
388 exit(1);
389 }
390 ifr.ifr_flags = IFF_UP;
391 if (ioctl(ifrfd, SIOCSIFFLAGS, (void *) &ifr) < 0)
392 {
393 log(0, 0, 0, 0, "Error setting tun flags: %s\n", strerror(errno));
394 exit(1);
395 }
396 if (ioctl(ifrfd, SIOCGIFHWADDR, (void *) &ifr) < 0)
397 {
398 log(0, 0, 0, 0, "Error setting tun hardware address: %s\n", strerror(errno));
399 exit(1);
400 }
401 memcpy(&tapmac, 2 + (u8 *) & ifr.ifr_hwaddr, 6);
402 if (ioctl(ifrfd, SIOCGIFINDEX, (void *) &ifr) < 0)
403 {
404 log(0, 0, 0, 0, "Error setting tun ifindex: %s\n", strerror(errno));
405 exit(1);
406 }
407 tapidx = ifr.ifr_ifindex;
408 }
409
410 // set up UDP port
411 void initudp(void)
412 {
413 int on = 1;
414 struct sockaddr_in addr;
415
416 // Tunnel
417 memset(&addr, 0, sizeof(addr));
418 addr.sin_family = AF_INET;
419 addr.sin_port = htons(L2TPPORT);
420 addr.sin_addr.s_addr = config->bind_address;
421 udpfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
422 setsockopt(udpfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
423 {
424 int flags = fcntl(udpfd, F_GETFL, 0);
425 fcntl(udpfd, F_SETFL, flags | O_NONBLOCK);
426 }
427 if (bind(udpfd, (void *) &addr, sizeof(addr)) < 0)
428 {
429 log(0, 0, 0, 0, "Error in UDP bind: %s\n", strerror(errno));
430 exit(1);
431 }
432 snoopfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
433 snoop_addr.sin_family = AF_INET;
434
435 // Control
436 memset(&addr, 0, sizeof(addr));
437 addr.sin_family = AF_INET;
438 addr.sin_port = htons(1702);
439 controlfd = socket(AF_INET, SOCK_DGRAM, 17);
440 setsockopt(controlfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
441 if (bind(controlfd, (void *) &addr, sizeof(addr)) < 0)
442 {
443 log(0, 0, 0, 0, "Error in control bind: %s\n", strerror(errno));
444 exit(1);
445 }
446 }
447
448 //
449 // Find session by IP, < 1 for not found
450 //
451 // Confusingly enough, this 'ip' must be
452 // in _network_ order. This being the common
453 // case when looking it up from IP packet headers.
454 //
455 // We actually use this cache for two things.
456 // #1. For used IP addresses, this maps to the
457 // session ID that it's used by.
458 // #2. For un-used IP addresses, this maps to the
459 // index into the pool table that contains that
460 // IP address.
461 //
462
463 int lookup_ipmap(ipt ip)
464 {
465 u8 *a = (u8 *)&ip;
466 char **d = (char **) ip_hash;
467 int s;
468
469 if (!(d = (char **) d[(size_t) *a++])) return 0;
470 if (!(d = (char **) d[(size_t) *a++])) return 0;
471 if (!(d = (char **) d[(size_t) *a++])) return 0;
472
473 s = (ipt) d[(size_t) *a];
474 return s;
475 }
476
477 sessionidt sessionbyip(ipt ip)
478 {
479 int s = lookup_ipmap(ip);
480 CSTAT(call_sessionbyip);
481
482 if (s > 0 && s < MAXSESSION && session[s].tunnel)
483 return s;
484 return 0;
485 }
486
487 //
488 // Take an IP address in HOST byte order and
489 // add it to the sessionid by IP cache.
490 //
491 // (It's actually cached in network order)
492 //
493 static void cache_ipmap(ipt ip, int s)
494 {
495 ipt nip = htonl(ip); // MUST be in network order. I.e. MSB must in be ((char*)(&ip))[0]
496 u8 *a = (u8 *) &nip;
497 char **d = (char **) ip_hash;
498 int i;
499
500 for (i = 0; i < 3; i++)
501 {
502 if (!d[(size_t) a[i]])
503 {
504 if (!(d[(size_t) a[i]] = calloc(256, sizeof (void *))))
505 return;
506 }
507
508 d = (char **) d[(size_t) a[i]];
509 }
510
511 d[(size_t) a[3]] = (char *)((int)s);
512
513 if (s > 0)
514 log(4, ip, s, session[s].tunnel, "Caching ip address %s\n", inet_toa(nip));
515 else if (s == 0)
516 log(4, ip, 0, 0, "Un-caching ip address %s\n", inet_toa(nip));
517 // else a map to an ip pool index.
518 }
519
520 static void uncache_ipmap(ipt ip)
521 {
522 cache_ipmap(ip, 0); // Assign it to the NULL session.
523 }
524
525 //
526 // CLI list to dump current ipcache.
527 //
528 int cmd_show_ipcache(struct cli_def *cli, char *command, char **argv, int argc)
529 {
530 char **d = (char **) ip_hash, **e, **f, **g;
531 int i, j, k, l;
532 int count = 0;
533
534 if (CLI_HELP_REQUESTED)
535 return CLI_HELP_NO_ARGS;
536
537 cli_print(cli, "%7s %s", "Sess#", "IP Address");
538
539 for (i = 0; i < 256; ++i) {
540 if (!d[i]) continue;
541 e = (char**) d[i];
542 for (j = 0; j < 256; ++j) {
543 if (!e[j]) continue;
544 f = (char**) e[j];
545 for (k = 0; k < 256; ++k) {
546 if (!f[k]) continue;
547 g = (char**)f[k];
548 for (l = 0; l < 256; ++l) {
549 if (!g[l]) continue;
550 cli_print(cli, "%7d %d.%d.%d.%d", (int) g[l], i, j, k, l);
551 ++count;
552 }
553 }
554 }
555 }
556 cli_print(cli, "%d entries in cache", count);
557 return CLI_OK;
558 }
559
560
561 // Find session by username, 0 for not found
562 // walled garden users aren't authenticated, so the username is
563 // reasonably useless. Ignore them to avoid incorrect actions
564 //
565 // This is VERY inefficent. Don't call it often. :)
566 //
567 sessionidt sessionbyuser(char *username)
568 {
569 int s;
570 CSTAT(call_sessionbyuser);
571
572 for (s = 1; s < MAXSESSION ; ++s) {
573 if (session[s].walled_garden)
574 continue; // Skip walled garden users.
575
576 if (!strncmp(session[s].user, username, 128))
577 return s;
578
579 }
580 return 0; // Not found.
581 }
582
583 void send_garp(ipt ip)
584 {
585 int s;
586 struct ifreq ifr;
587 u8 mac[6];
588
589 s = socket(PF_INET, SOCK_DGRAM, 0);
590 if (s < 0)
591 {
592 log(0, 0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno));
593 return;
594 }
595 memset(&ifr, 0, sizeof(ifr));
596 strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name) - 1);
597 if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
598 {
599 log(0, 0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno));
600 close(s);
601 return;
602 }
603 memcpy(mac, &ifr.ifr_hwaddr.sa_data, 6*sizeof(char));
604 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
605 {
606 log(0, 0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno));
607 close(s);
608 return;
609 }
610 close(s);
611 sendarp(ifr.ifr_ifindex, mac, ip);
612 }
613
614 // Find session by username, 0 for not found
615 sessiont *sessiontbysessionidt(sessionidt s)
616 {
617 if (!s || s > MAXSESSION) return NULL;
618 return &session[s];
619 }
620
621 sessionidt sessionidtbysessiont(sessiont *s)
622 {
623 sessionidt val = s-session;
624 if (s < session || val > MAXSESSION) return 0;
625 return val;
626 }
627
628 // Handle ARP requests
629 void processarp(u8 * buf, int len)
630 {
631 ipt ip;
632 sessionidt s;
633
634 CSTAT(call_processarp);
635 STAT(arp_recv);
636
637 if (len != 46)
638 {
639 log(0, 0, 0, 0, "Unexpected length ARP %d bytes\n", len);
640 STAT(arp_errors);
641 return;
642 }
643 if (*(u16 *) (buf + 16) != htons(PKTARP))
644 {
645 log(0, 0, 0, 0, "Unexpected ARP type %04X\n", ntohs(*(u16 *) (buf + 16)));
646 STAT(arp_errors);
647 return;
648 }
649 if (*(u16 *) (buf + 18) != htons(0x0001))
650 {
651 log(0, 0, 0, 0, "Unexpected ARP hard type %04X\n", ntohs(*(u16 *) (buf + 18)));
652 STAT(arp_errors);
653 return;
654 }
655 if (*(u16 *) (buf + 20) != htons(PKTIP))
656 {
657 log(0, 0, 0, 0, "Unexpected ARP prot type %04X\n", ntohs(*(u16 *) (buf + 20)));
658 STAT(arp_errors);
659 return;
660 }
661 if (buf[22] != 6)
662 {
663 log(0, 0, 0, 0, "Unexpected ARP hard len %d\n", buf[22]);
664 STAT(arp_errors);
665 return;
666 }
667 if (buf[23] != 4)
668 {
669 log(0, 0, 0, 0, "Unexpected ARP prot len %d\n", buf[23]);
670 STAT(arp_errors);
671 return;
672 }
673 if (*(u16 *) (buf + 24) != htons(0x0001))
674 {
675 log(0, 0, 0, 0, "Unexpected ARP op %04X\n", ntohs(*(u16 *) (buf + 24)));
676 STAT(arp_errors);
677 return;
678 }
679 ip = *(u32 *) (buf + 42);
680 // look up session
681 s = sessionbyip(ip);
682 if (s)
683 {
684 log(3, ntohl(ip), s, session[s].tunnel, "ARP reply for %s\n", inet_toa(ip));
685 memcpy(buf + 4, buf + 10, 6); // set destination as source
686 *(u16 *) (buf + 10) = htons(tapmac[0]); // set source address
687 *(u16 *) (buf + 12) = htons(tapmac[1]);
688 *(u16 *) (buf + 14) = htons(tapmac[2]);
689 *(u16 *) (buf + 24) = htons(0x0002); // ARP reply
690 memcpy(buf + 26, buf + 10, 6); // sender ethernet
691 memcpy(buf + 36, buf + 4, 6); // target ethernet
692 *(u32 *) (buf + 42) = *(u32 *) (buf + 32); // target IP
693 *(u32 *) (buf + 32) = ip; // sender IP
694 write(tapfd, buf, len);
695 STAT(arp_replies);
696 }
697 else
698 {
699 log(3, ntohl(ip), 0, 0, "ARP request for unknown IP %s\n", inet_toa(ip));
700 STAT(arp_discarded);
701 }
702 }
703
704 // actually send a control message for a specific tunnel
705 void tunnelsend(u8 * buf, u16 l, tunnelidt t)
706 {
707 struct sockaddr_in addr;
708
709 CSTAT(call_tunnelsend);
710
711 if (!t)
712 {
713 static int backtrace_count = 0;
714 log(0, 0, 0, t, "tunnelsend called with 0 as tunnel id\n");
715 STAT(tunnel_tx_errors);
716 log_backtrace(backtrace_count, 5)
717 return;
718 }
719
720 if (!tunnel[t].ip)
721 {
722 static int backtrace_count = 0;
723 log(1, 0, 0, t, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
724 log_backtrace(backtrace_count, 5)
725 STAT(tunnel_tx_errors);
726 return;
727 }
728 memset(&addr, 0, sizeof(addr));
729 addr.sin_family = AF_INET;
730 *(u32 *) & addr.sin_addr = htonl(tunnel[t].ip);
731 addr.sin_port = htons(tunnel[t].port);
732
733 // sequence expected, if sequence in message
734 if (*buf & 0x08) *(u16 *) (buf + ((*buf & 0x40) ? 10 : 8)) = htons(tunnel[t].nr);
735
736 // If this is a control message, deal with retries
737 if (*buf & 0x80)
738 {
739 tunnel[t].last = time_now; // control message sent
740 tunnel[t].retry = backoff(tunnel[t].try); // when to resend
741 if (tunnel[t].try > 1)
742 {
743 STAT(tunnel_retries);
744 log(3, tunnel[t].ip, 0, t, "Control message resend try %d\n", tunnel[t].try);
745 }
746 }
747
748 if (sendto(udpfd, buf, l, 0, (void *) &addr, sizeof(addr)) < 0)
749 {
750 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",
751 strerror(errno), udpfd, buf, l, inet_ntoa(addr.sin_addr));
752 STAT(tunnel_tx_errors);
753 return;
754 }
755
756 log_hex(5, "Send Tunnel Data", buf, l);
757 STAT(tunnel_tx_packets);
758 INC_STAT(tunnel_tx_bytes, l);
759 }
760
761 //
762 // Tiny helper function to write data to
763 // the 'tun' device.
764 //
765 int tun_write(u8 * data, int size)
766 {
767 return write(tapfd, data, size);
768 }
769
770 // process outgoing (to tunnel) IP
771 //
772 void processipout(u8 * buf, int len)
773 {
774 sessionidt s;
775 sessiont *sp;
776 tunnelidt t;
777 ipt ip;
778
779 char * data = buf; // Keep a copy of the originals.
780 int size = len;
781
782 u8 b[MAXETHER + 20];
783
784 CSTAT(call_processipout);
785
786 if (len < MIN_IP_SIZE)
787 {
788 log(1, 0, 0, 0, "Short IP, %d bytes\n", len);
789 STAT(tunnel_tx_errors);
790 return;
791 }
792 if (len >= MAXETHER)
793 {
794 log(1, 0, 0, 0, "Oversize IP packet %d bytes\n", len);
795 STAT(tunnel_tx_errors);
796 return;
797 }
798
799 // Skip the tun header
800 buf += 4;
801 len -= 4;
802
803 // Got an IP header now
804 if (*(u8 *)(buf) >> 4 != 4)
805 {
806 log(1, 0, 0, 0, "IP: Don't understand anything except IPv4\n");
807 return;
808 }
809
810 ip = *(u32 *)(buf + 16);
811 if (!(s = sessionbyip(ip)))
812 {
813 // Is this a packet for a session that doesn't exist?
814 static int rate = 0; // Number of ICMP packets we've sent this second.
815 static int last = 0; // Last time we reset the ICMP packet counter 'rate'.
816
817 if (last != time_now) {
818 last = time_now;
819 rate = 0;
820 }
821
822 if (rate++ < config->icmp_rate) // Only send a max of icmp_rate per second.
823 {
824 log(4, 0, 0, 0, "IP: Sending ICMP host unreachable to %s\n", inet_toa(*(u32 *)(buf + 12)));
825 host_unreachable(*(u32 *)(buf + 12), *(u16 *)(buf + 4), ip, buf, (len < 64) ? 64 : len);
826 }
827 return;
828 }
829 t = session[s].tunnel;
830 sp = &session[s];
831
832 if (sp->tbf_out)
833 {
834 // Are we throttling this session?
835 if (config->cluster_iam_master)
836 tbf_queue_packet(sp->tbf_out, data, size);
837 else
838 master_throttle_packet(sp->tbf_out, data, size);
839 return;
840 }
841 else if (sp->walled_garden && !config->cluster_iam_master)
842 {
843 // We are walled-gardening this
844 master_garden_packet(s, data, size);
845 return;
846 }
847
848 // Snooping this session, send it to intercept box
849 if (sp->snoop_ip && sp->snoop_port)
850 snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port);
851
852 log(5, session[s].ip, s, t, "Ethernet -> Tunnel (%d bytes)\n", len);
853
854 // Add on L2TP header
855 {
856 u8 *p = makeppp(b, sizeof(b), buf, len, t, s, PPPIP);
857 if (!p) {
858 log(3, session[s].ip, s, t, "failed to send packet in processipout.\n");
859 return;
860 }
861 tunnelsend(b, len + (p-b), t); // send it...
862 }
863
864 sp->cout += len; // byte count
865 sp->total_cout += len; // byte count
866 sp->pout++;
867 udp_tx += len;
868 sess_count[s].cout += len; // To send to master..
869 }
870
871 //
872 // Helper routine for the TBF filters.
873 // Used to send queued data in to the user!
874 //
875 void send_ipout(sessionidt s, u8 *buf, int len)
876 {
877 sessiont *sp;
878 tunnelidt t;
879 ipt ip;
880
881 u8 b[MAXETHER + 20];
882
883 if (len < 0 || len > MAXETHER) {
884 log(1,0,0,0, "Odd size IP packet: %d bytes\n", len);
885 return;
886 }
887
888 // Skip the tun header
889 buf += 4;
890 len -= 4;
891
892 ip = *(u32 *)(buf + 16);
893
894 if (!session[s].ip)
895 return;
896 t = session[s].tunnel;
897 sp = &session[s];
898
899 log(5, session[s].ip, s, t, "Ethernet -> Tunnel (%d bytes)\n", len);
900
901 // Snooping this session, send it to intercept box
902 if (sp->snoop_ip && sp->snoop_port)
903 snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port);
904
905 // Add on L2TP header
906 {
907 u8 *p = makeppp(b, sizeof(b), buf, len, t, s, PPPIP);
908 if (!p) {
909 log(3, session[s].ip, s, t, "failed to send packet in send_ipout.\n");
910 return;
911 }
912 tunnelsend(b, len + (p-b), t); // send it...
913 }
914 sp->cout += len; // byte count
915 sp->total_cout += len; // byte count
916 sp->pout++;
917 udp_tx += len;
918 sess_count[s].cout += len; // To send to master..
919 }
920
921 // add an AVP (16 bit)
922 void control16(controlt * c, u16 avp, u16 val, u8 m)
923 {
924 u16 l = (m ? 0x8008 : 0x0008);
925 *(u16 *) (c->buf + c->length + 0) = htons(l);
926 *(u16 *) (c->buf + c->length + 2) = htons(0);
927 *(u16 *) (c->buf + c->length + 4) = htons(avp);
928 *(u16 *) (c->buf + c->length + 6) = htons(val);
929 c->length += 8;
930 }
931
932 // add an AVP (32 bit)
933 void control32(controlt * c, u16 avp, u32 val, u8 m)
934 {
935 u16 l = (m ? 0x800A : 0x000A);
936 *(u16 *) (c->buf + c->length + 0) = htons(l);
937 *(u16 *) (c->buf + c->length + 2) = htons(0);
938 *(u16 *) (c->buf + c->length + 4) = htons(avp);
939 *(u32 *) (c->buf + c->length + 6) = htonl(val);
940 c->length += 10;
941 }
942
943 // add an AVP (32 bit)
944 void controls(controlt * c, u16 avp, char *val, u8 m)
945 {
946 u16 l = ((m ? 0x8000 : 0) + strlen(val) + 6);
947 *(u16 *) (c->buf + c->length + 0) = htons(l);
948 *(u16 *) (c->buf + c->length + 2) = htons(0);
949 *(u16 *) (c->buf + c->length + 4) = htons(avp);
950 memcpy(c->buf + c->length + 6, val, strlen(val));
951 c->length += 6 + strlen(val);
952 }
953
954 // add a binary AVP
955 void controlb(controlt * c, u16 avp, char *val, unsigned int len, u8 m)
956 {
957 u16 l = ((m ? 0x8000 : 0) + len + 6);
958 *(u16 *) (c->buf + c->length + 0) = htons(l);
959 *(u16 *) (c->buf + c->length + 2) = htons(0);
960 *(u16 *) (c->buf + c->length + 4) = htons(avp);
961 memcpy(c->buf + c->length + 6, val, len);
962 c->length += 6 + len;
963 }
964
965 // new control connection
966 controlt *controlnew(u16 mtype)
967 {
968 controlt *c;
969 if (!controlfree)
970 c = malloc(sizeof(controlt));
971 else
972 {
973 c = controlfree;
974 controlfree = c->next;
975 }
976 assert(c);
977 c->next = 0;
978 *(u16 *) (c->buf + 0) = htons(0xC802); // flags/ver
979 c->length = 12;
980 control16(c, 0, mtype, 1);
981 return c;
982 }
983
984 // send zero block if nothing is waiting
985 // (ZLB send).
986 void controlnull(tunnelidt t)
987 {
988 u8 buf[12];
989 if (tunnel[t].controlc) // Messages queued; They will carry the ack.
990 return;
991
992 *(u16 *) (buf + 0) = htons(0xC802); // flags/ver
993 *(u16 *) (buf + 2) = htons(12); // length
994 *(u16 *) (buf + 4) = htons(tunnel[t].far); // tunnel
995 *(u16 *) (buf + 6) = htons(0); // session
996 *(u16 *) (buf + 8) = htons(tunnel[t].ns); // sequence
997 *(u16 *) (buf + 10) = htons(tunnel[t].nr); // sequence
998 tunnelsend(buf, 12, t);
999 }
1000
1001 // add a control message to a tunnel, and send if within window
1002 void controladd(controlt * c, tunnelidt t, sessionidt s)
1003 {
1004 *(u16 *) (c->buf + 2) = htons(c->length); // length
1005 *(u16 *) (c->buf + 4) = htons(tunnel[t].far); // tunnel
1006 *(u16 *) (c->buf + 6) = htons(s ? session[s].far : 0); // session
1007 *(u16 *) (c->buf + 8) = htons(tunnel[t].ns); // sequence
1008 tunnel[t].ns++; // advance sequence
1009 // link in message in to queue
1010 if (tunnel[t].controlc)
1011 tunnel[t].controle->next = c;
1012 else
1013 tunnel[t].controls = c;
1014 tunnel[t].controle = c;
1015 tunnel[t].controlc++;
1016 // send now if space in window
1017 if (tunnel[t].controlc <= tunnel[t].window)
1018 {
1019 tunnel[t].try = 0; // first send
1020 tunnelsend(c->buf, c->length, t);
1021 }
1022 }
1023
1024 //
1025 // Throttle or Unthrottle a session
1026 //
1027 // Throttle the data folling through a session
1028 // to be no more than 'throttle' kbit/sec each way.
1029 //
1030 int throttle_session(sessionidt s, int throttle)
1031 {
1032 if (!session[s].tunnel)
1033 return 0; // No-one home.
1034
1035 if (!*session[s].user)
1036 return 0; // User not logged in
1037
1038 if (throttle) {
1039 if (session[s].tbf_in || session[s].tbf_out) {
1040 if (throttle == session[s].throttle)
1041 return 1;
1042
1043 // Currently throttled but the rate is changing.
1044
1045 free_tbf(session[s].tbf_in);
1046 free_tbf(session[s].tbf_out);
1047 }
1048
1049 session[s].tbf_in = new_tbf(s, throttle*1024/4, throttle*1024/8, send_ipin);
1050 session[s].tbf_out = new_tbf(s, throttle*1024/4, throttle*1024/8, send_ipout);
1051
1052 if (throttle != session[s].throttle) { // Changed. Flood to slaves.
1053 session[s].throttle = throttle;
1054 cluster_send_session(s);
1055 }
1056
1057 return 1;
1058 }
1059
1060 // else Unthrottling.
1061
1062 if (!session[s].tbf_in && !session[s].tbf_out && !session[s].throttle)
1063 return 0;
1064
1065 free_tbf(session[s].tbf_in);
1066 session[s].tbf_in = 0;
1067
1068 free_tbf(session[s].tbf_out);
1069 session[s].tbf_out = 0;
1070
1071 if (throttle != session[s].throttle) { // Changed. Flood to slaves.
1072 session[s].throttle = throttle;
1073 cluster_send_session(s);
1074 }
1075
1076 return 0;
1077 }
1078
1079 // start tidy shutdown of session
1080 void sessionshutdown(sessionidt s, char *reason)
1081 {
1082 int dead = session[s].die;
1083 int walled_garden = session[s].walled_garden;
1084
1085
1086 CSTAT(call_sessionshutdown);
1087
1088 if (!session[s].tunnel)
1089 {
1090 log(3, session[s].ip, s, session[s].tunnel, "Called sessionshutdown on a session with no tunnel.\n");
1091 return; // not a live session
1092 }
1093
1094 if (!session[s].die)
1095 log(2, 0, s, session[s].tunnel, "Shutting down session %d: %s\n", s, reason);
1096
1097 session[s].die = now() + 150; // Clean up in 15 seconds
1098
1099 {
1100 struct param_kill_session data = { &tunnel[session[s].tunnel], &session[s] };
1101 run_plugins(PLUGIN_KILL_SESSION, &data);
1102 }
1103
1104 // RADIUS Stop message
1105 if (session[s].opened && !walled_garden && !dead) {
1106 u16 r = session[s].radius;
1107 if (!r)
1108 {
1109 if (!(r = radiusnew(s)))
1110 {
1111 log(1, 0, s, session[s].tunnel, "No free RADIUS sessions for Stop message\n");
1112 STAT(radius_overflow);
1113 }
1114 else
1115 {
1116 int n;
1117 for (n = 0; n < 15; n++)
1118 radius[r].auth[n] = rand();
1119 }
1120 }
1121 if (r && radius[r].state != RADIUSSTOP)
1122 radiussend(r, RADIUSSTOP); // stop, if not already trying
1123 }
1124
1125 if (session[s].ip)
1126 { // IP allocated, clear and unroute
1127 int r;
1128 for (r = 0; r < MAXROUTE && session[s].route[r].ip; r++)
1129 {
1130 routeset(s, session[s].route[r].ip, session[s].route[r].mask, session[s].ip, 0);
1131 session[s].route[r].ip = 0;
1132 }
1133
1134 if (session[s].ip_pool_index == -1) // static ip
1135 {
1136 routeset(s, session[s].ip, 0, 0, 0); // Delete route.
1137 session[s].ip = 0;
1138 }
1139 else
1140 free_ip_address(s);
1141
1142 if (session[s].throttle) // Unthrottle if throttled.
1143 throttle_session(s, 0);
1144 }
1145 { // Send CDN
1146 controlt *c = controlnew(14); // sending CDN
1147 control16(c, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
1148 control16(c, 14, s, 1); // assigned session (our end)
1149 controladd(c, session[s].tunnel, s); // send the message
1150 }
1151 cluster_send_session(s);
1152 }
1153
1154 void sendipcp(tunnelidt t, sessionidt s)
1155 {
1156 u8 buf[MAXCONTROL];
1157 u16 r = session[s].radius;
1158 u8 *q;
1159
1160 CSTAT(call_sendipcp);
1161
1162 if (!r)
1163 r = radiusnew(s);
1164
1165 if (radius[r].state != RADIUSIPCP)
1166 {
1167 radius[r].state = RADIUSIPCP;
1168 radius[r].try = 0;
1169 }
1170
1171 radius[r].retry = backoff(radius[r].try++);
1172 if (radius[r].try > 10)
1173 {
1174 radiusclear(r, s); // Clear radius session.
1175 sessionshutdown(s, "No reply on IPCP");
1176 return;
1177 }
1178
1179 q = makeppp(buf,sizeof(buf), 0, 0, t, s, PPPIPCP);
1180 if (!q) {
1181 log(3, session[s].ip, s, t, "failed to send packet in sendipcp.\n");
1182 return;
1183 }
1184
1185 *q = ConfigReq;
1186 q[1] = r << RADIUS_SHIFT; // ID, dont care, we only send one type of request
1187 *(u16 *) (q + 2) = htons(10);
1188 q[4] = 3;
1189 q[5] = 6;
1190 *(u32 *) (q + 6) = config->bind_address; // send my IP
1191 tunnelsend(buf, 10 + (q - buf), t); // send it
1192 session[s].flags &= ~SF_IPCP_ACKED; // Clear flag.
1193 }
1194
1195 // kill a session now
1196 void sessionkill(sessionidt s, char *reason)
1197 {
1198
1199 CSTAT(call_sessionkill);
1200
1201 sessionshutdown(s, reason); // close radius/routes, etc.
1202 if (session[s].radius)
1203 radiusclear(session[s].radius, 0); // cant send clean accounting data, session is killed
1204
1205 log(2, 0, s, session[s].tunnel, "Kill session %d (%s): %s\n", s, session[s].user, reason);
1206
1207 throttle_session(s, 0); // Force session to be un-throttle. Free'ing TBF structures.
1208
1209 memset(&session[s], 0, sizeof(session[s]));
1210 session[s].tunnel = T_FREE; // Mark it as free.
1211 session[s].next = sessionfree;
1212 sessionfree = s;
1213 cluster_send_session(s);
1214 }
1215
1216 // kill a tunnel now
1217 void tunnelkill(tunnelidt t, char *reason)
1218 {
1219 sessionidt s;
1220 controlt *c;
1221
1222 CSTAT(call_tunnelkill);
1223
1224 tunnel[t].state = TUNNELDIE;
1225
1226 // free control messages
1227 while ((c = tunnel[t].controls))
1228 {
1229 controlt * n = c->next;
1230 tunnel[t].controls = n;
1231 tunnel[t].controlc--;
1232 c->next = controlfree;
1233 controlfree = c;
1234 }
1235 // kill sessions
1236 for (s = 1; s < MAXSESSION; s++)
1237 if (session[s].tunnel == t)
1238 sessionkill(s, reason);
1239
1240 // free tunnel
1241 tunnelclear(t);
1242 cluster_send_tunnel(t);
1243 log(1, 0, 0, t, "Kill tunnel %d: %s\n", t, reason);
1244 tunnel[t].die = 0;
1245 tunnel[t].state = TUNNELFREE;
1246 }
1247
1248 // shut down a tunnel cleanly
1249 void tunnelshutdown(tunnelidt t, char *reason)
1250 {
1251 sessionidt s;
1252
1253 CSTAT(call_tunnelshutdown);
1254
1255 if (!tunnel[t].last || !tunnel[t].far || tunnel[t].state == TUNNELFREE)
1256 {
1257 // never set up, can immediately kill
1258 tunnelkill(t, reason);
1259 return;
1260 }
1261 log(1, 0, 0, t, "Shutting down tunnel %d (%s)\n", t, reason);
1262
1263 // close session
1264 for (s = 1; s < MAXSESSION; s++)
1265 if (session[s].tunnel == t)
1266 sessionkill(s, reason);
1267
1268 tunnel[t].state = TUNNELDIE;
1269 tunnel[t].die = now() + 700; // Clean up in 70 seconds
1270 cluster_send_tunnel(t);
1271 // TBA - should we wait for sessions to stop?
1272 { // Send StopCCN
1273 controlt *c = controlnew(4); // sending StopCCN
1274 control16(c, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message
1275 control16(c, 9, t, 1); // assigned tunnel (our end)
1276 controladd(c, t, 0); // send the message
1277 }
1278 }
1279
1280 // read and process packet on tunnel (UDP)
1281 void processudp(u8 * buf, int len, struct sockaddr_in *addr)
1282 {
1283 char *chapresponse = NULL;
1284 u16 l = len, t = 0, s = 0, ns = 0, nr = 0;
1285 u8 *p = buf + 2;
1286
1287
1288 CSTAT(call_processudp);
1289
1290 udp_rx += len;
1291 udp_rx_pkt++;
1292 log_hex(5, "UDP Data", buf, len);
1293 STAT(tunnel_rx_packets);
1294 INC_STAT(tunnel_rx_bytes, len);
1295 if (len < 6)
1296 {
1297 log(1, ntohl(addr->sin_addr.s_addr), 0, 0, "Short UDP, %d bytes\n", len);
1298 STAT(tunnel_rx_errors);
1299 return;
1300 }
1301 if ((buf[1] & 0x0F) != 2)
1302 {
1303 log(1, ntohl(addr->sin_addr.s_addr), 0, 0, "Bad L2TP ver %d\n", (buf[1] & 0x0F) != 2);
1304 STAT(tunnel_rx_errors);
1305 return;
1306 }
1307 if (*buf & 0x40)
1308 { // length
1309 l = ntohs(*(u16 *) p);
1310 p += 2;
1311 }
1312 t = ntohs(*(u16 *) p);
1313 p += 2;
1314 s = ntohs(*(u16 *) p);
1315 p += 2;
1316 if (s >= MAXSESSION)
1317 {
1318 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Received UDP packet with invalid session ID\n");
1319 STAT(tunnel_rx_errors);
1320 return;
1321 }
1322 if (t >= MAXTUNNEL)
1323 {
1324 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Received UDP packet with invalid tunnel ID\n");
1325 STAT(tunnel_rx_errors);
1326 return;
1327 }
1328 if (*buf & 0x08)
1329 { // ns/nr
1330 ns = ntohs(*(u16 *) p);
1331 p += 2;
1332 nr = ntohs(*(u16 *) p);
1333 p += 2;
1334 }
1335 if (*buf & 0x02)
1336 { // offset
1337 u16 o = ntohs(*(u16 *) p);
1338 p += o + 2;
1339 }
1340 if ((p - buf) > l)
1341 {
1342 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Bad length %d>%d\n", (p - buf), l);
1343 STAT(tunnel_rx_errors);
1344 return;
1345 }
1346 l -= (p - buf);
1347 if (*buf & 0x80)
1348 { // control
1349 u16 message = 0xFFFF; // message type
1350 u8 fatal = 0;
1351 u8 mandatorymessage = 0;
1352 u8 chap = 0; // if CHAP being used
1353 u16 asession = 0; // assigned session
1354 u32 amagic = 0; // magic number
1355 u8 aflags = 0; // flags from last LCF
1356 u16 version = 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1357 int requestchap = 0; // do we request PAP instead of original CHAP request?
1358 char called[MAXTEL] = ""; // called number
1359 char calling[MAXTEL] = ""; // calling number
1360
1361 if (!config->cluster_iam_master) {
1362 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port);
1363 return;
1364 }
1365
1366 if ((*buf & 0xCA) != 0xC8)
1367 {
1368 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Bad control header %02X\n", *buf);
1369 STAT(tunnel_rx_errors);
1370 return;
1371 }
1372 log(3, ntohl(addr->sin_addr.s_addr), s, t, "Control message (%d bytes): (unacked %d) l-ns %d l-nr %d r-ns %d r-nr %d\n",
1373 l, tunnel[t].controlc, tunnel[t].ns, tunnel[t].nr, ns, nr);
1374 // if no tunnel specified, assign one
1375 if (!t)
1376 {
1377 int i;
1378
1379 //
1380 // Is this a duplicate of the first packet? (SCCRQ)
1381 //
1382 for ( i = 1; i <= config->cluster_highest_tunnelid ; ++i) {
1383 if (tunnel[t].state != TUNNELOPENING ||
1384 tunnel[t].ip != ntohl(*(ipt *) & addr->sin_addr) ||
1385 tunnel[t].port != ntohs(addr->sin_port) )
1386 continue;
1387 t = i;
1388 break;
1389 }
1390 }
1391
1392 if (!t) {
1393 if (!(t = new_tunnel()))
1394 {
1395 log(1, ntohl(addr->sin_addr.s_addr), 0, 0, "No more tunnels\n");
1396 STAT(tunnel_overflow);
1397 return;
1398 }
1399 tunnelclear(t);
1400 tunnel[t].ip = ntohl(*(ipt *) & addr->sin_addr);
1401 tunnel[t].port = ntohs(addr->sin_port);
1402 tunnel[t].window = 4; // default window
1403 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);
1404 STAT(tunnel_created);
1405 }
1406
1407 // This is used to time out old tunnels
1408 tunnel[t].lastrec = time_now;
1409
1410 // check sequence of this message
1411 {
1412 int skip = tunnel[t].window; // track how many in-window packets are still in queue
1413 // some to clear maybe?
1414 while (tunnel[t].controlc && (((tunnel[t].ns - tunnel[t].controlc) - nr) & 0x8000))
1415 {
1416 controlt *c = tunnel[t].controls;
1417 tunnel[t].controls = c->next;
1418 tunnel[t].controlc--;
1419 c->next = controlfree;
1420 controlfree = c;
1421 skip--;
1422 tunnel[t].try = 0; // we have progress
1423 }
1424
1425 // If the 'ns' just received is not the 'nr' we're
1426 // expecting, just send an ack and drop it.
1427 //
1428 // if 'ns' is less, then we got a retransmitted packet.
1429 // if 'ns' is greater than missed a packet. Either way
1430 // we should ignore it.
1431 if (ns != tunnel[t].nr)
1432 {
1433 // is this the sequence we were expecting?
1434 log(1, ntohl(addr->sin_addr.s_addr), 0, t, " Out of sequence tunnel %d, (%d is not the expected %d)\n", t, ns, tunnel[t].nr);
1435 STAT(tunnel_rx_errors);
1436
1437 if (l) // Is this not a ZLB?
1438 controlnull(t);
1439 return;
1440 }
1441 // receiver advance (do here so quoted correctly in any sends below)
1442 if (l) tunnel[t].nr = (ns + 1);
1443 if (skip < 0) skip = 0;
1444 if (skip < tunnel[t].controlc)
1445 {
1446 // some control packets can now be sent that were previous stuck out of window
1447 int tosend = tunnel[t].window - skip;
1448 controlt *c = tunnel[t].controls;
1449 while (c && skip)
1450 {
1451 c = c->next;
1452 skip--;
1453 }
1454 while (c && tosend)
1455 {
1456 tunnel[t].try = 0; // first send
1457 tunnelsend(c->buf, c->length, t);
1458 c = c->next;
1459 tosend--;
1460 }
1461 }
1462 if (!tunnel[t].controlc)
1463 tunnel[t].retry = 0; // caught up
1464 }
1465 if (l)
1466 { // if not a null message
1467 // process AVPs
1468 while (l && !(fatal & 0x80))
1469 {
1470 u16 n = (ntohs(*(u16 *) p) & 0x3FF);
1471 u8 *b = p;
1472 u8 flags = *p;
1473 u16 mtype;
1474 p += n; // next
1475 if (l < n)
1476 {
1477 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Invalid length in AVP\n");
1478 STAT(tunnel_rx_errors);
1479 fatal = flags;
1480 return;
1481 }
1482 l -= n;
1483 if (flags & 0x40)
1484 {
1485 // handle hidden AVPs
1486 if (!*config->l2tpsecret)
1487 {
1488 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Hidden AVP requested, but no L2TP secret.\n");
1489 fatal = flags;
1490 continue;
1491 }
1492 if (!session[s].random_vector_length)
1493 {
1494 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Hidden AVP requested, but no random vector.\n");
1495 fatal = flags;
1496 continue;
1497 }
1498 log(4, ntohl(addr->sin_addr.s_addr), s, t, "Hidden AVP\n");
1499 }
1500 if (*b & 0x3C)
1501 {
1502 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Unrecognised AVP flags %02X\n", *b);
1503 fatal = flags;
1504 continue; // next
1505 }
1506 b += 2;
1507 if (*(u16 *) (b))
1508 {
1509 log(2, ntohl(addr->sin_addr.s_addr), s, t, "Unknown AVP vendor %d\n", ntohs(*(u16 *) (b)));
1510 fatal = flags;
1511 continue; // next
1512 }
1513 b += 2;
1514 mtype = ntohs(*(u16 *) (b));
1515 b += 2;
1516 n -= 6;
1517
1518 log(4, ntohl(addr->sin_addr.s_addr), s, t, " AVP %d (%s) len %d\n", mtype, avpnames[mtype], n);
1519 switch (mtype)
1520 {
1521 case 0: // message type
1522 message = ntohs(*(u16 *) b);
1523 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Message type = %d (%s)\n", *b,
1524 l2tp_message_types[message]);
1525 mandatorymessage = flags;
1526 break;
1527 case 1: // result code
1528 {
1529 u16 rescode = ntohs(*(u16 *)(b));
1530 const char* resdesc = "(unknown)";
1531 if (message == 4) { /* StopCCN */
1532 if (rescode <= MAX_STOPCCN_RESULT_CODE)
1533 resdesc = stopccn_result_codes[rescode];
1534 } else if (message == 14) { /* CDN */
1535 if (rescode <= MAX_CDN_RESULT_CODE)
1536 resdesc = cdn_result_codes[rescode];
1537 }
1538
1539 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Result Code %d: %s\n",
1540 rescode, resdesc);
1541 if (n >= 4) {
1542 u16 errcode = ntohs(*(u16 *)(b + 2));
1543 const char* errdesc = "(unknown)";
1544 if (errcode <= MAX_ERROR_CODE)
1545 errdesc = error_codes[errcode];
1546 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Error Code %d: %s\n",
1547 errcode, errdesc);
1548 }
1549 if (n > 4) {
1550 /* %*s doesn't work?? */
1551 char *buf = (char *)strndup(b+4, n-4);
1552 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Error String: %s\n",
1553 buf);
1554 free(buf);
1555 }
1556 break;
1557 }
1558 break;
1559 case 2: // protocol version
1560 {
1561 version = ntohs(*(u16 *) (b));
1562 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Protocol version = %d\n", version);
1563 if (version && version != 0x0100)
1564 { // allow 0.0 and 1.0
1565 log(1, ntohl(addr->sin_addr.s_addr), s, t, " Bad protocol version %04X\n",
1566 version);
1567 fatal = flags;
1568 continue; // next
1569 }
1570 }
1571 break;
1572 case 3: // framing capabilities
1573 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Framing capabilities\n");
1574 break;
1575 case 4: // bearer capabilities
1576 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Bearer capabilities\n");
1577 break;
1578 case 5: // tie breaker
1579 // We never open tunnels, so we don't care about tie breakers
1580 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Tie breaker\n");
1581 continue;
1582 case 6: // firmware revision
1583 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Firmware revision\n");
1584 break;
1585 case 7: // host name
1586 memset(tunnel[t].hostname, 0, 128);
1587 memcpy(tunnel[t].hostname, b, (n >= 127) ? 127 : n);
1588 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Tunnel hostname = \"%s\"\n", tunnel[t].hostname);
1589 // TBA - to send to RADIUS
1590 break;
1591 case 8: // vendor name
1592 memset(tunnel[t].vendor, 0, sizeof(tunnel[t].vendor));
1593 memcpy(tunnel[t].vendor, b, (n >= sizeof(tunnel[t].vendor) - 1) ? sizeof(tunnel[t].vendor) - 1 : n);
1594 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Vendor name = \"%s\"\n", tunnel[t].vendor);
1595 break;
1596 case 9: // assigned tunnel
1597 tunnel[t].far = ntohs(*(u16 *) (b));
1598 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Remote tunnel id = %d\n", tunnel[t].far);
1599 break;
1600 case 10: // rx window
1601 tunnel[t].window = ntohs(*(u16 *) (b));
1602 if (!tunnel[t].window)
1603 tunnel[t].window = 1; // window of 0 is silly
1604 log(4, ntohl(addr->sin_addr.s_addr), s, t, " rx window = %d\n", tunnel[t].window);
1605 break;
1606 case 11: // Challenge
1607 {
1608 log(4, ntohl(addr->sin_addr.s_addr), s, t, " LAC requested CHAP authentication for tunnel\n");
1609 build_chap_response(b, 2, n, &chapresponse);
1610 }
1611 break;
1612 case 14: // assigned session
1613 asession = session[s].far = ntohs(*(u16 *) (b));
1614 log(4, ntohl(addr->sin_addr.s_addr), s, t, " assigned session = %d\n", asession);
1615 break;
1616 case 15: // call serial number
1617 log(4, ntohl(addr->sin_addr.s_addr), s, t, " call serial number = %d\n", ntohl(*(u32 *)b));
1618 break;
1619 case 18: // bearer type
1620 log(4, ntohl(addr->sin_addr.s_addr), s, t, " bearer type = %d\n", ntohl(*(u32 *)b));
1621 // TBA - for RADIUS
1622 break;
1623 case 19: // framing type
1624 log(4, ntohl(addr->sin_addr.s_addr), s, t, " framing type = %d\n", ntohl(*(u32 *)b));
1625 // TBA
1626 break;
1627 case 21: // called number
1628 memset(called, 0, MAXTEL);
1629 memcpy(called, b, (n >= MAXTEL) ? (MAXTEL-1) : n);
1630 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Called <%s>\n", called);
1631 break;
1632 case 22: // calling number
1633 memset(calling, 0, MAXTEL);
1634 memcpy(calling, b, (n >= MAXTEL) ? (MAXTEL-1) : n);
1635 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Calling <%s>\n", calling);
1636 break;
1637 case 24: // tx connect speed
1638 if (n == 4)
1639 {
1640 session[s].tx_connect_speed = ntohl(*(u32 *)b);
1641 }
1642 else
1643 {
1644 // AS5300s send connect speed as a string
1645 char tmp[30] = {0};
1646 memcpy(tmp, b, (n >= 30) ? 30 : n);
1647 session[s].tx_connect_speed = atol(tmp);
1648 }
1649 log(4, ntohl(addr->sin_addr.s_addr), s, t, " TX connect speed <%u>\n",
1650 session[s].tx_connect_speed);
1651 break;
1652 case 38: // rx connect speed
1653 if (n == 4)
1654 {
1655 session[s].rx_connect_speed = ntohl(*(u32 *)b);
1656 }
1657 else
1658 {
1659 // AS5300s send connect speed as a string
1660 char tmp[30] = {0};
1661 memcpy(tmp, b, (n >= 30) ? 30 : n);
1662 session[s].rx_connect_speed = atol(tmp);
1663 }
1664 log(4, ntohl(addr->sin_addr.s_addr), s, t, " RX connect speed <%u>\n",
1665 session[s].rx_connect_speed);
1666 break;
1667 case 25: // Physical Channel ID
1668 {
1669 u32 tmp = ntohl(*(u32 *)b);
1670 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Physical Channel ID <%X>\n", tmp);
1671 break;
1672 }
1673 case 29: // Proxy Authentication Type
1674 {
1675 u16 authtype = ntohs(*(u16 *)b);
1676 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth Type %d (%s)\n",
1677 authtype, authtypes[authtype]);
1678 requestchap = (authtype == 2);
1679 break;
1680 }
1681 case 30: // Proxy Authentication Name
1682 {
1683 char authname[64] = {0};
1684 memcpy(authname, b, (n > 63) ? 63 : n);
1685 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth Name (%s)\n",
1686 authname);
1687 break;
1688 }
1689 case 31: // Proxy Authentication Challenge
1690 {
1691 memcpy(radius[session[s].radius].auth, b, 16);
1692 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth Challenge\n");
1693 break;
1694 }
1695 case 32: // Proxy Authentication ID
1696 {
1697 u16 authid = ntohs(*(u16 *)(b));
1698 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth ID (%d)\n",
1699 authid);
1700 if (session[s].radius)
1701 radius[session[s].radius].id = authid;
1702 break;
1703 }
1704 case 33: // Proxy Authentication Response
1705 {
1706 char authresp[64] = {0};
1707 memcpy(authresp, b, (n > 63) ? 63 : n);
1708 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth Response\n");
1709 break;
1710 }
1711 case 27: // last send lcp
1712 { // find magic number
1713 u8 *p = b, *e = p + n;
1714 while (p < e && p[1])
1715 {
1716 if (*p == 5 && p[1] == 6)
1717 amagic = ntohl(*(u32 *) (p + 2));
1718 else if (*p == 3 && p[1] == 5 && *(u16 *) (p + 2) == htons(PPPCHAP) && p[4] == 5)
1719 chap = 1;
1720 else if (*p == 7)
1721 aflags |= SESSIONPFC;
1722 else if (*p == 8)
1723 aflags |= SESSIONACFC;
1724 p += p[1];
1725 }
1726
1727 {
1728 char tmp[500] = {0};
1729 tmp[0] = ConfigReq;
1730 memcpy((tmp + 1), b, n);
1731 }
1732 }
1733 break;
1734 case 28: // last recv lcp confreq
1735 {
1736 char tmp[500] = {0};
1737 tmp[0] = ConfigReq;
1738 memcpy((tmp + 1), b, n);
1739 break;
1740 }
1741 case 26: // Initial Received LCP CONFREQ
1742 {
1743 char tmp[500] = {0};
1744 tmp[0] = ConfigReq;
1745 memcpy((tmp + 1), b, n);
1746 }
1747 break;
1748 case 39: // seq required - we control it as an LNS anyway...
1749 break;
1750 case 36: // Random Vector
1751 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Random Vector received. Enabled AVP Hiding.\n");
1752 memset(session[s].random_vector, 0, sizeof(session[s].random_vector));
1753 memcpy(session[s].random_vector, b, n);
1754 session[s].random_vector_length = n;
1755 break;
1756 default:
1757 log(2, ntohl(addr->sin_addr.s_addr), s, t, " Unknown AVP type %d\n", mtype);
1758 fatal = flags;
1759 continue; // next
1760 }
1761 }
1762 // process message
1763 if (fatal & 0x80)
1764 tunnelshutdown(t, "Unknown Mandatory AVP");
1765 else
1766 switch (message)
1767 {
1768 case 1: // SCCRQ - Start Control Connection Request
1769 {
1770 controlt *c = controlnew(2); // sending SCCRP
1771 control16(c, 2, version, 1); // protocol version
1772 control32(c, 3, 3, 1); // framing
1773 controls(c, 7, tunnel[t].hostname, 1); // host name (TBA)
1774 if (chapresponse) controlb(c, 13, chapresponse, 16, 1); // Challenge response
1775 control16(c, 9, t, 1); // assigned tunnel
1776 controladd(c, t, s); // send the resply
1777 }
1778 tunnel[t].state = TUNNELOPENING;
1779 break;
1780 case 2: // SCCRP
1781 tunnel[t].state = TUNNELOPEN;
1782 break;
1783 case 3: // SCCN
1784 tunnel[t].state = TUNNELOPEN;
1785 controlnull(t); // ack
1786 break;
1787 case 4: // StopCCN
1788 controlnull(t); // ack
1789 tunnelshutdown(t, "Stopped"); // Shut down cleanly
1790 tunnelkill(t, "Stopped"); // Immediately force everything dead
1791 break;
1792 case 6: // HELLO
1793 controlnull(t); // simply ACK
1794 break;
1795 case 7: // OCRQ
1796 // TBA
1797 break;
1798 case 8: // OCRO
1799 // TBA
1800 break;
1801 case 9: // OCCN
1802 // TBA
1803 break;
1804 case 10: // ICRQ
1805 if (!sessionfree)
1806 {
1807 STAT(session_overflow);
1808 tunnelshutdown(t, "No free sessions");
1809 }
1810 else
1811 {
1812 u16 r;
1813 controlt *c;
1814
1815 s = sessionfree;
1816 sessionfree = session[s].next;
1817 memset(&session[s], 0, sizeof(session[s]));
1818
1819 if (s > config->cluster_highest_sessionid)
1820 config->cluster_highest_sessionid = s;
1821
1822 // make a RADIUS session
1823 if (!(r = radiusnew(s)))
1824 {
1825 log(1, ntohl(addr->sin_addr.s_addr), s, t, "No free RADIUS sessions for ICRQ\n");
1826 sessionkill(s, "no free RADIUS sesions");
1827 return;
1828 }
1829
1830 c = controlnew(11); // sending ICRP
1831 session[s].id = sessionid++;
1832 session[s].opened = time(NULL);
1833 session[s].tunnel = t;
1834 session[s].far = asession;
1835 session[s].last_packet = time_now;
1836 log(3, ntohl(addr->sin_addr.s_addr), s, t, "New session (%d/%d)\n", tunnel[t].far, session[s].far);
1837 control16(c, 14, s, 1); // assigned session
1838 controladd(c, t, s); // send the reply
1839 {
1840 // Generate a random challenge
1841 int n;
1842 for (n = 0; n < 15; n++)
1843 radius[r].auth[n] = rand();
1844 }
1845 strncpy(radius[r].calling, calling, sizeof(radius[r].calling) - 1);
1846 strncpy(session[s].called, called, sizeof(session[s].called) - 1);
1847 strncpy(session[s].calling, calling, sizeof(session[s].calling) - 1);
1848 STAT(session_created);
1849 }
1850 break;
1851 case 11: // ICRP
1852 // TBA
1853 break;
1854 case 12: // ICCN
1855 session[s].magic = amagic; // set magic number
1856 session[s].l2tp_flags = aflags; // set flags received
1857 log(3, ntohl(addr->sin_addr.s_addr), s, t, "Magic %X Flags %X\n", amagic, aflags);
1858 controlnull(t); // ack
1859 // In CHAP state, request PAP instead
1860 if (requestchap)
1861 initlcp(t, s);
1862 break;
1863 case 14: // CDN
1864 controlnull(t); // ack
1865 sessionshutdown(s, "Closed (Received CDN)");
1866 break;
1867 case 0xFFFF:
1868 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Missing message type\n");
1869 break;
1870 default:
1871 STAT(tunnel_rx_errors);
1872 if (mandatorymessage & 0x80)
1873 tunnelshutdown(t, "Unknown message");
1874 else
1875 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Unknown message type %d\n", message);
1876 break;
1877 }
1878 if (chapresponse) free(chapresponse);
1879 cluster_send_tunnel(t);
1880 }
1881 else
1882 {
1883 log(4, 0, s, t, " Got a ZLB ack\n");
1884 }
1885 }
1886 else
1887 { // data
1888 u16 prot;
1889
1890 log_hex(5, "Receive Tunnel Data", p, l);
1891 if (l > 2 && p[0] == 0xFF && p[1] == 0x03)
1892 { // HDLC address header, discard
1893 p += 2;
1894 l -= 2;
1895 }
1896 if (l < 2)
1897 {
1898 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Short ppp length %d\n", l);
1899 STAT(tunnel_rx_errors);
1900 return;
1901 }
1902 if (*p & 1)
1903 {
1904 prot = *p++;
1905 l--;
1906 }
1907 else
1908 {
1909 prot = ntohs(*(u16 *) p);
1910 p += 2;
1911 l -= 2;
1912 }
1913
1914 if (s && !session[s].tunnel) // Is something wrong??
1915 {
1916 if (!config->cluster_iam_master)
1917 {
1918 // Pass it off to the master to deal with..
1919 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port);
1920 return;
1921 }
1922
1923
1924 log(1, ntohl(addr->sin_addr.s_addr), s, t, "UDP packet contains session %d "
1925 "but no session[%d].tunnel exists (LAC said"
1926 " tunnel = %d). Dropping packet.\n", s, s, t);
1927 STAT(tunnel_rx_errors);
1928 return;
1929 }
1930
1931 if (session[s].die)
1932 {
1933 log(3, ntohl(addr->sin_addr.s_addr), s, t, "Session %d is closing. Don't process PPP packets\n", s);
1934 // I'm pretty sure this isn't right -- mo.
1935 // return; // closing session, PPP not processed
1936 }
1937 if (prot == PPPPAP)
1938 {
1939 session[s].last_packet = time_now;
1940 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
1941 processpap(t, s, p, l);
1942 }
1943 else if (prot == PPPCHAP)
1944 {
1945 session[s].last_packet = time_now;
1946 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
1947 processchap(t, s, p, l);
1948 }
1949 else if (prot == PPPLCP)
1950 {
1951 session[s].last_packet = time_now;
1952 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
1953 processlcp(t, s, p, l);
1954 }
1955 else if (prot == PPPIPCP)
1956 {
1957 session[s].last_packet = time_now;
1958 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
1959 processipcp(t, s, p, l);
1960 }
1961 else if (prot == PPPCCP)
1962 {
1963 session[s].last_packet = time_now;
1964 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
1965 processccp(t, s, p, l);
1966 }
1967 else if (prot == PPPIP)
1968 {
1969 if (!config->cluster_iam_master)
1970 {
1971 // We're a slave. Should we forward this packet to the master?
1972
1973 // Is this a walled garden session, or something that needs it's
1974 // idle time updated??
1975
1976 // Maintain the idle timeouts on the master. If this would
1977 // significantly reset the idletimeout, run it via the master
1978 // to refresh the master's idle timer.
1979 // Not sure this is ideal: It may re-order packets.
1980
1981 if (session[s].walled_garden || (session[s].last_packet + (ECHO_TIMEOUT/2)) < time_now)
1982 {
1983 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port);
1984 session[s].last_packet = time_now;
1985 return;
1986 }
1987 // fall through to processipin.
1988 } else
1989 session[s].last_packet = time_now;
1990 processipin(t, s, p, l);
1991 }
1992 else
1993 {
1994 STAT(tunnel_rx_errors);
1995 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Unknown PPP protocol %04X\n", prot);
1996 }
1997 }
1998 }
1999
2000 // read and process packet on tap
2001 void processtap(u8 * buf, int len)
2002 {
2003 log_hex(5, "Receive TAP Data", buf, len);
2004 STAT(tap_rx_packets);
2005 INC_STAT(tap_rx_bytes, len);
2006
2007 CSTAT(call_processtap);
2008
2009 eth_rx_pkt++;
2010 eth_rx += len;
2011 if (len < 22)
2012 {
2013 log(1, 0, 0, 0, "Short tap packet %d bytes\n", len);
2014 STAT(tap_rx_errors);
2015 return;
2016 }
2017 if (*(u16 *) (buf + 2) == htons(PKTARP)) // ARP
2018 processarp(buf, len);
2019 else if (*(u16 *) (buf + 2) == htons(PKTIP)) // IP
2020 processipout(buf, len);
2021 // Else discard.
2022 }
2023
2024 //
2025 // Maximum number of actions to complete.
2026 // This is to avoid sending out too many packets
2027 // at once.
2028 #define MAX_ACTIONS 500
2029
2030 int regular_cleanups(void)
2031 {
2032 static sessionidt s = 0; // Next session to check for actions on.
2033 tunnelidt t;
2034 int count=0,i;
2035 u16 r;
2036 static clockt next_acct = 0;
2037
2038 log(3, 0, 0, 0, "Begin regular cleanup\n");
2039
2040 for (r = 1; r < MAXRADIUS; r++)
2041 {
2042 if (!radius[r].state)
2043 continue;
2044 if (radius[r].retry)
2045 {
2046 if (radius[r].retry <= TIME)
2047 radiusretry(r);
2048 } else
2049 radius[r].retry = backoff(radius[r].try+1); // Is this really needed? --mo
2050 }
2051 for (t = 1; t <= config->cluster_highest_tunnelid; t++)
2052 {
2053 // check for expired tunnels
2054 if (tunnel[t].die && tunnel[t].die <= TIME)
2055 {
2056 STAT(tunnel_timeout);
2057 tunnelkill(t, "Expired");
2058 continue;
2059 }
2060 // check for message resend
2061 if (tunnel[t].retry && tunnel[t].controlc)
2062 {
2063 // resend pending messages as timeout on reply
2064 if (tunnel[t].retry <= TIME)
2065 {
2066 controlt *c = tunnel[t].controls;
2067 u8 w = tunnel[t].window;
2068 tunnel[t].try++; // another try
2069 if (tunnel[t].try > 5)
2070 tunnelkill(t, "Timeout on control message"); // game over
2071 else
2072 while (c && w--)
2073 {
2074 tunnelsend(c->buf, c->length, t);
2075 c = c->next;
2076 }
2077 }
2078 }
2079 // Send hello
2080 if (tunnel[t].state == TUNNELOPEN && tunnel[t].lastrec < TIME + 600)
2081 {
2082 controlt *c = controlnew(6); // sending HELLO
2083 controladd(c, t, 0); // send the message
2084 log(3, tunnel[t].ip, 0, t, "Sending HELLO message\n");
2085 }
2086 }
2087
2088 // Check for sessions that have been killed from the CLI
2089 if (cli_session_kill[0])
2090 {
2091 int i;
2092 for (i = 0; i < MAXSESSION && cli_session_kill[i]; i++)
2093 {
2094 log(2, 0, cli_session_kill[i], 0, "Dropping session by CLI\n");
2095 sessionshutdown(cli_session_kill[i], "Requested by administrator");
2096 cli_session_kill[i] = 0;
2097 }
2098 }
2099 // Check for tunnels that have been killed from the CLI
2100 if (cli_tunnel_kill[0])
2101 {
2102 int i;
2103 for (i = 1; i < MAXTUNNEL && cli_tunnel_kill[i]; i++)
2104 {
2105 log(2, 0, cli_tunnel_kill[i], 0, "Dropping tunnel by CLI\n");
2106 tunnelshutdown(cli_tunnel_kill[i], "Requested by administrator");
2107 cli_tunnel_kill[i] = 0;
2108 }
2109 }
2110
2111 count = 0;
2112 for (i = 1; i <= config->cluster_highest_sessionid; i++)
2113 {
2114
2115 s++;
2116 if (s > config->cluster_highest_sessionid)
2117 s = 1;
2118
2119 if (!session[s].tunnel) // Session isn't in use
2120 continue;
2121
2122 if (!session[s].die && session[s].ip && !(session[s].flags & SF_IPCP_ACKED) )
2123 {
2124 // IPCP has not completed yet. Resend
2125 log(3, session[s].ip, s, session[s].tunnel, "No ACK for initial IPCP ConfigReq... resending\n");
2126 sendipcp(session[s].tunnel, s);
2127 }
2128
2129 // check for expired sessions
2130 if (session[s].die && session[s].die <= TIME)
2131 {
2132 sessionkill(s, "Expired");
2133 if (++count >= MAX_ACTIONS) break;
2134 continue;
2135 }
2136
2137 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
2138 if (session[s].last_packet && (time_now - session[s].last_packet >= IDLE_TIMEOUT))
2139 {
2140 sessionkill(s, "No response to LCP ECHO requests");
2141 STAT(session_timeout);
2142 if (++count >= MAX_ACTIONS) break;
2143 continue;
2144 }
2145
2146 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
2147 if (session[s].user[0] && (time_now - session[s].last_packet >= ECHO_TIMEOUT))
2148 {
2149 u8 b[MAXCONTROL] = {0};
2150
2151 u8 *q = makeppp(b, sizeof(b), 0, 0, session[s].tunnel, s, PPPLCP);
2152 if (!q) {
2153 log(3, session[s].ip, s, t, "failed to send ECHO packet.\n");
2154 continue;
2155 }
2156
2157 *q = EchoReq;
2158 *(u8 *)(q + 1) = (time_now % 255); // ID
2159 *(u16 *)(q + 2) = htons(8); // Length
2160 *(u32 *)(q + 4) = 0; // Magic Number (not supported)
2161
2162 log(4, session[s].ip, s, session[s].tunnel, "No data in %d seconds, sending LCP ECHO\n",
2163 (int)(time_now - session[s].last_packet));
2164 tunnelsend(b, 24, session[s].tunnel); // send it
2165 if (++count >= MAX_ACTIONS) break;
2166 continue;
2167 }
2168 }
2169 if (config->accounting_dir && next_acct <= TIME)
2170 {
2171 // Dump accounting data
2172 next_acct = TIME + ACCT_TIME;
2173 dump_acct_info();
2174 }
2175
2176 if (count >= MAX_ACTIONS)
2177 return 1; // Didn't finish!
2178
2179 log(3, 0, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count, config->cleanup_interval);
2180 return 0;
2181 }
2182
2183
2184 //
2185 // Are we in the middle of a tunnel update, or radius
2186 // requests??
2187 //
2188 int still_busy(void)
2189 {
2190 int i;
2191 static int last_talked = 0;
2192 for (i = config->cluster_highest_tunnelid ; i > 0 ; --i) {
2193 if (!tunnel[i].controlc)
2194 continue;
2195
2196 if (last_talked != TIME) {
2197 log(2,0,0,0, "Tunnel %d still has un-acked control messages.\n", i);
2198 last_talked = TIME;
2199 }
2200 return 1;
2201 }
2202
2203 for (i = 1; i < MAXRADIUS; i++)
2204 {
2205 if (radius[i].state == RADIUSNULL)
2206 continue;
2207 if (radius[i].state == RADIUSWAIT)
2208 continue;
2209
2210 if (last_talked != TIME) {
2211 log(2,0,0,0, "Radius session %d is still busy (sid %d)\n", i, radius[i].session);
2212 last_talked = TIME;
2213 }
2214 return 1;
2215 }
2216
2217 return 0;
2218 }
2219
2220 // main loop - gets packets on tap or udp and processes them
2221 void mainloop(void)
2222 {
2223 fd_set cr;
2224 int cn, i;
2225 u8 buf[65536];
2226 struct timeval to;
2227 clockt next_cluster_ping = 0; // send initial ping immediately
2228 time_t next_clean = time_now + config->cleanup_interval;
2229
2230 log(4, 0, 0, 0, "Beginning of main loop. udpfd=%d, tapfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2231 udpfd, tapfd, cluster_sockfd, controlfd);
2232
2233 FD_ZERO(&cr);
2234 FD_SET(udpfd, &cr);
2235 FD_SET(tapfd, &cr);
2236 FD_SET(controlfd, &cr);
2237 FD_SET(clifd, &cr);
2238 if (cluster_sockfd) FD_SET(cluster_sockfd, &cr);
2239 cn = udpfd;
2240 if (cn < tapfd) cn = tapfd;
2241 if (cn < controlfd) cn = controlfd;
2242 if (cn < clifd) cn = clifd;
2243 if (cn < cluster_sockfd) cn = cluster_sockfd;
2244 for (i = 0; i < config->num_radfds; i++)
2245 {
2246 if (!radfds[i]) continue;
2247 FD_SET(radfds[i], &cr);
2248 if (radfds[i] > cn)
2249 cn = radfds[i];
2250 }
2251
2252 while (!main_quit || still_busy())
2253 {
2254 fd_set r;
2255 int n = cn;
2256 #ifdef BGP
2257 fd_set w;
2258 int bgp_set[BGP_NUM_PEERS];
2259 #endif /* BGP */
2260
2261 if (config->reload_config)
2262 {
2263 // Update the config state based on config settings
2264 update_config();
2265 }
2266
2267 memcpy(&r, &cr, sizeof(fd_set));
2268 to.tv_sec = 0;
2269 to.tv_usec = 100000; // 1/10th of a second.
2270
2271 #ifdef BGP
2272 FD_ZERO(&w);
2273 for (i = 0; i < BGP_NUM_PEERS; i++)
2274 {
2275 bgp_set[i] = bgp_select_state(&bgp_peers[i]);
2276 if (bgp_set[i] & 1)
2277 {
2278 FD_SET(bgp_peers[i].sock, &r);
2279 if (bgp_peers[i].sock > n)
2280 n = bgp_peers[i].sock;
2281 }
2282
2283 if (bgp_set[i] & 2)
2284 {
2285 FD_SET(bgp_peers[i].sock, &w);
2286 if (bgp_peers[i].sock > n)
2287 n = bgp_peers[i].sock;
2288 }
2289 }
2290
2291 n = select(n + 1, &r, &w, 0, &to);
2292 #else /* BGP */
2293 n = select(n + 1, &r, 0, 0, &to);
2294 #endif /* BGP */
2295
2296 TIME = now();
2297 if (n < 0)
2298 {
2299 if (errno == EINTR)
2300 continue;
2301
2302 log(0, 0, 0, 0, "Error returned from select(): %s\n", strerror(errno));
2303 main_quit++;
2304 break;
2305 }
2306 else if (n)
2307 {
2308 struct sockaddr_in addr;
2309 int alen = sizeof(addr);
2310 if (FD_ISSET(udpfd, &r))
2311 {
2312 int c, n;
2313 for (c = 0; c < config->multi_read_count; c++)
2314 {
2315 if ((n = recvfrom(udpfd, buf, sizeof(buf), 0, (void *) &addr, &alen)) > 0)
2316 processudp(buf, n, &addr);
2317 else
2318 break;
2319 }
2320 }
2321 if (FD_ISSET(tapfd, &r))
2322 {
2323 int c, n;
2324 for (c = 0; c < config->multi_read_count; c++)
2325 {
2326 if ((n = read(tapfd, buf, sizeof(buf))) > 0)
2327 processtap(buf, n);
2328 else
2329 break;
2330 }
2331 }
2332 for (i = 0; i < config->num_radfds; i++)
2333 if (FD_ISSET(radfds[i], &r))
2334 processrad(buf, recv(radfds[i], buf, sizeof(buf), 0), i);
2335 if (FD_ISSET(cluster_sockfd, &r)) {
2336 int size;
2337 size = recvfrom(cluster_sockfd, buf, sizeof(buf), MSG_WAITALL, (void *) &addr, &alen);
2338 processcluster(buf, size, addr.sin_addr.s_addr);
2339 }
2340 if (FD_ISSET(controlfd, &r))
2341 processcontrol(buf, recvfrom(controlfd, buf, sizeof(buf), MSG_WAITALL, (void *) &addr, &alen), &addr);
2342 if (FD_ISSET(clifd, &r))
2343 {
2344 struct sockaddr_in addr;
2345 int sockfd;
2346 int len = sizeof(addr);
2347
2348 if ((sockfd = accept(clifd, (struct sockaddr *)&addr, &len)) <= 0)
2349 {
2350 log(0, 0, 0, 0, "accept error: %s\n", strerror(errno));
2351 continue;
2352 }
2353 else
2354 {
2355 cli_do(sockfd);
2356 close(sockfd);
2357 }
2358 }
2359 }
2360
2361 // Runs on every machine (master and slaves).
2362 if (cluster_sockfd && next_cluster_ping <= TIME)
2363 {
2364 // Check to see which of the cluster is still alive..
2365 cluster_send_ping(basetime);
2366 cluster_check_master();
2367 cluster_heartbeat(); // Only does anything if we're a master.
2368 master_update_counts(); // If we're a slave, send our byte counters to our master.
2369 if (config->cluster_iam_master && !config->cluster_iam_uptodate)
2370 next_cluster_ping = TIME + 1; // out-of-date slaves, do fast updates
2371 else
2372 next_cluster_ping = TIME + config->cluster_hb_interval;
2373 }
2374
2375 // Run token bucket filtering queue..
2376 // Only run it every 1/10th of a second.
2377 // Runs on all machines both master and slave.
2378 {
2379 static clockt last_run = 0;
2380 if (last_run != TIME) {
2381 last_run = TIME;
2382 tbf_run_timer();
2383 }
2384 }
2385
2386 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2387 * something to read, else under load this will never actually run....
2388 *
2389 */
2390 if (config->cluster_iam_master && next_clean <= time_now) {
2391 if (regular_cleanups()) { // Did it finish?
2392 next_clean = time_now + 1 ; // Didn't finish. Check quickly.
2393 } else {
2394 next_clean = time_now + config->cleanup_interval; // Did. Move to next interval.
2395 }
2396 }
2397
2398 #ifdef BGP
2399 for (i = 0; i < BGP_NUM_PEERS; i++)
2400 {
2401 bgp_process(&bgp_peers[i],
2402 bgp_set[i] ? FD_ISSET(bgp_peers[i].sock, &r) : 0,
2403 bgp_set[i] ? FD_ISSET(bgp_peers[i].sock, &w) : 0);
2404 }
2405 #endif /* BGP */
2406 }
2407
2408 // Are we the master and shutting down??
2409 if (config->cluster_iam_master)
2410 cluster_heartbeat(); // Flush any queued changes..
2411
2412 // Ok. Notify everyone we're shutting down. If we're
2413 // the master, this will force an election.
2414 cluster_send_ping(0);
2415
2416 //
2417 // Important!!! We MUST not process any packets past this point!
2418 }
2419
2420 // Init data structures
2421 void initdata(void)
2422 {
2423 int i;
2424
2425 _statistics = mmap(NULL, sizeof(struct Tstats), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2426 if (_statistics == MAP_FAILED)
2427 {
2428 log(0, 0, 0, 0, "Error doing mmap for _statistics: %s\n", strerror(errno));
2429 exit(1);
2430 }
2431 config = mmap(NULL, sizeof(struct configt), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2432 if (config == MAP_FAILED)
2433 {
2434 log(0, 0, 0, 0, "Error doing mmap for configuration: %s\n", strerror(errno));
2435 exit(1);
2436 }
2437 memset(config, 0, sizeof(struct configt));
2438 time(&config->start_time);
2439 strncpy(config->config_file, CONFIGFILE, sizeof(config->config_file) - 1);
2440 tunnel = mmap(NULL, sizeof(tunnelt) * MAXTUNNEL, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2441 if (tunnel == MAP_FAILED)
2442 {
2443 log(0, 0, 0, 0, "Error doing mmap for tunnels: %s\n", strerror(errno));
2444 exit(1);
2445 }
2446 session = mmap(NULL, sizeof(sessiont) * MAXSESSION, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2447 if (session == MAP_FAILED)
2448 {
2449 log(0, 0, 0, 0, "Error doing mmap for sessions: %s\n", strerror(errno));
2450 exit(1);
2451 }
2452
2453 sess_count = mmap(NULL, sizeof(sessioncountt) * MAXSESSION, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2454 if (sess_count == MAP_FAILED)
2455 {
2456 log(0, 0, 0, 0, "Error doing mmap for sessions_count: %s\n", strerror(errno));
2457 exit(1);
2458 }
2459
2460 radius = mmap(NULL, sizeof(radiust) * MAXRADIUS, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2461 if (radius == MAP_FAILED)
2462 {
2463 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno));
2464 exit(1);
2465 }
2466 ip_address_pool = mmap(NULL, sizeof(ippoolt) * MAXIPPOOL, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2467 if (ip_address_pool == MAP_FAILED)
2468 {
2469 log(0, 0, 0, 0, "Error doing mmap for ip_address_pool: %s\n", strerror(errno));
2470 exit(1);
2471 }
2472 #ifdef RINGBUFFER
2473 ringbuffer = mmap(NULL, sizeof(struct Tringbuffer), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2474 if (ringbuffer == MAP_FAILED)
2475 {
2476 log(0, 0, 0, 0, "Error doing mmap for ringbuffer: %s\n", strerror(errno));
2477 exit(1);
2478 }
2479 memset(ringbuffer, 0, sizeof(struct Tringbuffer));
2480 #endif
2481
2482 cli_session_kill = mmap(NULL, sizeof(sessionidt) * MAXSESSION, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2483 if (cli_session_kill == MAP_FAILED)
2484 {
2485 log(0, 0, 0, 0, "Error doing mmap for cli session kill: %s\n", strerror(errno));
2486 exit(1);
2487 }
2488 memset(cli_session_kill, 0, sizeof(sessionidt) * MAXSESSION);
2489 cli_tunnel_kill = mmap(NULL, sizeof(tunnelidt) * MAXSESSION, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2490 if (cli_tunnel_kill == MAP_FAILED)
2491 {
2492 log(0, 0, 0, 0, "Error doing mmap for cli tunnel kill: %s\n", strerror(errno));
2493 exit(1);
2494 }
2495 memset(cli_tunnel_kill, 0, sizeof(tunnelidt) * MAXSESSION);
2496
2497 memset(tunnel, 0, sizeof(tunnelt) * MAXTUNNEL);
2498 memset(session, 0, sizeof(sessiont) * MAXSESSION);
2499 memset(radius, 0, sizeof(radiust) * MAXRADIUS);
2500 memset(ip_address_pool, 0, sizeof(ippoolt) * MAXIPPOOL);
2501
2502 // Put all the sessions on the free list marked as undefined.
2503 for (i = 1; i < MAXSESSION - 1; i++) {
2504 session[i].next = i + 1;
2505 session[i].tunnel = T_UNDEF; // mark it as not filled in.
2506 }
2507 session[MAXSESSION - 1].next = 0;
2508 sessionfree = 1;
2509
2510 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2511 for (i = 1; i < MAXTUNNEL- 1; i++) {
2512 tunnel[i].state = TUNNELUNDEF; // mark it as not filled in.
2513 }
2514
2515 if (!*hostname)
2516 {
2517 char *p;
2518 // Grab my hostname unless it's been specified
2519 gethostname(hostname, sizeof(hostname));
2520 if ((p = strchr(hostname, '.'))) *p = 0;
2521 }
2522 _statistics->start_time = _statistics->last_reset = time(NULL);
2523
2524 #ifdef BGP
2525 bgp_peers = mmap(NULL, sizeof(struct bgp_peer) * BGP_NUM_PEERS, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
2526 if (bgp_peers == MAP_FAILED)
2527 {
2528 log(0, 0, 0, 0, "Error doing mmap for bgp: %s\n", strerror(errno));
2529 exit(1);
2530 }
2531 #endif /* BGP */
2532 }
2533
2534 void initiptables(void)
2535 {
2536 /* Flush the tables here so that we have a clean slate */
2537
2538 // Not needed. 'nat' is setup by garden.c
2539 // mangle isn't used (as throttling is done by tbf inhouse).
2540 }
2541
2542 int assign_ip_address(sessionidt s)
2543 {
2544 u32 i;
2545 int best = -1;
2546 time_t best_time = time_now;
2547 char *u = session[s].user;
2548 char reuse = 0;
2549
2550
2551 CSTAT(call_assign_ip_address);
2552
2553 for (i = 1; i < ip_pool_size; i++)
2554 {
2555 if (!ip_address_pool[i].address || ip_address_pool[i].assigned)
2556 continue;
2557
2558 if (!session[s].walled_garden && ip_address_pool[i].user[0] && !strcmp(u, ip_address_pool[i].user))
2559 {
2560 best = i;
2561 reuse = 1;
2562 break;
2563 }
2564
2565 if (ip_address_pool[i].last < best_time)
2566 {
2567 best = i;
2568 if (!(best_time = ip_address_pool[i].last))
2569 break; // never used, grab this one
2570 }
2571 }
2572
2573 if (best < 0)
2574 {
2575 log(0, 0, s, session[s].tunnel, "assign_ip_address(): out of addresses\n");
2576 return 0;
2577 }
2578
2579 session[s].ip = ip_address_pool[best].address;
2580 session[s].ip_pool_index = best;
2581 ip_address_pool[best].assigned = 1;
2582 ip_address_pool[best].last = time_now;
2583 ip_address_pool[best].session = s;
2584 if (session[s].walled_garden)
2585 /* Don't track addresses of users in walled garden (note: this
2586 means that their address isn't "sticky" even if they get
2587 un-gardened). */
2588 ip_address_pool[best].user[0] = 0;
2589 else
2590 strncpy(ip_address_pool[best].user, u, sizeof(ip_address_pool[best].user) - 1);
2591
2592 STAT(ip_allocated);
2593 log(4, ip_address_pool[best].address, s, session[s].tunnel,
2594 "assign_ip_address(): %s ip address %d from pool\n", reuse ? "Reusing" : "Allocating", best);
2595
2596 return 1;
2597 }
2598
2599 void free_ip_address(sessionidt s)
2600 {
2601 int i = session[s].ip_pool_index;
2602
2603 if (!session[s].ip)
2604 return; // what the?
2605
2606 if (i < 0) // Is this actually part of the ip pool?
2607 i = 0;
2608
2609 STAT(ip_freed);
2610 cache_ipmap(session[s].ip, -i); // Change the mapping to point back to the ip pool index.
2611 session[s].ip = 0;
2612 ip_address_pool[i].assigned = 0;
2613 ip_address_pool[i].session = 0;
2614 ip_address_pool[i].last = time_now;
2615
2616
2617 CSTAT(call_free_ip_address);
2618
2619 }
2620
2621 //
2622 // Fsck the address pool against the session table.
2623 // Normally only called when we become a master.
2624 //
2625 // This isn't perfect: We aren't keep tracking of which
2626 // users used to have an IP address.
2627 //
2628 void rebuild_address_pool(void)
2629 {
2630 int i;
2631
2632 //
2633 // Zero the IP pool allocation, and build
2634 // a map from IP address to pool index.
2635 for (i = 1; i < MAXIPPOOL; ++i) {
2636 ip_address_pool[i].assigned = 0;
2637 ip_address_pool[i].session = 0;
2638 if (!ip_address_pool[i].address)
2639 continue;
2640
2641 cache_ipmap(ip_address_pool[i].address, -i); // Map pool IP to pool index.
2642 }
2643
2644 for (i = 0; i < MAXSESSION; ++i) {
2645 int ipid;
2646 if (!session[i].ip || !session[i].tunnel)
2647 continue;
2648 ipid = - lookup_ipmap(htonl(session[i].ip));
2649
2650 if (session[i].ip_pool_index < 0) { // Not allocated out of the pool.
2651 if (ipid < 1) // Not found in the pool either? good.
2652 continue;
2653
2654 log(0, 0, i, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2655 i, inet_toa(session[i].ip), ipid);
2656
2657 // Fall through and process it as part of the pool.
2658 }
2659
2660
2661 if (ipid > MAXIPPOOL || ipid < 0) {
2662 log(0, 0, i, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i, ipid);
2663 ipid = -1;
2664 session[i].ip_pool_index = ipid;
2665 continue;
2666 }
2667
2668 ip_address_pool[ipid].assigned = 1;
2669 ip_address_pool[ipid].session = i;
2670 ip_address_pool[ipid].last = time_now;
2671 strncpy(ip_address_pool[ipid].user, session[i].user, sizeof(ip_address_pool[ipid].user) - 1);
2672 session[i].ip_pool_index = ipid;
2673 cache_ipmap(session[i].ip, i); // Fix the ip map.
2674 }
2675 }
2676
2677 //
2678 // Fix the address pool to match a changed session.
2679 // (usually when the master sends us an update).
2680 void fix_address_pool(int sid)
2681 {
2682 int ipid;
2683
2684 ipid = session[sid].ip_pool_index;
2685
2686 if (ipid > ip_pool_size)
2687 return; // Ignore it. rebuild_address_pool will fix it up.
2688
2689 if (ip_address_pool[ipid].address != session[sid].ip)
2690 return; // Just ignore it. rebuild_address_pool will take care of it.
2691
2692 ip_address_pool[ipid].assigned = 1;
2693 ip_address_pool[ipid].session = sid;
2694 ip_address_pool[ipid].last = time_now;
2695 strncpy(ip_address_pool[ipid].user, session[sid].user, sizeof(ip_address_pool[ipid].user) - 1);
2696 }
2697
2698 //
2699 // Add a block of addresses to the IP pool to hand out.
2700 //
2701 void add_to_ip_pool(u32 addr, u32 mask)
2702 {
2703 int i;
2704 if (mask == 0)
2705 mask = 0xffffffff; // Host route only.
2706
2707 addr &= mask;
2708
2709 if (ip_pool_size >= MAXIPPOOL) // Pool is full!
2710 return ;
2711
2712 for (i = addr ;(i & mask) == addr; ++i)
2713 {
2714 if ((i & 0xff) == 0 || (i&0xff) == 255)
2715 continue; // Skip 0 and broadcast addresses.
2716
2717 ip_address_pool[ip_pool_size].address = i;
2718 ip_address_pool[ip_pool_size].assigned = 0;
2719 ++ip_pool_size;
2720 if (ip_pool_size >= MAXIPPOOL)
2721 {
2722 log(0,0,0,0, "Overflowed IP pool adding %s\n", inet_toa(htonl(addr)) );
2723 return;
2724 }
2725 }
2726 }
2727
2728 // Initialize the IP address pool
2729 void initippool()
2730 {
2731 FILE *f;
2732 char *p;
2733 char buf[4096];
2734 memset(ip_address_pool, 0, sizeof(ip_address_pool));
2735
2736 if (!(f = fopen(IPPOOLFILE, "r")))
2737 {
2738 log(0, 0, 0, 0, "Can't load pool file " IPPOOLFILE ": %s\n", strerror(errno));
2739 exit(1);
2740 }
2741
2742 while (ip_pool_size < MAXIPPOOL && fgets(buf, 4096, f))
2743 {
2744 char *pool = buf;
2745 buf[4095] = 0; // Force it to be zero terminated/
2746
2747 if (*buf == '#' || *buf == '\n')
2748 continue; // Skip comments / blank lines
2749 if ((p = (char *)strrchr(buf, '\n'))) *p = 0;
2750 if ((p = (char *)strchr(buf, ':')))
2751 {
2752 ipt src;
2753 *p = '\0';
2754 src = inet_addr(buf);
2755 if (src == INADDR_NONE)
2756 {
2757 log(0, 0, 0, 0, "Invalid address pool IP %s\n", buf);
2758 exit(1);
2759 }
2760 // This entry is for a specific IP only
2761 if (src != config->bind_address)
2762 continue;
2763 *p = ':';
2764 pool = p+1;
2765 }
2766 if ((p = (char *)strchr(pool, '/')))
2767 {
2768 // It's a range
2769 int numbits = 0;
2770 u32 start = 0, mask = 0;
2771
2772 log(2, 0, 0, 0, "Adding IP address range %s\n", buf);
2773 *p++ = 0;
2774 if (!*p || !(numbits = atoi(p)))
2775 {
2776 log(0, 0, 0, 0, "Invalid pool range %s\n", buf);
2777 continue;
2778 }
2779 start = ntohl(inet_addr(pool));
2780 mask = (u32)(pow(2, numbits) - 1) << (32 - numbits);
2781
2782 // Add a static route for this pool
2783 log(5, 0, 0, 0, "Adding route for address pool %s/%u\n", inet_toa(htonl(start)), 32 + mask);
2784 routeset(0, start, mask, 0, 1);
2785
2786 add_to_ip_pool(start, mask);
2787 }
2788 else
2789 {
2790 // It's a single ip address
2791 add_to_ip_pool(inet_addr(pool), 0);
2792 }
2793 }
2794 fclose(f);
2795 log(1, 0, 0, 0, "IP address pool is %d addresses\n", ip_pool_size - 1);
2796 }
2797
2798 void snoop_send_packet(char *packet, u16 size, ipt destination, u16 port)
2799 {
2800 if (!destination || !port || snoopfd <= 0 || size <= 0 || !packet)
2801 return;
2802
2803 snoop_addr.sin_addr.s_addr = destination;
2804 snoop_addr.sin_port = ntohs(port);
2805
2806 log(5, 0, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n",
2807 packet, size, inet_toa(snoop_addr.sin_addr.s_addr), htons(snoop_addr.sin_port));
2808 if (sendto(snoopfd, packet, size, MSG_DONTWAIT | MSG_NOSIGNAL, (void *) &snoop_addr, sizeof(snoop_addr)) < 0)
2809 log(0, 0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno));
2810 STAT(packets_snooped);
2811 }
2812
2813 void dump_acct_info()
2814 {
2815 char filename[1024];
2816 char timestr[64];
2817 time_t t = time(NULL);
2818 int i;
2819 FILE *f = NULL;
2820
2821
2822 CSTAT(call_dump_acct_info);
2823
2824 strftime(timestr, 64, "%Y%m%d%H%M%S", localtime(&t));
2825 snprintf(filename, 1024, "%s/%s", config->accounting_dir, timestr);
2826
2827 for (i = 0; i < MAXSESSION; i++)
2828 {
2829 if (!session[i].opened || !session[i].ip || !session[i].cin || !session[i].cout || !*session[i].user || session[i].walled_garden)
2830 continue;
2831 if (!f)
2832 {
2833 time_t now = time(NULL);
2834 if (!(f = fopen(filename, "w")))
2835 {
2836 log(0, 0, 0, 0, "Can't write accounting info to %s: %s\n", filename, strerror(errno));
2837 return;
2838 }
2839 log(3, 0, 0, 0, "Dumping accounting information to %s\n", filename);
2840 fprintf(f, "# dslwatch.pl dump file V1.01\n"
2841 "# host: %s\n"
2842 "# time: %ld\n"
2843 "# uptime: %ld\n"
2844 "# format: username ip qos uptxoctets downrxoctets\n",
2845 hostname,
2846 now,
2847 now - basetime);
2848 }
2849
2850 log(4, 0, 0, 0, "Dumping accounting information for %s\n", session[i].user);
2851 fprintf(f, "%s %s %d %u %u\n",
2852 session[i].user, // username
2853 inet_toa(htonl(session[i].ip)), // ip
2854 (session[i].throttle) ? 2 : 1, // qos
2855 (u32)session[i].cin, // uptxoctets
2856 (u32)session[i].cout); // downrxoctets
2857
2858 session[i].pin = session[i].cin = 0;
2859 session[i].pout = session[i].cout = 0;
2860 }
2861
2862 if (f) fclose(f);
2863 }
2864
2865 // Main program
2866 int main(int argc, char *argv[])
2867 {
2868 int o;
2869
2870 _program_name = strdup(argv[0]);
2871
2872 time(&basetime); // start clock
2873
2874 // scan args
2875 while ((o = getopt(argc, argv, "vc:h:a:")) >= 0)
2876 {
2877 switch (o)
2878 {
2879 case 'd':
2880 // Double fork to detach from terminal
2881 if (fork()) exit(0);
2882 if (fork()) exit(0);
2883 break;
2884 case 'v':
2885 config->debug++;
2886 break;
2887 case 'h':
2888 snprintf(hostname, sizeof(hostname), "%s", optarg);
2889 break;
2890 case '?':
2891 default:
2892 printf("Args are:\n"
2893 "\t-d\tDetach from terminal\n"
2894 "\t-c <file>\tConfig file\n"
2895 "\t-h <hostname>\tForce hostname\n"
2896 "\t-a <address>\tUse specific address\n"
2897 "\t-v\t\tDebug\n");
2898
2899 return (0);
2900 break;
2901 }
2902 }
2903
2904 // Start the timer routine off
2905 time(&time_now);
2906 strftime(time_now_string, 64, "%Y-%m-%d %H:%M:%S", localtime(&time_now));
2907 signal(SIGALRM, sigalrm_handler);
2908 siginterrupt(SIGALRM, 0);
2909
2910 initiptables();
2911 initplugins();
2912 initdata();
2913 init_tbf();
2914 init_cli(hostname);
2915 read_config_file();
2916
2917 log(0, 0, 0, 0, "L2TPNS version " VERSION "\n");
2918 log(0, 0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
2919 log(0, 0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
2920 {
2921 struct rlimit rlim;
2922 rlim.rlim_cur = RLIM_INFINITY;
2923 rlim.rlim_max = RLIM_INFINITY;
2924 // Remove the maximum core size
2925 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
2926 log(0, 0, 0, 0, "Can't set ulimit: %s\n", strerror(errno));
2927 // Make core dumps go to /tmp
2928 chdir("/tmp");
2929 }
2930
2931 if (config->scheduler_fifo)
2932 {
2933 int ret;
2934 struct sched_param params = {0};
2935 params.sched_priority = 1;
2936
2937 if (get_nprocs() < 2)
2938 {
2939 log(0, 0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
2940 config->scheduler_fifo = 0;
2941 }
2942 else
2943 {
2944 if ((ret = sched_setscheduler(0, SCHED_FIFO, &params)) == 0)
2945 {
2946 log(1, 0, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
2947 }
2948 else
2949 {
2950 log(0, 0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno));
2951 config->scheduler_fifo = 0;
2952 }
2953 }
2954 }
2955
2956 /* Set up the cluster communications port. */
2957 if (cluster_init(config->bind_address) < 0)
2958 exit(1);
2959
2960 #ifdef BGP
2961 signal(SIGPIPE, SIG_IGN);
2962 bgp_setup(config->as_number);
2963 bgp_add_route(config->bind_address, 0xffffffff);
2964 if (*config->bgp_peer[0])
2965 bgp_start(&bgp_peers[0], config->bgp_peer[0],
2966 config->bgp_peer_as[0], 0); /* 0 = routing disabled */
2967
2968 if (*config->bgp_peer[1])
2969 bgp_start(&bgp_peers[1], config->bgp_peer[1],
2970 config->bgp_peer_as[1], 0);
2971 #endif /* BGP */
2972
2973 inittap();
2974 log(1, 0, 0, 0, "Set up on interface %s\n", config->tapdevice);
2975
2976 initudp();
2977 initrad();
2978 initippool();
2979
2980 read_state();
2981
2982 signal(SIGHUP, sighup_handler);
2983 signal(SIGTERM, sigterm_handler);
2984 signal(SIGINT, sigterm_handler);
2985 signal(SIGQUIT, sigquit_handler);
2986 signal(SIGCHLD, sigchild_handler);
2987
2988 alarm(1);
2989
2990 // Drop privileges here
2991 if (config->target_uid > 0 && geteuid() == 0)
2992 setuid(config->target_uid);
2993
2994 mainloop();
2995
2996 #ifdef BGP
2997 /* try to shut BGP down cleanly; with luck the sockets will be
2998 writable since we're out of the select */
2999 {
3000 int i;
3001 for (i = 0; i < BGP_NUM_PEERS; i++)
3002 if (bgp_peers[i].state == Established)
3003 bgp_stop(&bgp_peers[i]);
3004 }
3005 #endif /* BGP */
3006
3007 /* remove plugins (so cleanup code gets run) */
3008 plugins_done();
3009
3010 /* kill CLI children */
3011 signal(SIGTERM, SIG_IGN);
3012 kill(0, SIGTERM);
3013 return 0;
3014 }
3015
3016 void sighup_handler(int junk)
3017 {
3018 if (log_stream && log_stream != stderr)
3019 {
3020 fclose(log_stream);
3021 log_stream = NULL;
3022 }
3023
3024 read_config_file();
3025 }
3026
3027 void sigalrm_handler(int junk)
3028 {
3029 // Log current traffic stats
3030
3031 snprintf(config->bandwidth, sizeof(config->bandwidth),
3032 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3033 (udp_rx / 1024.0 / 1024.0 * 8),
3034 (eth_tx / 1024.0 / 1024.0 * 8),
3035 (eth_rx / 1024.0 / 1024.0 * 8),
3036 (udp_tx / 1024.0 / 1024.0 * 8),
3037 ((udp_tx + udp_rx + eth_tx + eth_rx) / 1024.0 / 1024.0 * 8),
3038 udp_rx_pkt, eth_rx_pkt);
3039
3040 udp_tx = udp_rx = 0;
3041 udp_rx_pkt = eth_rx_pkt = 0;
3042 eth_tx = eth_rx = 0;
3043
3044 if (config->dump_speed)
3045 printf("%s\n", config->bandwidth);
3046
3047 // Update the internal time counter
3048 time(&time_now);
3049 strftime(time_now_string, 64, "%Y-%m-%d %H:%M:%S", localtime(&time_now));
3050 alarm(1);
3051
3052 {
3053 // Run timer hooks
3054 struct param_timer p = { time_now };
3055 run_plugins(PLUGIN_TIMER, &p);
3056 }
3057
3058 }
3059
3060 void sigterm_handler(int junk)
3061 {
3062 log(1, 0, 0, 0, "Shutting down cleanly\n");
3063 if (config->save_state)
3064 dump_state();
3065
3066 main_quit++;
3067 }
3068
3069 void sigquit_handler(int junk)
3070 {
3071 int i;
3072
3073 log(1, 0, 0, 0, "Shutting down without saving sessions\n");
3074 for (i = 1; i < MAXSESSION; i++)
3075 {
3076 if (session[i].opened)
3077 sessionkill(i, "L2TPNS Closing");
3078 }
3079 for (i = 1; i < MAXTUNNEL; i++)
3080 {
3081 if (tunnel[i].ip || tunnel[i].state)
3082 tunnelshutdown(i, "L2TPNS Closing");
3083 }
3084
3085 main_quit++;
3086 }
3087
3088 void sigchild_handler(int signal)
3089 {
3090 while (waitpid(-1, NULL, WNOHANG) > 0)
3091 ;
3092 }
3093
3094 void read_state()
3095 {
3096 struct stat sb;
3097 int i;
3098 ippoolt itmp;
3099 FILE *f;
3100 char magic[sizeof(DUMP_MAGIC)-1];
3101 u32 buf[2];
3102
3103 if (!config->save_state)
3104 {
3105 unlink(STATEFILE);
3106 return;
3107 }
3108
3109 if (stat(STATEFILE, &sb) < 0)
3110 {
3111 unlink(STATEFILE);
3112 return;
3113 }
3114
3115 if (sb.st_mtime < (time(NULL) - 60))
3116 {
3117 log(0, 0, 0, 0, "State file is too old to read, ignoring\n");
3118 unlink(STATEFILE);
3119 return;
3120 }
3121
3122 f = fopen(STATEFILE, "r");
3123 unlink(STATEFILE);
3124
3125 if (!f)
3126 {
3127 log(0, 0, 0, 0, "Can't read state file: %s\n", strerror(errno));
3128 exit(1);
3129 }
3130
3131 if (fread(magic, sizeof(magic), 1, f) != 1 || strncmp(magic, DUMP_MAGIC, sizeof(magic)))
3132 {
3133 log(0, 0, 0, 0, "Bad state file magic\n");
3134 exit(1);
3135 }
3136
3137 log(1, 0, 0, 0, "Reading state information\n");
3138 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] > MAXIPPOOL || buf[1] != sizeof(ippoolt))
3139 {
3140 log(0, 0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3141 exit(1);
3142 }
3143
3144 if (buf[0] > ip_pool_size)
3145 {
3146 log(0, 0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf[0], ip_pool_size);
3147 exit(1);
3148 }
3149
3150 log(2, 0, 0, 0, "Loading %u ip addresses\n", buf[0]);
3151 for (i = 0; i < buf[0]; i++)
3152 {
3153 if (fread(&itmp, sizeof(itmp), 1, f) != 1)
3154 {
3155 log(0, 0, 0, 0, "Error reading ip %d from state file: %s\n", i, strerror(errno));
3156 exit(1);
3157 }
3158
3159 if (itmp.address != ip_address_pool[i].address)
3160 {
3161 log(0, 0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i);
3162 exit(1);
3163 }
3164
3165 memcpy(&ip_address_pool[i], &itmp, sizeof(itmp));
3166 }
3167
3168 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] != MAXTUNNEL || buf[1] != sizeof(tunnelt))
3169 {
3170 log(0, 0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3171 exit(1);
3172 }
3173
3174 log(2, 0, 0, 0, "Loading %u tunnels\n", MAXTUNNEL);
3175 if (fread(tunnel, sizeof(tunnelt), MAXTUNNEL, f) != MAXTUNNEL)
3176 {
3177 log(0, 0, 0, 0, "Error reading tunnel data from state file\n");
3178 exit(1);
3179 }
3180
3181 for (i = 0; i < MAXTUNNEL; i++)
3182 {
3183 tunnel[i].controlc = 0;
3184 tunnel[i].controls = NULL;
3185 tunnel[i].controle = NULL;
3186 if (*tunnel[i].hostname)
3187 log(3, 0, 0, 0, "Created tunnel for %s\n", tunnel[i].hostname);
3188 }
3189
3190 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] != MAXSESSION || buf[1] != sizeof(sessiont))
3191 {
3192 log(0, 0, 0, 0, "Error/mismatch reading session header from state file\n");
3193 exit(1);
3194 }
3195
3196 log(2, 0, 0, 0, "Loading %u sessions\n", MAXSESSION);
3197 if (fread(session, sizeof(sessiont), MAXSESSION, f) != MAXSESSION)
3198 {
3199 log(0, 0, 0, 0, "Error reading session data from state file\n");
3200 exit(1);
3201 }
3202
3203 for (i = 0; i < MAXSESSION; i++)
3204 {
3205 session[i].tbf_in = 0;
3206 session[i].tbf_out = 0;
3207 if (session[i].opened)
3208 {
3209 log(2, 0, i, 0, "Loaded active session for user %s\n", session[i].user);
3210 if (session[i].ip)
3211 sessionsetup(session[i].tunnel, i);
3212 }
3213 }
3214
3215 fclose(f);
3216 log(0, 0, 0, 0, "Loaded saved state information\n");
3217 }
3218
3219 void dump_state()
3220 {
3221 FILE *f;
3222 u32 buf[2];
3223
3224 if (!config->save_state)
3225 return;
3226
3227 do {
3228 if (!(f = fopen(STATEFILE, "w")))
3229 break;
3230
3231 log(1, 0, 0, 0, "Dumping state information\n");
3232
3233 if (fwrite(DUMP_MAGIC, sizeof(DUMP_MAGIC)-1, 1, f) != 1) break;
3234
3235 log(2, 0, 0, 0, "Dumping %u ip addresses\n", ip_pool_size);
3236 buf[0] = ip_pool_size;
3237 buf[1] = sizeof(ippoolt);
3238 if (fwrite(buf, sizeof(buf), 1, f) != 1) break;
3239 if (fwrite(ip_address_pool, sizeof(ippoolt), ip_pool_size, f) != ip_pool_size) break;
3240
3241 log(2, 0, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL);
3242 buf[0] = MAXTUNNEL;
3243 buf[1] = sizeof(tunnelt);
3244 if (fwrite(buf, sizeof(buf), 1, f) != 1) break;
3245 if (fwrite(tunnel, sizeof(tunnelt), MAXTUNNEL, f) != MAXTUNNEL) break;
3246
3247 log(2, 0, 0, 0, "Dumping %u sessions\n", MAXSESSION);
3248 buf[0] = MAXSESSION;
3249 buf[1] = sizeof(sessiont);
3250 if (fwrite(buf, sizeof(buf), 1, f) != 1) break;
3251 if (fwrite(session, sizeof(sessiont), MAXSESSION, f) != MAXSESSION) break;
3252
3253 if (fclose(f) == 0) return; // OK
3254 } while (0);
3255
3256 log(0, 0, 0, 0, "Can't write state information: %s\n", strerror(errno));
3257 unlink(STATEFILE);
3258 }
3259
3260 void build_chap_response(char *challenge, u8 id, u16 challenge_length, char **challenge_response)
3261 {
3262 MD5_CTX ctx;
3263 *challenge_response = NULL;
3264
3265 if (!*config->l2tpsecret)
3266 {
3267 log(0, 0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3268 return;
3269 }
3270
3271 log(4, 0, 0, 0, " Building challenge response for CHAP request\n");
3272
3273 *challenge_response = (char *)calloc(17, 1);
3274
3275 MD5Init(&ctx);
3276 MD5Update(&ctx, &id, 1);
3277 MD5Update(&ctx, config->l2tpsecret, strlen(config->l2tpsecret));
3278 MD5Update(&ctx, challenge, challenge_length);
3279 MD5Final(*challenge_response, &ctx);
3280
3281 return;
3282 }
3283
3284 static int facility_value(char *name)
3285 {
3286 int i;
3287 for (i = 0; facilitynames[i].c_name; i++)
3288 {
3289 if (strcmp(facilitynames[i].c_name, name) == 0)
3290 return facilitynames[i].c_val;
3291 }
3292 return 0;
3293 }
3294
3295 void update_config()
3296 {
3297 int i;
3298 static int timeout = 0;
3299 static int interval = 0;
3300
3301 // Update logging
3302 closelog();
3303 syslog_log = 0;
3304 if (log_stream)
3305 {
3306 fclose(log_stream);
3307 log_stream = NULL;
3308 }
3309 if (*config->log_filename)
3310 {
3311 if (strstr(config->log_filename, "syslog:") == config->log_filename)
3312 {
3313 char *p = config->log_filename + 7;
3314 if (*p)
3315 {
3316 openlog("l2tpns", LOG_PID, facility_value(p));
3317 syslog_log = 1;
3318 }
3319 }
3320 else if (strchr(config->log_filename, '/') == config->log_filename)
3321 {
3322 if ((log_stream = fopen((char *)(config->log_filename), "a")))
3323 {
3324 fseek(log_stream, 0, SEEK_END);
3325 setbuf(log_stream, NULL);
3326 }
3327 else
3328 {
3329 log_stream = stderr;
3330 setbuf(log_stream, NULL);
3331 }
3332 }
3333 }
3334 else
3335 {
3336 log_stream = stderr;
3337 setbuf(log_stream, NULL);
3338 }
3339
3340
3341 // Update radius
3342 config->numradiusservers = 0;
3343 for (i = 0; i < MAXRADSERVER; i++)
3344 if (config->radiusserver[i]) config->numradiusservers++;
3345
3346 if (!config->numradiusservers)
3347 {
3348 log(0, 0, 0, 0, "No RADIUS servers defined!\n");
3349 }
3350
3351 config->num_radfds = 2 << RADIUS_SHIFT;
3352
3353 // Update plugins
3354 for (i = 0; i < MAXPLUGINS; i++)
3355 {
3356 if (strcmp(config->plugins[i], config->old_plugins[i]) == 0)
3357 continue;
3358 if (*config->plugins[i])
3359 {
3360 // Plugin added
3361 add_plugin(config->plugins[i]);
3362 }
3363 else if (*config->old_plugins[i])
3364 {
3365 // Plugin removed
3366 remove_plugin(config->old_plugins[i]);
3367 }
3368 }
3369 memcpy(config->old_plugins, config->plugins, sizeof(config->plugins));
3370 if (!config->cleanup_interval) config->cleanup_interval = 10;
3371 if (!config->multi_read_count) config->multi_read_count = 10;
3372 if (!config->cluster_address) config->cluster_address = inet_addr(DEFAULT_MCAST_ADDR);
3373 if (!*config->cluster_interface)
3374 strncpy(config->cluster_interface, DEFAULT_MCAST_INTERFACE, sizeof(config->cluster_interface) - 1);
3375
3376 if (!config->cluster_hb_interval)
3377 config->cluster_hb_interval = PING_INTERVAL; // Heartbeat every 0.5 seconds.
3378
3379 if (!config->cluster_hb_timeout)
3380 config->cluster_hb_timeout = HB_TIMEOUT; // 10 missed heartbeat triggers an election.
3381
3382 if (interval != config->cluster_hb_interval || timeout != config->cluster_hb_timeout)
3383 {
3384 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3385 // late, ensure we're sufficiently larger than that
3386 int t = 4 * config->cluster_hb_interval + 11;
3387
3388 if (config->cluster_hb_timeout < t)
3389 {
3390 log(0,0,0,0, "Heartbeat timeout %d too low, adjusting to %d\n", config->cluster_hb_timeout, t);
3391 config->cluster_hb_timeout = t;
3392 }
3393
3394 // Push timing changes to the slaves immediately if we're the master
3395 if (config->cluster_iam_master)
3396 cluster_heartbeat();
3397
3398 interval = config->cluster_hb_interval;
3399 timeout = config->cluster_hb_timeout;
3400 }
3401
3402 config->reload_config = 0;
3403 }
3404
3405 void read_config_file()
3406 {
3407 FILE *f;
3408
3409 if (!config->config_file) return;
3410 if (!(f = fopen(config->config_file, "r"))) {
3411 fprintf(stderr, "Can't open config file %s: %s\n", config->config_file, strerror(errno));
3412 return;
3413 }
3414
3415 log(3, 0, 0, 0, "Reading config file %s\n", config->config_file);
3416 cli_do_file(f);
3417 log(3, 0, 0, 0, "Done reading config file\n");
3418 fclose(f);
3419 update_config();
3420 }
3421
3422 int sessionsetup(tunnelidt t, sessionidt s)
3423 {
3424 // A session now exists, set it up
3425 ipt ip;
3426 char *user;
3427 sessionidt i;
3428 int r;
3429
3430 CSTAT(call_sessionsetup);
3431
3432
3433 log(3, session[s].ip, s, t, "Doing session setup for session\n");
3434
3435 if (!session[s].ip || session[s].ip == 0xFFFFFFFE)
3436 {
3437 assign_ip_address(s);
3438 if (session[s].ip)
3439 log(3, 0, s, t, " No IP allocated. Assigned %s from pool\n",
3440 inet_toa(htonl(session[s].ip)));
3441 else
3442 log(0, 0, s, t, " No IP allocated. The IP address pool is FULL!\n");
3443 }
3444
3445
3446 // Make sure this is right
3447 session[s].tunnel = t;
3448
3449 // zap old sessions with same IP and/or username
3450 // Don't kill gardened sessions - doing so leads to a DoS
3451 // from someone who doesn't need to know the password
3452 {
3453 ip = session[s].ip;
3454 user = session[s].user;
3455 for (i = 1; i <= config->cluster_highest_sessionid; i++)
3456 {
3457 if (i == s) continue;
3458 if (ip == session[i].ip) sessionkill(i, "Duplicate IP address");
3459 if (!session[s].walled_garden && !session[i].walled_garden && strcasecmp(user, session[i].user) == 0)
3460 sessionkill(i, "Duplicate session for users");
3461 }
3462 }
3463
3464 // Add the route for this session.
3465 //
3466 // Static IPs need to be routed. Anything else
3467 // is part of the IP address pool and is already routed,
3468 // it just needs to be added to the IP cache.
3469 if (session[s].ip_pool_index == -1) // static ip
3470 routeset(s, session[s].ip, 0, 0, 1);
3471 else
3472 cache_ipmap(session[s].ip, s);
3473
3474 for (r = 0; r < MAXROUTE && session[s].route[r].ip; r++)
3475 routeset(s, session[s].route[r].ip, session[s].route[r].mask, session[s].ip, 1);
3476
3477 if (!session[s].sid) { // did this session just finish radius?
3478 log(3, session[s].ip, s, t, "Sending initial IPCP to client\n");
3479 sendipcp(t, s);
3480 session[s].sid = ++last_sid;
3481 }
3482
3483 // Run the plugin's against this new session.
3484 {
3485 struct param_new_session data = { &tunnel[t], &session[s] };
3486 run_plugins(PLUGIN_NEW_SESSION, &data);
3487 }
3488
3489 // Force throttling on or off (Actually : refresh the current throttling status)
3490 // This has the advantage of cleaning up after another throttled user who may have left
3491 // firewall rules lying around
3492 throttle_session(s, session[s].throttle);
3493
3494 session[s].last_packet = time_now;
3495
3496 {
3497 char *sessionip, *tunnelip;
3498 sessionip = strdup(inet_toa(htonl(session[s].ip)));
3499 tunnelip = strdup(inet_toa(htonl(tunnel[t].ip)));
3500 log(2, session[s].ip, s, t, "Login by %s at %s from %s (%s)\n",
3501 session[s].user, sessionip, tunnelip, tunnel[t].hostname);
3502 if (sessionip) free(sessionip);
3503 if (tunnelip) free(tunnelip);
3504 }
3505
3506 cluster_send_session(s); // Mark it as dirty, and needing to the flooded to the cluster.
3507
3508 return 1; // RADIUS OK and IP allocated, done...
3509 }
3510
3511 //
3512 // This session just got dropped on us by the master or something.
3513 // Make sure our tables up up to date...
3514 //
3515 int load_session(sessionidt s, sessiont *new)
3516 {
3517 int i;
3518
3519 // Sanity checks.
3520 if (new->ip_pool_index >= MAXIPPOOL ||
3521 new->tunnel >= MAXTUNNEL) {
3522 log(0,0,s,0, "Strange session update received!\n");
3523 // FIXME! What to do here?
3524 return 0;
3525 }
3526
3527 //
3528 // Ok. All sanity checks passed. Now we're committed to
3529 // loading the new session.
3530 //
3531
3532 session[s].tunnel = new->tunnel; // For logging in cache_ipmap
3533
3534
3535 if (new->ip != session[s].ip) // Changed ip. fix up hash tables.
3536 {
3537 if (session[s].ip) // If there's an old one, remove it.
3538 {
3539 // Remove any routes if the IP has changed
3540 for (i = 0; i < MAXROUTE && session[s].route[i].ip; i++)
3541 {
3542 routeset(s, session[s].route[i].ip, session[s].route[i].mask, session[s].ip, 0);
3543 session[s].route[i].ip = 0;
3544 }
3545
3546 if (session[s].ip_pool_index == -1) // static IP
3547 routeset(s, session[s].ip, 0, 0, 0);
3548 else // It's part of the IP pool, remove it manually.
3549 uncache_ipmap(session[s].ip);
3550 }
3551
3552 if (new->ip) { // If there's a new one, add it.
3553 if (new->ip_pool_index == -1)
3554 routeset(s, new->ip, 0, 0, 1);
3555 else
3556 cache_ipmap(new->ip, s);
3557 }
3558 }
3559
3560 // Update routed networks
3561 for (i = 0; i < MAXROUTE && (session[s].route[i].ip || new->route[i].ip); i++)
3562 {
3563 if (new->route[i].ip == session[s].route[i].ip &&
3564 new->route[i].mask == session[s].route[i].mask)
3565 continue;
3566
3567 if (session[s].route[i].ip) // Remove the old one if it exists.
3568 routeset(s, session[s].route[i].ip, session[s].route[i].mask, session[s].ip, 0);
3569
3570 if (new->route[i].ip) // Add the new one if it exists.
3571 routeset(s, new->route[i].ip, new->route[i].mask, new->ip, 1);
3572 }
3573
3574 if (new->tunnel && s > config->cluster_highest_sessionid) // Maintain this in the slave. It's used
3575 // for walking the sessions to forward byte counts to the master.
3576 config->cluster_highest_sessionid = s;
3577
3578 memcpy(&session[s], new, sizeof(session[s])); // Copy over..
3579
3580 // Do fixups into address pool.
3581 if (new->ip_pool_index != -1)
3582 fix_address_pool(s);
3583
3584 return 1;
3585 }
3586
3587 #ifdef RINGBUFFER
3588 void ringbuffer_dump(FILE *stream)
3589 {
3590 int i = ringbuffer->head;
3591
3592 while (i != ringbuffer->tail)
3593 {
3594 if (*ringbuffer->buffer[i].message)
3595 fprintf(stream, "%d-%s", ringbuffer->buffer[i].level, ringbuffer->buffer[i].message);
3596 if (++i == ringbuffer->tail) break;
3597 if (i == RINGBUFFER_SIZE) i = 0;
3598 }
3599 }
3600 #endif
3601
3602 void initplugins()
3603 {
3604 int i;
3605
3606 loaded_plugins = ll_init();
3607 // Initialize the plugins to nothing
3608 for (i = 0; i < MAX_PLUGIN_TYPES; i++)
3609 plugins[i] = ll_init();
3610 }
3611
3612 static void *open_plugin(char *plugin_name, int load)
3613 {
3614 char path[256] = "";
3615
3616 snprintf(path, 256, PLUGINDIR "/%s.so", plugin_name);
3617 log(2, 0, 0, 0, "%soading plugin from %s\n", load ? "L" : "Un-l", path);
3618 return dlopen(path, RTLD_NOW);
3619 }
3620
3621 void add_plugin(char *plugin_name)
3622 {
3623 static struct pluginfuncs funcs = {
3624 _log,
3625 _log_hex,
3626 inet_toa,
3627 sessionbyuser,
3628 sessiontbysessionidt,
3629 sessionidtbysessiont,
3630 sessionkill,
3631 radiusnew,
3632 radiussend,
3633 };
3634
3635 void *p = open_plugin(plugin_name, 1);
3636 int (*initfunc)(struct pluginfuncs *);
3637 int i;
3638
3639 if (!p)
3640 {
3641 log(1, 0, 0, 0, " Plugin load failed: %s\n", dlerror());
3642 return;
3643 }
3644
3645 if (ll_contains(loaded_plugins, p))
3646 {
3647 dlclose(p);
3648 return;
3649 }
3650
3651 {
3652 int *v = dlsym(p, "__plugin_api_version");
3653 if (!v || *v != PLUGIN_API_VERSION)
3654 {
3655 log(1, 0, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
3656 dlclose(p);
3657 return;
3658 }
3659 }
3660
3661 if ((initfunc = dlsym(p, "plugin_init")))
3662 {
3663 if (!initfunc(&funcs))
3664 {
3665 log(1, 0, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
3666 dlclose(p);
3667 return;
3668 }
3669 }
3670
3671 ll_push(loaded_plugins, p);
3672
3673 for (i = 0; i < max_plugin_functions; i++)
3674 {
3675 void *x;
3676 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
3677 {
3678 log(3, 0, 0, 0, " Supports function \"%s\"\n", plugin_functions[i]);
3679 ll_push(plugins[i], x);
3680 }
3681 }
3682
3683 log(2, 0, 0, 0, " Loaded plugin %s\n", plugin_name);
3684 }
3685
3686 static void run_plugin_done(void *plugin)
3687 {
3688 int (*donefunc)(void) = dlsym(plugin, "plugin_done");
3689
3690 if (donefunc)
3691 donefunc();
3692 }
3693
3694 void remove_plugin(char *plugin_name)
3695 {
3696 void *p = open_plugin(plugin_name, 0);
3697 int i;
3698
3699 if (!p)
3700 return;
3701
3702 for (i = 0; i < max_plugin_functions; i++)
3703 {
3704 void *x;
3705 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
3706 ll_delete(plugins[i], x);
3707 }
3708
3709 if (ll_contains(loaded_plugins, p))
3710 {
3711 ll_delete(loaded_plugins, p);
3712 run_plugin_done(p);
3713 }
3714
3715 dlclose(p);
3716 log(2, 0, 0, 0, "Removed plugin %s\n", plugin_name);
3717 }
3718
3719 int run_plugins(int plugin_type, void *data)
3720 {
3721 int (*func)(void *data);
3722 if (!plugins[plugin_type] || plugin_type > max_plugin_functions) return 1;
3723
3724 ll_reset(plugins[plugin_type]);
3725 while ((func = ll_next(plugins[plugin_type])))
3726 {
3727 int rc;
3728 rc = func(data);
3729 if (rc == PLUGIN_RET_STOP) return 1;
3730 if (rc == PLUGIN_RET_ERROR) return 0;
3731 }
3732 return 1;
3733 }
3734
3735 void plugins_done()
3736 {
3737 void *p;
3738
3739 ll_reset(loaded_plugins);
3740 while ((p = ll_next(loaded_plugins)))
3741 run_plugin_done(p);
3742 }
3743
3744 void processcontrol(u8 * buf, int len, struct sockaddr_in *addr)
3745 {
3746 char *resp;
3747 int l;
3748 struct param_control param = { buf, len, ntohl(addr->sin_addr.s_addr), ntohs(addr->sin_port), NULL, 0, 0 };
3749
3750
3751 if (log_stream && config->debug >= 4)
3752 {
3753 log(4, ntohl(addr->sin_addr.s_addr), 0, 0, "Received ");
3754 dump_packet(buf, log_stream);
3755 }
3756
3757 resp = calloc(1400, 1);
3758 l = new_packet(PKT_RESP_ERROR, resp);
3759 *(int *)(resp + 6) = *(int *)(buf + 6);
3760
3761 param.type = ntohs(*(short *)(buf + 2));
3762 param.id = ntohl(*(int *)(buf + 6));
3763 param.data_length = ntohs(*(short *)(buf + 4)) - 10;
3764 param.data = (param.data_length > 0) ? (char *)(buf + 10) : NULL;
3765 param.response = resp;
3766 param.response_length = l;
3767
3768 run_plugins(PLUGIN_CONTROL, &param);
3769
3770 if (param.send_response)
3771 {
3772 send_packet(controlfd, ntohl(addr->sin_addr.s_addr), ntohs(addr->sin_port), param.response, param.response_length);
3773 log(4, ntohl(addr->sin_addr.s_addr), 0, 0, "Sent Control packet response\n");
3774 }
3775
3776 free(resp);
3777 }
3778
3779 /*
3780 * HACK
3781 * Go through all of the tunnels and do some cleanups
3782 */
3783 void tunnel_clean()
3784 {
3785 int i;
3786
3787 log(1, 0, 0, 0, "Cleaning tunnels array\n");
3788
3789 for (i = 1; i < MAXTUNNEL; i++)
3790 {
3791 if (!tunnel[i].ip
3792 || !*tunnel[i].hostname
3793 || (tunnel[i].state == TUNNELDIE && tunnel[i].die >= time_now))
3794 {
3795 tunnelclear(i);
3796 }
3797 }
3798 }
3799
3800 void tunnelclear(tunnelidt t)
3801 {
3802 if (!t) return;
3803 memset(&tunnel[t], 0, sizeof(tunnel[t]));
3804 tunnel[t].state = TUNNELFREE;
3805 }
3806
3807 tunnelidt new_tunnel()
3808 {
3809 tunnelidt i;
3810 for (i = 1; i < MAXTUNNEL; i++)
3811 {
3812 if (tunnel[i].state == TUNNELFREE)
3813 {
3814 log(4, 0, 0, i, "Assigning tunnel ID %d\n", i);
3815 if (i > config->cluster_highest_tunnelid)
3816 config->cluster_highest_tunnelid = i;
3817 return i;
3818 }
3819 }
3820 log(0, 0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
3821 return 0;
3822 }
3823
3824 //
3825 // We're becoming the master. Do any required setup..
3826 //
3827 // This is principally telling all the plugins that we're
3828 // now a master, and telling them about all the sessions
3829 // that are active too..
3830 //
3831 void become_master(void)
3832 {
3833 int s;
3834 run_plugins(PLUGIN_BECOME_MASTER, NULL);
3835
3836 for (s = 1; s <= config->cluster_highest_sessionid ; ++s) {
3837 if (!session[s].tunnel) // Not an in-use session.
3838 continue;
3839
3840 run_plugins(PLUGIN_NEW_SESSION_MASTER, &session[s]);
3841 }
3842 }
3843
3844
3845
3846 int cmd_show_hist_idle(struct cli_def *cli, char *command, char **argv, int argc)
3847 {
3848 int s, i;
3849 int count = 0;
3850 int buckets[64];
3851
3852 if (CLI_HELP_REQUESTED)
3853 return CLI_HELP_NO_ARGS;
3854
3855 time(&time_now);
3856 for (i = 0; i < 64;++i) buckets[i] = 0;
3857
3858 for (s = 1; s <= config->cluster_highest_sessionid ; ++s) {
3859 int idle;
3860 if (!session[s].tunnel)
3861 continue;
3862
3863 idle = time_now - session[s].last_packet;
3864 idle /= 5 ; // In multiples of 5 seconds.
3865 if (idle < 0)
3866 idle = 0;
3867 if (idle > 63)
3868 idle = 63;
3869
3870 ++count;
3871 ++buckets[idle];
3872 }
3873
3874 for (i = 0; i < 63; ++i) {
3875 cli_print(cli, "%3d seconds : %7.2f%% (%6d)", i * 5, (double) buckets[i] * 100.0 / count , buckets[i]);
3876 }
3877 cli_print(cli, "lots of secs : %7.2f%% (%6d)", (double) buckets[63] * 100.0 / count , buckets[i]);
3878 cli_print(cli, "%d total sessions open.", count);
3879 return CLI_OK;
3880 }
3881
3882 int cmd_show_hist_open(struct cli_def *cli, char *command, char **argv, int argc)
3883 {
3884 int s, i;
3885 int count = 0;
3886 int buckets[64];
3887
3888 if (CLI_HELP_REQUESTED)
3889 return CLI_HELP_NO_ARGS;
3890
3891 time(&time_now);
3892 for (i = 0; i < 64;++i) buckets[i] = 0;
3893
3894 for (s = 1; s <= config->cluster_highest_sessionid ; ++s) {
3895 int open = 0, d;
3896 if (!session[s].tunnel)
3897 continue;
3898
3899 d = time_now - session[s].opened;
3900 if (d < 0)
3901 d = 0;
3902 while (d > 1 && open < 32) {
3903 ++open;
3904 d >>= 1; // half.
3905 }
3906 ++count;
3907 ++buckets[open];
3908 }
3909
3910 s = 1;
3911 for (i = 0; i < 30; ++i) {
3912 cli_print(cli, " < %8d seconds : %7.2f%% (%6d)", s, (double) buckets[i] * 100.0 / count , buckets[i]);
3913 s <<= 1;
3914 }
3915 cli_print(cli, "%d total sessions open.", count);
3916 return CLI_OK;
3917 }