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