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