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