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