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