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