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