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