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