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