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