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