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