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