fdaba0ca0f4a7602eb3e4a07d0013d710567bf46
[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.91 2005/04/27 13:53:15 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 = NULL; // 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 (!(_statistics = shared_malloc(sizeof(struct Tstats))))
3145 {
3146 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno));
3147 exit(1);
3148 }
3149 if (!(config = shared_malloc(sizeof(configt))))
3150 {
3151 LOG(0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno));
3152 exit(1);
3153 }
3154 memset(config, 0, sizeof(configt));
3155 time(&config->start_time);
3156 strncpy(config->config_file, optconfig, strlen(optconfig));
3157 config->debug = optdebug;
3158 config->num_tbfs = MAXTBFS;
3159 config->rl_rate = 28; // 28kbps
3160 strcpy(config->random_device, RANDOMDEVICE);
3161
3162 if (!(tunnel = shared_malloc(sizeof(tunnelt) * MAXTUNNEL)))
3163 {
3164 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno));
3165 exit(1);
3166 }
3167 if (!(session = shared_malloc(sizeof(sessiont) * MAXSESSION)))
3168 {
3169 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno));
3170 exit(1);
3171 }
3172
3173 if (!(sess_local = shared_malloc(sizeof(sessionlocalt) * MAXSESSION)))
3174 {
3175 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno));
3176 exit(1);
3177 }
3178
3179 if (!(radius = shared_malloc(sizeof(radiust) * MAXRADIUS)))
3180 {
3181 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno));
3182 exit(1);
3183 }
3184
3185 if (!(ip_address_pool = shared_malloc(sizeof(ippoolt) * MAXIPPOOL)))
3186 {
3187 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno));
3188 exit(1);
3189 }
3190
3191 if (!(ip_filters = shared_malloc(sizeof(ip_filtert) * MAXFILTER)))
3192 {
3193 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno));
3194 exit(1);
3195 }
3196 memset(ip_filters, 0, sizeof(ip_filtert) * MAXFILTER);
3197
3198 #ifdef RINGBUFFER
3199 if (!(ringbuffer = shared_malloc(sizeof(struct Tringbuffer))))
3200 {
3201 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno));
3202 exit(1);
3203 }
3204 memset(ringbuffer, 0, sizeof(struct Tringbuffer));
3205 #endif
3206
3207 if (!(cli_session_actions = shared_malloc(sizeof(struct cli_session_actions) * MAXSESSION)))
3208 {
3209 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno));
3210 exit(1);
3211 }
3212 memset(cli_session_actions, 0, sizeof(struct cli_session_actions) * MAXSESSION);
3213
3214 if (!(cli_tunnel_actions = shared_malloc(sizeof(struct cli_tunnel_actions) * MAXSESSION)))
3215 {
3216 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno));
3217 exit(1);
3218 }
3219 memset(cli_tunnel_actions, 0, sizeof(struct cli_tunnel_actions) * MAXSESSION);
3220
3221 memset(tunnel, 0, sizeof(tunnelt) * MAXTUNNEL);
3222 memset(session, 0, sizeof(sessiont) * MAXSESSION);
3223 memset(radius, 0, sizeof(radiust) * MAXRADIUS);
3224 memset(ip_address_pool, 0, sizeof(ippoolt) * MAXIPPOOL);
3225
3226 // Put all the sessions on the free list marked as undefined.
3227 for (i = 1; i < MAXSESSION; i++)
3228 {
3229 session[i].next = i + 1;
3230 session[i].tunnel = T_UNDEF; // mark it as not filled in.
3231 }
3232 session[MAXSESSION - 1].next = 0;
3233 sessionfree = 1;
3234
3235 // Mark all the tunnels as undefined (waiting to be filled in by a download).
3236 for (i = 1; i < MAXTUNNEL; i++)
3237 tunnel[i].state = TUNNELUNDEF; // mark it as not filled in.
3238
3239 if (!*hostname)
3240 {
3241 // Grab my hostname unless it's been specified
3242 gethostname(hostname, sizeof(hostname));
3243 stripdomain(hostname);
3244 }
3245
3246 _statistics->start_time = _statistics->last_reset = time(NULL);
3247
3248 #ifdef BGP
3249 if (!(bgp_peers = shared_malloc(sizeof(struct bgp_peer) * BGP_NUM_PEERS)))
3250 {
3251 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno));
3252 exit(1);
3253 }
3254 #endif /* BGP */
3255 }
3256
3257 static int assign_ip_address(sessionidt s)
3258 {
3259 uint32_t i;
3260 int best = -1;
3261 time_t best_time = time_now;
3262 char *u = session[s].user;
3263 char reuse = 0;
3264
3265
3266 CSTAT(assign_ip_address);
3267
3268 for (i = 1; i < ip_pool_size; i++)
3269 {
3270 if (!ip_address_pool[i].address || ip_address_pool[i].assigned)
3271 continue;
3272
3273 if (!session[s].walled_garden && ip_address_pool[i].user[0] && !strcmp(u, ip_address_pool[i].user))
3274 {
3275 best = i;
3276 reuse = 1;
3277 break;
3278 }
3279
3280 if (ip_address_pool[i].last < best_time)
3281 {
3282 best = i;
3283 if (!(best_time = ip_address_pool[i].last))
3284 break; // never used, grab this one
3285 }
3286 }
3287
3288 if (best < 0)
3289 {
3290 LOG(0, s, session[s].tunnel, "assign_ip_address(): out of addresses\n");
3291 return 0;
3292 }
3293
3294 session[s].ip = ip_address_pool[best].address;
3295 session[s].ip_pool_index = best;
3296 ip_address_pool[best].assigned = 1;
3297 ip_address_pool[best].last = time_now;
3298 ip_address_pool[best].session = s;
3299 if (session[s].walled_garden)
3300 /* Don't track addresses of users in walled garden (note: this
3301 means that their address isn't "sticky" even if they get
3302 un-gardened). */
3303 ip_address_pool[best].user[0] = 0;
3304 else
3305 strncpy(ip_address_pool[best].user, u, sizeof(ip_address_pool[best].user) - 1);
3306
3307 STAT(ip_allocated);
3308 LOG(4, s, session[s].tunnel, "assign_ip_address(): %s ip address %d from pool\n",
3309 reuse ? "Reusing" : "Allocating", best);
3310
3311 return 1;
3312 }
3313
3314 static void free_ip_address(sessionidt s)
3315 {
3316 int i = session[s].ip_pool_index;
3317
3318
3319 CSTAT(free_ip_address);
3320
3321 if (!session[s].ip)
3322 return; // what the?
3323
3324 if (i < 0) // Is this actually part of the ip pool?
3325 i = 0;
3326
3327 STAT(ip_freed);
3328 cache_ipmap(session[s].ip, -i); // Change the mapping to point back to the ip pool index.
3329 session[s].ip = 0;
3330 ip_address_pool[i].assigned = 0;
3331 ip_address_pool[i].session = 0;
3332 ip_address_pool[i].last = time_now;
3333 }
3334
3335 //
3336 // Fsck the address pool against the session table.
3337 // Normally only called when we become a master.
3338 //
3339 // This isn't perfect: We aren't keep tracking of which
3340 // users used to have an IP address.
3341 //
3342 void rebuild_address_pool(void)
3343 {
3344 int i;
3345
3346 //
3347 // Zero the IP pool allocation, and build
3348 // a map from IP address to pool index.
3349 for (i = 1; i < MAXIPPOOL; ++i)
3350 {
3351 ip_address_pool[i].assigned = 0;
3352 ip_address_pool[i].session = 0;
3353 if (!ip_address_pool[i].address)
3354 continue;
3355
3356 cache_ipmap(ip_address_pool[i].address, -i); // Map pool IP to pool index.
3357 }
3358
3359 for (i = 0; i < MAXSESSION; ++i)
3360 {
3361 int ipid;
3362 if (!(session[i].opened && session[i].ip))
3363 continue;
3364
3365 ipid = - lookup_ipmap(htonl(session[i].ip));
3366
3367 if (session[i].ip_pool_index < 0)
3368 {
3369 // Not allocated out of the pool.
3370 if (ipid < 1) // Not found in the pool either? good.
3371 continue;
3372
3373 LOG(0, i, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
3374 i, fmtaddr(session[i].ip, 0), ipid);
3375
3376 // Fall through and process it as part of the pool.
3377 }
3378
3379
3380 if (ipid > MAXIPPOOL || ipid < 0)
3381 {
3382 LOG(0, i, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i, ipid);
3383 ipid = -1;
3384 session[i].ip_pool_index = ipid;
3385 continue;
3386 }
3387
3388 ip_address_pool[ipid].assigned = 1;
3389 ip_address_pool[ipid].session = i;
3390 ip_address_pool[ipid].last = time_now;
3391 strncpy(ip_address_pool[ipid].user, session[i].user, sizeof(ip_address_pool[ipid].user) - 1);
3392 session[i].ip_pool_index = ipid;
3393 cache_ipmap(session[i].ip, i); // Fix the ip map.
3394 }
3395 }
3396
3397 //
3398 // Fix the address pool to match a changed session.
3399 // (usually when the master sends us an update).
3400 static void fix_address_pool(int sid)
3401 {
3402 int ipid;
3403
3404 ipid = session[sid].ip_pool_index;
3405
3406 if (ipid > ip_pool_size)
3407 return; // Ignore it. rebuild_address_pool will fix it up.
3408
3409 if (ip_address_pool[ipid].address != session[sid].ip)
3410 return; // Just ignore it. rebuild_address_pool will take care of it.
3411
3412 ip_address_pool[ipid].assigned = 1;
3413 ip_address_pool[ipid].session = sid;
3414 ip_address_pool[ipid].last = time_now;
3415 strncpy(ip_address_pool[ipid].user, session[sid].user, sizeof(ip_address_pool[ipid].user) - 1);
3416 }
3417
3418 //
3419 // Add a block of addresses to the IP pool to hand out.
3420 //
3421 static void add_to_ip_pool(in_addr_t addr, in_addr_t mask)
3422 {
3423 int i;
3424 if (mask == 0)
3425 mask = 0xffffffff; // Host route only.
3426
3427 addr &= mask;
3428
3429 if (ip_pool_size >= MAXIPPOOL) // Pool is full!
3430 return ;
3431
3432 for (i = addr ;(i & mask) == addr; ++i)
3433 {
3434 if ((i & 0xff) == 0 || (i&0xff) == 255)
3435 continue; // Skip 0 and broadcast addresses.
3436
3437 ip_address_pool[ip_pool_size].address = i;
3438 ip_address_pool[ip_pool_size].assigned = 0;
3439 ++ip_pool_size;
3440 if (ip_pool_size >= MAXIPPOOL)
3441 {
3442 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr), 0));
3443 return;
3444 }
3445 }
3446 }
3447
3448 // Initialize the IP address pool
3449 static void initippool()
3450 {
3451 FILE *f;
3452 char *p;
3453 char buf[4096];
3454 memset(ip_address_pool, 0, sizeof(ip_address_pool));
3455
3456 if (!(f = fopen(IPPOOLFILE, "r")))
3457 {
3458 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE ": %s\n", strerror(errno));
3459 exit(1);
3460 }
3461
3462 while (ip_pool_size < MAXIPPOOL && fgets(buf, 4096, f))
3463 {
3464 char *pool = buf;
3465 buf[4095] = 0; // Force it to be zero terminated/
3466
3467 if (*buf == '#' || *buf == '\n')
3468 continue; // Skip comments / blank lines
3469 if ((p = (char *)strrchr(buf, '\n'))) *p = 0;
3470 if ((p = (char *)strchr(buf, ':')))
3471 {
3472 in_addr_t src;
3473 *p = '\0';
3474 src = inet_addr(buf);
3475 if (src == INADDR_NONE)
3476 {
3477 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf);
3478 exit(1);
3479 }
3480 // This entry is for a specific IP only
3481 if (src != config->bind_address)
3482 continue;
3483 *p = ':';
3484 pool = p+1;
3485 }
3486 if ((p = (char *)strchr(pool, '/')))
3487 {
3488 // It's a range
3489 int numbits = 0;
3490 in_addr_t start = 0, mask = 0;
3491
3492 LOG(2, 0, 0, "Adding IP address range %s\n", buf);
3493 *p++ = 0;
3494 if (!*p || !(numbits = atoi(p)))
3495 {
3496 LOG(0, 0, 0, "Invalid pool range %s\n", buf);
3497 continue;
3498 }
3499 start = ntohl(inet_addr(pool));
3500 mask = (in_addr_t) (pow(2, numbits) - 1) << (32 - numbits);
3501
3502 // Add a static route for this pool
3503 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
3504 fmtaddr(htonl(start), 0), 32 + mask);
3505
3506 routeset(0, start, mask, 0, 1);
3507
3508 add_to_ip_pool(start, mask);
3509 }
3510 else
3511 {
3512 // It's a single ip address
3513 add_to_ip_pool(inet_addr(pool), 0);
3514 }
3515 }
3516 fclose(f);
3517 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size - 1);
3518 }
3519
3520 void snoop_send_packet(char *packet, uint16_t size, in_addr_t destination, uint16_t port)
3521 {
3522 struct sockaddr_in snoop_addr = {0};
3523 if (!destination || !port || snoopfd <= 0 || size <= 0 || !packet)
3524 return;
3525
3526 snoop_addr.sin_family = AF_INET;
3527 snoop_addr.sin_addr.s_addr = destination;
3528 snoop_addr.sin_port = ntohs(port);
3529
3530 LOG(5, 0, 0, "Snooping %d byte packet to %s:%d\n", size,
3531 fmtaddr(snoop_addr.sin_addr.s_addr, 0),
3532 htons(snoop_addr.sin_port));
3533
3534 if (sendto(snoopfd, packet, size, MSG_DONTWAIT | MSG_NOSIGNAL, (void *) &snoop_addr, sizeof(snoop_addr)) < 0)
3535 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno));
3536
3537 STAT(packets_snooped);
3538 }
3539
3540 static int dump_session(FILE **f, sessiont *s)
3541 {
3542 if (!s->opened || !s->ip || !(s->cin || s->cout) || !*s->user || s->walled_garden)
3543 return 1;
3544
3545 if (!*f)
3546 {
3547 char filename[1024];
3548 char timestr[64];
3549 time_t now = time(NULL);
3550
3551 strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&now));
3552 snprintf(filename, sizeof(filename), "%s/%s", config->accounting_dir, timestr);
3553
3554 if (!(*f = fopen(filename, "w")))
3555 {
3556 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename, strerror(errno));
3557 return 0;
3558 }
3559
3560 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename);
3561 fprintf(*f, "# dslwatch.pl dump file V1.01\n"
3562 "# host: %s\n"
3563 "# time: %ld\n"
3564 "# uptime: %ld\n"
3565 "# format: username ip qos uptxoctets downrxoctets\n",
3566 hostname,
3567 now,
3568 now - basetime);
3569 }
3570
3571 LOG(4, 0, 0, "Dumping accounting information for %s\n", s->user);
3572 fprintf(*f, "%s %s %d %u %u\n",
3573 s->user, // username
3574 fmtaddr(htonl(s->ip), 0), // ip
3575 (s->throttle_in || s->throttle_out) ? 2 : 1, // qos
3576 (uint32_t) s->cin, // uptxoctets
3577 (uint32_t) s->cout); // downrxoctets
3578
3579 s->pin = s->cin = 0;
3580 s->pout = s->cout = 0;
3581
3582 return 1;
3583 }
3584
3585 static void dump_acct_info(int all)
3586 {
3587 int i;
3588 FILE *f = NULL;
3589
3590
3591 CSTAT(dump_acct_info);
3592
3593 if (shut_acct_n)
3594 {
3595 for (i = 0; i < shut_acct_n; i++)
3596 dump_session(&f, &shut_acct[i]);
3597
3598 shut_acct_n = 0;
3599 }
3600
3601 if (all)
3602 for (i = 1; i <= config->cluster_highest_sessionid; i++)
3603 dump_session(&f, &session[i]);
3604
3605 if (f)
3606 fclose(f);
3607 }
3608
3609 // Main program
3610 int main(int argc, char *argv[])
3611 {
3612 int i;
3613 int optdebug = 0;
3614 char *optconfig = CONFIGFILE;
3615
3616 time(&basetime); // start clock
3617
3618 // scan args
3619 while ((i = getopt(argc, argv, "dvc:h:")) >= 0)
3620 {
3621 switch (i)
3622 {
3623 case 'd':
3624 if (fork()) exit(0);
3625 setsid();
3626 freopen("/dev/null", "r", stdin);
3627 freopen("/dev/null", "w", stdout);
3628 freopen("/dev/null", "w", stderr);
3629 break;
3630 case 'v':
3631 optdebug++;
3632 break;
3633 case 'c':
3634 optconfig = optarg;
3635 break;
3636 case 'h':
3637 snprintf(hostname, sizeof(hostname), "%s", optarg);
3638 break;
3639 default:
3640 printf("Args are:\n"
3641 "\t-d\t\tDetach from terminal\n"
3642 "\t-c <file>\tConfig file\n"
3643 "\t-h <hostname>\tForce hostname\n"
3644 "\t-v\t\tDebug\n");
3645
3646 return (0);
3647 break;
3648 }
3649 }
3650
3651 // Start the timer routine off
3652 time(&time_now);
3653 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
3654 signal(SIGALRM, sigalrm_handler);
3655 siginterrupt(SIGALRM, 0);
3656
3657 initplugins();
3658 initdata(optdebug, optconfig);
3659
3660 init_cli(hostname);
3661 read_config_file();
3662 init_tbf(config->num_tbfs);
3663
3664 LOG(0, 0, 0, "L2TPNS version " VERSION "\n");
3665 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005 Optus Internet Engineering\n");
3666 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3667 {
3668 struct rlimit rlim;
3669 rlim.rlim_cur = RLIM_INFINITY;
3670 rlim.rlim_max = RLIM_INFINITY;
3671 // Remove the maximum core size
3672 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
3673 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno));
3674
3675 // Make core dumps go to /tmp
3676 chdir("/tmp");
3677 }
3678
3679 if (config->scheduler_fifo)
3680 {
3681 int ret;
3682 struct sched_param params = {0};
3683 params.sched_priority = 1;
3684
3685 if (get_nprocs() < 2)
3686 {
3687 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3688 config->scheduler_fifo = 0;
3689 }
3690 else
3691 {
3692 if ((ret = sched_setscheduler(0, SCHED_FIFO, &params)) == 0)
3693 {
3694 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3695 }
3696 else
3697 {
3698 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno));
3699 config->scheduler_fifo = 0;
3700 }
3701 }
3702 }
3703
3704 /* Set up the cluster communications port. */
3705 if (cluster_init() < 0)
3706 exit(1);
3707
3708 #ifdef BGP
3709 signal(SIGPIPE, SIG_IGN);
3710 bgp_setup(config->as_number);
3711 bgp_add_route(config->bind_address, 0xffffffff);
3712 for (i = 0; i < BGP_NUM_PEERS; i++)
3713 {
3714 if (config->neighbour[i].name[0])
3715 bgp_start(&bgp_peers[i], config->neighbour[i].name,
3716 config->neighbour[i].as, config->neighbour[i].keepalive,
3717 config->neighbour[i].hold, 0); /* 0 = routing disabled */
3718 }
3719 #endif /* BGP */
3720
3721 inittun();
3722 LOG(1, 0, 0, "Set up on interface %s\n", config->tundevice);
3723
3724 initudp();
3725 initrad();
3726 initippool();
3727
3728 signal(SIGHUP, sighup_handler);
3729 signal(SIGTERM, sigterm_handler);
3730 signal(SIGINT, sigterm_handler);
3731 signal(SIGQUIT, sigquit_handler);
3732 signal(SIGCHLD, sigchild_handler);
3733
3734 // Prevent us from getting paged out
3735 if (config->lock_pages)
3736 {
3737 if (!mlockall(MCL_CURRENT))
3738 LOG(1, 0, 0, "Locking pages into memory\n");
3739 else
3740 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno));
3741 }
3742
3743 alarm(1);
3744
3745 // Drop privileges here
3746 if (config->target_uid > 0 && geteuid() == 0)
3747 setuid(config->target_uid);
3748
3749 mainloop();
3750
3751 #ifdef BGP
3752 /* try to shut BGP down cleanly; with luck the sockets will be
3753 writable since we're out of the select */
3754 for (i = 0; i < BGP_NUM_PEERS; i++)
3755 if (bgp_peers[i].state == Established)
3756 bgp_stop(&bgp_peers[i]);
3757 #endif /* BGP */
3758
3759 /* remove plugins (so cleanup code gets run) */
3760 plugins_done();
3761
3762 // Remove the PID file if we wrote it
3763 if (config->wrote_pid && *config->pid_file == '/')
3764 unlink(config->pid_file);
3765
3766 /* kill CLI children */
3767 signal(SIGTERM, SIG_IGN);
3768 kill(0, SIGTERM);
3769 return 0;
3770 }
3771
3772 static void sighup_handler(int sig)
3773 {
3774 if (log_stream && log_stream != stderr)
3775 {
3776 fclose(log_stream);
3777 log_stream = NULL;
3778 }
3779
3780 read_config_file();
3781 }
3782
3783 static void sigalrm_handler(int sig)
3784 {
3785 // Log current traffic stats
3786
3787 snprintf(config->bandwidth, sizeof(config->bandwidth),
3788 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3789 (udp_rx / 1024.0 / 1024.0 * 8),
3790 (eth_tx / 1024.0 / 1024.0 * 8),
3791 (eth_rx / 1024.0 / 1024.0 * 8),
3792 (udp_tx / 1024.0 / 1024.0 * 8),
3793 ((udp_tx + udp_rx + eth_tx + eth_rx) / 1024.0 / 1024.0 * 8),
3794 udp_rx_pkt, eth_rx_pkt);
3795
3796 udp_tx = udp_rx = 0;
3797 udp_rx_pkt = eth_rx_pkt = 0;
3798 eth_tx = eth_rx = 0;
3799
3800 if (config->dump_speed)
3801 printf("%s\n", config->bandwidth);
3802
3803 // Update the internal time counter
3804 time(&time_now);
3805 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
3806 alarm(1);
3807
3808 {
3809 // Run timer hooks
3810 struct param_timer p = { time_now };
3811 run_plugins(PLUGIN_TIMER, &p);
3812 }
3813
3814 }
3815
3816 static void sigterm_handler(int sig)
3817 {
3818 LOG(1, 0, 0, "Shutting down cleanly\n");
3819 main_quit++;
3820 }
3821
3822 static void sigquit_handler(int sig)
3823 {
3824 int i;
3825
3826 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3827
3828 if (config->cluster_iam_master)
3829 {
3830 for (i = 1; i < MAXSESSION; i++)
3831 {
3832 if (session[i].opened)
3833 sessionkill(i, "L2TPNS Closing");
3834 }
3835 for (i = 1; i < MAXTUNNEL; i++)
3836 {
3837 if (tunnel[i].ip || tunnel[i].state)
3838 tunnelshutdown(i, "L2TPNS Closing", 6, 0, 0);
3839 }
3840 }
3841
3842 main_quit++;
3843 }
3844
3845 static void sigchild_handler(int sig)
3846 {
3847 while (waitpid(-1, NULL, WNOHANG) > 0)
3848 ;
3849 }
3850
3851 static void build_chap_response(char *challenge, uint8_t id, uint16_t challenge_length, char **challenge_response)
3852 {
3853 MD5_CTX ctx;
3854 *challenge_response = NULL;
3855
3856 if (!*config->l2tpsecret)
3857 {
3858 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3859 return;
3860 }
3861
3862 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
3863
3864 *challenge_response = (char *)calloc(17, 1);
3865
3866 MD5Init(&ctx);
3867 MD5Update(&ctx, &id, 1);
3868 MD5Update(&ctx, config->l2tpsecret, strlen(config->l2tpsecret));
3869 MD5Update(&ctx, challenge, challenge_length);
3870 MD5Final(*challenge_response, &ctx);
3871
3872 return;
3873 }
3874
3875 static int facility_value(char *name)
3876 {
3877 int i;
3878 for (i = 0; facilitynames[i].c_name; i++)
3879 {
3880 if (strcmp(facilitynames[i].c_name, name) == 0)
3881 return facilitynames[i].c_val;
3882 }
3883 return 0;
3884 }
3885
3886 static void update_config()
3887 {
3888 int i;
3889 char *p;
3890 static int timeout = 0;
3891 static int interval = 0;
3892
3893 // Update logging
3894 closelog();
3895 syslog_log = 0;
3896 if (log_stream)
3897 {
3898 fclose(log_stream);
3899 log_stream = NULL;
3900 }
3901
3902 if (*config->log_filename)
3903 {
3904 if (strstr(config->log_filename, "syslog:") == config->log_filename)
3905 {
3906 char *p = config->log_filename + 7;
3907 if (*p)
3908 {
3909 openlog("l2tpns", LOG_PID, facility_value(p));
3910 syslog_log = 1;
3911 }
3912 }
3913 else if (strchr(config->log_filename, '/') == config->log_filename)
3914 {
3915 if ((log_stream = fopen((char *)(config->log_filename), "a")))
3916 {
3917 fseek(log_stream, 0, SEEK_END);
3918 setbuf(log_stream, NULL);
3919 }
3920 else
3921 {
3922 log_stream = stderr;
3923 setbuf(log_stream, NULL);
3924 }
3925 }
3926 }
3927 else
3928 {
3929 log_stream = stderr;
3930 setbuf(log_stream, NULL);
3931 }
3932
3933 // Update radius
3934 config->numradiusservers = 0;
3935 for (i = 0; i < MAXRADSERVER; i++)
3936 if (config->radiusserver[i])
3937 {
3938 config->numradiusservers++;
3939 // Set radius port: if not set, take the port from the
3940 // first radius server. For the first radius server,
3941 // take the #defined default value from l2tpns.h
3942
3943 // test twice, In case someone works with
3944 // a secondary radius server without defining
3945 // a primary one, this will work even then.
3946 if (i>0 && !config->radiusport[i])
3947 config->radiusport[i] = config->radiusport[i-1];
3948 if (!config->radiusport[i])
3949 config->radiusport[i] = RADPORT;
3950 }
3951
3952 if (!config->numradiusservers)
3953 LOG(0, 0, 0, "No RADIUS servers defined!\n");
3954
3955 config->num_radfds = 2 << RADIUS_SHIFT;
3956
3957 // parse radius_authtypes_s
3958 config->radius_authtypes = config->radius_authprefer = 0;
3959 p = config->radius_authtypes_s;
3960 while (*p)
3961 {
3962 char *s = strpbrk(p, " \t,");
3963 int type = 0;
3964
3965 if (s)
3966 {
3967 *s++ = 0;
3968 while (*s == ' ' || *s == '\t')
3969 s++;
3970
3971 if (!*s)
3972 s = 0;
3973 }
3974
3975 if (!strncasecmp("chap", p, strlen(p)))
3976 type = AUTHCHAP;
3977 else if (!strncasecmp("pap", p, strlen(p)))
3978 type = AUTHPAP;
3979 else
3980 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"", p);
3981
3982 config->radius_authtypes |= type;
3983 if (!config->radius_authprefer)
3984 config->radius_authprefer = type;
3985 }
3986
3987 if (!config->radius_authtypes)
3988 {
3989 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
3990 config->radius_authtypes = config->radius_authprefer = AUTHPAP;
3991 }
3992
3993 // normalise radius_authtypes_s
3994 if (config->radius_authprefer == AUTHPAP)
3995 {
3996 strcpy(config->radius_authtypes_s, "pap");
3997 if (config->radius_authtypes & AUTHCHAP)
3998 strcat(config->radius_authtypes_s, ", chap");
3999 }
4000 else
4001 {
4002 strcpy(config->radius_authtypes_s, "chap");
4003 if (config->radius_authtypes & AUTHPAP)
4004 strcat(config->radius_authtypes_s, ", pap");
4005 }
4006
4007 // re-initialise the random number source
4008 initrandom(config->random_device);
4009
4010 // Update plugins
4011 for (i = 0; i < MAXPLUGINS; i++)
4012 {
4013 if (strcmp(config->plugins[i], config->old_plugins[i]) == 0)
4014 continue;
4015
4016 if (*config->plugins[i])
4017 {
4018 // Plugin added
4019 add_plugin(config->plugins[i]);
4020 }
4021 else if (*config->old_plugins[i])
4022 {
4023 // Plugin removed
4024 remove_plugin(config->old_plugins[i]);
4025 }
4026 }
4027
4028 memcpy(config->old_plugins, config->plugins, sizeof(config->plugins));
4029 if (!config->cleanup_interval) config->cleanup_interval = 10;
4030 if (!config->multi_read_count) config->multi_read_count = 10;
4031 if (!config->cluster_address) config->cluster_address = inet_addr(DEFAULT_MCAST_ADDR);
4032 if (!*config->cluster_interface)
4033 strncpy(config->cluster_interface, DEFAULT_MCAST_INTERFACE, sizeof(config->cluster_interface) - 1);
4034
4035 if (!config->cluster_hb_interval)
4036 config->cluster_hb_interval = PING_INTERVAL; // Heartbeat every 0.5 seconds.
4037
4038 if (!config->cluster_hb_timeout)
4039 config->cluster_hb_timeout = HB_TIMEOUT; // 10 missed heartbeat triggers an election.
4040
4041 if (interval != config->cluster_hb_interval || timeout != config->cluster_hb_timeout)
4042 {
4043 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
4044 // late, ensure we're sufficiently larger than that
4045 int t = 4 * config->cluster_hb_interval + 11;
4046
4047 if (config->cluster_hb_timeout < t)
4048 {
4049 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config->cluster_hb_timeout, t);
4050 config->cluster_hb_timeout = t;
4051 }
4052
4053 // Push timing changes to the slaves immediately if we're the master
4054 if (config->cluster_iam_master)
4055 cluster_heartbeat();
4056
4057 interval = config->cluster_hb_interval;
4058 timeout = config->cluster_hb_timeout;
4059 }
4060
4061 // Write PID file
4062 if (*config->pid_file == '/' && !config->wrote_pid)
4063 {
4064 FILE *f;
4065 if ((f = fopen(config->pid_file, "w")))
4066 {
4067 fprintf(f, "%d\n", getpid());
4068 fclose(f);
4069 config->wrote_pid = 1;
4070 }
4071 else
4072 {
4073 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config->pid_file, strerror(errno));
4074 }
4075 }
4076
4077 config->reload_config = 0;
4078 }
4079
4080 static void read_config_file()
4081 {
4082 FILE *f;
4083
4084 if (!config->config_file) return;
4085 if (!(f = fopen(config->config_file, "r")))
4086 {
4087 fprintf(stderr, "Can't open config file %s: %s\n", config->config_file, strerror(errno));
4088 return;
4089 }
4090
4091 LOG(3, 0, 0, "Reading config file %s\n", config->config_file);
4092 cli_do_file(f);
4093 LOG(3, 0, 0, "Done reading config file\n");
4094 fclose(f);
4095 update_config();
4096 }
4097
4098 int sessionsetup(tunnelidt t, sessionidt s)
4099 {
4100 // A session now exists, set it up
4101 in_addr_t ip;
4102 char *user;
4103 sessionidt i;
4104 int r;
4105
4106 CSTAT(sessionsetup);
4107
4108 LOG(3, s, t, "Doing session setup for session\n");
4109
4110 if (!session[s].ip)
4111 {
4112 assign_ip_address(s);
4113 if (!session[s].ip)
4114 {
4115 LOG(0, s, t, " No IP allocated. The IP address pool is FULL!\n");
4116 sessionshutdown(s, "No IP addresses available.", 2, 7);
4117 return 0;
4118 }
4119 LOG(3, s, t, " No IP allocated. Assigned %s from pool\n",
4120 fmtaddr(htonl(session[s].ip), 0));
4121 }
4122
4123
4124 // Make sure this is right
4125 session[s].tunnel = t;
4126
4127 // zap old sessions with same IP and/or username
4128 // Don't kill gardened sessions - doing so leads to a DoS
4129 // from someone who doesn't need to know the password
4130 {
4131 ip = session[s].ip;
4132 user = session[s].user;
4133 for (i = 1; i <= config->cluster_highest_sessionid; i++)
4134 {
4135 if (i == s) continue;
4136 if (ip == session[i].ip) sessionkill(i, "Duplicate IP address");
4137 if (!session[s].walled_garden && !session[i].walled_garden && strcasecmp(user, session[i].user) == 0)
4138 sessionkill(i, "Duplicate session for users");
4139 }
4140 }
4141
4142 {
4143 int routed = 0;
4144
4145 // Add the route for this session.
4146 for (r = 0; r < MAXROUTE && session[s].route[r].ip; r++)
4147 {
4148 if ((session[s].ip & session[s].route[r].mask) ==
4149 (session[s].route[r].ip & session[s].route[r].mask))
4150 routed++;
4151
4152 routeset(s, session[s].route[r].ip, session[s].route[r].mask, 0, 1);
4153 }
4154
4155 // Static IPs need to be routed if not already
4156 // convered by a Framed-Route. Anything else is part
4157 // of the IP address pool and is already routed, it
4158 // just needs to be added to the IP cache.
4159 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
4160 if (session[s].ip_pool_index == -1) // static ip
4161 {
4162 if (!routed) routeset(s, session[s].ip, 0, 0, 1);
4163 }
4164 else
4165 cache_ipmap(session[s].ip, s);
4166 }
4167
4168 if (!session[s].unique_id)
4169 {
4170 // did this session just finish radius?
4171 LOG(3, s, t, "Sending initial IPCP to client\n");
4172 sendipcp(t, s);
4173 session[s].unique_id = ++last_id;
4174 }
4175
4176 // Run the plugin's against this new session.
4177 {
4178 struct param_new_session data = { &tunnel[t], &session[s] };
4179 run_plugins(PLUGIN_NEW_SESSION, &data);
4180 }
4181
4182 // Allocate TBFs if throttled
4183 if (session[s].throttle_in || session[s].throttle_out)
4184 throttle_session(s, session[s].throttle_in, session[s].throttle_out);
4185
4186 session[s].last_packet = time_now;
4187
4188 LOG(2, s, t, "Login by %s at %s from %s (%s)\n", session[s].user,
4189 fmtaddr(htonl(session[s].ip), 0),
4190 fmtaddr(htonl(tunnel[t].ip), 1), tunnel[t].hostname);
4191
4192 cluster_send_session(s); // Mark it as dirty, and needing to the flooded to the cluster.
4193
4194 return 1; // RADIUS OK and IP allocated, done...
4195 }
4196
4197 //
4198 // This session just got dropped on us by the master or something.
4199 // Make sure our tables up up to date...
4200 //
4201 int load_session(sessionidt s, sessiont *new)
4202 {
4203 int i;
4204 int newip = 0;
4205
4206 // Sanity checks.
4207 if (new->ip_pool_index >= MAXIPPOOL ||
4208 new->tunnel >= MAXTUNNEL)
4209 {
4210 LOG(0, s, 0, "Strange session update received!\n");
4211 // FIXME! What to do here?
4212 return 0;
4213 }
4214
4215 //
4216 // Ok. All sanity checks passed. Now we're committed to
4217 // loading the new session.
4218 //
4219
4220 session[s].tunnel = new->tunnel; // For logging in cache_ipmap
4221
4222 // See if routes/ip cache need updating
4223 if (new->ip != session[s].ip)
4224 newip++;
4225
4226 for (i = 0; !newip && i < MAXROUTE && (session[s].route[i].ip || new->route[i].ip); i++)
4227 if (new->route[i].ip != session[s].route[i].ip ||
4228 new->route[i].mask != session[s].route[i].mask)
4229 newip++;
4230
4231 // needs update
4232 if (newip)
4233 {
4234 int routed = 0;
4235
4236 // remove old routes...
4237 for (i = 0; i < MAXROUTE && session[s].route[i].ip; i++)
4238 {
4239 if ((session[s].ip & session[s].route[i].mask) ==
4240 (session[s].route[i].ip & session[s].route[i].mask))
4241 routed++;
4242
4243 routeset(s, session[s].route[i].ip, session[s].route[i].mask, 0, 0);
4244 }
4245
4246 // ...ip
4247 if (session[s].ip)
4248 {
4249 if (session[s].ip_pool_index == -1) // static IP
4250 {
4251 if (!routed) routeset(s, session[s].ip, 0, 0, 0);
4252 }
4253 else // It's part of the IP pool, remove it manually.
4254 uncache_ipmap(session[s].ip);
4255 }
4256
4257 routed = 0;
4258
4259 // add new routes...
4260 for (i = 0; i < MAXROUTE && new->route[i].ip; i++)
4261 {
4262 if ((new->ip & new->route[i].mask) ==
4263 (new->route[i].ip & new->route[i].mask))
4264 routed++;
4265
4266 routeset(s, new->route[i].ip, new->route[i].mask, 0, 1);
4267 }
4268
4269 // ...ip
4270 if (new->ip)
4271 {
4272 // If there's a new one, add it.
4273 if (new->ip_pool_index == -1)
4274 {
4275 if (!routed) routeset(s, new->ip, 0, 0, 1);
4276 }
4277 else
4278 cache_ipmap(new->ip, s);
4279 }
4280 }
4281
4282 // check v6 routing
4283 if (new->flags & SF_IPV6_ROUTED && !(session[s].flags & SF_IPV6_ROUTED))
4284 route6set(s, new->ipv6route, new->ipv6prefixlen, 1);
4285
4286 // check filters
4287 if (new->filter_in && (new->filter_in > MAXFILTER || !ip_filters[new->filter_in - 1].name[0]))
4288 {
4289 LOG(2, s, session[s].tunnel, "Dropping invalid input filter %d\n", (int) new->filter_in);
4290 new->filter_in = 0;
4291 }
4292
4293 if (new->filter_out && (new->filter_out > MAXFILTER || !ip_filters[new->filter_out - 1].name[0]))
4294 {
4295 LOG(2, s, session[s].tunnel, "Dropping invalid output filter %d\n", (int) new->filter_out);
4296 new->filter_out = 0;
4297 }
4298
4299 if (new->filter_in != session[s].filter_in)
4300 {
4301 if (session[s].filter_in) ip_filters[session[s].filter_in - 1].used--;
4302 if (new->filter_in) ip_filters[new->filter_in - 1].used++;
4303 }
4304
4305 if (new->filter_out != session[s].filter_out)
4306 {
4307 if (session[s].filter_out) ip_filters[session[s].filter_out - 1].used--;
4308 if (new->filter_out) ip_filters[new->filter_out - 1].used++;
4309 }
4310
4311 if (new->tunnel && s > config->cluster_highest_sessionid) // Maintain this in the slave. It's used
4312 // for walking the sessions to forward byte counts to the master.
4313 config->cluster_highest_sessionid = s;
4314
4315 // TEMP: old session struct used a uint32_t to define the throttle
4316 // speed for both up/down, new uses a uint16_t for each. Deal with
4317 // sessions from an old master for migration.
4318 if (new->throttle_out == 0 && new->tbf_out)
4319 new->throttle_out = new->throttle_in;
4320
4321 memcpy(&session[s], new, sizeof(session[s])); // Copy over..
4322
4323 // Do fixups into address pool.
4324 if (new->ip_pool_index != -1)
4325 fix_address_pool(s);
4326
4327 return 1;
4328 }
4329
4330 static void initplugins()
4331 {
4332 int i;
4333
4334 loaded_plugins = ll_init();
4335 // Initialize the plugins to nothing
4336 for (i = 0; i < MAX_PLUGIN_TYPES; i++)
4337 plugins[i] = ll_init();
4338 }
4339
4340 static void *open_plugin(char *plugin_name, int load)
4341 {
4342 char path[256] = "";
4343
4344 snprintf(path, 256, PLUGINDIR "/%s.so", plugin_name);
4345 LOG(2, 0, 0, "%soading plugin from %s\n", load ? "L" : "Un-l", path);
4346 return dlopen(path, RTLD_NOW);
4347 }
4348
4349 // plugin callback to get a config value
4350 static void *getconfig(char *key, enum config_typet type)
4351 {
4352 int i;
4353
4354 for (i = 0; config_values[i].key; i++)
4355 {
4356 if (!strcmp(config_values[i].key, key))
4357 {
4358 if (config_values[i].type == type)
4359 return ((void *) config) + config_values[i].offset;
4360
4361 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
4362 key, type, config_values[i].type);
4363
4364 return 0;
4365 }
4366 }
4367
4368 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key);
4369 return 0;
4370 }
4371
4372 static int add_plugin(char *plugin_name)
4373 {
4374 static struct pluginfuncs funcs = {
4375 _log,
4376 _log_hex,
4377 fmtaddr,
4378 sessionbyuser,
4379 sessiontbysessionidt,
4380 sessionidtbysessiont,
4381 radiusnew,
4382 radiussend,
4383 getconfig,
4384 sessionkill,
4385 throttle_session,
4386 cluster_send_session,
4387 };
4388
4389 void *p = open_plugin(plugin_name, 1);
4390 int (*initfunc)(struct pluginfuncs *);
4391 int i;
4392
4393 if (!p)
4394 {
4395 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
4396 return -1;
4397 }
4398
4399 if (ll_contains(loaded_plugins, p))
4400 {
4401 dlclose(p);
4402 return 0; // already loaded
4403 }
4404
4405 {
4406 int *v = dlsym(p, "plugin_api_version");
4407 if (!v || *v != PLUGIN_API_VERSION)
4408 {
4409 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
4410 dlclose(p);
4411 return -1;
4412 }
4413 }
4414
4415 if ((initfunc = dlsym(p, "plugin_init")))
4416 {
4417 if (!initfunc(&funcs))
4418 {
4419 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
4420 dlclose(p);
4421 return -1;
4422 }
4423 }
4424
4425 ll_push(loaded_plugins, p);
4426
4427 for (i = 0; i < max_plugin_functions; i++)
4428 {
4429 void *x;
4430 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
4431 {
4432 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions[i]);
4433 ll_push(plugins[i], x);
4434 }
4435 }
4436
4437 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name);
4438 return 1;
4439 }
4440
4441 static void run_plugin_done(void *plugin)
4442 {
4443 int (*donefunc)(void) = dlsym(plugin, "plugin_done");
4444
4445 if (donefunc)
4446 donefunc();
4447 }
4448
4449 static int remove_plugin(char *plugin_name)
4450 {
4451 void *p = open_plugin(plugin_name, 0);
4452 int loaded = 0;
4453
4454 if (!p)
4455 return -1;
4456
4457 if (ll_contains(loaded_plugins, p))
4458 {
4459 int i;
4460 for (i = 0; i < max_plugin_functions; i++)
4461 {
4462 void *x;
4463 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
4464 ll_delete(plugins[i], x);
4465 }
4466
4467 ll_delete(loaded_plugins, p);
4468 run_plugin_done(p);
4469 loaded = 1;
4470 }
4471
4472 dlclose(p);
4473 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name);
4474 return loaded;
4475 }
4476
4477 int run_plugins(int plugin_type, void *data)
4478 {
4479 int (*func)(void *data);
4480
4481 if (!plugins[plugin_type] || plugin_type > max_plugin_functions)
4482 return PLUGIN_RET_ERROR;
4483
4484 ll_reset(plugins[plugin_type]);
4485 while ((func = ll_next(plugins[plugin_type])))
4486 {
4487 int r = func(data);
4488
4489 if (r != PLUGIN_RET_OK)
4490 return r; // stop here
4491 }
4492
4493 return PLUGIN_RET_OK;
4494 }
4495
4496 static void plugins_done()
4497 {
4498 void *p;
4499
4500 ll_reset(loaded_plugins);
4501 while ((p = ll_next(loaded_plugins)))
4502 run_plugin_done(p);
4503 }
4504
4505 static void processcontrol(uint8_t * buf, int len, struct sockaddr_in *addr, int alen)
4506 {
4507 struct nsctl request;
4508 struct nsctl response;
4509 int type = unpack_control(&request, buf, len);
4510 int r;
4511 void *p;
4512
4513 if (log_stream && config->debug >= 4)
4514 {
4515 if (type < 0)
4516 {
4517 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4518 fmtaddr(addr->sin_addr.s_addr, 0), type);
4519 }
4520 else
4521 {
4522 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
4523 dump_control(&request, log_stream);
4524 }
4525 }
4526
4527 switch (type)
4528 {
4529 case NSCTL_REQ_LOAD:
4530 if (request.argc != 1)
4531 {
4532 response.type = NSCTL_RES_ERR;
4533 response.argc = 1;
4534 response.argv[0] = "name of plugin required";
4535 }
4536 else if ((r = add_plugin(request.argv[0])) < 1)
4537 {
4538 response.type = NSCTL_RES_ERR;
4539 response.argc = 1;
4540 response.argv[0] = !r
4541 ? "plugin already loaded"
4542 : "error loading plugin";
4543 }
4544 else
4545 {
4546 response.type = NSCTL_RES_OK;
4547 response.argc = 0;
4548 }
4549
4550 break;
4551
4552 case NSCTL_REQ_UNLOAD:
4553 if (request.argc != 1)
4554 {
4555 response.type = NSCTL_RES_ERR;
4556 response.argc = 1;
4557 response.argv[0] = "name of plugin required";
4558 }
4559 else if ((r = remove_plugin(request.argv[0])) < 1)
4560 {
4561 response.type = NSCTL_RES_ERR;
4562 response.argc = 1;
4563 response.argv[0] = !r
4564 ? "plugin not loaded"
4565 : "plugin not found";
4566 }
4567 else
4568 {
4569 response.type = NSCTL_RES_OK;
4570 response.argc = 0;
4571 }
4572
4573 break;
4574
4575 case NSCTL_REQ_HELP:
4576 response.type = NSCTL_RES_OK;
4577 response.argc = 0;
4578
4579 ll_reset(loaded_plugins);
4580 while ((p = ll_next(loaded_plugins)))
4581 {
4582 char **help = dlsym(p, "plugin_control_help");
4583 while (response.argc < 0xff && help && *help)
4584 response.argv[response.argc++] = *help++;
4585 }
4586
4587 break;
4588
4589 case NSCTL_REQ_CONTROL:
4590 {
4591 struct param_control param = {
4592 config->cluster_iam_master,
4593 request.argc,
4594 request.argv,
4595 0,
4596 NULL,
4597 };
4598
4599 int r = run_plugins(PLUGIN_CONTROL, &param);
4600
4601 if (r == PLUGIN_RET_ERROR)
4602 {
4603 response.type = NSCTL_RES_ERR;
4604 response.argc = 1;
4605 response.argv[0] = param.additional
4606 ? param.additional
4607 : "error returned by plugin";
4608 }
4609 else if (r == PLUGIN_RET_NOTMASTER)
4610 {
4611 static char msg[] = "must be run on master: 000.000.000.000";
4612
4613 response.type = NSCTL_RES_ERR;
4614 response.argc = 1;
4615 if (config->cluster_master_address)
4616 {
4617 strcpy(msg + 23, fmtaddr(config->cluster_master_address, 0));
4618 response.argv[0] = msg;
4619 }
4620 else
4621 {
4622 response.argv[0] = "must be run on master: none elected";
4623 }
4624 }
4625 else if (!(param.response & NSCTL_RESPONSE))
4626 {
4627 response.type = NSCTL_RES_ERR;
4628 response.argc = 1;
4629 response.argv[0] = param.response
4630 ? "unrecognised response value from plugin"
4631 : "unhandled action";
4632 }
4633 else
4634 {
4635 response.type = param.response;
4636 response.argc = 0;
4637 if (param.additional)
4638 {
4639 response.argc = 1;
4640 response.argv[0] = param.additional;
4641 }
4642 }
4643 }
4644
4645 break;
4646
4647 default:
4648 response.type = NSCTL_RES_ERR;
4649 response.argc = 1;
4650 response.argv[0] = "error unpacking control packet";
4651 }
4652
4653 buf = calloc(NSCTL_MAX_PKT_SZ, 1);
4654 if (!buf)
4655 {
4656 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4657 return;
4658 }
4659
4660 r = pack_control(buf, NSCTL_MAX_PKT_SZ, response.type, response.argc, response.argv);
4661 if (r > 0)
4662 {
4663 sendto(controlfd, buf, r, 0, (const struct sockaddr *) addr, alen);
4664 if (log_stream && config->debug >= 4)
4665 {
4666 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
4667 dump_control(&response, log_stream);
4668 }
4669 }
4670 else
4671 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4672 fmtaddr(addr->sin_addr.s_addr, 0), r);
4673
4674 free(buf);
4675 }
4676
4677 static tunnelidt new_tunnel()
4678 {
4679 tunnelidt i;
4680 for (i = 1; i < MAXTUNNEL; i++)
4681 {
4682 if (tunnel[i].state == TUNNELFREE)
4683 {
4684 LOG(4, 0, i, "Assigning tunnel ID %d\n", i);
4685 if (i > config->cluster_highest_tunnelid)
4686 config->cluster_highest_tunnelid = i;
4687 return i;
4688 }
4689 }
4690 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4691 return 0;
4692 }
4693
4694 //
4695 // We're becoming the master. Do any required setup..
4696 //
4697 // This is principally telling all the plugins that we're
4698 // now a master, and telling them about all the sessions
4699 // that are active too..
4700 //
4701 void become_master(void)
4702 {
4703 int s, i;
4704 run_plugins(PLUGIN_BECOME_MASTER, NULL);
4705
4706 // running a bunch of iptables commands is slow and can cause
4707 // the master to drop tunnels on takeover--kludge around the
4708 // problem by forking for the moment (note: race)
4709 if (!fork_and_close())
4710 {
4711 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
4712 {
4713 if (!session[s].opened) // Not an in-use session.
4714 continue;
4715
4716 run_plugins(PLUGIN_NEW_SESSION_MASTER, &session[s]);
4717 }
4718 exit(0);
4719 }
4720
4721 // add radius fds
4722 for (i = 0; i < config->num_radfds; i++)
4723 {
4724 FD_SET(radfds[i], &readset);
4725 if (radfds[i] > readset_n)
4726 readset_n = radfds[i];
4727 }
4728 }
4729
4730 int cmd_show_hist_idle(struct cli_def *cli, char *command, char **argv, int argc)
4731 {
4732 int s, i;
4733 int count = 0;
4734 int buckets[64];
4735
4736 if (CLI_HELP_REQUESTED)
4737 return CLI_HELP_NO_ARGS;
4738
4739 time(&time_now);
4740 for (i = 0; i < 64;++i) buckets[i] = 0;
4741
4742 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
4743 {
4744 int idle;
4745 if (!session[s].opened)
4746 continue;
4747
4748 idle = time_now - session[s].last_packet;
4749 idle /= 5 ; // In multiples of 5 seconds.
4750 if (idle < 0)
4751 idle = 0;
4752 if (idle > 63)
4753 idle = 63;
4754
4755 ++count;
4756 ++buckets[idle];
4757 }
4758
4759 for (i = 0; i < 63; ++i)
4760 {
4761 cli_print(cli, "%3d seconds : %7.2f%% (%6d)", i * 5, (double) buckets[i] * 100.0 / count , buckets[i]);
4762 }
4763 cli_print(cli, "lots of secs : %7.2f%% (%6d)", (double) buckets[63] * 100.0 / count , buckets[i]);
4764 cli_print(cli, "%d total sessions open.", count);
4765 return CLI_OK;
4766 }
4767
4768 int cmd_show_hist_open(struct cli_def *cli, char *command, char **argv, int argc)
4769 {
4770 int s, i;
4771 int count = 0;
4772 int buckets[64];
4773
4774 if (CLI_HELP_REQUESTED)
4775 return CLI_HELP_NO_ARGS;
4776
4777 time(&time_now);
4778 for (i = 0; i < 64;++i) buckets[i] = 0;
4779
4780 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
4781 {
4782 int open = 0, d;
4783 if (!session[s].opened)
4784 continue;
4785
4786 d = time_now - session[s].opened;
4787 if (d < 0)
4788 d = 0;
4789 while (d > 1 && open < 32)
4790 {
4791 ++open;
4792 d >>= 1; // half.
4793 }
4794 ++count;
4795 ++buckets[open];
4796 }
4797
4798 s = 1;
4799 for (i = 0; i < 30; ++i)
4800 {
4801 cli_print(cli, " < %8d seconds : %7.2f%% (%6d)", s, (double) buckets[i] * 100.0 / count , buckets[i]);
4802 s <<= 1;
4803 }
4804 cli_print(cli, "%d total sessions open.", count);
4805 return CLI_OK;
4806 }
4807
4808 /* Unhide an avp.
4809 *
4810 * This unencodes the AVP using the L2TP secret and the previously
4811 * stored random vector. It overwrites the hidden data with the
4812 * unhidden AVP subformat.
4813 */
4814 static void unhide_value(uint8_t *value, size_t len, uint16_t type, uint8_t *vector, size_t vec_len)
4815 {
4816 MD5_CTX ctx;
4817 uint8_t digest[16];
4818 uint8_t *last;
4819 size_t d = 0;
4820
4821 // Compute initial pad
4822 MD5Init(&ctx);
4823 MD5Update(&ctx, (uint8_t) (type >> 8) & 0xff, 1);
4824 MD5Update(&ctx, (uint8_t) type & 0xff, 1);
4825 MD5Update(&ctx, config->l2tpsecret, strlen(config->l2tpsecret));
4826 MD5Update(&ctx, vector, vec_len);
4827 MD5Final(digest, &ctx);
4828
4829 // pointer to last decoded 16 octets
4830 last = value;
4831
4832 while (len > 0)
4833 {
4834 // calculate a new pad based on the last decoded block
4835 if (d >= sizeof(digest))
4836 {
4837 MD5Init(&ctx);
4838 MD5Update(&ctx, config->l2tpsecret, strlen(config->l2tpsecret));
4839 MD5Update(&ctx, last, sizeof(digest));
4840 MD5Final(digest, &ctx);
4841
4842 d = 0;
4843 last = value;
4844 }
4845
4846 *value++ ^= digest[d++];
4847 len--;
4848 }
4849 }
4850
4851 static int ip_filter_port(ip_filter_portt *p, uint16_t port)
4852 {
4853 switch (p->op)
4854 {
4855 case FILTER_PORT_OP_EQ: return port == p->port;
4856 case FILTER_PORT_OP_NEQ: return port != p->port;
4857 case FILTER_PORT_OP_GT: return port > p->port;
4858 case FILTER_PORT_OP_LT: return port < p->port;
4859 case FILTER_PORT_OP_RANGE: return port >= p->port && port <= p->port2;
4860 }
4861
4862 return 0;
4863 }
4864
4865 static int ip_filter_flag(uint8_t op, uint8_t sflags, uint8_t cflags, uint8_t flags)
4866 {
4867 switch (op)
4868 {
4869 case FILTER_FLAG_OP_ANY:
4870 return (flags & sflags) || (~flags & cflags);
4871
4872 case FILTER_FLAG_OP_ALL:
4873 return (flags & sflags) == sflags && (~flags & cflags) == cflags;
4874
4875 case FILTER_FLAG_OP_EST:
4876 return (flags & (TCP_FLAG_ACK|TCP_FLAG_RST)) && (~flags & TCP_FLAG_SYN);
4877 }
4878
4879 return 0;
4880 }
4881
4882 int ip_filter(uint8_t *buf, int len, uint8_t filter)
4883 {
4884 uint16_t frag_offset;
4885 uint8_t proto;
4886 in_addr_t src_ip;
4887 in_addr_t dst_ip;
4888 uint16_t src_port = 0;
4889 uint16_t dst_port = 0;
4890 uint8_t flags = 0;
4891 ip_filter_rulet *rule;
4892
4893 if (len < 20) // up to end of destination address
4894 return 0;
4895
4896 if ((*buf >> 4) != 4) // IPv4
4897 return 0;
4898
4899 frag_offset = ntohs(*(uint16_t *) (buf + 6)) & 0x1fff;
4900 proto = buf[9];
4901 src_ip = *(in_addr_t *) (buf + 12);
4902 dst_ip = *(in_addr_t *) (buf + 16);
4903
4904 if (frag_offset == 0 && (proto == IPPROTO_TCP || proto == IPPROTO_UDP))
4905 {
4906 int l = (buf[0] & 0xf) * 4; // length of IP header
4907 if (len < l + 4) // ports
4908 return 0;
4909
4910 src_port = ntohs(*(uint16_t *) (buf + l));
4911 dst_port = ntohs(*(uint16_t *) (buf + l + 2));
4912 if (proto == IPPROTO_TCP)
4913 {
4914 if (len < l + 14) // flags
4915 return 0;
4916
4917 flags = buf[l + 13] & 0x3f;
4918 }
4919 }
4920
4921 for (rule = ip_filters[filter].rules; rule->action; rule++)
4922 {
4923 if (rule->proto != IPPROTO_IP && proto != rule->proto)
4924 continue;
4925
4926 if (rule->src_wild != INADDR_BROADCAST &&
4927 (src_ip & ~rule->src_wild) != (rule->src_ip & ~rule->src_wild))
4928 continue;
4929
4930 if (rule->dst_wild != INADDR_BROADCAST &&
4931 (dst_ip & ~rule->dst_wild) != (rule->dst_ip & ~rule->dst_wild))
4932 continue;
4933
4934 if (frag_offset)
4935 {
4936 if (!rule->frag || rule->action == FILTER_ACTION_DENY)
4937 continue;
4938 }
4939 else
4940 {
4941 if (rule->frag)
4942 continue;
4943
4944 if (proto == IPPROTO_TCP || proto == IPPROTO_UDP)
4945 {
4946 if (rule->src_ports.op && !ip_filter_port(&rule->src_ports, src_port))
4947 continue;
4948
4949 if (rule->dst_ports.op && !ip_filter_port(&rule->dst_ports, dst_port))
4950 continue;
4951
4952 if (proto == IPPROTO_TCP && rule->tcp_flag_op &&
4953 !ip_filter_flag(rule->tcp_flag_op, rule->tcp_sflags, rule->tcp_cflags, flags))
4954 continue;
4955 }
4956 }
4957
4958 // matched
4959 rule->counter++;
4960 return rule->action == FILTER_ACTION_PERMIT;
4961 }
4962
4963 // default deny
4964 return 0;
4965 }