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