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