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