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