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