aed42ddcc52467e60443ffb06c9f74d4a881369a
[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.67 2004-12-13 05:20:39 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 dump_acct_info(1);
2210 }
2211 else if (next_shut_acct <= TIME)
2212 {
2213 // Dump accounting data for shutdown sessions
2214 next_shut_acct = TIME + ACCT_SHUT_TIME;
2215 if (shut_acct_n)
2216 dump_acct_info(0);
2217 }
2218 }
2219
2220 if (count >= MAX_ACTIONS)
2221 return 1; // Didn't finish!
2222
2223 LOG(3, 0, 0, "End regular cleanup (%d actions), next in %d seconds\n", count, config->cleanup_interval);
2224 return 0;
2225 }
2226
2227
2228 //
2229 // Are we in the middle of a tunnel update, or radius
2230 // requests??
2231 //
2232 static int still_busy(void)
2233 {
2234 int i;
2235 static clockt last_talked = 0;
2236 static clockt start_busy_wait = 0;
2237 if (start_busy_wait == 0)
2238 start_busy_wait = TIME;
2239
2240 for (i = config->cluster_highest_tunnelid ; i > 0 ; --i)
2241 {
2242 if (!tunnel[i].controlc)
2243 continue;
2244
2245 if (last_talked != TIME)
2246 {
2247 LOG(2, 0, 0, "Tunnel %d still has un-acked control messages.\n", i);
2248 last_talked = TIME;
2249 }
2250 return 1;
2251 }
2252
2253 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
2254 if (abs(TIME - start_busy_wait) > BUSY_WAIT_TIME)
2255 {
2256 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
2257 return 0;
2258 }
2259
2260 for (i = 1; i < MAXRADIUS; i++)
2261 {
2262 if (radius[i].state == RADIUSNULL)
2263 continue;
2264 if (radius[i].state == RADIUSWAIT)
2265 continue;
2266
2267 if (last_talked != TIME)
2268 {
2269 LOG(2, 0, 0, "Radius session %d is still busy (sid %d)\n", i, radius[i].session);
2270 last_talked = TIME;
2271 }
2272 return 1;
2273 }
2274
2275 return 0;
2276 }
2277
2278 static fd_set readset;
2279 static int readset_n = 0;
2280
2281 // main loop - gets packets on tun or udp and processes them
2282 static void mainloop(void)
2283 {
2284 int i;
2285 u8 buf[65536];
2286 struct timeval to;
2287 clockt next_cluster_ping = 0; // send initial ping immediately
2288 time_t next_clean = time_now + config->cleanup_interval;
2289
2290 LOG(4, 0, 0, "Beginning of main loop. udpfd=%d, tunfd=%d, cluster_sockfd=%d, controlfd=%d\n",
2291 udpfd, tunfd, cluster_sockfd, controlfd);
2292
2293 FD_ZERO(&readset);
2294 FD_SET(udpfd, &readset);
2295 FD_SET(tunfd, &readset);
2296 FD_SET(controlfd, &readset);
2297 FD_SET(clifd, &readset);
2298 if (cluster_sockfd) FD_SET(cluster_sockfd, &readset);
2299 readset_n = udpfd;
2300 if (tunfd > readset_n) readset_n = tunfd;
2301 if (controlfd > readset_n) readset_n = controlfd;
2302 if (clifd > readset_n) readset_n = clifd;
2303 if (cluster_sockfd > readset_n) readset_n = cluster_sockfd;
2304
2305 while (!main_quit || still_busy())
2306 {
2307 fd_set r;
2308 int n = readset_n;
2309 #ifdef BGP
2310 fd_set w;
2311 int bgp_set[BGP_NUM_PEERS];
2312 #endif /* BGP */
2313
2314 if (config->reload_config)
2315 {
2316 // Update the config state based on config settings
2317 update_config();
2318 }
2319
2320 memcpy(&r, &readset, sizeof(fd_set));
2321 to.tv_sec = 0;
2322 to.tv_usec = 100000; // 1/10th of a second.
2323
2324 #ifdef BGP
2325 FD_ZERO(&w);
2326 for (i = 0; i < BGP_NUM_PEERS; i++)
2327 {
2328 bgp_set[i] = bgp_select_state(&bgp_peers[i]);
2329 if (bgp_set[i] & 1)
2330 {
2331 FD_SET(bgp_peers[i].sock, &r);
2332 if (bgp_peers[i].sock > n)
2333 n = bgp_peers[i].sock;
2334 }
2335
2336 if (bgp_set[i] & 2)
2337 {
2338 FD_SET(bgp_peers[i].sock, &w);
2339 if (bgp_peers[i].sock > n)
2340 n = bgp_peers[i].sock;
2341 }
2342 }
2343
2344 n = select(n + 1, &r, &w, 0, &to);
2345 #else /* BGP */
2346 n = select(n + 1, &r, 0, 0, &to);
2347 #endif /* BGP */
2348
2349 TIME = now();
2350 if (n < 0)
2351 {
2352 if (errno == EINTR ||
2353 errno == ECHILD) // EINTR was clobbered by sigchild_handler()
2354 continue;
2355
2356 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno));
2357 main_quit++;
2358 break;
2359 }
2360 else if (n)
2361 {
2362 struct sockaddr_in addr;
2363 int alen, c, s;
2364
2365 // nsctl commands
2366 if (FD_ISSET(controlfd, &r))
2367 {
2368 alen = sizeof(addr);
2369 processcontrol(buf, recvfrom(controlfd, buf, sizeof(buf), MSG_WAITALL, (void *) &addr, &alen), &addr, alen);
2370 n--;
2371 }
2372
2373 // RADIUS responses
2374 if (config->cluster_iam_master)
2375 {
2376 for (i = 0; i < config->num_radfds; i++)
2377 {
2378 if (FD_ISSET(radfds[i], &r))
2379 {
2380 processrad(buf, recv(radfds[i], buf, sizeof(buf), 0), i);
2381 n--;
2382 }
2383 }
2384 }
2385
2386 // CLI connections
2387 if (FD_ISSET(clifd, &r))
2388 {
2389 int cli;
2390
2391 alen = sizeof(addr);
2392 if ((cli = accept(clifd, (struct sockaddr *)&addr, &alen)) >= 0)
2393 {
2394 cli_do(cli);
2395 close(cli);
2396 }
2397 else
2398 LOG(0, 0, 0, "accept error: %s\n", strerror(errno));
2399
2400 n--;
2401 }
2402
2403 #ifdef BGP
2404 for (i = 0; i < BGP_NUM_PEERS; i++)
2405 {
2406 int isr = bgp_set[i] ? FD_ISSET(bgp_peers[i].sock, &r) : 0;
2407 int isw = bgp_set[i] ? FD_ISSET(bgp_peers[i].sock, &w) : 0;
2408 bgp_process(&bgp_peers[i], isr, isw);
2409 if (isr) n--;
2410 if (isw) n--;
2411 }
2412 #endif /* BGP */
2413
2414 for (c = 0; n && c < config->multi_read_count; c++)
2415 {
2416 // L2TP
2417 if (FD_ISSET(udpfd, &r))
2418 {
2419 alen = sizeof(addr);
2420 if ((s = recvfrom(udpfd, buf, sizeof(buf), 0, (void *) &addr, &alen)) > 0)
2421 {
2422 processudp(buf, s, &addr);
2423 }
2424 else
2425 {
2426 FD_CLR(udpfd, &r);
2427 n--;
2428 }
2429 }
2430
2431 // incoming IP
2432 if (FD_ISSET(tunfd, &r))
2433 {
2434 if ((s = read(tunfd, buf, sizeof(buf))) > 0)
2435 {
2436 processtun(buf, s);
2437 }
2438 else
2439 {
2440 FD_CLR(tunfd, &r);
2441 n--;
2442 }
2443 }
2444
2445 // cluster
2446 if (FD_ISSET(cluster_sockfd, &r))
2447 {
2448 alen = sizeof(addr);
2449 if ((s = recvfrom(cluster_sockfd, buf, sizeof(buf), MSG_WAITALL, (void *) &addr, &alen)) > 0)
2450 {
2451 processcluster(buf, s, addr.sin_addr.s_addr);
2452 }
2453 else
2454 {
2455 FD_CLR(cluster_sockfd, &r);
2456 n--;
2457 }
2458 }
2459 }
2460 }
2461
2462 // Runs on every machine (master and slaves).
2463 if (cluster_sockfd && next_cluster_ping <= TIME)
2464 {
2465 // Check to see which of the cluster is still alive..
2466
2467 cluster_send_ping(basetime); // Only does anything if we're a slave
2468 cluster_check_master(); // ditto.
2469
2470 cluster_heartbeat(); // Only does anything if we're a master.
2471 cluster_check_slaves(); // ditto.
2472
2473 master_update_counts(); // If we're a slave, send our byte counters to our master.
2474
2475 if (config->cluster_iam_master && !config->cluster_iam_uptodate)
2476 next_cluster_ping = TIME + 1; // out-of-date slaves, do fast updates
2477 else
2478 next_cluster_ping = TIME + config->cluster_hb_interval;
2479 }
2480
2481 // Run token bucket filtering queue..
2482 // Only run it every 1/10th of a second.
2483 // Runs on all machines both master and slave.
2484 {
2485 static clockt last_run = 0;
2486 if (last_run != TIME)
2487 {
2488 last_run = TIME;
2489 tbf_run_timer();
2490 }
2491 }
2492
2493 /* Handle timeouts. Make sure that this gets run anyway, even if there was
2494 * something to read, else under load this will never actually run....
2495 *
2496 */
2497 if (config->cluster_iam_master && next_clean <= time_now)
2498 {
2499 if (regular_cleanups())
2500 {
2501 // Did it finish?
2502 next_clean = time_now + 1 ; // Didn't finish. Check quickly.
2503 }
2504 else
2505 {
2506 next_clean = time_now + config->cleanup_interval; // Did. Move to next interval.
2507 }
2508 }
2509 }
2510
2511 // Are we the master and shutting down??
2512 if (config->cluster_iam_master)
2513 cluster_heartbeat(); // Flush any queued changes..
2514
2515 // Ok. Notify everyone we're shutting down. If we're
2516 // the master, this will force an election.
2517 cluster_send_ping(0);
2518
2519 //
2520 // Important!!! We MUST not process any packets past this point!
2521 }
2522
2523 static void stripdomain(char *host)
2524 {
2525 char *p;
2526
2527 if ((p = strchr(host, '.')))
2528 {
2529 char *domain = 0;
2530 char _domain[1024];
2531
2532 // strip off domain
2533 FILE *resolv = fopen("/etc/resolv.conf", "r");
2534 if (resolv)
2535 {
2536 char buf[1024];
2537 char *b;
2538
2539 while (fgets(buf, sizeof(buf), resolv))
2540 {
2541 if (strncmp(buf, "domain", 6) && strncmp(buf, "search", 6))
2542 continue;
2543
2544 if (!isspace(buf[6]))
2545 continue;
2546
2547 b = buf + 7;
2548 while (isspace(*b)) b++;
2549
2550 if (*b)
2551 {
2552 char *d = b;
2553 while (*b && !isspace(*b)) b++;
2554 *b = 0;
2555 if (buf[0] == 'd') // domain is canonical
2556 {
2557 domain = d;
2558 break;
2559 }
2560
2561 // first search line
2562 if (!domain)
2563 {
2564 // hold, may be subsequent domain line
2565 strncpy(_domain, d, sizeof(_domain))[sizeof(_domain)-1] = 0;
2566 domain = _domain;
2567 }
2568 }
2569 }
2570
2571 fclose(resolv);
2572 }
2573
2574 if (domain)
2575 {
2576 int hl = strlen(host);
2577 int dl = strlen(domain);
2578 if (dl < hl && host[hl - dl - 1] == '.' && !strcmp(host + hl - dl, domain))
2579 host[hl -dl - 1] = 0;
2580 }
2581 else
2582 {
2583 *p = 0; // everything after first dot
2584 }
2585 }
2586 }
2587
2588 // Init data structures
2589 static void initdata(int optdebug, char *optconfig)
2590 {
2591 int i;
2592
2593 if (!(_statistics = shared_malloc(sizeof(struct Tstats))))
2594 {
2595 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno));
2596 exit(1);
2597 }
2598 if (!(config = shared_malloc(sizeof(configt))))
2599 {
2600 LOG(0, 0, 0, "Error doing malloc for configuration: %s\n", strerror(errno));
2601 exit(1);
2602 }
2603 memset(config, 0, sizeof(configt));
2604 time(&config->start_time);
2605 strncpy(config->config_file, optconfig, strlen(optconfig));
2606 config->debug = optdebug;
2607 config->num_tbfs = MAXTBFS;
2608 config->rl_rate = 28; // 28kbps
2609
2610 if (!(tunnel = shared_malloc(sizeof(tunnelt) * MAXTUNNEL)))
2611 {
2612 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno));
2613 exit(1);
2614 }
2615 if (!(session = shared_malloc(sizeof(sessiont) * MAXSESSION)))
2616 {
2617 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno));
2618 exit(1);
2619 }
2620
2621 if (!(sess_count = shared_malloc(sizeof(sessioncountt) * MAXSESSION)))
2622 {
2623 LOG(0, 0, 0, "Error doing malloc for sessions_count: %s\n", strerror(errno));
2624 exit(1);
2625 }
2626
2627 if (!(radius = shared_malloc(sizeof(radiust) * MAXRADIUS)))
2628 {
2629 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno));
2630 exit(1);
2631 }
2632
2633 if (!(ip_address_pool = shared_malloc(sizeof(ippoolt) * MAXIPPOOL)))
2634 {
2635 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno));
2636 exit(1);
2637 }
2638
2639 if (!(ip_filters = shared_malloc(sizeof(ip_filtert) * MAXFILTER)))
2640 {
2641 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno));
2642 exit(1);
2643 }
2644 memset(ip_filters, 0, sizeof(ip_filtert) * MAXFILTER);
2645
2646 #ifdef RINGBUFFER
2647 if (!(ringbuffer = shared_malloc(sizeof(struct Tringbuffer))))
2648 {
2649 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno));
2650 exit(1);
2651 }
2652 memset(ringbuffer, 0, sizeof(struct Tringbuffer));
2653 #endif
2654
2655 if (!(cli_session_actions = shared_malloc(sizeof(struct cli_session_actions) * MAXSESSION)))
2656 {
2657 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno));
2658 exit(1);
2659 }
2660 memset(cli_session_actions, 0, sizeof(struct cli_session_actions) * MAXSESSION);
2661
2662 if (!(cli_tunnel_actions = shared_malloc(sizeof(struct cli_tunnel_actions) * MAXSESSION)))
2663 {
2664 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno));
2665 exit(1);
2666 }
2667 memset(cli_tunnel_actions, 0, sizeof(struct cli_tunnel_actions) * MAXSESSION);
2668
2669 memset(tunnel, 0, sizeof(tunnelt) * MAXTUNNEL);
2670 memset(session, 0, sizeof(sessiont) * MAXSESSION);
2671 memset(radius, 0, sizeof(radiust) * MAXRADIUS);
2672 memset(ip_address_pool, 0, sizeof(ippoolt) * MAXIPPOOL);
2673
2674 // Put all the sessions on the free list marked as undefined.
2675 for (i = 1; i < MAXSESSION - 1; i++)
2676 {
2677 session[i].next = i + 1;
2678 session[i].tunnel = T_UNDEF; // mark it as not filled in.
2679 }
2680 session[MAXSESSION - 1].next = 0;
2681 sessionfree = 1;
2682
2683 // Mark all the tunnels as undefined (waiting to be filled in by a download).
2684 for (i = 1; i < MAXTUNNEL- 1; i++)
2685 tunnel[i].state = TUNNELUNDEF; // mark it as not filled in.
2686
2687 if (!*hostname)
2688 {
2689 // Grab my hostname unless it's been specified
2690 gethostname(hostname, sizeof(hostname));
2691 stripdomain(hostname);
2692 }
2693
2694 _statistics->start_time = _statistics->last_reset = time(NULL);
2695
2696 #ifdef BGP
2697 if (!(bgp_peers = shared_malloc(sizeof(struct bgp_peer) * BGP_NUM_PEERS)))
2698 {
2699 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno));
2700 exit(1);
2701 }
2702 #endif /* BGP */
2703 }
2704
2705 static int assign_ip_address(sessionidt s)
2706 {
2707 u32 i;
2708 int best = -1;
2709 time_t best_time = time_now;
2710 char *u = session[s].user;
2711 char reuse = 0;
2712
2713
2714 CSTAT(call_assign_ip_address);
2715
2716 for (i = 1; i < ip_pool_size; i++)
2717 {
2718 if (!ip_address_pool[i].address || ip_address_pool[i].assigned)
2719 continue;
2720
2721 if (!session[s].walled_garden && ip_address_pool[i].user[0] && !strcmp(u, ip_address_pool[i].user))
2722 {
2723 best = i;
2724 reuse = 1;
2725 break;
2726 }
2727
2728 if (ip_address_pool[i].last < best_time)
2729 {
2730 best = i;
2731 if (!(best_time = ip_address_pool[i].last))
2732 break; // never used, grab this one
2733 }
2734 }
2735
2736 if (best < 0)
2737 {
2738 LOG(0, s, session[s].tunnel, "assign_ip_address(): out of addresses\n");
2739 return 0;
2740 }
2741
2742 session[s].ip = ip_address_pool[best].address;
2743 session[s].ip_pool_index = best;
2744 ip_address_pool[best].assigned = 1;
2745 ip_address_pool[best].last = time_now;
2746 ip_address_pool[best].session = s;
2747 if (session[s].walled_garden)
2748 /* Don't track addresses of users in walled garden (note: this
2749 means that their address isn't "sticky" even if they get
2750 un-gardened). */
2751 ip_address_pool[best].user[0] = 0;
2752 else
2753 strncpy(ip_address_pool[best].user, u, sizeof(ip_address_pool[best].user) - 1);
2754
2755 STAT(ip_allocated);
2756 LOG(4, s, session[s].tunnel, "assign_ip_address(): %s ip address %d from pool\n",
2757 reuse ? "Reusing" : "Allocating", best);
2758
2759 return 1;
2760 }
2761
2762 static void free_ip_address(sessionidt s)
2763 {
2764 int i = session[s].ip_pool_index;
2765
2766
2767 CSTAT(call_free_ip_address);
2768
2769 if (!session[s].ip)
2770 return; // what the?
2771
2772 if (i < 0) // Is this actually part of the ip pool?
2773 i = 0;
2774
2775 STAT(ip_freed);
2776 cache_ipmap(session[s].ip, -i); // Change the mapping to point back to the ip pool index.
2777 session[s].ip = 0;
2778 ip_address_pool[i].assigned = 0;
2779 ip_address_pool[i].session = 0;
2780 ip_address_pool[i].last = time_now;
2781 }
2782
2783 //
2784 // Fsck the address pool against the session table.
2785 // Normally only called when we become a master.
2786 //
2787 // This isn't perfect: We aren't keep tracking of which
2788 // users used to have an IP address.
2789 //
2790 void rebuild_address_pool(void)
2791 {
2792 int i;
2793
2794 //
2795 // Zero the IP pool allocation, and build
2796 // a map from IP address to pool index.
2797 for (i = 1; i < MAXIPPOOL; ++i)
2798 {
2799 ip_address_pool[i].assigned = 0;
2800 ip_address_pool[i].session = 0;
2801 if (!ip_address_pool[i].address)
2802 continue;
2803
2804 cache_ipmap(ip_address_pool[i].address, -i); // Map pool IP to pool index.
2805 }
2806
2807 for (i = 0; i < MAXSESSION; ++i)
2808 {
2809 int ipid;
2810 if (!session[i].ip || !session[i].tunnel)
2811 continue;
2812 ipid = - lookup_ipmap(htonl(session[i].ip));
2813
2814 if (session[i].ip_pool_index < 0)
2815 {
2816 // Not allocated out of the pool.
2817 if (ipid < 1) // Not found in the pool either? good.
2818 continue;
2819
2820 LOG(0, i, 0, "Session %d has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
2821 i, fmtaddr(session[i].ip, 0), ipid);
2822
2823 // Fall through and process it as part of the pool.
2824 }
2825
2826
2827 if (ipid > MAXIPPOOL || ipid < 0)
2828 {
2829 LOG(0, i, 0, "Session %d has a pool IP that's not found in the pool! (%d)\n", i, ipid);
2830 ipid = -1;
2831 session[i].ip_pool_index = ipid;
2832 continue;
2833 }
2834
2835 ip_address_pool[ipid].assigned = 1;
2836 ip_address_pool[ipid].session = i;
2837 ip_address_pool[ipid].last = time_now;
2838 strncpy(ip_address_pool[ipid].user, session[i].user, sizeof(ip_address_pool[ipid].user) - 1);
2839 session[i].ip_pool_index = ipid;
2840 cache_ipmap(session[i].ip, i); // Fix the ip map.
2841 }
2842 }
2843
2844 //
2845 // Fix the address pool to match a changed session.
2846 // (usually when the master sends us an update).
2847 static void fix_address_pool(int sid)
2848 {
2849 int ipid;
2850
2851 ipid = session[sid].ip_pool_index;
2852
2853 if (ipid > ip_pool_size)
2854 return; // Ignore it. rebuild_address_pool will fix it up.
2855
2856 if (ip_address_pool[ipid].address != session[sid].ip)
2857 return; // Just ignore it. rebuild_address_pool will take care of it.
2858
2859 ip_address_pool[ipid].assigned = 1;
2860 ip_address_pool[ipid].session = sid;
2861 ip_address_pool[ipid].last = time_now;
2862 strncpy(ip_address_pool[ipid].user, session[sid].user, sizeof(ip_address_pool[ipid].user) - 1);
2863 }
2864
2865 //
2866 // Add a block of addresses to the IP pool to hand out.
2867 //
2868 static void add_to_ip_pool(u32 addr, u32 mask)
2869 {
2870 int i;
2871 if (mask == 0)
2872 mask = 0xffffffff; // Host route only.
2873
2874 addr &= mask;
2875
2876 if (ip_pool_size >= MAXIPPOOL) // Pool is full!
2877 return ;
2878
2879 for (i = addr ;(i & mask) == addr; ++i)
2880 {
2881 if ((i & 0xff) == 0 || (i&0xff) == 255)
2882 continue; // Skip 0 and broadcast addresses.
2883
2884 ip_address_pool[ip_pool_size].address = i;
2885 ip_address_pool[ip_pool_size].assigned = 0;
2886 ++ip_pool_size;
2887 if (ip_pool_size >= MAXIPPOOL)
2888 {
2889 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr), 0));
2890 return;
2891 }
2892 }
2893 }
2894
2895 // Initialize the IP address pool
2896 static void initippool()
2897 {
2898 FILE *f;
2899 char *p;
2900 char buf[4096];
2901 memset(ip_address_pool, 0, sizeof(ip_address_pool));
2902
2903 if (!(f = fopen(IPPOOLFILE, "r")))
2904 {
2905 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE ": %s\n", strerror(errno));
2906 exit(1);
2907 }
2908
2909 while (ip_pool_size < MAXIPPOOL && fgets(buf, 4096, f))
2910 {
2911 char *pool = buf;
2912 buf[4095] = 0; // Force it to be zero terminated/
2913
2914 if (*buf == '#' || *buf == '\n')
2915 continue; // Skip comments / blank lines
2916 if ((p = (char *)strrchr(buf, '\n'))) *p = 0;
2917 if ((p = (char *)strchr(buf, ':')))
2918 {
2919 ipt src;
2920 *p = '\0';
2921 src = inet_addr(buf);
2922 if (src == INADDR_NONE)
2923 {
2924 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf);
2925 exit(1);
2926 }
2927 // This entry is for a specific IP only
2928 if (src != config->bind_address)
2929 continue;
2930 *p = ':';
2931 pool = p+1;
2932 }
2933 if ((p = (char *)strchr(pool, '/')))
2934 {
2935 // It's a range
2936 int numbits = 0;
2937 u32 start = 0, mask = 0;
2938
2939 LOG(2, 0, 0, "Adding IP address range %s\n", buf);
2940 *p++ = 0;
2941 if (!*p || !(numbits = atoi(p)))
2942 {
2943 LOG(0, 0, 0, "Invalid pool range %s\n", buf);
2944 continue;
2945 }
2946 start = ntohl(inet_addr(pool));
2947 mask = (u32)(pow(2, numbits) - 1) << (32 - numbits);
2948
2949 // Add a static route for this pool
2950 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
2951 fmtaddr(htonl(start), 0), 32 + mask);
2952
2953 routeset(0, start, mask, 0, 1);
2954
2955 add_to_ip_pool(start, mask);
2956 }
2957 else
2958 {
2959 // It's a single ip address
2960 add_to_ip_pool(inet_addr(pool), 0);
2961 }
2962 }
2963 fclose(f);
2964 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size - 1);
2965 }
2966
2967 void snoop_send_packet(char *packet, u16 size, ipt destination, u16 port)
2968 {
2969 struct sockaddr_in snoop_addr = {0};
2970 if (!destination || !port || snoopfd <= 0 || size <= 0 || !packet)
2971 return;
2972
2973 snoop_addr.sin_family = AF_INET;
2974 snoop_addr.sin_addr.s_addr = destination;
2975 snoop_addr.sin_port = ntohs(port);
2976
2977 LOG(5, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n",
2978 packet, size, fmtaddr(snoop_addr.sin_addr.s_addr, 0),
2979 htons(snoop_addr.sin_port));
2980
2981 if (sendto(snoopfd, packet, size, MSG_DONTWAIT | MSG_NOSIGNAL, (void *) &snoop_addr, sizeof(snoop_addr)) < 0)
2982 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno));
2983
2984 STAT(packets_snooped);
2985 }
2986
2987 static int dump_session(FILE **f, sessiont *s)
2988 {
2989 if (!s->opened || !s->ip || !(s->cin || s->cout) || !*s->user || s->walled_garden)
2990 return 1;
2991
2992 if (!*f)
2993 {
2994 char filename[1024];
2995 char timestr[64];
2996 time_t now = time(NULL);
2997
2998 strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&now));
2999 snprintf(filename, sizeof(filename), "%s/%s", config->accounting_dir, timestr);
3000
3001 if (!(*f = fopen(filename, "w")))
3002 {
3003 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename, strerror(errno));
3004 return 0;
3005 }
3006
3007 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename);
3008 fprintf(*f, "# dslwatch.pl dump file V1.01\n"
3009 "# host: %s\n"
3010 "# time: %ld\n"
3011 "# uptime: %ld\n"
3012 "# format: username ip qos uptxoctets downrxoctets\n",
3013 hostname,
3014 now,
3015 now - basetime);
3016 }
3017
3018 LOG(4, 0, 0, "Dumping accounting information for %s\n", s->user);
3019 fprintf(*f, "%s %s %d %u %u\n",
3020 s->user, // username
3021 fmtaddr(htonl(s->ip), 0), // ip
3022 (s->throttle_in || s->throttle_out) ? 2 : 1, // qos
3023 (u32) s->cin, // uptxoctets
3024 (u32) s->cout); // downrxoctets
3025
3026 s->pin = s->cin = 0;
3027 s->pout = s->cout = 0;
3028
3029 return 1;
3030 }
3031
3032 static void dump_acct_info(int all)
3033 {
3034 int i;
3035 FILE *f = NULL;
3036
3037
3038 CSTAT(call_dump_acct_info);
3039
3040 if (shut_acct_n)
3041 {
3042 for (i = 0; i < shut_acct_n; i++)
3043 dump_session(&f, &shut_acct[i]);
3044
3045 shut_acct_n = 0;
3046 }
3047
3048 if (all)
3049 for (i = 1; i <= config->cluster_highest_sessionid; i++)
3050 dump_session(&f, &session[i]);
3051
3052 if (f)
3053 fclose(f);
3054 }
3055
3056 // Main program
3057 int main(int argc, char *argv[])
3058 {
3059 int i;
3060 int optdebug = 0;
3061 char *optconfig = CONFIGFILE;
3062
3063 time(&basetime); // start clock
3064
3065 // scan args
3066 while ((i = getopt(argc, argv, "dvc:h:")) >= 0)
3067 {
3068 switch (i)
3069 {
3070 case 'd':
3071 if (fork()) exit(0);
3072 setsid();
3073 freopen("/dev/null", "r", stdin);
3074 freopen("/dev/null", "w", stdout);
3075 freopen("/dev/null", "w", stderr);
3076 break;
3077 case 'v':
3078 optdebug++;
3079 break;
3080 case 'c':
3081 optconfig = optarg;
3082 break;
3083 case 'h':
3084 snprintf(hostname, sizeof(hostname), "%s", optarg);
3085 break;
3086 default:
3087 printf("Args are:\n"
3088 "\t-d\t\tDetach from terminal\n"
3089 "\t-c <file>\tConfig file\n"
3090 "\t-h <hostname>\tForce hostname\n"
3091 "\t-v\t\tDebug\n");
3092
3093 return (0);
3094 break;
3095 }
3096 }
3097
3098 // Start the timer routine off
3099 time(&time_now);
3100 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
3101 signal(SIGALRM, sigalrm_handler);
3102 siginterrupt(SIGALRM, 0);
3103
3104 initplugins();
3105 initdata(optdebug, optconfig);
3106
3107 init_cli(hostname);
3108 read_config_file();
3109 init_tbf(config->num_tbfs);
3110
3111 LOG(0, 0, 0, "L2TPNS version " VERSION "\n");
3112 LOG(0, 0, 0, "Copyright (c) 2003, 2004 Optus Internet Engineering\n");
3113 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
3114 {
3115 struct rlimit rlim;
3116 rlim.rlim_cur = RLIM_INFINITY;
3117 rlim.rlim_max = RLIM_INFINITY;
3118 // Remove the maximum core size
3119 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
3120 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno));
3121
3122 // Make core dumps go to /tmp
3123 chdir("/tmp");
3124 }
3125
3126 if (config->scheduler_fifo)
3127 {
3128 int ret;
3129 struct sched_param params = {0};
3130 params.sched_priority = 1;
3131
3132 if (get_nprocs() < 2)
3133 {
3134 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
3135 config->scheduler_fifo = 0;
3136 }
3137 else
3138 {
3139 if ((ret = sched_setscheduler(0, SCHED_FIFO, &params)) == 0)
3140 {
3141 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
3142 }
3143 else
3144 {
3145 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno));
3146 config->scheduler_fifo = 0;
3147 }
3148 }
3149 }
3150
3151 /* Set up the cluster communications port. */
3152 if (cluster_init() < 0)
3153 exit(1);
3154
3155 #ifdef BGP
3156 signal(SIGPIPE, SIG_IGN);
3157 bgp_setup(config->as_number);
3158 bgp_add_route(config->bind_address, 0xffffffff);
3159 for (i = 0; i < BGP_NUM_PEERS; i++)
3160 {
3161 if (config->neighbour[i].name[0])
3162 bgp_start(&bgp_peers[i], config->neighbour[i].name,
3163 config->neighbour[i].as, config->neighbour[i].keepalive,
3164 config->neighbour[i].hold, 0); /* 0 = routing disabled */
3165 }
3166 #endif /* BGP */
3167
3168 inittun();
3169 LOG(1, 0, 0, "Set up on interface %s\n", config->tundevice);
3170
3171 initudp();
3172 initrad();
3173 initippool();
3174
3175 read_state();
3176
3177 signal(SIGHUP, sighup_handler);
3178 signal(SIGTERM, sigterm_handler);
3179 signal(SIGINT, sigterm_handler);
3180 signal(SIGQUIT, sigquit_handler);
3181 signal(SIGCHLD, sigchild_handler);
3182
3183 // Prevent us from getting paged out
3184 if (config->lock_pages)
3185 {
3186 if (!mlockall(MCL_CURRENT))
3187 LOG(1, 0, 0, "Locking pages into memory\n");
3188 else
3189 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno));
3190 }
3191
3192 alarm(1);
3193
3194 // Drop privileges here
3195 if (config->target_uid > 0 && geteuid() == 0)
3196 setuid(config->target_uid);
3197
3198 mainloop();
3199
3200 #ifdef BGP
3201 /* try to shut BGP down cleanly; with luck the sockets will be
3202 writable since we're out of the select */
3203 for (i = 0; i < BGP_NUM_PEERS; i++)
3204 if (bgp_peers[i].state == Established)
3205 bgp_stop(&bgp_peers[i]);
3206 #endif /* BGP */
3207
3208 /* remove plugins (so cleanup code gets run) */
3209 plugins_done();
3210
3211 // Remove the PID file if we wrote it
3212 if (config->wrote_pid && *config->pid_file == '/')
3213 unlink(config->pid_file);
3214
3215 /* kill CLI children */
3216 signal(SIGTERM, SIG_IGN);
3217 kill(0, SIGTERM);
3218 return 0;
3219 }
3220
3221 static void sighup_handler(int sig)
3222 {
3223 if (log_stream && log_stream != stderr)
3224 {
3225 fclose(log_stream);
3226 log_stream = NULL;
3227 }
3228
3229 read_config_file();
3230 }
3231
3232 static void sigalrm_handler(int sig)
3233 {
3234 // Log current traffic stats
3235
3236 snprintf(config->bandwidth, sizeof(config->bandwidth),
3237 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3238 (udp_rx / 1024.0 / 1024.0 * 8),
3239 (eth_tx / 1024.0 / 1024.0 * 8),
3240 (eth_rx / 1024.0 / 1024.0 * 8),
3241 (udp_tx / 1024.0 / 1024.0 * 8),
3242 ((udp_tx + udp_rx + eth_tx + eth_rx) / 1024.0 / 1024.0 * 8),
3243 udp_rx_pkt, eth_rx_pkt);
3244
3245 udp_tx = udp_rx = 0;
3246 udp_rx_pkt = eth_rx_pkt = 0;
3247 eth_tx = eth_rx = 0;
3248
3249 if (config->dump_speed)
3250 printf("%s\n", config->bandwidth);
3251
3252 // Update the internal time counter
3253 time(&time_now);
3254 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
3255 alarm(1);
3256
3257 {
3258 // Run timer hooks
3259 struct param_timer p = { time_now };
3260 run_plugins(PLUGIN_TIMER, &p);
3261 }
3262
3263 }
3264
3265 static void sigterm_handler(int sig)
3266 {
3267 LOG(1, 0, 0, "Shutting down cleanly\n");
3268 if (config->save_state)
3269 dump_state();
3270
3271 main_quit++;
3272 }
3273
3274 static void sigquit_handler(int sig)
3275 {
3276 int i;
3277
3278 LOG(1, 0, 0, "Shutting down without saving sessions\n");
3279
3280 if (config->cluster_iam_master)
3281 {
3282 for (i = 1; i < MAXSESSION; i++)
3283 {
3284 if (session[i].opened)
3285 sessionkill(i, "L2TPNS Closing");
3286 }
3287 for (i = 1; i < MAXTUNNEL; i++)
3288 {
3289 if (tunnel[i].ip || tunnel[i].state)
3290 tunnelshutdown(i, "L2TPNS Closing");
3291 }
3292 }
3293
3294 main_quit++;
3295 }
3296
3297 static void sigchild_handler(int sig)
3298 {
3299 while (waitpid(-1, NULL, WNOHANG) > 0)
3300 ;
3301 }
3302
3303 static void read_state()
3304 {
3305 struct stat sb;
3306 int i;
3307 ippoolt itmp;
3308 FILE *f;
3309 char magic[sizeof(DUMP_MAGIC) - 1];
3310 u32 buf[2];
3311
3312 if (!config->save_state)
3313 {
3314 unlink(STATEFILE);
3315 return ;
3316 }
3317
3318 if (stat(STATEFILE, &sb) < 0)
3319 {
3320 unlink(STATEFILE);
3321 return ;
3322 }
3323
3324 if (sb.st_mtime < (time(NULL) - 60))
3325 {
3326 LOG(0, 0, 0, "State file is too old to read, ignoring\n");
3327 unlink(STATEFILE);
3328 return ;
3329 }
3330
3331 f = fopen(STATEFILE, "r");
3332 unlink(STATEFILE);
3333
3334 if (!f)
3335 {
3336 LOG(0, 0, 0, "Can't read state file: %s\n", strerror(errno));
3337 exit(1);
3338 }
3339
3340 if (fread(magic, sizeof(magic), 1, f) != 1 || strncmp(magic, DUMP_MAGIC, sizeof(magic)))
3341 {
3342 LOG(0, 0, 0, "Bad state file magic\n");
3343 exit(1);
3344 }
3345
3346 LOG(1, 0, 0, "Reading state information\n");
3347 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] > MAXIPPOOL || buf[1] != sizeof(ippoolt))
3348 {
3349 LOG(0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
3350 exit(1);
3351 }
3352
3353 if (buf[0] > ip_pool_size)
3354 {
3355 LOG(0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf[0], ip_pool_size);
3356 exit(1);
3357 }
3358
3359 LOG(2, 0, 0, "Loading %u ip addresses\n", buf[0]);
3360 for (i = 0; i < buf[0]; i++)
3361 {
3362 if (fread(&itmp, sizeof(itmp), 1, f) != 1)
3363 {
3364 LOG(0, 0, 0, "Error reading ip %d from state file: %s\n", i, strerror(errno));
3365 exit(1);
3366 }
3367
3368 if (itmp.address != ip_address_pool[i].address)
3369 {
3370 LOG(0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i);
3371 exit(1);
3372 }
3373
3374 memcpy(&ip_address_pool[i], &itmp, sizeof(itmp));
3375 }
3376
3377 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] != MAXTUNNEL || buf[1] != sizeof(tunnelt))
3378 {
3379 LOG(0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
3380 exit(1);
3381 }
3382
3383 LOG(2, 0, 0, "Loading %u tunnels\n", MAXTUNNEL);
3384 if (fread(tunnel, sizeof(tunnelt), MAXTUNNEL, f) != MAXTUNNEL)
3385 {
3386 LOG(0, 0, 0, "Error reading tunnel data from state file\n");
3387 exit(1);
3388 }
3389
3390 for (i = 0; i < MAXTUNNEL; i++)
3391 {
3392 tunnel[i].controlc = 0;
3393 tunnel[i].controls = NULL;
3394 tunnel[i].controle = NULL;
3395 if (*tunnel[i].hostname)
3396 LOG(3, 0, 0, "Created tunnel for %s\n", tunnel[i].hostname);
3397 }
3398
3399 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] != MAXSESSION || buf[1] != sizeof(sessiont))
3400 {
3401 LOG(0, 0, 0, "Error/mismatch reading session header from state file\n");
3402 exit(1);
3403 }
3404
3405 LOG(2, 0, 0, "Loading %u sessions\n", MAXSESSION);
3406 if (fread(session, sizeof(sessiont), MAXSESSION, f) != MAXSESSION)
3407 {
3408 LOG(0, 0, 0, "Error reading session data from state file\n");
3409 exit(1);
3410 }
3411
3412 for (i = 0; i < MAXSESSION; i++)
3413 {
3414 session[i].tbf_in = 0;
3415 session[i].tbf_out = 0;
3416 if (session[i].opened)
3417 {
3418 LOG(2, i, 0, "Loaded active session for user %s\n", session[i].user);
3419 if (session[i].ip)
3420 sessionsetup(session[i].tunnel, i);
3421 }
3422 }
3423
3424 fclose(f);
3425 LOG(0, 0, 0, "Loaded saved state information\n");
3426 }
3427
3428 static void dump_state()
3429 {
3430 FILE *f;
3431 u32 buf[2];
3432
3433 if (!config->save_state)
3434 return;
3435
3436 do
3437 {
3438 if (!(f = fopen(STATEFILE, "w")))
3439 break;
3440
3441 LOG(1, 0, 0, "Dumping state information\n");
3442
3443 if (fwrite(DUMP_MAGIC, sizeof(DUMP_MAGIC) - 1, 1, f) != 1)
3444 break;
3445
3446 LOG(2, 0, 0, "Dumping %u ip addresses\n", ip_pool_size);
3447 buf[0] = ip_pool_size;
3448 buf[1] = sizeof(ippoolt);
3449 if (fwrite(buf, sizeof(buf), 1, f) != 1)
3450 break;
3451 if (fwrite(ip_address_pool, sizeof(ippoolt), ip_pool_size, f) != ip_pool_size)
3452 break;
3453
3454 LOG(2, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL);
3455 buf[0] = MAXTUNNEL;
3456 buf[1] = sizeof(tunnelt);
3457 if (fwrite(buf, sizeof(buf), 1, f) != 1)
3458 break;
3459 if (fwrite(tunnel, sizeof(tunnelt), MAXTUNNEL, f) != MAXTUNNEL)
3460 break;
3461
3462 LOG(2, 0, 0, "Dumping %u sessions\n", MAXSESSION);
3463 buf[0] = MAXSESSION;
3464 buf[1] = sizeof(sessiont);
3465 if (fwrite(buf, sizeof(buf), 1, f) != 1)
3466 break;
3467 if (fwrite(session, sizeof(sessiont), MAXSESSION, f) != MAXSESSION)
3468 break;
3469
3470 if (fclose(f) == 0)
3471 return ; // OK
3472 }
3473 while (0);
3474
3475 LOG(0, 0, 0, "Can't write state information: %s\n", strerror(errno));
3476 unlink(STATEFILE);
3477 }
3478
3479 static void build_chap_response(char *challenge, u8 id, u16 challenge_length, char **challenge_response)
3480 {
3481 MD5_CTX ctx;
3482 *challenge_response = NULL;
3483
3484 if (!*config->l2tpsecret)
3485 {
3486 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
3487 return;
3488 }
3489
3490 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
3491
3492 *challenge_response = (char *)calloc(17, 1);
3493
3494 MD5Init(&ctx);
3495 MD5Update(&ctx, &id, 1);
3496 MD5Update(&ctx, config->l2tpsecret, strlen(config->l2tpsecret));
3497 MD5Update(&ctx, challenge, challenge_length);
3498 MD5Final(*challenge_response, &ctx);
3499
3500 return;
3501 }
3502
3503 static int facility_value(char *name)
3504 {
3505 int i;
3506 for (i = 0; facilitynames[i].c_name; i++)
3507 {
3508 if (strcmp(facilitynames[i].c_name, name) == 0)
3509 return facilitynames[i].c_val;
3510 }
3511 return 0;
3512 }
3513
3514 static void update_config()
3515 {
3516 int i;
3517 static int timeout = 0;
3518 static int interval = 0;
3519
3520 // Update logging
3521 closelog();
3522 syslog_log = 0;
3523 if (log_stream)
3524 {
3525 fclose(log_stream);
3526 log_stream = NULL;
3527 }
3528 if (*config->log_filename)
3529 {
3530 if (strstr(config->log_filename, "syslog:") == config->log_filename)
3531 {
3532 char *p = config->log_filename + 7;
3533 if (*p)
3534 {
3535 openlog("l2tpns", LOG_PID, facility_value(p));
3536 syslog_log = 1;
3537 }
3538 }
3539 else if (strchr(config->log_filename, '/') == config->log_filename)
3540 {
3541 if ((log_stream = fopen((char *)(config->log_filename), "a")))
3542 {
3543 fseek(log_stream, 0, SEEK_END);
3544 setbuf(log_stream, NULL);
3545 }
3546 else
3547 {
3548 log_stream = stderr;
3549 setbuf(log_stream, NULL);
3550 }
3551 }
3552 }
3553 else
3554 {
3555 log_stream = stderr;
3556 setbuf(log_stream, NULL);
3557 }
3558
3559
3560 // Update radius
3561 config->numradiusservers = 0;
3562 for (i = 0; i < MAXRADSERVER; i++)
3563 if (config->radiusserver[i])
3564 {
3565 config->numradiusservers++;
3566 // Set radius port: if not set, take the port from the
3567 // first radius server. For the first radius server,
3568 // take the #defined default value from l2tpns.h
3569
3570 // test twice, In case someone works with
3571 // a secondary radius server without defining
3572 // a primary one, this will work even then.
3573 if (i>0 && !config->radiusport[i])
3574 config->radiusport[i] = config->radiusport[i-1];
3575 if (!config->radiusport[i])
3576 config->radiusport[i] = RADPORT;
3577 }
3578
3579 if (!config->numradiusservers)
3580 LOG(0, 0, 0, "No RADIUS servers defined!\n");
3581
3582 config->num_radfds = 2 << RADIUS_SHIFT;
3583
3584 // Update plugins
3585 for (i = 0; i < MAXPLUGINS; i++)
3586 {
3587 if (strcmp(config->plugins[i], config->old_plugins[i]) == 0)
3588 continue;
3589
3590 if (*config->plugins[i])
3591 {
3592 // Plugin added
3593 add_plugin(config->plugins[i]);
3594 }
3595 else if (*config->old_plugins[i])
3596 {
3597 // Plugin removed
3598 remove_plugin(config->old_plugins[i]);
3599 }
3600 }
3601 memcpy(config->old_plugins, config->plugins, sizeof(config->plugins));
3602 if (!config->cleanup_interval) config->cleanup_interval = 10;
3603 if (!config->multi_read_count) config->multi_read_count = 10;
3604 if (!config->cluster_address) config->cluster_address = inet_addr(DEFAULT_MCAST_ADDR);
3605 if (!*config->cluster_interface)
3606 strncpy(config->cluster_interface, DEFAULT_MCAST_INTERFACE, sizeof(config->cluster_interface) - 1);
3607
3608 if (!config->cluster_hb_interval)
3609 config->cluster_hb_interval = PING_INTERVAL; // Heartbeat every 0.5 seconds.
3610
3611 if (!config->cluster_hb_timeout)
3612 config->cluster_hb_timeout = HB_TIMEOUT; // 10 missed heartbeat triggers an election.
3613
3614 if (interval != config->cluster_hb_interval || timeout != config->cluster_hb_timeout)
3615 {
3616 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
3617 // late, ensure we're sufficiently larger than that
3618 int t = 4 * config->cluster_hb_interval + 11;
3619
3620 if (config->cluster_hb_timeout < t)
3621 {
3622 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config->cluster_hb_timeout, t);
3623 config->cluster_hb_timeout = t;
3624 }
3625
3626 // Push timing changes to the slaves immediately if we're the master
3627 if (config->cluster_iam_master)
3628 cluster_heartbeat();
3629
3630 interval = config->cluster_hb_interval;
3631 timeout = config->cluster_hb_timeout;
3632 }
3633
3634 // Write PID file
3635 if (*config->pid_file == '/' && !config->wrote_pid)
3636 {
3637 FILE *f;
3638 if ((f = fopen(config->pid_file, "w")))
3639 {
3640 fprintf(f, "%d\n", getpid());
3641 fclose(f);
3642 config->wrote_pid = 1;
3643 }
3644 else
3645 {
3646 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config->pid_file, strerror(errno));
3647 }
3648 }
3649
3650 config->reload_config = 0;
3651 }
3652
3653 static void read_config_file()
3654 {
3655 FILE *f;
3656
3657 if (!config->config_file) return;
3658 if (!(f = fopen(config->config_file, "r")))
3659 {
3660 fprintf(stderr, "Can't open config file %s: %s\n", config->config_file, strerror(errno));
3661 return;
3662 }
3663
3664 LOG(3, 0, 0, "Reading config file %s\n", config->config_file);
3665 cli_do_file(f);
3666 LOG(3, 0, 0, "Done reading config file\n");
3667 fclose(f);
3668 update_config();
3669 }
3670
3671 int sessionsetup(tunnelidt t, sessionidt s)
3672 {
3673 // A session now exists, set it up
3674 ipt ip;
3675 char *user;
3676 sessionidt i;
3677 int r;
3678
3679 CSTAT(call_sessionsetup);
3680
3681 LOG(3, s, t, "Doing session setup for session\n");
3682
3683 if (!session[s].ip || session[s].ip == 0xFFFFFFFE)
3684 {
3685 assign_ip_address(s);
3686 if (!session[s].ip)
3687 {
3688 LOG(0, s, t, " No IP allocated. The IP address pool is FULL!\n");
3689 sessionshutdown(s, "No IP addresses available");
3690 return 0;
3691 }
3692 LOG(3, s, t, " No IP allocated. Assigned %s from pool\n",
3693 fmtaddr(htonl(session[s].ip), 0));
3694 }
3695
3696
3697 // Make sure this is right
3698 session[s].tunnel = t;
3699
3700 // zap old sessions with same IP and/or username
3701 // Don't kill gardened sessions - doing so leads to a DoS
3702 // from someone who doesn't need to know the password
3703 {
3704 ip = session[s].ip;
3705 user = session[s].user;
3706 for (i = 1; i <= config->cluster_highest_sessionid; i++)
3707 {
3708 if (i == s) continue;
3709 if (ip == session[i].ip) sessionkill(i, "Duplicate IP address");
3710 if (!session[s].walled_garden && !session[i].walled_garden && strcasecmp(user, session[i].user) == 0)
3711 sessionkill(i, "Duplicate session for users");
3712 }
3713 }
3714
3715 {
3716 int routed = 0;
3717
3718 // Add the route for this session.
3719 for (r = 0; r < MAXROUTE && session[s].route[r].ip; r++)
3720 {
3721 if ((session[s].ip & session[s].route[r].mask) ==
3722 (session[s].route[r].ip & session[s].route[r].mask))
3723 routed++;
3724
3725 routeset(s, session[s].route[r].ip, session[s].route[r].mask, 0, 1);
3726 }
3727
3728 // Static IPs need to be routed if not already
3729 // convered by a Framed-Route. Anything else is part
3730 // of the IP address pool and is already routed, it
3731 // just needs to be added to the IP cache.
3732 if (session[s].ip_pool_index == -1) // static ip
3733 {
3734 if (!routed) routeset(s, session[s].ip, 0, 0, 1);
3735 }
3736 else
3737 cache_ipmap(session[s].ip, s);
3738 }
3739
3740 if (!session[s].unique_id)
3741 {
3742 // did this session just finish radius?
3743 LOG(3, s, t, "Sending initial IPCP to client\n");
3744 sendipcp(t, s);
3745 session[s].unique_id = ++last_id;
3746 }
3747
3748 // Run the plugin's against this new session.
3749 {
3750 struct param_new_session data = { &tunnel[t], &session[s] };
3751 run_plugins(PLUGIN_NEW_SESSION, &data);
3752 }
3753
3754 // Allocate TBFs if throttled
3755 if (session[s].throttle_in || session[s].throttle_out)
3756 throttle_session(s, session[s].throttle_in, session[s].throttle_out);
3757
3758 session[s].last_packet = time_now;
3759
3760 LOG(2, s, t, "Login by %s at %s from %s (%s)\n", session[s].user,
3761 fmtaddr(htonl(session[s].ip), 0),
3762 fmtaddr(htonl(tunnel[t].ip), 1), tunnel[t].hostname);
3763
3764 cluster_send_session(s); // Mark it as dirty, and needing to the flooded to the cluster.
3765
3766 return 1; // RADIUS OK and IP allocated, done...
3767 }
3768
3769 //
3770 // This session just got dropped on us by the master or something.
3771 // Make sure our tables up up to date...
3772 //
3773 int load_session(sessionidt s, sessiont *new)
3774 {
3775 int i;
3776 int newip = 0;
3777
3778 // Sanity checks.
3779 if (new->ip_pool_index >= MAXIPPOOL ||
3780 new->tunnel >= MAXTUNNEL)
3781 {
3782 LOG(0, s, 0, "Strange session update received!\n");
3783 // FIXME! What to do here?
3784 return 0;
3785 }
3786
3787 //
3788 // Ok. All sanity checks passed. Now we're committed to
3789 // loading the new session.
3790 //
3791
3792 session[s].tunnel = new->tunnel; // For logging in cache_ipmap
3793
3794 // See if routes/ip cache need updating
3795 if (new->ip != session[s].ip)
3796 newip++;
3797
3798 for (i = 0; !newip && i < MAXROUTE && (session[s].route[i].ip || new->route[i].ip); i++)
3799 if (new->route[i].ip != session[s].route[i].ip ||
3800 new->route[i].mask != session[s].route[i].mask)
3801 newip++;
3802
3803 // needs update
3804 if (newip)
3805 {
3806 int routed = 0;
3807
3808 // remove old routes...
3809 for (i = 0; i < MAXROUTE && session[s].route[i].ip; i++)
3810 {
3811 if ((session[s].ip & session[s].route[i].mask) ==
3812 (session[s].route[i].ip & session[s].route[i].mask))
3813 routed++;
3814
3815 routeset(s, session[s].route[i].ip, session[s].route[i].mask, 0, 0);
3816 }
3817
3818 // ...ip
3819 if (session[s].ip)
3820 {
3821 if (session[s].ip_pool_index == -1) // static IP
3822 {
3823 if (!routed) routeset(s, session[s].ip, 0, 0, 0);
3824 }
3825 else // It's part of the IP pool, remove it manually.
3826 uncache_ipmap(session[s].ip);
3827 }
3828
3829 routed = 0;
3830
3831 // add new routes...
3832 for (i = 0; i < MAXROUTE && new->route[i].ip; i++)
3833 {
3834 if ((new->ip & new->route[i].mask) ==
3835 (new->route[i].ip & new->route[i].mask))
3836 routed++;
3837
3838 routeset(s, new->route[i].ip, new->route[i].mask, 0, 1);
3839 }
3840
3841 // ...ip
3842 if (new->ip)
3843 {
3844 // If there's a new one, add it.
3845 if (new->ip_pool_index == -1)
3846 {
3847 if (!routed) routeset(s, new->ip, 0, 0, 1);
3848 }
3849 else
3850 cache_ipmap(new->ip, s);
3851 }
3852 }
3853
3854 // check filters
3855 if (new->filter_in && (new->filter_in > MAXFILTER || !ip_filters[new->filter_in - 1].name[0]))
3856 {
3857 LOG(2, s, session[s].tunnel, "Dropping invalid input filter %d\n", (int) new->filter_in);
3858 new->filter_in = 0;
3859 }
3860
3861 if (new->filter_out && (new->filter_out > MAXFILTER || !ip_filters[new->filter_out - 1].name[0]))
3862 {
3863 LOG(2, s, session[s].tunnel, "Dropping invalid output filter %d\n", (int) new->filter_out);
3864 new->filter_out = 0;
3865 }
3866
3867 if (new->filter_in != session[s].filter_in)
3868 {
3869 if (session[s].filter_in) ip_filters[session[s].filter_in - 1].used--;
3870 if (new->filter_in) ip_filters[new->filter_in - 1].used++;
3871 }
3872
3873 if (new->filter_out != session[s].filter_out)
3874 {
3875 if (session[s].filter_out) ip_filters[session[s].filter_out - 1].used--;
3876 if (new->filter_out) ip_filters[new->filter_out - 1].used++;
3877 }
3878
3879 if (new->tunnel && s > config->cluster_highest_sessionid) // Maintain this in the slave. It's used
3880 // for walking the sessions to forward byte counts to the master.
3881 config->cluster_highest_sessionid = s;
3882
3883 // TEMP: old session struct used a u32 to define the throttle
3884 // speed for both up/down, new uses a u16 for each. Deal with
3885 // sessions from an old master for migration.
3886 if (new->throttle_out == 0 && new->tbf_out)
3887 new->throttle_out = new->throttle_in;
3888
3889 memcpy(&session[s], new, sizeof(session[s])); // Copy over..
3890
3891 // Do fixups into address pool.
3892 if (new->ip_pool_index != -1)
3893 fix_address_pool(s);
3894
3895 return 1;
3896 }
3897
3898 static void initplugins()
3899 {
3900 int i;
3901
3902 loaded_plugins = ll_init();
3903 // Initialize the plugins to nothing
3904 for (i = 0; i < MAX_PLUGIN_TYPES; i++)
3905 plugins[i] = ll_init();
3906 }
3907
3908 static void *open_plugin(char *plugin_name, int load)
3909 {
3910 char path[256] = "";
3911
3912 snprintf(path, 256, PLUGINDIR "/%s.so", plugin_name);
3913 LOG(2, 0, 0, "%soading plugin from %s\n", load ? "L" : "Un-l", path);
3914 return dlopen(path, RTLD_NOW);
3915 }
3916
3917 // plugin callback to get a config value
3918 static void *getconfig(char *key, enum config_typet type)
3919 {
3920 int i;
3921
3922 for (i = 0; config_values[i].key; i++)
3923 {
3924 if (!strcmp(config_values[i].key, key))
3925 {
3926 if (config_values[i].type == type)
3927 return ((void *) config) + config_values[i].offset;
3928
3929 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
3930 key, type, config_values[i].type);
3931
3932 return 0;
3933 }
3934 }
3935
3936 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key);
3937 return 0;
3938 }
3939
3940 static int add_plugin(char *plugin_name)
3941 {
3942 static struct pluginfuncs funcs = {
3943 _log,
3944 _log_hex,
3945 fmtaddr,
3946 sessionbyuser,
3947 sessiontbysessionidt,
3948 sessionidtbysessiont,
3949 radiusnew,
3950 radiussend,
3951 getconfig,
3952 sessionkill,
3953 throttle_session,
3954 cluster_send_session,
3955 };
3956
3957 void *p = open_plugin(plugin_name, 1);
3958 int (*initfunc)(struct pluginfuncs *);
3959 int i;
3960
3961 if (!p)
3962 {
3963 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
3964 return -1;
3965 }
3966
3967 if (ll_contains(loaded_plugins, p))
3968 {
3969 dlclose(p);
3970 return 0; // already loaded
3971 }
3972
3973 {
3974 int *v = dlsym(p, "plugin_api_version");
3975 if (!v || *v != PLUGIN_API_VERSION)
3976 {
3977 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
3978 dlclose(p);
3979 return -1;
3980 }
3981 }
3982
3983 if ((initfunc = dlsym(p, "plugin_init")))
3984 {
3985 if (!initfunc(&funcs))
3986 {
3987 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
3988 dlclose(p);
3989 return -1;
3990 }
3991 }
3992
3993 ll_push(loaded_plugins, p);
3994
3995 for (i = 0; i < max_plugin_functions; i++)
3996 {
3997 void *x;
3998 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
3999 {
4000 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions[i]);
4001 ll_push(plugins[i], x);
4002 }
4003 }
4004
4005 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name);
4006 return 1;
4007 }
4008
4009 static void run_plugin_done(void *plugin)
4010 {
4011 int (*donefunc)(void) = dlsym(plugin, "plugin_done");
4012
4013 if (donefunc)
4014 donefunc();
4015 }
4016
4017 static int remove_plugin(char *plugin_name)
4018 {
4019 void *p = open_plugin(plugin_name, 0);
4020 int loaded = 0;
4021
4022 if (!p)
4023 return -1;
4024
4025 if (ll_contains(loaded_plugins, p))
4026 {
4027 int i;
4028 for (i = 0; i < max_plugin_functions; i++)
4029 {
4030 void *x;
4031 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
4032 ll_delete(plugins[i], x);
4033 }
4034
4035 ll_delete(loaded_plugins, p);
4036 run_plugin_done(p);
4037 loaded = 1;
4038 }
4039
4040 dlclose(p);
4041 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name);
4042 return loaded;
4043 }
4044
4045 int run_plugins(int plugin_type, void *data)
4046 {
4047 int (*func)(void *data);
4048
4049 if (!plugins[plugin_type] || plugin_type > max_plugin_functions)
4050 return PLUGIN_RET_ERROR;
4051
4052 ll_reset(plugins[plugin_type]);
4053 while ((func = ll_next(plugins[plugin_type])))
4054 {
4055 int r = func(data);
4056
4057 if (r != PLUGIN_RET_OK)
4058 return r; // stop here
4059 }
4060
4061 return PLUGIN_RET_OK;
4062 }
4063
4064 static void plugins_done()
4065 {
4066 void *p;
4067
4068 ll_reset(loaded_plugins);
4069 while ((p = ll_next(loaded_plugins)))
4070 run_plugin_done(p);
4071 }
4072
4073 static void processcontrol(u8 * buf, int len, struct sockaddr_in *addr, int alen)
4074 {
4075 struct nsctl request;
4076 struct nsctl response;
4077 int type = unpack_control(&request, buf, len);
4078 int r;
4079 void *p;
4080
4081 if (log_stream && config->debug >= 4)
4082 {
4083 if (type < 0)
4084 {
4085 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
4086 fmtaddr(addr->sin_addr.s_addr, 0), type);
4087 }
4088 else
4089 {
4090 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
4091 dump_control(&request, log_stream);
4092 }
4093 }
4094
4095 switch (type)
4096 {
4097 case NSCTL_REQ_LOAD:
4098 if (request.argc != 1)
4099 {
4100 response.type = NSCTL_RES_ERR;
4101 response.argc = 1;
4102 response.argv[0] = "name of plugin required";
4103 }
4104 else if ((r = add_plugin(request.argv[0])) < 1)
4105 {
4106 response.type = NSCTL_RES_ERR;
4107 response.argc = 1;
4108 response.argv[0] = !r
4109 ? "plugin already loaded"
4110 : "error loading plugin";
4111 }
4112 else
4113 {
4114 response.type = NSCTL_RES_OK;
4115 response.argc = 0;
4116 }
4117
4118 break;
4119
4120 case NSCTL_REQ_UNLOAD:
4121 if (request.argc != 1)
4122 {
4123 response.type = NSCTL_RES_ERR;
4124 response.argc = 1;
4125 response.argv[0] = "name of plugin required";
4126 }
4127 else if ((r = remove_plugin(request.argv[0])) < 1)
4128 {
4129 response.type = NSCTL_RES_ERR;
4130 response.argc = 1;
4131 response.argv[0] = !r
4132 ? "plugin not loaded"
4133 : "plugin not found";
4134 }
4135 else
4136 {
4137 response.type = NSCTL_RES_OK;
4138 response.argc = 0;
4139 }
4140
4141 break;
4142
4143 case NSCTL_REQ_HELP:
4144 response.type = NSCTL_RES_OK;
4145 response.argc = 0;
4146
4147 ll_reset(loaded_plugins);
4148 while ((p = ll_next(loaded_plugins)))
4149 {
4150 char **help = dlsym(p, "plugin_control_help");
4151 while (response.argc < 0xff && help && *help)
4152 response.argv[response.argc++] = *help++;
4153 }
4154
4155 break;
4156
4157 case NSCTL_REQ_CONTROL:
4158 {
4159 struct param_control param = {
4160 config->cluster_iam_master,
4161 request.argc,
4162 request.argv,
4163 0,
4164 NULL,
4165 };
4166
4167 int r = run_plugins(PLUGIN_CONTROL, &param);
4168
4169 if (r == PLUGIN_RET_ERROR)
4170 {
4171 response.type = NSCTL_RES_ERR;
4172 response.argc = 1;
4173 response.argv[0] = param.additional
4174 ? param.additional
4175 : "error returned by plugin";
4176 }
4177 else if (r == PLUGIN_RET_NOTMASTER)
4178 {
4179 static char msg[] = "must be run on master: 000.000.000.000";
4180
4181 response.type = NSCTL_RES_ERR;
4182 response.argc = 1;
4183 if (config->cluster_master_address)
4184 {
4185 strcpy(msg + 23, fmtaddr(config->cluster_master_address, 0));
4186 response.argv[0] = msg;
4187 }
4188 else
4189 {
4190 response.argv[0] = "must be run on master: none elected";
4191 }
4192 }
4193 else if (!(param.response & NSCTL_RESPONSE))
4194 {
4195 response.type = NSCTL_RES_ERR;
4196 response.argc = 1;
4197 response.argv[0] = param.response
4198 ? "unrecognised response value from plugin"
4199 : "unhandled action";
4200 }
4201 else
4202 {
4203 response.type = param.response;
4204 response.argc = 0;
4205 if (param.additional)
4206 {
4207 response.argc = 1;
4208 response.argv[0] = param.additional;
4209 }
4210 }
4211 }
4212
4213 break;
4214
4215 default:
4216 response.type = NSCTL_RES_ERR;
4217 response.argc = 1;
4218 response.argv[0] = "error unpacking control packet";
4219 }
4220
4221 buf = calloc(NSCTL_MAX_PKT_SZ, 1);
4222 if (!buf)
4223 {
4224 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
4225 return;
4226 }
4227
4228 r = pack_control(buf, NSCTL_MAX_PKT_SZ, response.type, response.argc, response.argv);
4229 if (r > 0)
4230 {
4231 sendto(controlfd, buf, r, 0, (const struct sockaddr *) addr, alen);
4232 if (log_stream && config->debug >= 4)
4233 {
4234 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
4235 dump_control(&response, log_stream);
4236 }
4237 }
4238 else
4239 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
4240 fmtaddr(addr->sin_addr.s_addr, 0), r);
4241
4242 free(buf);
4243 }
4244
4245 static tunnelidt new_tunnel()
4246 {
4247 tunnelidt i;
4248 for (i = 1; i < MAXTUNNEL; i++)
4249 {
4250 if (tunnel[i].state == TUNNELFREE)
4251 {
4252 LOG(4, 0, i, "Assigning tunnel ID %d\n", i);
4253 if (i > config->cluster_highest_tunnelid)
4254 config->cluster_highest_tunnelid = i;
4255 return i;
4256 }
4257 }
4258 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
4259 return 0;
4260 }
4261
4262 //
4263 // We're becoming the master. Do any required setup..
4264 //
4265 // This is principally telling all the plugins that we're
4266 // now a master, and telling them about all the sessions
4267 // that are active too..
4268 //
4269 void become_master(void)
4270 {
4271 int s, i;
4272 run_plugins(PLUGIN_BECOME_MASTER, NULL);
4273
4274 // running a bunch of iptables commands is slow and can cause
4275 // the master to drop tunnels on takeover--kludge around the
4276 // problem by forking for the moment (note: race)
4277 if (!fork_and_close())
4278 {
4279 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
4280 {
4281 if (!session[s].tunnel) // Not an in-use session.
4282 continue;
4283
4284 run_plugins(PLUGIN_NEW_SESSION_MASTER, &session[s]);
4285 }
4286 exit(0);
4287 }
4288
4289 // add radius fds
4290 for (i = 0; i < config->num_radfds; i++)
4291 {
4292 FD_SET(radfds[i], &readset);
4293 if (radfds[i] > readset_n)
4294 readset_n = radfds[i];
4295 }
4296 }
4297
4298 int cmd_show_hist_idle(struct cli_def *cli, char *command, char **argv, int argc)
4299 {
4300 int s, i;
4301 int count = 0;
4302 int buckets[64];
4303
4304 if (CLI_HELP_REQUESTED)
4305 return CLI_HELP_NO_ARGS;
4306
4307 time(&time_now);
4308 for (i = 0; i < 64;++i) buckets[i] = 0;
4309
4310 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
4311 {
4312 int idle;
4313 if (!session[s].tunnel)
4314 continue;
4315
4316 idle = time_now - session[s].last_packet;
4317 idle /= 5 ; // In multiples of 5 seconds.
4318 if (idle < 0)
4319 idle = 0;
4320 if (idle > 63)
4321 idle = 63;
4322
4323 ++count;
4324 ++buckets[idle];
4325 }
4326
4327 for (i = 0; i < 63; ++i)
4328 {
4329 cli_print(cli, "%3d seconds : %7.2f%% (%6d)", i * 5, (double) buckets[i] * 100.0 / count , buckets[i]);
4330 }
4331 cli_print(cli, "lots of secs : %7.2f%% (%6d)", (double) buckets[63] * 100.0 / count , buckets[i]);
4332 cli_print(cli, "%d total sessions open.", count);
4333 return CLI_OK;
4334 }
4335
4336 int cmd_show_hist_open(struct cli_def *cli, char *command, char **argv, int argc)
4337 {
4338 int s, i;
4339 int count = 0;
4340 int buckets[64];
4341
4342 if (CLI_HELP_REQUESTED)
4343 return CLI_HELP_NO_ARGS;
4344
4345 time(&time_now);
4346 for (i = 0; i < 64;++i) buckets[i] = 0;
4347
4348 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
4349 {
4350 int open = 0, d;
4351 if (!session[s].tunnel)
4352 continue;
4353
4354 d = time_now - session[s].opened;
4355 if (d < 0)
4356 d = 0;
4357 while (d > 1 && open < 32)
4358 {
4359 ++open;
4360 d >>= 1; // half.
4361 }
4362 ++count;
4363 ++buckets[open];
4364 }
4365
4366 s = 1;
4367 for (i = 0; i < 30; ++i)
4368 {
4369 cli_print(cli, " < %8d seconds : %7.2f%% (%6d)", s, (double) buckets[i] * 100.0 / count , buckets[i]);
4370 s <<= 1;
4371 }
4372 cli_print(cli, "%d total sessions open.", count);
4373 return CLI_OK;
4374 }
4375
4376 /* Unhide an avp.
4377 *
4378 * This unencodes the AVP using the L2TP CHAP secret and the
4379 * previously stored random vector. It replaces the hidden data with
4380 * the cleartext data and returns the length of the cleartext data
4381 * (including the AVP "header" of 6 bytes).
4382 *
4383 * Based on code from rp-l2tpd by Roaring Penguin Software Inc.
4384 */
4385 static int unhide_avp(u8 *avp, tunnelidt t, sessionidt s, u16 length)
4386 {
4387 MD5_CTX ctx;
4388 u8 *cursor;
4389 u8 digest[16];
4390 u8 working_vector[16];
4391 uint16_t hidden_length;
4392 u8 type[2];
4393 size_t done, todo;
4394 u8 *output;
4395
4396 // Find the AVP type.
4397 type[0] = *(avp + 4);
4398 type[1] = *(avp + 5);
4399
4400 // Line up with the hidden data
4401 cursor = output = avp + 6;
4402
4403 // Compute initial pad
4404 MD5Init(&ctx);
4405 MD5Update(&ctx, type, 2);
4406 MD5Update(&ctx, config->l2tpsecret, strlen(config->l2tpsecret));
4407 MD5Update(&ctx, session[s].random_vector, session[s].random_vector_length);
4408 MD5Final(digest, &ctx);
4409
4410 // Get hidden length
4411 hidden_length = ((uint16_t) (digest[0] ^ cursor[0])) * 256 + (uint16_t) (digest[1] ^ cursor[1]);
4412
4413 // Keep these for later use
4414 working_vector[0] = *cursor;
4415 working_vector[1] = *(cursor + 1);
4416 cursor += 2;
4417
4418 if (hidden_length > length - 8)
4419 {
4420 LOG(1, s, t, "Hidden length %d too long in AVP of length %d\n", (int) hidden_length, (int) length);
4421 return 0;
4422 }
4423
4424 /* Decrypt remainder */
4425 done = 2;
4426 todo = hidden_length;
4427 while (todo)
4428 {
4429 working_vector[done] = *cursor;
4430 *output = digest[done] ^ *cursor;
4431 ++output;
4432 ++cursor;
4433 --todo;
4434 ++done;
4435 if (done == 16 && todo)
4436 {
4437 // Compute new digest
4438 done = 0;
4439 MD5Init(&ctx);
4440 MD5Update(&ctx, config->l2tpsecret, strlen(config->l2tpsecret));
4441 MD5Update(&ctx, &working_vector, 16);
4442 MD5Final(digest, &ctx);
4443 }
4444 }
4445
4446 return hidden_length + 6;
4447 }
4448
4449 static int ip_filter_port(ip_filter_portt *p, portt port)
4450 {
4451 switch (p->op)
4452 {
4453 case FILTER_PORT_OP_EQ: return port == p->port;
4454 case FILTER_PORT_OP_NEQ: return port != p->port;
4455 case FILTER_PORT_OP_GT: return port > p->port;
4456 case FILTER_PORT_OP_LT: return port < p->port;
4457 case FILTER_PORT_OP_RANGE: return port >= p->port && port <= p->port2;
4458 }
4459
4460 return 0;
4461 }
4462
4463 static int ip_filter_flag(u8 op, u8 sflags, u8 cflags, u8 flags)
4464 {
4465 switch (op)
4466 {
4467 case FILTER_FLAG_OP_ANY:
4468 return (flags & sflags) || (~flags & cflags);
4469
4470 case FILTER_FLAG_OP_ALL:
4471 return (flags & sflags) == sflags && (~flags & cflags) == cflags;
4472
4473 case FILTER_FLAG_OP_EST:
4474 return (flags & (TCP_FLAG_ACK|TCP_FLAG_RST)) && (~flags & TCP_FLAG_SYN);
4475 }
4476
4477 return 0;
4478 }
4479
4480 int ip_filter(u8 *buf, int len, u8 filter)
4481 {
4482 u16 frag_offset;
4483 u8 proto;
4484 ipt src_ip;
4485 ipt dst_ip;
4486 portt src_port = 0;
4487 portt dst_port = 0;
4488 u8 flags = 0;
4489 ip_filter_rulet *rule;
4490
4491 if (len < 20) // up to end of destination address
4492 return 0;
4493
4494 if ((*buf >> 4) != 4) // IPv4
4495 return 0;
4496
4497 frag_offset = ntohs(*(u16 *) (buf + 6)) & 0x1fff;
4498 proto = buf[9];
4499 src_ip = *(u32 *) (buf + 12);
4500 dst_ip = *(u32 *) (buf + 16);
4501
4502 if (frag_offset == 0 && (proto == IPPROTO_TCP || proto == IPPROTO_UDP))
4503 {
4504 int l = (buf[0] & 0xf) * 4; // length of IP header
4505 if (len < l + 4) // ports
4506 return 0;
4507
4508 src_port = ntohs(*(u16 *) (buf + l));
4509 dst_port = ntohs(*(u16 *) (buf + l + 2));
4510 if (proto == IPPROTO_TCP)
4511 {
4512 if (len < l + 14) // flags
4513 return 0;
4514
4515 flags = buf[l + 13] & 0x3f;
4516 }
4517 }
4518
4519 for (rule = ip_filters[filter].rules; rule->action; rule++)
4520 {
4521 if (rule->proto != IPPROTO_IP && proto != rule->proto)
4522 continue;
4523
4524 if (rule->src_wild != INADDR_BROADCAST &&
4525 (src_ip & ~rule->src_wild) != (rule->src_ip & ~rule->src_wild))
4526 continue;
4527
4528 if (rule->dst_wild != INADDR_BROADCAST &&
4529 (dst_ip & ~rule->dst_wild) != (rule->dst_ip & ~rule->dst_wild))
4530 continue;
4531
4532 if (frag_offset)
4533 {
4534 if (!rule->frag || rule->action == FILTER_ACTION_DENY)
4535 continue;
4536 }
4537 else
4538 {
4539 if (rule->frag)
4540 continue;
4541
4542 if (proto == IPPROTO_TCP || proto == IPPROTO_UDP)
4543 {
4544 if (rule->src_ports.op && !ip_filter_port(&rule->src_ports, src_port))
4545 continue;
4546
4547 if (rule->dst_ports.op && !ip_filter_port(&rule->dst_ports, dst_port))
4548 continue;
4549
4550 if (proto == IPPROTO_TCP && rule->tcp_flag_op &&
4551 !ip_filter_flag(rule->tcp_flag_op, rule->tcp_sflags, rule->tcp_cflags, flags))
4552 continue;
4553 }
4554 }
4555
4556 // matched
4557 rule->counter++;
4558 return rule->action == FILTER_ACTION_PERMIT;
4559 }
4560
4561 // default deny
4562 return 0;
4563 }