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