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