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