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