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