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