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