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