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