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