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