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