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