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