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