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