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