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