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