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