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