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