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