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