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