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