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