Use multiple radius sockets to allow more concurrent authentication requests
[l2tpns.git] / l2tpns.c
1 // L2TP Network Server
2 // Adrian Kennard 2002
3 // (c) Copyrigth 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd)
4 // vim: sw=8 ts=8
5
6 #include <arpa/inet.h>
7 #include <assert.h>
8 #include <errno.h>
9 #include <fcntl.h>
10 #include <linux/if_tun.h>
11 #define SYSLOG_NAMES
12 #include <syslog.h>
13 #include <malloc.h>
14 #include <math.h>
15 #include <net/route.h>
16 #include <sys/mman.h>
17 #include <netdb.h>
18 #include <netinet/in.h>
19 #include <signal.h>
20 #include <stdarg.h>
21 #include <stdlib.h>
22 #include <stdio.h>
23 #define __USE_GNU
24 #include <string.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
27 #include <sys/stat.h>
28 #include <sys/time.h>
29 #include <sys/resource.h>
30 #include <sys/types.h>
31 #include <sys/wait.h>
32 #include <linux/if.h>
33 #include <stddef.h>
34 #include <time.h>
35 #include <dlfcn.h>
36 #include <unistd.h>
37 #include "md5.h"
38 #include "l2tpns.h"
39 #include "cluster.h"
40 #include "plugin.h"
41 #include "ll.h"
42 #include "constants.h"
43 #include "control.h"
44 #include "util.h"
45
46 // Globals
47 struct configt *config = NULL; // all configuration
48 int tapfd = -1; // tap interface file handle
49 int udpfd = -1; // UDP file handle
50 int controlfd = -1; // Control signal handle
51 int snoopfd = -1; // UDP file handle for sending out intercept data
52 int *radfds = NULL; // RADIUS requests file handles
53 int ifrfd = -1; // File descriptor for routing, etc
54 time_t basetime = 0; // base clock
55 char hostname[1000] = ""; // us.
56 ipt myip = 0; // MY IP
57 u16 tapmac[3]; // MAC of tap interface
58 int tapidx; // ifr_ifindex of tap device
59 u32 sessionid = 0; // session id for radius accounting
60 int syslog_log = 0; // are we logging to syslog
61 FILE *log_stream = NULL;
62 struct sockaddr_in snoop_addr = {0};
63 extern int cluster_sockfd;
64 unsigned long last_sid = 0;
65 int clifd = 0;
66 sessionidt *cli_session_kill = NULL;
67 tunnelidt *cli_tunnel_kill = NULL;
68 static void *ip_hash[256];
69 unsigned long udp_tx = 0, udp_rx = 0, udp_rx_pkt = 0;
70 unsigned long eth_tx = 0, eth_rx = 0, eth_rx_pkt = 0;
71 unsigned int ip_pool_size = 0;
72 time_t time_now;
73 char time_now_string[64] = {0};
74 char main_quit = 0;
75 char *_program_name = NULL;
76 linked_list *loaded_plugins;
77 linked_list *plugins[MAX_PLUGIN_TYPES];
78
79 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
80 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(struct configt, MEMBER), membersize(struct configt, MEMBER), TYPE }
81
82 struct config_descriptt config_values[] = {
83 CONFIG("debug", debug, INT),
84 CONFIG("log_file", log_filename, STRING),
85 CONFIG("l2tp_secret", l2tpsecret, STRING),
86 CONFIG("primary_dns", default_dns1, IP),
87 CONFIG("secondary_dns", default_dns2, IP),
88 CONFIG("save_state", save_state, BOOL),
89 CONFIG("snoop_host", snoop_destination_host, IP),
90 CONFIG("snoop_port", snoop_destination_port, SHORT),
91 CONFIG("primary_radius", radiusserver[0], IP),
92 CONFIG("secondary_radius", radiusserver[1], IP),
93 CONFIG("radius_accounting", radius_accounting, BOOL),
94 CONFIG("radius_secret", radiussecret, STRING),
95 CONFIG("bind_address", bind_address, IP),
96 CONFIG("cluster_master", cluster_address, IP),
97 CONFIG("throttle_speed", rl_rate, UNSIGNED_LONG),
98 CONFIG("accounting_dir", accounting_dir, STRING),
99 CONFIG("setuid", target_uid, INT),
100 CONFIG("dump_speed", dump_speed, BOOL),
101 CONFIG("cleanup_interval", cleanup_interval, INT),
102 CONFIG("multi_read_count", multi_read_count, INT),
103 { NULL, 0, 0, 0 },
104 };
105
106 char *plugin_functions[] = {
107 NULL,
108 "plugin_pre_auth",
109 "plugin_post_auth",
110 "plugin_packet_rx",
111 "plugin_packet_tx",
112 "plugin_timer",
113 "plugin_new_session",
114 "plugin_kill_session",
115 "plugin_control",
116 "plugin_radius_response",
117 };
118 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
119
120 tunnelt *tunnel = NULL; // 1000 * 45 = 45000 = 45k
121 sessiont *session = NULL; // 5000 * 213 = 1065000 = 1 Mb
122 radiust *radius = NULL;
123 ippoolt *ip_address_pool = NULL;
124 controlt *controlfree = 0;
125 struct Tstats *_statistics = NULL;
126 #ifdef RINGBUFFER
127 struct Tringbuffer *ringbuffer = NULL;
128 #endif
129 tbft *filter_buckets = NULL;
130
131 void sigalrm_handler(int);
132 void sighup_handler(int);
133 void sigterm_handler(int);
134 void sigquit_handler(int);
135 void sigchild_handler(int);
136 void read_config_file();
137 void read_state();
138 void dump_state();
139 void tunnel_clean();
140 tunnelidt new_tunnel();
141 void update_config();
142
143 // return internal time (10ths since run)
144 clockt now(void)
145 {
146 struct timeval t;
147 gettimeofday(&t, 0);
148 return (t.tv_sec - basetime) * 10 + t.tv_usec / 100000 + 1;
149 }
150
151 // work out a retry time based on try number
152 clockt backoff(u8 try)
153 {
154 if (try > 5) try = 5; // max backoff
155 return now() + 10 * (1 << try);
156 }
157
158 void _log(int level, ipt address, sessionidt s, tunnelidt t, const char *format, ...)
159 {
160 static char message[65535] = {0};
161 static char message2[65535] = {0};
162 va_list ap;
163
164 #ifdef RINGBUFFER
165 if (ringbuffer)
166 {
167 if (++ringbuffer->tail >= RINGBUFFER_SIZE)
168 ringbuffer->tail = 0;
169 if (ringbuffer->tail == ringbuffer->head)
170 if (++ringbuffer->head >= RINGBUFFER_SIZE)
171 ringbuffer->head = 0;
172
173 ringbuffer->buffer[ringbuffer->tail].level = level;
174 ringbuffer->buffer[ringbuffer->tail].address = address;
175 ringbuffer->buffer[ringbuffer->tail].session = s;
176 ringbuffer->buffer[ringbuffer->tail].tunnel = t;
177 va_start(ap, format);
178 vsnprintf(ringbuffer->buffer[ringbuffer->tail].message, 4095, format, ap);
179 va_end(ap);
180 }
181 #endif
182
183 if (config->debug < level) return;
184
185 va_start(ap, format);
186 if (log_stream)
187 {
188 vsnprintf(message2, 65535, format, ap);
189 snprintf(message, 65535, "%s %02d/%02d %s", time_now_string, t, s, message2);
190 fprintf(log_stream, message);
191 }
192 else if (syslog_log)
193 {
194 vsnprintf(message2, 65535, format, ap);
195 snprintf(message, 65535, "%02d/%02d %s", t, s, message2);
196 syslog(level + 2, message); // We don't need LOG_EMERG or LOG_ALERT
197 }
198 va_end(ap);
199 }
200
201 void _log_hex(int level, ipt address, sessionidt s, tunnelidt t, const char *title, const char *data, int maxsize)
202 {
203 int i, j;
204 unsigned const char *d = (unsigned const char *)data;
205
206 if (config->debug < level) return;
207
208 // No support for log_hex to syslog
209 if (log_stream)
210 {
211 log(level, address, s, t, "%s (%d bytes):\n", title, maxsize);
212 setvbuf(log_stream, NULL, _IOFBF, 16384);
213
214 for (i = 0; i < maxsize; )
215 {
216 fprintf(log_stream, "%4X: ", i);
217 for (j = i; j < maxsize && j < (i + 16); j++)
218 {
219 fprintf(log_stream, "%02X ", d[j]);
220 if (j == i + 7)
221 fputs(": ", log_stream);
222 }
223
224 for (; j < i + 16; j++)
225 {
226 fputs(" ", log_stream);
227 if (j == i + 7)
228 fputs(": ", log_stream);
229 }
230
231 fputs(" ", log_stream);
232 for (j = i; j < maxsize && j < (i + 16); j++)
233 {
234 if (d[j] >= 0x20 && d[j] < 0x7f && d[j] != 0x20)
235 fputc(d[j], log_stream);
236 else
237 fputc('.', log_stream);
238
239 if (j == i + 7)
240 fputs(" ", log_stream);
241 }
242
243 i = j;
244 fputs("\n", log_stream);
245 }
246
247 fflush(log_stream);
248 setbuf(log_stream, NULL);
249 }
250 }
251
252
253 // Add a route
254 void routeset(ipt ip, ipt mask, ipt gw, u8 add)
255 {
256 struct rtentry r;
257 memset(&r, 0, sizeof(r));
258 r.rt_dev = config->tapdevice;
259 r.rt_dst.sa_family = AF_INET;
260 *(u32 *) & (((struct sockaddr_in *) &r.rt_dst)->sin_addr.s_addr) = htonl(ip);
261 r.rt_gateway.sa_family = AF_INET;
262 *(u32 *) & (((struct sockaddr_in *) &r.rt_gateway)->sin_addr.s_addr) = htonl(gw);
263 r.rt_genmask.sa_family = AF_INET;
264 *(u32 *) & (((struct sockaddr_in *) &r.rt_genmask)->sin_addr.s_addr) = htonl(mask ? mask : 0xFFFFFFF);
265 r.rt_flags = (RTF_UP | RTF_STATIC);
266 if (gw)
267 r.rt_flags |= RTF_GATEWAY;
268 else
269 r.rt_flags |= RTF_HOST;
270 if (ioctl(ifrfd, add ? SIOCADDRT : SIOCDELRT, (void *) &r) < 0) perror("routeset");
271 log(1, ip, 0, 0, "Route %s %u.%u.%u.%u/%u.%u.%u.%u %u.%u.%u.%u\n", add ? "Add" : "Del", ip >> 24, ip >> 16 & 255, ip >> 8 & 255, ip & 255, mask >> 24, mask >> 16 & 255, mask >> 8 & 255, mask & 255, gw >> 24, gw >> 16 & 255, gw >> 8 & 255, gw & 255);
272 }
273
274 // Set up TAP interface
275 void inittap(void)
276 {
277 struct ifreq ifr;
278 struct sockaddr_in sin = {0};
279 memset(&ifr, 0, sizeof(ifr));
280 ifr.ifr_flags = IFF_TUN;
281
282 tapfd = open(TAPDEVICE, O_RDWR);
283 if (tapfd < 0)
284 { // fatal
285 log(0, 0, 0, 0, "Can't open %s: %s\n", TAPDEVICE, strerror(errno));
286 exit(-1);
287 }
288 {
289 int flags = fcntl(tapfd, F_GETFL, 0);
290 fcntl(tapfd, F_SETFL, flags | O_NONBLOCK);
291 }
292 if (ioctl(tapfd, TUNSETIFF, (void *) &ifr) < 0)
293 {
294 log(0, 0, 0, 0, "Can't set tap interface: %s\n", strerror(errno));
295 exit(-1);
296 }
297 assert(strlen(ifr.ifr_name) < sizeof(config->tapdevice));
298 strncpy(config->tapdevice, ifr.ifr_name, sizeof(config->tapdevice) - 1);
299 ifrfd = socket(PF_INET, SOCK_DGRAM, IPPROTO_IP);
300
301 sin.sin_family = AF_INET;
302 sin.sin_addr.s_addr = config->bind_address ? config->bind_address : 0x01010101; // 1.1.1.1
303 memcpy(&ifr.ifr_addr, &sin, sizeof(struct sockaddr));
304
305 if (ioctl(ifrfd, SIOCSIFADDR, (void *) &ifr) < 0)
306 {
307 perror("set tap addr");
308 exit( -1);
309 }
310 /* Bump up the qlen to deal with bursts from the network */
311 ifr.ifr_qlen = 1000;
312 if (ioctl(ifrfd, SIOCSIFTXQLEN, (void *) &ifr) < 0)
313 {
314 perror("set tap qlen");
315 exit( -1);
316 }
317 ifr.ifr_flags = IFF_UP;
318 if (ioctl(ifrfd, SIOCSIFFLAGS, (void *) &ifr) < 0)
319 {
320 perror("set tap flags");
321 exit( -1);
322 }
323 if (ioctl(ifrfd, SIOCGIFHWADDR, (void *) &ifr) < 0)
324 {
325 perror("get tap hwaddr");
326 exit( -1);
327 }
328 memcpy(&tapmac, 2 + (u8 *) & ifr.ifr_hwaddr, 6);
329 if (ioctl(ifrfd, SIOCGIFINDEX, (void *) &ifr) < 0)
330 {
331 perror("get tap ifindex");
332 exit( -1);
333 }
334 tapidx = ifr.ifr_ifindex;
335 }
336
337 // set up UDP port
338 void initudp(void)
339 {
340 int on = 1;
341 struct sockaddr_in addr;
342
343 // Tunnel
344 memset(&addr, 0, sizeof(addr));
345 addr.sin_family = AF_INET;
346 addr.sin_port = htons(L2TPPORT);
347 addr.sin_addr.s_addr = config->bind_address;
348 udpfd = socket(AF_INET, SOCK_DGRAM, UDP);
349 setsockopt(udpfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
350 {
351 int flags = fcntl(udpfd, F_GETFL, 0);
352 fcntl(udpfd, F_SETFL, flags | O_NONBLOCK);
353 }
354 if (bind(udpfd, (void *) &addr, sizeof(addr)) < 0)
355 {
356 perror("udp bind");
357 exit( -1);
358 }
359 snoopfd = socket(AF_INET, SOCK_DGRAM, UDP);
360
361 // Control
362 memset(&addr, 0, sizeof(addr));
363 addr.sin_family = AF_INET;
364 addr.sin_port = htons(1702);
365 controlfd = socket(AF_INET, SOCK_DGRAM, 17);
366 setsockopt(controlfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
367 if (bind(controlfd, (void *) &addr, sizeof(addr)) < 0)
368 {
369 perror("bind");
370 exit(-1);
371 }
372 }
373
374 // Find session by IP, 0 for not found
375 sessionidt sessionbyip(ipt ip)
376 {
377 unsigned char *a = (unsigned char *)&ip;
378 char **d = (char **) ip_hash;
379 sessionidt s;
380
381 #ifdef STAT_CALLS
382 STAT(call_sessionbyip);
383 #endif
384
385 if (!(d = (char **) d[(size_t) *a++])) return 0;
386 if (!(d = (char **) d[(size_t) *a++])) return 0;
387 if (!(d = (char **) d[(size_t) *a++])) return 0;
388
389 s = (ipt) d[(size_t) *a];
390 if (s && session[s].tunnel)
391 return s;
392 return 0;
393 }
394
395 void cache_sessionid(ipt ip, sessionidt s)
396 {
397 unsigned char *a = (unsigned char *) &ip;
398 char **d = (char **) ip_hash;
399 int i;
400
401 for (i = 0; i < 3; i++)
402 {
403 if (!d[(size_t) a[i]])
404 {
405 if (!(d[(size_t) a[i]] = calloc(256, sizeof (void *))))
406 return;
407 }
408
409 d = (char **) d[(size_t) a[i]];
410 }
411
412 log(4, ip, s, session[s].tunnel, "Caching session ID %d for ip address\n", s);
413 d[(size_t) a[3]] = (char *)((int)s);
414 }
415
416 void uncache_sessionid(ipt ip)
417 {
418 unsigned char *a = (unsigned char *) &ip;
419 char **d = (char **) ip_hash;
420 int i;
421
422 for (i = 0; i < 3; i++)
423 {
424 if (!d[(size_t) a[i]]) return;
425 d = (char **) d[(size_t) a[i]];
426 }
427 d[(size_t) a[3]] = NULL;
428 }
429
430 // Find session by username, 0 for not found
431 // walled garden users aren't authenticated, so the username is
432 // reasonably useless. Ignore them to avoid incorrect actions
433 sessionidt sessionbyuser(char *username)
434 {
435 int s;
436 #ifdef STAT_CALLS
437 STAT(call_sessionbyuser);
438 #endif
439 for (s = 1; s < MAXSESSION && (session[s].walled_garden || strncmp(session[s].user, username, 128)); s++);
440 if (s < MAXSESSION)
441 return s;
442 return 0;
443 }
444
445 void send_garp(ipt ip)
446 {
447 int s;
448 struct ifreq ifr;
449 unsigned char mac[6];
450
451 s = socket(PF_INET, SOCK_DGRAM, 0);
452 if (s < 0)
453 {
454 log(0, 0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno));
455 return;
456 }
457 memset(&ifr, 0, sizeof(ifr));
458 strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name) - 1);
459 if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
460 {
461 log(0, 0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno));
462 close(s);
463 return;
464 }
465 memcpy(mac, &ifr.ifr_hwaddr.sa_data, 6*sizeof(char));
466 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
467 {
468 log(0, 0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno));
469 close(s);
470 return;
471 }
472 close(s);
473 sendarp(ifr.ifr_ifindex, mac, ip);
474 }
475
476 // Find session by username, 0 for not found
477 sessiont *sessiontbysessionidt(sessionidt s)
478 {
479 if (!s || s > MAXSESSION) return NULL;
480 return &session[s];
481 }
482
483 sessionidt sessionidtbysessiont(sessiont *s)
484 {
485 sessionidt val = s-session;
486 if (s < session || val > MAXSESSION) return 0;
487 return val;
488 }
489
490 // send gratuitous ARP to set ARP table for newly allocated IP
491 void sessionsendarp(sessionidt s)
492 {
493 unsigned char mac[6];
494 #ifdef STAT_CALLS
495 STAT(call_sendarp);
496 #endif
497 *(u16 *) (mac + 0) = htons(tapmac[0]); // set source address
498 *(u16 *) (mac + 2) = htons(tapmac[1]);
499 *(u16 *) (mac + 4) = htons(tapmac[2]);
500 sendarp(tapidx, mac, session[s].ip);
501 STAT(arp_sent);
502 }
503
504 // Handle ARP requests
505 void processarp(u8 * buf, int len)
506 {
507 ipt ip;
508 sessionidt s;
509
510 #ifdef STAT_CALLS
511 STAT(call_processarp);
512 #endif
513 STAT(arp_recv);
514 if (len != 46)
515 {
516 log(0, 0, 0, 0, "Unexpected length ARP %d bytes\n", len);
517 STAT(arp_errors);
518 return;
519 }
520 if (*(u16 *) (buf + 16) != htons(PKTARP))
521 {
522 log(0, 0, 0, 0, "Unexpected ARP type %04X\n", ntohs(*(u16 *) (buf + 16)));
523 STAT(arp_errors);
524 return;
525 }
526 if (*(u16 *) (buf + 18) != htons(0x0001))
527 {
528 log(0, 0, 0, 0, "Unexpected ARP hard type %04X\n", ntohs(*(u16 *) (buf + 18)));
529 STAT(arp_errors);
530 return;
531 }
532 if (*(u16 *) (buf + 20) != htons(PKTIP))
533 {
534 log(0, 0, 0, 0, "Unexpected ARP prot type %04X\n", ntohs(*(u16 *) (buf + 20)));
535 STAT(arp_errors);
536 return;
537 }
538 if (buf[22] != 6)
539 {
540 log(0, 0, 0, 0, "Unexpected ARP hard len %d\n", buf[22]);
541 STAT(arp_errors);
542 return;
543 }
544 if (buf[23] != 4)
545 {
546 log(0, 0, 0, 0, "Unexpected ARP prot len %d\n", buf[23]);
547 STAT(arp_errors);
548 return;
549 }
550 if (*(u16 *) (buf + 24) != htons(0x0001))
551 {
552 log(0, 0, 0, 0, "Unexpected ARP op %04X\n", ntohs(*(u16 *) (buf + 24)));
553 STAT(arp_errors);
554 return;
555 }
556 ip = ntohl(*(u32 *) (buf + 42));
557 // look up session
558 s = sessionbyip(htonl(ip));
559 if (s)
560 {
561 log(3, ip, s, session[s].tunnel, "ARP reply for %u.%u.%u.%u\n", ip >> 24, ip >> 16 & 255, ip >> 8 & 255, ip & 255);
562 memcpy(buf + 4, buf + 10, 6); // set destination as source
563 *(u16 *) (buf + 10) = htons(tapmac[0]); // set soucre address
564 *(u16 *) (buf + 12) = htons(tapmac[1]);
565 *(u16 *) (buf + 14) = htons(tapmac[2]);
566 *(u16 *) (buf + 24) = htons(0x0002); // ARP reply
567 memcpy(buf + 26, buf + 10, 6); // sender ethernet
568 memcpy(buf + 36, buf + 4, 6); // target ethernet
569 *(u32 *) (buf + 42) = *(u32 *) (buf + 32); // target IP
570 *(u32 *) (buf + 32) = htonl(ip); // sender IP
571 write(tapfd, buf, len);
572 STAT(arp_replies);
573 }
574 else
575 {
576 log(3, ip, 0, 0, "ARP request for unknown IP %u.%u.%u.%u\n", ip >> 24, ip >> 16 & 255, ip >> 8 & 255, ip & 255);
577 STAT(arp_discarded);
578 }
579 }
580
581 // actually send a control message for a specific tunnel
582 void tunnelsend(u8 * buf, u16 l, tunnelidt t)
583 {
584 struct sockaddr_in addr;
585
586 #ifdef STAT_CALLS
587 STAT(call_tunnelsend);
588 #endif
589 if (!t)
590 {
591 static int backtrace_count = 0;
592 log(0, 0, 0, t, "tunnelsend called with 0 as tunnel id\n");
593 STAT(tunnel_tx_errors);
594 log_backtrace(backtrace_count, 5)
595 return;
596 }
597
598 if (!tunnel[t].ip)
599 {
600 static int backtrace_count = 0;
601 log(1, 0, 0, t, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
602 log_backtrace(backtrace_count, 5)
603 STAT(tunnel_tx_errors);
604 return;
605 }
606 memset(&addr, 0, sizeof(addr));
607 addr.sin_family = AF_INET;
608 *(u32 *) & addr.sin_addr = htonl(tunnel[t].ip);
609 addr.sin_port = htons(tunnel[t].port);
610
611 // sequence expected, if sequence in message
612 if (*buf & 0x08) *(u16 *) (buf + ((*buf & 0x40) ? 10 : 8)) = htons(tunnel[t].nr);
613
614 // If this is a control message, deal with retries
615 if (*buf & 0x80)
616 {
617 tunnel[t].last = time_now; // control message sent
618 tunnel[t].retry = backoff(tunnel[t].try); // when to resend
619 if (tunnel[t].try > 1)
620 {
621 STAT(tunnel_retries);
622 log(3, tunnel[t].ip, 0, t, "Control message resend try %d\n", tunnel[t].try);
623 }
624 }
625
626 if (sendto(udpfd, buf, l, 0, (void *) &addr, sizeof(addr)) < 0)
627 {
628 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",
629 strerror(errno), udpfd, buf, l, inet_ntoa(addr.sin_addr));
630 STAT(tunnel_tx_errors);
631 return;
632 }
633
634 log_hex(5, "Send Tunnel Data", buf, l);
635 STAT(tunnel_tx_packets);
636 INC_STAT(tunnel_tx_bytes, l);
637 }
638
639 // process outgoing (to tunnel) IP
640 void processipout(u8 * buf, int len)
641 {
642 sessionidt s;
643 sessiont *sp;
644 tunnelidt t;
645 ipt ip;
646 u8 b[MAXETHER];
647 #ifdef STAT_CALLS
648 STAT(call_processipout);
649 #endif
650 if (len < MIN_IP_SIZE)
651 {
652 log(1, 0, 0, 0, "Short IP, %d bytes\n", len);
653 STAT(tunnel_tx_errors);
654 return;
655 }
656
657 // Skip the tun header
658 buf += 4;
659 len -= 4;
660
661 // Got an IP header now
662 if (*(u8 *)(buf) >> 4 != 4)
663 {
664 log(1, 0, 0, 0, "IP: Don't understand anything except IPv4\n");
665 return;
666 }
667
668 ip = *(u32 *)(buf + 16);
669 if (!(s = sessionbyip(ip)))
670 {
671 log(4, 0, 0, 0, "IP: Sending ICMP host unreachable to %s\n", inet_toa(*(u32 *)(buf + 12)));
672 host_unreachable(*(u32 *)(buf + 12), *(u16 *)(buf + 4), ip, buf, (len < 64) ? 64 : len);
673 return;
674 }
675 t = session[s].tunnel;
676 sp = &session[s];
677
678 // Snooping this session, send it to ASIO
679 if (sp->snoop) snoop_send_packet(buf, len);
680
681 log(5, session[s].ip, s, t, "Ethernet -> Tunnel (%d bytes)\n", len);
682
683 // Add on L2TP header
684 {
685 u8 *p = makeppp(b, buf, len, t, s, PPPIP);
686 tunnelsend(b, len + (p-b), t); // send it...
687 sp->cout += len; // byte count
688 sp->total_cout += len; // byte count
689 sp->pout++;
690 udp_tx += len;
691 }
692 }
693
694 // add an AVP (16 bit)
695 void control16(controlt * c, u16 avp, u16 val, u8 m)
696 {
697 u16 l = (m ? 0x8008 : 0x0008);
698 *(u16 *) (c->buf + c->length + 0) = htons(l);
699 *(u16 *) (c->buf + c->length + 2) = htons(0);
700 *(u16 *) (c->buf + c->length + 4) = htons(avp);
701 *(u16 *) (c->buf + c->length + 6) = htons(val);
702 c->length += 8;
703 }
704
705 // add an AVP (32 bit)
706 void control32(controlt * c, u16 avp, u32 val, u8 m)
707 {
708 u16 l = (m ? 0x800A : 0x000A);
709 *(u16 *) (c->buf + c->length + 0) = htons(l);
710 *(u16 *) (c->buf + c->length + 2) = htons(0);
711 *(u16 *) (c->buf + c->length + 4) = htons(avp);
712 *(u32 *) (c->buf + c->length + 6) = htonl(val);
713 c->length += 10;
714 }
715
716 // add an AVP (32 bit)
717 void controls(controlt * c, u16 avp, char *val, u8 m)
718 {
719 u16 l = ((m ? 0x8000 : 0) + strlen(val) + 6);
720 *(u16 *) (c->buf + c->length + 0) = htons(l);
721 *(u16 *) (c->buf + c->length + 2) = htons(0);
722 *(u16 *) (c->buf + c->length + 4) = htons(avp);
723 memcpy(c->buf + c->length + 6, val, strlen(val));
724 c->length += 6 + strlen(val);
725 }
726
727 // add a binary AVP
728 void controlb(controlt * c, u16 avp, char *val, unsigned int len, u8 m)
729 {
730 u16 l = ((m ? 0x8000 : 0) + len + 6);
731 *(u16 *) (c->buf + c->length + 0) = htons(l);
732 *(u16 *) (c->buf + c->length + 2) = htons(0);
733 *(u16 *) (c->buf + c->length + 4) = htons(avp);
734 memcpy(c->buf + c->length + 6, val, len);
735 c->length += 6 + len;
736 }
737
738 // new control connection
739 controlt *controlnew(u16 mtype)
740 {
741 controlt *c;
742 if (!controlfree)
743 c = malloc(sizeof(controlt));
744 else
745 {
746 c = controlfree;
747 controlfree = c->next;
748 }
749 assert(c);
750 c->next = 0;
751 *(u16 *) (c->buf + 0) = htons(0xC802); // flags/ver
752 c->length = 12;
753 control16(c, 0, mtype, 1);
754 return c;
755 }
756
757 // send zero block if nothing is waiting
758 void controlnull(tunnelidt t)
759 {
760 u8 buf[12];
761 if (tunnel[t].controlc)
762 return;
763 *(u16 *) (buf + 0) = htons(0xC802); // flags/ver
764 *(u16 *) (buf + 2) = htons(12); // length
765 *(u16 *) (buf + 4) = htons(tunnel[t].far); // tunnel
766 *(u16 *) (buf + 6) = htons(0); // session
767 *(u16 *) (buf + 8) = htons(tunnel[t].ns); // sequence
768 *(u16 *) (buf + 10) = htons(tunnel[t].nr); // sequence
769 tunnelsend(buf, 12, t);
770 }
771
772 // add a control message to a tunnel, and send if within window
773 void controladd(controlt * c, tunnelidt t, sessionidt s)
774 {
775 *(u16 *) (c->buf + 2) = htons(c->length); // length
776 *(u16 *) (c->buf + 4) = htons(tunnel[t].far); // tunnel
777 *(u16 *) (c->buf + 6) = htons(s ? session[s].far : 0); // session
778 *(u16 *) (c->buf + 8) = htons(tunnel[t].ns); // sequence
779 tunnel[t].ns++; // advance sequence
780 // link in message in to queue
781 if (tunnel[t].controlc)
782 tunnel[t].controle->next = c;
783 else
784 tunnel[t].controls = c;
785 tunnel[t].controle = c;
786 tunnel[t].controlc++;
787 // send now if space in window
788 if (tunnel[t].controlc <= tunnel[t].window)
789 {
790 tunnel[t].try = 0; // first send
791 tunnelsend(c->buf, c->length, t);
792 }
793 }
794
795 // start tidy shutdown of session
796 void sessionshutdown(sessionidt s, char *reason)
797 {
798 int dead = session[s].die;
799 int walled_garden = session[s].walled_garden;
800
801 #ifdef STAT_CALLS
802 STAT(call_sessionshutdown);
803 #endif
804 if (!session[s].tunnel)
805 {
806 log(3, session[s].ip, s, session[s].tunnel, "Called sessionshutdown on a session with no tunnel.\n");
807 return; // not a live session
808 }
809
810 if (!session[s].die)
811 log(2, 0, s, session[s].tunnel, "Shutting down session %d: %s\n", s, reason);
812
813 session[s].die = now() + 150; // Clean up in 15 seconds
814
815 {
816 struct param_kill_session data = { &tunnel[session[s].tunnel], &session[s] };
817 run_plugins(PLUGIN_KILL_SESSION, &data);
818 }
819
820 // RADIUS Stop message
821 if (session[s].opened && !walled_garden && !dead) {
822 u16 r = session[s].radius;
823 if (!r)
824 {
825 if (!(r = radiusnew(s)))
826 {
827 log(1, 0, s, session[s].tunnel, "No free RADIUS sessions for Stop message\n");
828 STAT(radius_overflow);
829 }
830 else
831 {
832 int n;
833 for (n = 0; n < 15; n++)
834 radius[r].auth[n] = rand();
835 }
836 }
837 if (r && radius[r].state != RADIUSSTOP)
838 radiussend(r, RADIUSSTOP); // stop, if not already trying
839 }
840
841 if (session[s].ip)
842 { // IP allocated, clear and unroute
843 u16 r;
844 if (session[s].route[0].ip)
845 {
846 routeset(session[s].ip, 0, 0, 0);
847 for (r = 0; r < MAXROUTE; r++)
848 {
849 if (session[s].route[r].ip)
850 {
851 routeset(session[s].route[r].ip, session[s].route[r].mask, session[s].ip, 0);
852 session[s].route[r].ip = 0;
853 }
854 }
855 }
856 if (session[s].throttle) throttle_session(s, 0); session[s].throttle = 0;
857 free_ip_address(s);
858 }
859 { // Send CDN
860 controlt *c = controlnew(14); // sending CDN
861 control16(c, 1, 3, 1); // result code (admin reasons - TBA make error, general error, add message
862 control16(c, 14, s, 1); // assigned session (our end)
863 controladd(c, session[s].tunnel, s); // send the message
864 }
865 cluster_send_session(s);
866 }
867
868 void sendipcp(tunnelidt t, sessionidt s)
869 {
870 u8 buf[MAXCONTROL];
871 u16 r = session[s].radius;
872 u8 *q;
873 #ifdef STAT_CALLS
874 STAT(call_sendipcp);
875 #endif
876 if (!r)
877 r = radiusnew(s);
878 if (radius[r].state != RADIUSIPCP)
879 {
880 radius[r].state = RADIUSIPCP;
881 radius[r].try = 0;
882 }
883 radius[r].retry = backoff(radius[r].try++);
884 if (radius[r].try > 10)
885 {
886 sessionshutdown(s, "No reply on IPCP");
887 return;
888 }
889 q = makeppp(buf, 0, 0, t, s, PPPIPCP);
890 *q = ConfigReq;
891 q[1] = r << RADIUS_SHIFT; // ID, dont care, we only send one type of request
892 *(u16 *) (q + 2) = htons(10);
893 q[4] = 3;
894 q[5] = 6;
895 *(u32 *) (q + 6) = htonl(myip ? myip : session[s].ip); // send my IP (use theirs if I dont have one)
896 tunnelsend(buf, 10 + (q - buf), t); // send it
897 }
898
899 // kill a session now
900 void sessionkill(sessionidt s, char *reason)
901 {
902 #ifdef STAT_CALLS
903 STAT(call_sessionkill);
904 #endif
905 sessionshutdown(s, reason); // close radius/routes, etc.
906 if (session[s].radius)
907 radiusclear(session[s].radius, 0); // cant send clean accounting data, session is killed
908 log(2, 0, s, session[s].tunnel, "Kill session %d: %s\n", s, reason);
909 memset(&session[s], 0, sizeof(session[s]));
910 session[s].next = sessionfree;
911 sessionfree = s;
912 cluster_send_session(s);
913 }
914
915 // kill a tunnel now
916 void tunnelkill(tunnelidt t, char *reason)
917 {
918 sessionidt s;
919 controlt *c;
920 #ifdef STAT_CALLS
921 STAT(call_tunnelkill);
922 #endif
923
924 tunnel[t].state = TUNNELDIE;
925
926 // free control messages
927 while ((c = tunnel[t].controls))
928 {
929 controlt * n = c->next;
930 tunnel[t].controls = n;
931 tunnel[t].controlc--;
932 c->next = controlfree;
933 controlfree = c;
934 }
935 // kill sessions
936 for (s = 1; s < MAXSESSION; s++)
937 if (session[s].tunnel == t)
938 sessionkill(s, reason);
939
940 // free tunnel
941 tunnelclear(t);
942 cluster_send_tunnel(t);
943 log(1, 0, 0, t, "Kill tunnel %d: %s\n", t, reason);
944 tunnel[t].die = 0;
945 tunnel[t].state = TUNNELFREE;
946 }
947
948 // shut down a tunnel cleanly
949 void tunnelshutdown(tunnelidt t, char *reason)
950 {
951 sessionidt s;
952 #ifdef STAT_CALLS
953 STAT(call_tunnelshutdown);
954 #endif
955 if (!tunnel[t].last || !tunnel[t].far || tunnel[t].state == TUNNELFREE)
956 {
957 // never set up, can immediately kill
958 tunnelkill(t, reason);
959 return;
960 }
961 log(1, 0, 0, t, "Shutting down tunnel %d (%s)\n", t, reason);
962
963 // close session
964 for (s = 1; s < MAXSESSION; s++)
965 if (session[s].tunnel == t)
966 sessionkill(s, reason);
967
968 tunnel[t].state = TUNNELDIE;
969 tunnel[t].die = now() + 700; // Clean up in 70 seconds
970 cluster_send_tunnel(t);
971 // TBA - should we wait for sessions to stop?
972 { // Send StopCCN
973 controlt *c = controlnew(4); // sending StopCCN
974 control16(c, 1, 1, 1); // result code (admin reasons - TBA make error, general error, add message
975 control16(c, 9, t, 1); // assigned tunnel (our end)
976 controladd(c, t, 0); // send the message
977 }
978 }
979
980 // read and process packet on tunnel (UDP)
981 void processudp(u8 * buf, int len, struct sockaddr_in *addr)
982 {
983 char *chapresponse = NULL;
984 u16 l = len, t = 0, s = 0, ns = 0, nr = 0;
985 u8 *p = buf + 2;
986
987 #ifdef STAT_CALLS
988 STAT(call_processudp);
989 #endif
990 udp_rx += len;
991 udp_rx_pkt++;
992 log_hex(5, "UDP Data", buf, len);
993 STAT(tunnel_rx_packets);
994 INC_STAT(tunnel_rx_bytes, len);
995 if (len < 6)
996 {
997 log(1, ntohl(addr->sin_addr.s_addr), 0, 0, "Short UDP, %d bytes\n", len);
998 STAT(tunnel_rx_errors);
999 return;
1000 }
1001 if ((buf[1] & 0x0F) != 2)
1002 {
1003 log(1, ntohl(addr->sin_addr.s_addr), 0, 0, "Bad L2TP ver %d\n", (buf[1] & 0x0F) != 2);
1004 STAT(tunnel_rx_errors);
1005 return;
1006 }
1007 if (*buf & 0x40)
1008 { // length
1009 l = ntohs(*(u16 *) p);
1010 p += 2;
1011 }
1012 t = ntohs(*(u16 *) p);
1013 p += 2;
1014 s = ntohs(*(u16 *) p);
1015 p += 2;
1016 if (s >= MAXSESSION)
1017 {
1018 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Received UDP packet with invalid session ID\n");
1019 STAT(tunnel_rx_errors);
1020 return;
1021 }
1022 if (t >= MAXTUNNEL)
1023 {
1024 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Received UDP packet with invalid tunnel ID\n");
1025 STAT(tunnel_rx_errors);
1026 return;
1027 }
1028 if (s && !session[s].tunnel)
1029 {
1030 log(1, ntohl(addr->sin_addr.s_addr), s, t, "UDP packet contains session %d but no session[%d].tunnel exists (LAC said tunnel = %d). Dropping packet.\n", s, s, t);
1031 STAT(tunnel_rx_errors);
1032 return;
1033 }
1034 if (*buf & 0x08)
1035 { // ns/nr
1036 ns = ntohs(*(u16 *) p);
1037 p += 2;
1038 nr = ntohs(*(u16 *) p);
1039 p += 2;
1040 }
1041 if (*buf & 0x02)
1042 { // offset
1043 u16 o = ntohs(*(u16 *) p);
1044 p += o + 2;
1045 }
1046 if ((p - buf) > l)
1047 {
1048 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Bad length %d>%d\n", (p - buf), l);
1049 STAT(tunnel_rx_errors);
1050 return;
1051 }
1052 l -= (p - buf);
1053 if (*buf & 0x80)
1054 { // control
1055 u16 message = 0xFFFF; // message type
1056 u8 fatal = 0;
1057 u8 mandatorymessage = 0;
1058 u8 chap = 0; // if CHAP being used
1059 u16 asession = 0; // assigned session
1060 u32 amagic = 0; // magic number
1061 u8 aflags = 0; // flags from last LCF
1062 u16 version = 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
1063 int requestchap = 0; // do we request PAP instead of original CHAP request?
1064 char called[MAXTEL] = ""; // called number
1065 char calling[MAXTEL] = ""; // calling number
1066 if ((*buf & 0xCA) != 0xC8)
1067 {
1068 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Bad control header %02X\n", *buf);
1069 STAT(tunnel_rx_errors);
1070 return;
1071 }
1072 log(3, ntohl(addr->sin_addr.s_addr), s, t, "Control message (%d bytes): %d ns %d nr %d ns %d nr %d\n",
1073 l, tunnel[t].controlc, tunnel[t].ns, tunnel[t].nr, ns, nr);
1074 // if no tunnel specified, assign one
1075 if (!t)
1076 {
1077 if (!(t = new_tunnel()))
1078 {
1079 log(1, ntohl(addr->sin_addr.s_addr), 0, 0, "No more tunnels\n");
1080 STAT(tunnel_overflow);
1081 return;
1082 }
1083 tunnelclear(t);
1084 tunnel[t].ip = ntohl(*(ipt *) & addr->sin_addr);
1085 tunnel[t].port = ntohs(addr->sin_port);
1086 tunnel[t].window = 4; // default window
1087 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);
1088 STAT(tunnel_created);
1089 }
1090
1091 // This is used to time out old tunnels
1092 tunnel[t].lastrec = time_now;
1093
1094 // check sequence of this message
1095 {
1096 int skip = tunnel[t].window; // track how many in-window packets are still in queue
1097 if (tunnel[t].controlc)
1098 { // some to clear maybe
1099 while (tunnel[t].controlc && (((tunnel[t].ns - tunnel[t].controlc) - nr) & 0x8000))
1100 {
1101 controlt *c = tunnel[t].controls;
1102 tunnel[t].controls = c->next;
1103 tunnel[t].controlc--;
1104 c->next = controlfree;
1105 controlfree = c;
1106 skip--;
1107 tunnel[t].try = 0; // we have progress
1108 }
1109 }
1110 if (tunnel[t].nr < ns && tunnel[t].nr != 0)
1111 {
1112 // is this the sequence we were expecting?
1113 log(1, ntohl(addr->sin_addr.s_addr), 0, t, " Out of sequence tunnel %d, (%d not %d)\n", t, ns, tunnel[t].nr);
1114 STAT(tunnel_rx_errors);
1115 // controlnull(t);
1116 return;
1117 }
1118 // receiver advance (do here so quoted correctly in any sends below)
1119 if (l) tunnel[t].nr++;
1120 if (skip < 0) skip = 0;
1121 if (skip < tunnel[t].controlc)
1122 {
1123 // some control packets can now be sent that were previous stuck out of window
1124 int tosend = tunnel[t].window - skip;
1125 controlt *c = tunnel[t].controls;
1126 while (c && skip)
1127 {
1128 c = c->next;
1129 skip--;
1130 }
1131 while (c && tosend)
1132 {
1133 tunnel[t].try = 0; // first send
1134 tunnelsend(c->buf, c->length, t);
1135 c = c->next;
1136 tosend--;
1137 }
1138 }
1139 if (!tunnel[t].controlc)
1140 tunnel[t].retry = 0; // caught up
1141 }
1142 if (l)
1143 { // if not a null message
1144 // process AVPs
1145 while (l && !(fatal & 0x80))
1146 {
1147 u16 n = (ntohs(*(u16 *) p) & 0x3FF);
1148 u8 *b = p;
1149 u8 flags = *p;
1150 u16 mtype;
1151 p += n; // next
1152 if (l < n)
1153 {
1154 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Invalid length in AVP\n");
1155 STAT(tunnel_rx_errors);
1156 fatal = flags;
1157 return;
1158 }
1159 l -= n;
1160 if (flags & 0x40)
1161 {
1162 // handle hidden AVPs
1163 if (!*config->l2tpsecret)
1164 {
1165 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Hidden AVP requested, but no L2TP secret.\n");
1166 fatal = flags;
1167 continue;
1168 }
1169 if (!session[s].random_vector_length)
1170 {
1171 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Hidden AVP requested, but no random vector.\n");
1172 fatal = flags;
1173 continue;
1174 }
1175 log(4, ntohl(addr->sin_addr.s_addr), s, t, "Hidden AVP\n");
1176 }
1177 if (*b & 0x3C)
1178 {
1179 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Unrecognised AVP flags %02X\n", *b);
1180 fatal = flags;
1181 continue; // next
1182 }
1183 b += 2;
1184 if (*(u16 *) (b))
1185 {
1186 log(2, ntohl(addr->sin_addr.s_addr), s, t, "Unknown AVP vendor %d\n", ntohs(*(u16 *) (b)));
1187 fatal = flags;
1188 continue; // next
1189 }
1190 b += 2;
1191 mtype = ntohs(*(u16 *) (b));
1192 b += 2;
1193 n -= 6;
1194
1195 log(4, ntohl(addr->sin_addr.s_addr), s, t, " AVP %d (%s) len %d\n", mtype, avpnames[mtype], n);
1196 switch (mtype)
1197 {
1198 case 0: // message type
1199 message = ntohs(*(u16 *) b);
1200 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Message type = %d (%s)\n", *b,
1201 l2tp_message_types[message]);
1202 mandatorymessage = flags;
1203 break;
1204 case 1: // result code
1205 {
1206 u16 rescode = ntohs(*(u16 *)(b));
1207 const char* resdesc = "(unknown)";
1208 if (message == 4) { /* StopCCN */
1209 if (rescode <= MAX_STOPCCN_RESULT_CODE)
1210 resdesc = stopccn_result_codes[rescode];
1211 } else if (message == 14) { /* CDN */
1212 if (rescode <= MAX_CDN_RESULT_CODE)
1213 resdesc = cdn_result_codes[rescode];
1214 }
1215
1216 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Result Code %d: %s\n",
1217 rescode, resdesc);
1218 if (n >= 4) {
1219 u16 errcode = ntohs(*(u16 *)(b + 2));
1220 const char* errdesc = "(unknown)";
1221 if (errcode <= MAX_ERROR_CODE)
1222 errdesc = error_codes[errcode];
1223 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Error Code %d: %s\n",
1224 errcode, errdesc);
1225 }
1226 if (n > 4) {
1227 /* %*s doesn't work?? */
1228 char *buf = (char *)strndup(b+4, n-4);
1229 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Error String: %s\n",
1230 buf);
1231 free(buf);
1232 }
1233 break;
1234 }
1235 break;
1236 case 2: // protocol version
1237 {
1238 version = ntohs(*(u16 *) (b));
1239 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Protocol version = %d\n", version);
1240 if (version && version != 0x0100)
1241 { // allow 0.0 and 1.0
1242 log(1, ntohl(addr->sin_addr.s_addr), s, t, " Bad protocol version %04X\n",
1243 version);
1244 fatal = flags;
1245 continue; // next
1246 }
1247 }
1248 break;
1249 case 3: // framing capabilities
1250 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Framing capabilities\n");
1251 break;
1252 case 4: // bearer capabilities
1253 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Bearer capabilities\n");
1254 break;
1255 case 5: // tie breaker
1256 // We never open tunnels, so we don't care about tie breakers
1257 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Tie breaker\n");
1258 continue;
1259 case 6: // firmware revision
1260 // log(4, ntohl(addr->sin_addr.s_addr), s, t, "Firmware revision\n");
1261 break;
1262 case 7: // host name
1263 memset(tunnel[t].hostname, 0, 128);
1264 memcpy(tunnel[t].hostname, b, (n >= 127) ? 127 : n);
1265 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Tunnel hostname = \"%s\"\n", tunnel[t].hostname);
1266 // TBA - to send to RADIUS
1267 break;
1268 case 8: // vendor name
1269 memset(tunnel[t].vendor, 0, 128);
1270 memcpy(tunnel[t].vendor, b, (n >= 127) ? 127 : n);
1271 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Vendor name = \"%s\"\n", tunnel[t].vendor);
1272 break;
1273 case 9: // assigned tunnel
1274 tunnel[t].far = ntohs(*(u16 *) (b));
1275 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Remote tunnel id = %d\n", tunnel[t].far);
1276 break;
1277 case 10: // rx window
1278 tunnel[t].window = ntohs(*(u16 *) (b));
1279 if (!tunnel[t].window)
1280 tunnel[t].window = 1; // window of 0 is silly
1281 log(4, ntohl(addr->sin_addr.s_addr), s, t, " rx window = %d\n", tunnel[t].window);
1282 break;
1283 case 11: // Challenge
1284 {
1285 log(4, ntohl(addr->sin_addr.s_addr), s, t, " LAC requested CHAP authentication for tunnel\n");
1286 build_chap_response(b, 2, n, &chapresponse);
1287 }
1288 break;
1289 case 14: // assigned session
1290 asession = session[s].far = ntohs(*(u16 *) (b));
1291 log(4, ntohl(addr->sin_addr.s_addr), s, t, " assigned session = %d\n", asession);
1292 break;
1293 case 15: // call serial number
1294 log(4, ntohl(addr->sin_addr.s_addr), s, t, " call serial number = %d\n", ntohl(*(u32 *)b));
1295 break;
1296 case 18: // bearer type
1297 log(4, ntohl(addr->sin_addr.s_addr), s, t, " bearer type = %d\n", ntohl(*(u32 *)b));
1298 // TBA - for RADIUS
1299 break;
1300 case 19: // framing type
1301 log(4, ntohl(addr->sin_addr.s_addr), s, t, " framing type = %d\n", ntohl(*(u32 *)b));
1302 // TBA
1303 break;
1304 case 21: // called number
1305 memset(called, 0, MAXTEL);
1306 memcpy(called, b, (n >= MAXTEL) ? (MAXTEL-1) : n);
1307 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Called <%s>\n", called);
1308 break;
1309 case 22: // calling number
1310 memset(calling, 0, MAXTEL);
1311 memcpy(calling, b, (n >= MAXTEL) ? (MAXTEL-1) : n);
1312 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Calling <%s>\n", calling);
1313 break;
1314 case 24: // tx connect speed
1315 if (n == 4)
1316 {
1317 session[s].tx_connect_speed = ntohl(*(u32 *)b);
1318 }
1319 else
1320 {
1321 // AS5300s send connect speed as a string
1322 char tmp[30] = {0};
1323 memcpy(tmp, b, (n >= 30) ? 30 : n);
1324 session[s].tx_connect_speed = atol(tmp);
1325 }
1326 log(4, ntohl(addr->sin_addr.s_addr), s, t, " TX connect speed <%lu>\n",
1327 session[s].tx_connect_speed);
1328 break;
1329 case 38: // rx connect speed
1330 if (n == 4)
1331 {
1332 session[s].rx_connect_speed = ntohl(*(u32 *)b);
1333 }
1334 else
1335 {
1336 // AS5300s send connect speed as a string
1337 char tmp[30] = {0};
1338 memcpy(tmp, b, (n >= 30) ? 30 : n);
1339 session[s].rx_connect_speed = atol(tmp);
1340 }
1341 log(4, ntohl(addr->sin_addr.s_addr), s, t, " RX connect speed <%lu>\n",
1342 session[s].rx_connect_speed);
1343 break;
1344 case 25: // Physical Channel ID
1345 {
1346 u32 tmp = ntohl(*(u32 *)b);
1347 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Physical Channel ID <%X>\n", tmp);
1348 break;
1349 }
1350 case 29: // Proxy Authentication Type
1351 {
1352 u16 authtype = ntohs(*(u16 *)b);
1353 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth Type %d (%s)\n",
1354 authtype, authtypes[authtype]);
1355 requestchap = (authtype == 2);
1356 break;
1357 }
1358 case 30: // Proxy Authentication Name
1359 {
1360 char authname[64] = {0};
1361 memcpy(authname, b, (n > 63) ? 63 : n);
1362 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth Name (%s)\n",
1363 authname);
1364 break;
1365 }
1366 case 31: // Proxy Authentication Challenge
1367 {
1368 memcpy(radius[session[s].radius].auth, b, 16);
1369 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth Challenge\n");
1370 break;
1371 }
1372 case 32: // Proxy Authentication ID
1373 {
1374 u16 authid = ntohs(*(u16 *)(b));
1375 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth ID (%d)\n",
1376 authid);
1377 if (session[s].radius)
1378 radius[session[s].radius].id = authid;
1379 break;
1380 }
1381 case 33: // Proxy Authentication Response
1382 {
1383 char authresp[64] = {0};
1384 memcpy(authresp, b, (n > 63) ? 63 : n);
1385 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Proxy Auth Response\n");
1386 break;
1387 }
1388 case 27: // last send lcp
1389 { // find magic number
1390 u8 *p = b, *e = p + n;
1391 while (p < e && p[1])
1392 {
1393 if (*p == 5 && p[1] == 6)
1394 amagic = ntohl(*(u32 *) (p + 2));
1395 else if (*p == 3 && p[1] == 5 && *(u16 *) (p + 2) == htons(PPPCHAP) && p[4] == 5)
1396 chap = 1;
1397 else if (*p == 7)
1398 aflags |= SESSIONPFC;
1399 else if (*p == 8)
1400 aflags |= SESSIONACFC;
1401 p += p[1];
1402 }
1403
1404 {
1405 char tmp[500] = {0};
1406 tmp[0] = ConfigReq;
1407 memcpy((tmp + 1), b, n);
1408 }
1409 }
1410 break;
1411 case 28: // last recv lcp confreq
1412 {
1413 char tmp[500] = {0};
1414 tmp[0] = ConfigReq;
1415 memcpy((tmp + 1), b, n);
1416 break;
1417 }
1418 case 26: // Initial Received LCP CONFREQ
1419 {
1420 char tmp[500] = {0};
1421 tmp[0] = ConfigReq;
1422 memcpy((tmp + 1), b, n);
1423 }
1424 break;
1425 case 39: // seq required - we control it as an LNS anyway...
1426 break;
1427 case 36: // Random Vector
1428 log(4, ntohl(addr->sin_addr.s_addr), s, t, " Random Vector received. Enabled AVP Hiding.\n");
1429 memset(session[s].random_vector, 0, sizeof(session[s].random_vector));
1430 memcpy(session[s].random_vector, b, n);
1431 session[s].random_vector_length = n;
1432 break;
1433 default:
1434 log(2, ntohl(addr->sin_addr.s_addr), s, t, " Unknown AVP type %d\n", mtype);
1435 fatal = flags;
1436 continue; // next
1437 }
1438 }
1439 // process message
1440 if (fatal & 0x80)
1441 tunnelshutdown(t, "Unknown Mandatory AVP");
1442 else
1443 switch (message)
1444 {
1445 case 1: // SCCRQ - Start Control Connection Request
1446 {
1447 controlt *c = controlnew(2); // sending SCCRP
1448 control16(c, 2, version, 1); // protocol version
1449 control32(c, 3, 3, 1); // framing
1450 controls(c, 7, tunnel[t].hostname, 1); // host name (TBA)
1451 if (chapresponse) controlb(c, 13, chapresponse, 16, 1); // Challenge response
1452 control16(c, 9, t, 1); // assigned tunnel
1453 controladd(c, t, s); // send the resply
1454 }
1455 tunnel[t].state = TUNNELOPENING;
1456 break;
1457 case 2: // SCCRP
1458 tunnel[t].state = TUNNELOPEN;
1459 break;
1460 case 3: // SCCN
1461 tunnel[t].state = TUNNELOPEN;
1462 controlnull(t); // ack
1463 break;
1464 case 4: // StopCCN
1465 controlnull(t); // ack
1466 tunnelshutdown(t, "Stopped"); // Shut down cleanly
1467 tunnelkill(t, "Stopped"); // Immediately force everything dead
1468 break;
1469 case 6: // HELLO
1470 controlnull(t); // simply ACK
1471 break;
1472 case 7: // OCRQ
1473 // TBA
1474 break;
1475 case 8: // OCRO
1476 // TBA
1477 break;
1478 case 9: // OCCN
1479 // TBA
1480 break;
1481 case 10: // ICRQ
1482 if (!sessionfree)
1483 {
1484 STAT(session_overflow);
1485 tunnelshutdown(t, "No free sessions");
1486 }
1487 else
1488 {
1489 u16 r;
1490 controlt *c;
1491
1492 s = sessionfree;
1493 sessionfree = session[s].next;
1494 memset(&session[s], 0, sizeof(session[s]));
1495
1496 // make a RADIUS session
1497 if (!(r = radiusnew(s)))
1498 {
1499 log(1, ntohl(addr->sin_addr.s_addr), s, t, "No free RADIUS sessions for ICRQ\n");
1500 return;
1501 }
1502
1503 c = controlnew(11); // sending ICRP
1504 session[s].id = sessionid++;
1505 session[s].opened = time(NULL);
1506 session[s].tunnel = t;
1507 session[s].far = asession;
1508 session[s].last_packet = time_now;
1509 log(3, ntohl(addr->sin_addr.s_addr), s, t, "New session (%d/%d)\n", tunnel[t].far, session[s].far);
1510 control16(c, 14, s, 1); // assigned session
1511 controladd(c, t, s); // send the reply
1512 {
1513 // Generate a random challenge
1514 int n;
1515 for (n = 0; n < 15; n++)
1516 radius[r].auth[n] = rand();
1517 }
1518 strncpy(radius[r].calling, calling, sizeof(radius[r].calling) - 1);
1519 strncpy(session[s].called, called, sizeof(session[s].called) - 1);
1520 strncpy(session[s].calling, calling, sizeof(session[s].calling) - 1);
1521 STAT(session_created);
1522 }
1523 break;
1524 case 11: // ICRP
1525 // TBA
1526 break;
1527 case 12: // ICCN
1528 session[s].magic = amagic; // set magic number
1529 session[s].flags = aflags; // set flags received
1530 log(3, ntohl(addr->sin_addr.s_addr), s, t, "Magic %X Flags %X\n", amagic, aflags);
1531 controlnull(t); // ack
1532 // In CHAP state, request PAP instead
1533 if (requestchap)
1534 initlcp(t, s);
1535 break;
1536 case 14: // CDN
1537 controlnull(t); // ack
1538 sessionshutdown(s, "Closed (Received CDN)");
1539 break;
1540 case 0xFFFF:
1541 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Missing message type\n");
1542 break;
1543 default:
1544 STAT(tunnel_rx_errors);
1545 if (mandatorymessage & 0x80)
1546 tunnelshutdown(t, "Unknown message");
1547 else
1548 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Unknown message type %d\n", message);
1549 break;
1550 }
1551 if (chapresponse) free(chapresponse);
1552 cluster_send_tunnel(t);
1553 }
1554 else
1555 {
1556 log(4, 0, s, t, " Got a ZLB ack\n");
1557 }
1558 }
1559 else
1560 { // data
1561 u16 prot;
1562
1563 log_hex(5, "Receive Tunnel Data", p, l);
1564 if (session[s].die)
1565 {
1566 log(3, ntohl(addr->sin_addr.s_addr), s, t, "Session %d is closing. Don't process PPP packets\n", s);
1567 return; // closing session, PPP not processed
1568 }
1569 if (l > 2 && p[0] == 0xFF && p[1] == 0x03)
1570 { // HDLC address header, discard
1571 p += 2;
1572 l -= 2;
1573 }
1574 if (l < 2)
1575 {
1576 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Short ppp length %d\n", l);
1577 STAT(tunnel_rx_errors);
1578 return;
1579 }
1580 if (*p & 1)
1581 {
1582 prot = *p++;
1583 l--;
1584 }
1585 else
1586 {
1587 prot = ntohs(*(u16 *) p);
1588 p += 2;
1589 l -= 2;
1590 }
1591 if (prot == PPPPAP)
1592 {
1593 session[s].last_packet = time_now;
1594 processpap(t, s, p, l);
1595 }
1596 else if (prot == PPPCHAP)
1597 {
1598 session[s].last_packet = time_now;
1599 processchap(t, s, p, l);
1600 }
1601 else if (prot == PPPLCP)
1602 {
1603 session[s].last_packet = time_now;
1604 processlcp(t, s, p, l);
1605 }
1606 else if (prot == PPPIPCP)
1607 {
1608 session[s].last_packet = time_now;
1609 processipcp(t, s, p, l);
1610 }
1611 else if (prot == PPPCCP)
1612 {
1613 session[s].last_packet = time_now;
1614 processccp(t, s, p, l);
1615 }
1616 else if (prot == PPPIP)
1617 {
1618 session[s].last_packet = time_now;
1619 processipin(t, s, p, l);
1620 }
1621 else
1622 {
1623 STAT(tunnel_rx_errors);
1624 log(1, ntohl(addr->sin_addr.s_addr), s, t, "Unknown PPP protocol %04X\n", prot);
1625 }
1626 }
1627 }
1628
1629 // read and process packet on tap
1630 void processtap(u8 * buf, int len)
1631 {
1632 log_hex(5, "Receive TAP Data", buf, len);
1633 STAT(tap_rx_packets);
1634 INC_STAT(tap_rx_bytes, len);
1635 #ifdef STAT_CALLS
1636 STAT(call_processtap);
1637 #endif
1638 eth_rx_pkt++;
1639 eth_rx += len;
1640 if (len < 22)
1641 {
1642 log(1, 0, 0, 0, "Short tap packet %d bytes\n", len);
1643 STAT(tap_rx_errors);
1644 return;
1645 }
1646 if (*(u16 *) (buf + 2) == htons(PKTARP)) // ARP
1647 processarp(buf, len);
1648 else if (*(u16 *) (buf + 2) == htons(PKTIP)) // IP
1649 processipout(buf, len);
1650 }
1651
1652 // main loop - gets packets on tap or udp and processes them
1653 void mainloop(void)
1654 {
1655 fd_set cr;
1656 int cn, i;
1657 u8 buf[65536];
1658 struct timeval to;
1659
1660 clockt slow = now(); // occasional functions like session/tunnel expiry, tunnel hello, etc
1661 clockt next_acct = slow + ACCT_TIME;
1662 clockt next_cluster_ping = slow + 50;
1663 clockt next_clean = time_now + config->cleanup_interval;
1664 to.tv_sec = 1;
1665 to.tv_usec = 0;
1666 log(4, 0, 0, 0, "Beginning of main loop. udpfd=%d, tapfd=%d, cluster_sockfd=%d, controlfd=%d\n",
1667 udpfd, tapfd, cluster_sockfd, controlfd);
1668
1669 FD_ZERO(&cr);
1670 FD_SET(udpfd, &cr);
1671 FD_SET(tapfd, &cr);
1672 FD_SET(controlfd, &cr);
1673 FD_SET(clifd, &cr);
1674 if (cluster_sockfd) FD_SET(cluster_sockfd, &cr);
1675 cn = udpfd;
1676 if (cn < tapfd) cn = tapfd;
1677 if (cn < controlfd) cn = controlfd;
1678 if (cn < clifd) cn = clifd;
1679 if (cn < cluster_sockfd) cn = cluster_sockfd;
1680 for (i = 0; i < config->num_radfds; i++)
1681 {
1682 if (!radfds[i]) continue;
1683 FD_SET(radfds[i], &cr);
1684 if (radfds[i] > cn)
1685 cn = radfds[i];
1686 }
1687
1688 while (!main_quit)
1689 {
1690 fd_set r;
1691 int n = cn;
1692
1693 if (config->reload_config)
1694 {
1695 // Update the config state based on config settings
1696 update_config();
1697 }
1698
1699 memcpy(&r, &cr, sizeof(fd_set));
1700 n = select(n + 1, &r, 0, 0, &to);
1701 if (n < 0)
1702 {
1703 if (errno != EINTR)
1704 {
1705 perror("select");
1706 exit( -1);
1707 }
1708 }
1709 else if (n)
1710 {
1711 struct sockaddr_in addr;
1712 int alen = sizeof(addr);
1713 if (FD_ISSET(udpfd, &r))
1714 {
1715 int c, n;
1716 for (c = 0; c < config->multi_read_count; c++)
1717 {
1718 if ((n = recvfrom(udpfd, buf, sizeof(buf), 0, (void *) &addr, &alen)) > 0)
1719 processudp(buf, n, &addr);
1720 else
1721 break;
1722 }
1723 }
1724 if (FD_ISSET(tapfd, &r))
1725 {
1726 int c, n;
1727 for (c = 0; c < config->multi_read_count; c++)
1728 {
1729 if ((n = read(tapfd, buf, sizeof(buf))) > 0)
1730 processtap(buf, n);
1731 else
1732 break;
1733 }
1734 }
1735 for (i = 0; i < config->num_radfds; i++)
1736 if (FD_ISSET(radfds[i], &r))
1737 processrad(buf, recv(radfds[i], buf, sizeof(buf), 0), i);
1738 if (FD_ISSET(cluster_sockfd, &r))
1739 processcluster(buf, recvfrom(cluster_sockfd, buf, sizeof(buf), MSG_WAITALL, (void *) &addr, &alen));
1740 if (FD_ISSET(controlfd, &r))
1741 processcontrol(buf, recvfrom(controlfd, buf, sizeof(buf), MSG_WAITALL, (void *) &addr, &alen), &addr);
1742 if (FD_ISSET(clifd, &r))
1743 {
1744 struct sockaddr_in addr;
1745 int sockfd;
1746 int len = sizeof(addr);
1747
1748 if ((sockfd = accept(clifd, (struct sockaddr *)&addr, &len)) <= 0)
1749 {
1750 log(0, 0, 0, 0, "accept error: %s\n", strerror(errno));
1751 continue;
1752 }
1753 else
1754 {
1755 cli_do(sockfd);
1756 close(sockfd);
1757 }
1758 }
1759 }
1760
1761 /* Handle timeouts. Make sure that this gets run anyway, even if there was
1762 * something to read, else under load this will never actually run....
1763 */
1764 if (n == 0 || next_clean <= time_now) {
1765 clockt when = now();
1766 clockt best = when + 100; // default timeout
1767 sessionidt s;
1768 tunnelidt t;
1769 int count;
1770 u16 r;
1771
1772 log(3, 0, 0, 0, "Begin regular cleanup\n");
1773 for (r = 1; r < MAXRADIUS; r++)
1774 {
1775 if (radius[r].state && radius[r].retry)
1776 {
1777 if (radius[r].retry <= when)
1778 radiusretry(r);
1779 if (radius[r].retry && radius[r].retry < best)
1780 best = radius[r].retry;
1781 }
1782 else if (radius[r].state && !radius[r].retry)
1783 radius[r].retry = backoff(radius[r].try+1);
1784 }
1785 for (t = 1; t < MAXTUNNEL; t++)
1786 {
1787 // check for expired tunnels
1788 if (tunnel[t].die && tunnel[t].die <= when)
1789 {
1790 STAT(tunnel_timeout);
1791 tunnelkill(t, "Expired");
1792 continue;
1793 }
1794 // check for message resend
1795 if (tunnel[t].retry && tunnel[t].controlc)
1796 {
1797 // resend pending messages as timeout on reply
1798 if (tunnel[t].retry <= when)
1799 {
1800 controlt *c = tunnel[t].controls;
1801 u8 w = tunnel[t].window;
1802 tunnel[t].try++; // another try
1803 if (tunnel[t].try > 5)
1804 tunnelkill(t, "Timeout on control message"); // game over
1805 else
1806 while (c && w--)
1807 {
1808 tunnelsend(c->buf, c->length, t);
1809 c = c->next;
1810 }
1811 }
1812 if (tunnel[t].retry && tunnel[t].retry < best)
1813 best = tunnel[t].retry;
1814 }
1815 // Send hello
1816 if (tunnel[t].state == TUNNELOPEN && tunnel[t].lastrec < when + 600)
1817 {
1818 controlt *c = controlnew(6); // sending HELLO
1819 controladd(c, t, 0); // send the message
1820 log(3, tunnel[t].ip, 0, t, "Sending HELLO message\n");
1821 }
1822 }
1823
1824 // Check for sessions that have been killed from the CLI
1825 if (cli_session_kill[0])
1826 {
1827 int i;
1828 for (i = 0; i < MAXSESSION && cli_session_kill[i]; i++)
1829 {
1830 log(2, 0, cli_session_kill[i], 0, "Dropping session by CLI\n");
1831 sessionshutdown(cli_session_kill[i], "Requested by administrator");
1832 cli_session_kill[i] = 0;
1833 }
1834 }
1835 // Check for tunnels that have been killed from the CLI
1836 if (cli_tunnel_kill[0])
1837 {
1838 int i;
1839 for (i = 1; i < MAXTUNNEL && cli_tunnel_kill[i]; i++)
1840 {
1841 log(2, 0, cli_tunnel_kill[i], 0, "Dropping tunnel by CLI\n");
1842 tunnelshutdown(cli_tunnel_kill[i], "Requested by administrator");
1843 cli_tunnel_kill[i] = 0;
1844 }
1845 }
1846
1847 count = 0;
1848 for (s = 1; s < MAXSESSION; s++)
1849 {
1850 // check for expired sessions
1851 if (session[s].die && session[s].die <= when)
1852 {
1853 sessionkill(s, "Expired");
1854 if (++count >= 1000) break;
1855 continue;
1856 }
1857
1858 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
1859 if (session[s].last_packet && (time_now - session[s].last_packet >= IDLE_TIMEOUT))
1860 {
1861 sessionkill(s, "No response to LCP ECHO requests");
1862 STAT(session_timeout);
1863 if (++count >= 1000) break;
1864 continue;
1865 }
1866
1867 // No data in IDLE_TIMEOUT seconds, send LCP ECHO
1868 if (session[s].user[0] && (time_now - session[s].last_packet >= ECHO_TIMEOUT))
1869 {
1870 u8 b[MAXCONTROL] = {0};
1871 u8 *q = makeppp(b, 0, 0, session[s].tunnel, s, PPPLCP);
1872
1873 *q = EchoReq;
1874 *(u8 *)(q + 1) = (time_now % 255); // ID
1875 *(u16 *)(q + 2) = htons(8); // Length
1876 *(u32 *)(q + 4) = 0; // Magic Number (not supported)
1877
1878 log(4, session[s].ip, s, session[s].tunnel, "No data in %d seconds, sending LCP ECHO\n",
1879 (int)(time_now - session[s].last_packet));
1880 tunnelsend(b, 24, session[s].tunnel); // send it
1881 if (++count >= 1000) break;
1882 continue;
1883 }
1884 }
1885 if (config->accounting_dir && next_acct <= when)
1886 {
1887 // Dump accounting data
1888 next_acct = when + ACCT_TIME;
1889 dump_acct_info();
1890 }
1891
1892 if (cluster_sockfd && next_cluster_ping <= when)
1893 {
1894 // Dump accounting data
1895 next_cluster_ping = when + 50;
1896 cluster_send_message(config->cluster_address, config->bind_address, C_PING, hostname, strlen(hostname));
1897 }
1898
1899 if (best < when + config->cleanup_interval)
1900 best = when + config->cleanup_interval; // Throttle to at most once per 10 seconds
1901 next_clean = time_now + config->cleanup_interval;
1902 to.tv_sec = config->cleanup_interval;
1903 to.tv_usec = 0;
1904 log(3, 0, 0, 0, "End regular cleanup, next in %d seconds\n", config->cleanup_interval);
1905 }
1906 }
1907 }
1908
1909 // Init data structures
1910 void initdata(void)
1911 {
1912 int i;
1913
1914 _statistics = mmap(NULL, sizeof(struct Tstats), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1915 if (_statistics == MAP_FAILED)
1916 {
1917 log(0, 0, 0, 0, "Error doing mmap for _statistics: %s\n", strerror(errno));
1918 exit(1);
1919 }
1920 config = mmap(NULL, sizeof(struct configt), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1921 if (config == MAP_FAILED)
1922 {
1923 log(0, 0, 0, 0, "Error doing mmap for configuration: %s\n", strerror(errno));
1924 exit(1);
1925 }
1926 memset(config, 0, sizeof(struct configt));
1927 time(&config->start_time);
1928 strncpy(config->config_file, CONFIGFILE, sizeof(config->config_file) - 1);
1929 tunnel = mmap(NULL, sizeof(tunnelt) * MAXTUNNEL, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1930 if (tunnel == MAP_FAILED)
1931 {
1932 log(0, 0, 0, 0, "Error doing mmap for tunnels: %s\n", strerror(errno));
1933 exit(1);
1934 }
1935 session = mmap(NULL, sizeof(sessiont) * MAXSESSION, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1936 if (session == MAP_FAILED)
1937 {
1938 log(0, 0, 0, 0, "Error doing mmap for sessions: %s\n", strerror(errno));
1939 exit(1);
1940 }
1941 radius = mmap(NULL, sizeof(radiust) * MAXRADIUS, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1942 if (radius == MAP_FAILED)
1943 {
1944 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno));
1945 exit(1);
1946 }
1947 ip_address_pool = mmap(NULL, sizeof(ippoolt) * MAXIPPOOL, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1948 if (ip_address_pool == MAP_FAILED)
1949 {
1950 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno));
1951 exit(1);
1952 }
1953 #ifdef RINGBUFFER
1954 ringbuffer = mmap(NULL, sizeof(struct Tringbuffer), PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1955 if (ringbuffer == MAP_FAILED)
1956 {
1957 log(0, 0, 0, 0, "Error doing mmap for radius: %s\n", strerror(errno));
1958 exit(1);
1959 }
1960 memset(ringbuffer, 0, sizeof(struct Tringbuffer));
1961 #endif
1962
1963 cli_session_kill = mmap(NULL, sizeof(sessionidt) * MAXSESSION, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1964 if (cli_session_kill == MAP_FAILED)
1965 {
1966 log(0, 0, 0, 0, "Error doing mmap for cli session kill: %s\n", strerror(errno));
1967 exit(1);
1968 }
1969 memset(cli_session_kill, 0, sizeof(sessionidt) * MAXSESSION);
1970 cli_tunnel_kill = mmap(NULL, sizeof(tunnelidt) * MAXSESSION, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1971 if (cli_tunnel_kill == MAP_FAILED)
1972 {
1973 log(0, 0, 0, 0, "Error doing mmap for cli tunnel kill: %s\n", strerror(errno));
1974 exit(1);
1975 }
1976 memset(cli_tunnel_kill, 0, sizeof(tunnelidt) * MAXSESSION);
1977
1978 filter_buckets = mmap(NULL, sizeof(tbft) * MAXSESSION, PROT_READ | PROT_WRITE, MAP_SHARED | MAP_ANONYMOUS, 0, 0);
1979 if (filter_buckets == MAP_FAILED)
1980 {
1981 log(0, 0, 0, 0, "Error doing mmap for filter buckets: %s\n", strerror(errno));
1982 exit(1);
1983 }
1984 memset(filter_buckets, 0, sizeof(tbft) * MAXSESSION);
1985
1986 memset(tunnel, 0, sizeof(tunnelt) * MAXTUNNEL);
1987 memset(session, 0, sizeof(sessiont) * MAXSESSION);
1988 memset(radius, 0, sizeof(radiust) * MAXRADIUS);
1989 memset(ip_address_pool, 0, sizeof(ippoolt) * MAXIPPOOL);
1990 for (i = 1; i < MAXSESSION - 1; i++)
1991 session[i].next = i + 1;
1992 session[MAXSESSION - 1].next = 0;
1993 sessionfree = 1;
1994 if (!*hostname)
1995 {
1996 char *p;
1997 // Grab my hostname unless it's been specified
1998 gethostname(hostname, sizeof(hostname));
1999 {
2000 struct hostent *h = gethostbyname(hostname);
2001 if (h)
2002 myip = ntohl(*(u32 *) h->h_addr);
2003 }
2004
2005 if ((p = strstr(hostname, ".optusnet.com.au"))) *p = 0;
2006 }
2007 _statistics->start_time = _statistics->last_reset = time(NULL);
2008 }
2009
2010 void initiptables(void)
2011 {
2012 /* Flush the tables here so that we have a clean slate */
2013 system("iptables -t nat -F l2tpns");
2014 system("iptables -t mangle -F l2tpns");
2015 }
2016
2017 int assign_ip_address(sessionidt s)
2018 {
2019 unsigned i;
2020 int best = -1;
2021 clockt best_time = time_now;
2022 char *u = session[s].user;
2023 char reuse = 0;
2024
2025 #ifdef STAT_CALLS
2026 STAT(call_assign_ip_address);
2027 #endif
2028 for (i = 0; i < ip_pool_size; i++)
2029 {
2030 if (!ip_address_pool[i].address || ip_address_pool[i].assigned)
2031 continue;
2032
2033 if (!session[s].walled_garden && ip_address_pool[i].user[0] && !strcmp(u, ip_address_pool[i].user))
2034 {
2035 best = i;
2036 reuse = 1;
2037 break;
2038 }
2039
2040 if (ip_address_pool[i].last < best_time)
2041 {
2042 best = i;
2043 if (!(best_time = ip_address_pool[i].last))
2044 break; // never used, grab this one
2045 }
2046 }
2047
2048 if (best < 0)
2049 {
2050 log(0, 0, s, session[s].tunnel, "assign_ip_address(): out of addresses\n");
2051 return 0;
2052 }
2053
2054 session[s].ip = ntohl(ip_address_pool[best].address);
2055 session[s].ip_pool_index = best;
2056 ip_address_pool[best].assigned = 1;
2057 ip_address_pool[best].last = time_now;
2058 ip_address_pool[best].session = s;
2059 if (session[s].walled_garden)
2060 /* Don't track addresses of users in walled garden (note: this
2061 means that their address isn't "sticky" even if they get
2062 un-gardened). */
2063 ip_address_pool[best].user[0] = 0;
2064 else
2065 strncpy(ip_address_pool[best].user, u, sizeof(ip_address_pool[best].user) - 1);
2066
2067 STAT(ip_allocated);
2068 log(4, ip_address_pool[best].address, s, session[s].tunnel,
2069 "assign_ip_address(): %s ip address %d from pool\n", reuse ? "Reusing" : "Allocating", best);
2070
2071 return 1;
2072 }
2073
2074 void free_ip_address(sessionidt s)
2075 {
2076 int i = session[s].ip_pool_index;
2077
2078 #ifdef STAT_CALLS
2079 STAT(call_free_ip_address);
2080 #endif
2081
2082 if (!session[s].ip)
2083 return; // what the?
2084
2085 STAT(ip_freed);
2086 uncache_sessionid(session[s].ip);
2087 session[s].ip = 0;
2088 ip_address_pool[i].assigned = 0;
2089 ip_address_pool[i].session = 0;
2090 ip_address_pool[i].last = time_now;
2091 }
2092
2093 // Initialize the IP address pool
2094 void initippool()
2095 {
2096 FILE *f;
2097 char *buf, *p;
2098 int pi = 0;
2099 memset(ip_address_pool, 0, sizeof(ip_address_pool));
2100
2101 if (!(f = fopen(IPPOOLFILE, "r")))
2102 {
2103 log(0, 0, 0, 0, "Can't load pool file " IPPOOLFILE ": %s\n", strerror(errno));
2104 exit(-1);
2105 }
2106
2107 buf = (char *)malloc(4096);
2108
2109 while (pi < MAXIPPOOL && fgets(buf, 4096, f))
2110 {
2111 char* pool = buf;
2112 if (*buf == '#' || *buf == '\n')
2113 continue; // Skip comments / blank lines
2114 if ((p = (char *)strrchr(buf, '\n'))) *p = 0;
2115 if ((p = (char *)strchr(buf, ':')))
2116 {
2117 ipt src;
2118 *p = '\0';
2119 src = inet_addr(buf);
2120 if (src == INADDR_NONE)
2121 {
2122 log(0, 0, 0, 0, "Invalid address pool IP %s", buf);
2123 exit(-1);
2124 }
2125 // This entry is for a specific IP only
2126 if (src != config->bind_address)
2127 continue;
2128 *p = ':';
2129 pool = p+1;
2130 }
2131 if ((p = (char *)strchr(pool, '/')))
2132 {
2133 // It's a range
2134 int numbits = 0;
2135 unsigned long start = 0, end = 0, mask = 0, ip;
2136 struct rtentry r;
2137
2138 log(2, 0, 0, 0, "Adding IP address range %s\n", buf);
2139 *p++ = 0;
2140 if (!*p || !(numbits = atoi(p)))
2141 {
2142 log(0, 0, 0, 0, "Invalid pool range %s\n", buf);
2143 continue;
2144 }
2145 start = end = ntohl(inet_addr(pool));
2146 mask = (unsigned long)(pow(2, numbits) - 1) << (32 - numbits);
2147 start &= mask;
2148 end = start + (int)(pow(2, (32 - numbits))) - 1;
2149 for (ip = (start + 1); ip < end && pi < MAXIPPOOL; ip++)
2150 {
2151 if ((ip & 0xFF) == 0 || (ip & 0xFF) == 255)
2152 continue;
2153 ip_address_pool[pi++].address = htonl(ip);
2154 }
2155
2156 // Add a static route for this pool
2157 log(5, 0, 0, 0, "Adding route for address pool %s/%lu\n", inet_toa(htonl(start)), 32 + mask);
2158 memset(&r, 0, sizeof(r));
2159 r.rt_dev = config->tapdevice;
2160 r.rt_dst.sa_family = AF_INET;
2161 *(u32 *) & (((struct sockaddr_in *) &r.rt_dst)->sin_addr.s_addr) = htonl(start);
2162 r.rt_genmask.sa_family = AF_INET;
2163 *(u32 *) & (((struct sockaddr_in *) &r.rt_genmask)->sin_addr.s_addr) = htonl(mask);
2164 r.rt_flags = (RTF_UP | RTF_STATIC);
2165 if (ioctl(ifrfd, SIOCADDRT, (void *) &r) < 0)
2166 {
2167 log(0, 0, 0, 0, "Error adding ip address pool route %s/%lu: %s\n",
2168 inet_toa(start), mask, strerror(errno));
2169 }
2170 }
2171 else
2172 {
2173 // It's a single ip address
2174 ip_address_pool[pi++].address = inet_addr(pool);
2175 }
2176 }
2177
2178 free(buf);
2179 fclose(f);
2180 log(1, 0, 0, 0, "IP address pool is %d addresses\n", pi);
2181 ip_pool_size = pi;
2182 }
2183
2184 void snoop_send_packet(char *packet, u16 size)
2185 {
2186 if (!snoop_addr.sin_port || snoopfd <= 0 || size <= 0 || !packet)
2187 return;
2188
2189 log(5, 0, 0, 0, "Snooping packet at %p (%d bytes) to %s:%d\n", packet, size, inet_toa(snoop_addr.sin_addr.s_addr), htons(snoop_addr.sin_port));
2190 if (sendto(snoopfd, packet, size, MSG_DONTWAIT | MSG_NOSIGNAL, (void *) &snoop_addr, sizeof(snoop_addr)) < 0)
2191 log(0, 0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno));
2192 STAT(packets_snooped);
2193 }
2194
2195 void dump_acct_info()
2196 {
2197 char filename[1024];
2198 char timestr[64];
2199 time_t t = time(NULL);
2200 int i;
2201 FILE *f = NULL;
2202
2203 #ifdef STAT_CALLS
2204 STAT(call_dump_acct_info);
2205 #endif
2206 strftime(timestr, 64, "%Y%m%d%H%M%S", localtime(&t));
2207 snprintf(filename, 1024, "%s/%s", config->accounting_dir, timestr);
2208
2209 for (i = 0; i < MAXSESSION; i++)
2210 {
2211 if (!session[i].opened || !session[i].ip || !session[i].cin || !session[i].cout || !*session[i].user || session[i].walled_garden)
2212 continue;
2213 if (!f)
2214 {
2215 time_t now = time(NULL);
2216 if (!(f = fopen(filename, "w")))
2217 {
2218 log(0, 0, 0, 0, "Can't write accounting info to %s: %s\n", filename, strerror(errno));
2219 return;
2220 }
2221 log(3, 0, 0, 0, "Dumping accounting information to %s\n", filename);
2222 fprintf(f, "# dslwatch.pl dump file V1.01\n"
2223 "# host: %s\n"
2224 "# time: %ld\n"
2225 "# uptime: %ld\n"
2226 "# format: username ip qos uptxoctets downrxoctets\n",
2227 hostname,
2228 now,
2229 now - basetime);
2230 }
2231
2232 log(4, 0, 0, 0, "Dumping accounting information for %s\n", session[i].user);
2233 fprintf(f, "%s %s %d %lu %lu\n",
2234 session[i].user, // username
2235 inet_toa(htonl(session[i].ip)), // ip
2236 (session[i].throttle) ? 2 : 1, // qos
2237 (unsigned long)session[i].cin, // uptxoctets
2238 (unsigned long)session[i].cout); // downrxoctets
2239
2240 session[i].pin = session[i].cin = 0;
2241 session[i].pout = session[i].cout = 0;
2242 }
2243
2244 if (f) fclose(f);
2245 }
2246
2247 // Main program
2248 int main(int argc, char *argv[])
2249 {
2250 int o;
2251
2252 _program_name = strdup(argv[0]);
2253
2254 time(&basetime); // start clock
2255 // scan args
2256
2257 while ((o = getopt(argc, argv, "vc:h:a:")) >= 0)
2258 {
2259 switch (o)
2260 {
2261 case 'v':
2262 config->debug++;
2263 break;
2264 case 'h':
2265 strncpy(hostname, optarg, 999);
2266 break;
2267 case '?':
2268 default:
2269 printf("Args are:\n\t-c <file>\tConfig file\n\t-h <hostname>\tForce hostname\n\t-a <address>\tUse specific address\n\t-v\t\tDebug\n");
2270 return (0);
2271 break;
2272 }
2273 }
2274
2275 // Start the timer routine off
2276 time(&time_now);
2277 strftime(time_now_string, 64, "%Y-%m-%d %H:%M:%S", localtime(&time_now));
2278 signal(SIGALRM, sigalrm_handler);
2279 siginterrupt(SIGALRM, 0);
2280
2281 initiptables();
2282 initplugins();
2283 initdata();
2284 init_cli();
2285 read_config_file();
2286 log(0, 0, 0, 0, "$Id: l2tpns.c,v 1.6 2004-05-24 04:20:28 fred_nerk Exp $\n(c) Copyright 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
2287 {
2288 struct rlimit rlim;
2289 rlim.rlim_cur = RLIM_INFINITY;
2290 rlim.rlim_max = RLIM_INFINITY;
2291 // Remove the maximum core size
2292 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
2293 log(0, 0, 0, 0, "Can't set ulimit: %s\n", strerror(errno));
2294 // Make core dumps go to /tmp
2295 chdir("/tmp");
2296 }
2297
2298 /* Start up the cluster first, so that we don't have two machines with
2299 * the same IP at once.
2300 * This is still racy, but the second GARP should fix that
2301 */
2302 cluster_init(config->bind_address, 0);
2303 cluster_send_message(config->cluster_address, config->bind_address, C_HELLO, hostname, strlen(hostname));
2304
2305 inittap();
2306 log(1, 0, 0, 0, "Set up on interface %s\n", config->tapdevice);
2307
2308 initudp();
2309 initrad();
2310 initippool();
2311 init_rl();
2312 if (config->bind_address)
2313 send_garp(config->bind_address);
2314
2315 // If NOSTATEFILE exists, we will ignore any updates from the cluster master for this execution
2316 if (!unlink(NOSTATEFILE))
2317 config->ignore_cluster_updates = 1;
2318
2319 read_state();
2320
2321 signal(SIGHUP, sighup_handler);
2322 signal(SIGTERM, sigterm_handler);
2323 signal(SIGINT, sigterm_handler);
2324 signal(SIGQUIT, sigquit_handler);
2325 signal(SIGCHLD, sigchild_handler);
2326
2327 alarm(1);
2328
2329 // Drop privileges here
2330 if (config->target_uid > 0 && geteuid() == 0)
2331 setuid(config->target_uid);
2332
2333 mainloop();
2334 return 0;
2335 }
2336
2337 void sighup_handler(int junk)
2338 {
2339 if (log_stream && log_stream != stderr)
2340 {
2341 fclose(log_stream);
2342 log_stream = NULL;
2343 }
2344
2345 read_config_file();
2346 }
2347
2348 void sigalrm_handler(int junk)
2349 {
2350 // Log current traffic stats
2351
2352 snprintf(config->bandwidth, sizeof(config->bandwidth),
2353 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%lu OUT:%lu",
2354 (udp_rx / 1024.0 / 1024.0 * 8),
2355 (eth_tx / 1024.0 / 1024.0 * 8),
2356 (eth_rx / 1024.0 / 1024.0 * 8),
2357 (udp_tx / 1024.0 / 1024.0 * 8),
2358 ((udp_tx + udp_rx + eth_tx + eth_rx) / 1024.0 / 1024.0 * 8),
2359 udp_rx_pkt, eth_rx_pkt);
2360
2361 udp_tx = udp_rx = 0;
2362 udp_rx_pkt = eth_rx_pkt = 0;
2363 eth_tx = eth_rx = 0;
2364
2365 if (config->dump_speed)
2366 printf("%s\n", config->bandwidth);
2367
2368 // Update the internal time counter
2369 time(&time_now);
2370 strftime(time_now_string, 64, "%Y-%m-%d %H:%M:%S", localtime(&time_now));
2371 alarm(1);
2372
2373 {
2374 // Run timer hooks
2375 struct param_timer p = { time_now };
2376 run_plugins(PLUGIN_TIMER, &p);
2377 }
2378
2379 }
2380
2381 void sigterm_handler(int junk)
2382 {
2383 log(1, 0, 0, 0, "Shutting down cleanly\n");
2384 if (config->save_state)
2385 dump_state();
2386 main_quit++;
2387 }
2388
2389 void sigquit_handler(int junk)
2390 {
2391 FILE *f;
2392 int i;
2393
2394 log(1, 0, 0, 0, "Shutting down without saving sessions\n");
2395 for (i = 1; i < MAXSESSION; i++)
2396 {
2397 if (session[i].opened)
2398 sessionkill(i, "L2TPNS Closing");
2399 }
2400 for (i = 1; i < MAXTUNNEL; i++)
2401 {
2402 if (tunnel[i].ip || tunnel[i].state)
2403 tunnelshutdown(i, "L2TPNS Closing");
2404 }
2405
2406 cluster_send_goodbye();
2407
2408 // Touch a file which says not to reload the state
2409 f = fopen(NOSTATEFILE, "w");
2410 if (f) fclose(f);
2411
2412 main_quit++;
2413 }
2414
2415 void sigchild_handler(int signal)
2416 {
2417 while (waitpid(-1, NULL, WNOHANG) > 0)
2418 ;
2419 }
2420
2421 void read_state()
2422 {
2423 struct stat sb;
2424 int i;
2425 ippoolt itmp;
2426 FILE *f;
2427 char magic[sizeof(DUMP_MAGIC)-1];
2428 u32 buf[2];
2429
2430 if (!config->save_state)
2431 return;
2432
2433 // Ignore saved state if NOSTATEFILE exists
2434 if (config->ignore_cluster_updates)
2435 {
2436 unlink(STATEFILE);
2437 return;
2438 }
2439
2440 if (stat(STATEFILE, &sb) < 0)
2441 return;
2442
2443 if (sb.st_mtime < (time(NULL) - 60))
2444 {
2445 log(0, 0, 0, 0, "State file is too old to read, ignoring\n");
2446 unlink(STATEFILE);
2447 return;
2448 }
2449
2450 f = fopen(STATEFILE, "r");
2451 unlink(STATEFILE);
2452
2453 if (!f)
2454 {
2455 log(0, 0, 0, 0, "Can't read state file: %s\n", strerror(errno));
2456 exit(1);
2457 }
2458
2459 if (fread(magic, sizeof(magic), 1, f) != 1 || strncmp(magic, DUMP_MAGIC, sizeof(magic)))
2460 {
2461 log(0, 0, 0, 0, "Bad state file magic\n");
2462 exit(1);
2463 }
2464
2465 log(1, 0, 0, 0, "Reading state information\n");
2466 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] > MAXIPPOOL || buf[1] != sizeof(ippoolt))
2467 {
2468 log(0, 0, 0, 0, "Error/mismatch reading ip pool header from state file\n");
2469 exit(1);
2470 }
2471
2472 if (buf[0] > ip_pool_size)
2473 {
2474 log(0, 0, 0, 0, "ip pool has shrunk! state = %d, current = %d\n", buf[0], ip_pool_size);
2475 exit(1);
2476 }
2477
2478 log(2, 0, 0, 0, "Loading %u ip addresses\n", buf[0]);
2479 for (i = 0; i < buf[0]; i++)
2480 {
2481 if (fread(&itmp, sizeof(itmp), 1, f) != 1)
2482 {
2483 log(0, 0, 0, 0, "Error reading ip %d from state file: %s\n", i, strerror(errno));
2484 exit(1);
2485 }
2486
2487 if (itmp.address != ip_address_pool[i].address)
2488 {
2489 log(0, 0, 0, 0, "Mismatched ip %d from state file: pool may only be extended\n", i);
2490 exit(1);
2491 }
2492
2493 memcpy(&ip_address_pool[i], &itmp, sizeof(itmp));
2494 }
2495
2496 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] != MAXTUNNEL || buf[1] != sizeof(tunnelt))
2497 {
2498 log(0, 0, 0, 0, "Error/mismatch reading tunnel header from state file\n");
2499 exit(1);
2500 }
2501
2502 log(2, 0, 0, 0, "Loading %u tunnels\n", MAXTUNNEL);
2503 if (fread(tunnel, sizeof(tunnelt), MAXTUNNEL, f) != MAXTUNNEL)
2504 {
2505 log(0, 0, 0, 0, "Error reading tunnel data from state file\n");
2506 exit(1);
2507 }
2508
2509 for (i = 0; i < MAXTUNNEL; i++)
2510 {
2511 tunnel[i].controlc = 0;
2512 tunnel[i].controls = NULL;
2513 tunnel[i].controle = NULL;
2514 if (*tunnel[i].hostname)
2515 log(3, 0, 0, 0, "Created tunnel for %s\n", tunnel[i].hostname);
2516 }
2517
2518 if (fread(buf, sizeof(buf), 1, f) != 1 || buf[0] != MAXSESSION || buf[1] != sizeof(sessiont))
2519 {
2520 log(0, 0, 0, 0, "Error/mismatch reading session header from state file\n");
2521 exit(1);
2522 }
2523
2524 log(2, 0, 0, 0, "Loading %u sessions\n", MAXSESSION);
2525 if (fread(session, sizeof(sessiont), MAXSESSION, f) != MAXSESSION)
2526 {
2527 log(0, 0, 0, 0, "Error reading session data from state file\n");
2528 exit(1);
2529 }
2530
2531 for (i = 0; i < MAXSESSION; i++)
2532 {
2533 session[i].tbf = 0;
2534 if (session[i].opened)
2535 {
2536 log(2, 0, i, 0, "Loaded active session for user %s\n", session[i].user);
2537 if (session[i].ip && session[i].ip != 0xFFFFFFFE)
2538 sessionsetup(session[i].tunnel, i, 0);
2539 }
2540 }
2541
2542 fclose(f);
2543 log(0, 0, 0, 0, "Loaded saved state information\n");
2544 }
2545
2546 void dump_state()
2547 {
2548 FILE *f;
2549 u32 buf[2];
2550
2551 if (!config->save_state)
2552 return;
2553
2554 do {
2555 if (!(f = fopen(STATEFILE, "w")))
2556 break;
2557
2558 log(1, 0, 0, 0, "Dumping state information\n");
2559
2560 if (fwrite(DUMP_MAGIC, sizeof(DUMP_MAGIC)-1, 1, f) != 1) break;
2561
2562 log(2, 0, 0, 0, "Dumping %u ip addresses\n", ip_pool_size);
2563 buf[0] = ip_pool_size;
2564 buf[1] = sizeof(ippoolt);
2565 if (fwrite(buf, sizeof(buf), 1, f) != 1) break;
2566 if (fwrite(ip_address_pool, sizeof(ippoolt), ip_pool_size, f) != ip_pool_size) break;
2567
2568 log(2, 0, 0, 0, "Dumping %u tunnels\n", MAXTUNNEL);
2569 buf[0] = MAXTUNNEL;
2570 buf[1] = sizeof(tunnelt);
2571 if (fwrite(buf, sizeof(buf), 1, f) != 1) break;
2572 if (fwrite(tunnel, sizeof(tunnelt), MAXTUNNEL, f) != MAXTUNNEL) break;
2573
2574 log(2, 0, 0, 0, "Dumping %u sessions\n", MAXSESSION);
2575 buf[0] = MAXSESSION;
2576 buf[1] = sizeof(sessiont);
2577 if (fwrite(buf, sizeof(buf), 1, f) != 1) break;
2578 if (fwrite(session, sizeof(sessiont), MAXSESSION, f) != MAXSESSION) break;
2579
2580 if (fclose(f) == 0) return; // OK
2581 } while (0);
2582
2583 log(0, 0, 0, 0, "Can't write state information: %s\n", strerror(errno));
2584 unlink(STATEFILE);
2585 }
2586
2587 void build_chap_response(char *challenge, u8 id, u16 challenge_length, char **challenge_response)
2588 {
2589 MD5_CTX ctx;
2590 *challenge_response = NULL;
2591
2592 if (!*config->l2tpsecret)
2593 {
2594 log(0, 0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
2595 return;
2596 }
2597
2598 log(4, 0, 0, 0, " Building challenge response for CHAP request\n");
2599
2600 *challenge_response = (char *)calloc(17, 1);
2601
2602 MD5Init(&ctx);
2603 MD5Update(&ctx, &id, 1);
2604 MD5Update(&ctx, config->l2tpsecret, strlen(config->l2tpsecret));
2605 MD5Update(&ctx, challenge, challenge_length);
2606 MD5Final(*challenge_response, &ctx);
2607
2608 return;
2609 }
2610
2611 static int facility_value(char *name)
2612 {
2613 int i;
2614 for (i = 0; facilitynames[i].c_name; i++)
2615 {
2616 if (strcmp(facilitynames[i].c_name, name) == 0)
2617 return facilitynames[i].c_val;
2618 }
2619 return 0;
2620 }
2621
2622 void update_config()
2623 {
2624 int i;
2625
2626 snoop_addr.sin_family = AF_INET;
2627 snoop_addr.sin_addr.s_addr = config->snoop_destination_host;
2628 snoop_addr.sin_port = htons(config->snoop_destination_port);
2629
2630 // Update logging
2631 closelog();
2632 syslog_log = 0;
2633 if (log_stream)
2634 {
2635 fclose(log_stream);
2636 log_stream = NULL;
2637 }
2638 if (*config->log_filename)
2639 {
2640 if (strstr(config->log_filename, "syslog:") == config->log_filename)
2641 {
2642 char *p = config->log_filename + 7;
2643 if (*p)
2644 {
2645 openlog("l2tpns", LOG_PID, facility_value(p));
2646 syslog_log = 1;
2647 }
2648 }
2649 else if (strchr(config->log_filename, '/') == config->log_filename)
2650 {
2651 if ((log_stream = fopen((char *)(config->log_filename), "a")))
2652 {
2653 fseek(log_stream, 0, SEEK_END);
2654 setbuf(log_stream, NULL);
2655 }
2656 else
2657 {
2658 log_stream = stderr;
2659 setbuf(log_stream, NULL);
2660 }
2661 }
2662 }
2663 else
2664 {
2665 log_stream = stderr;
2666 setbuf(log_stream, NULL);
2667 }
2668
2669
2670 // Update radius
2671 config->numradiusservers = 0;
2672 for (i = 0; i < MAXRADSERVER; i++)
2673 if (config->radiusserver[i]) config->numradiusservers++;
2674
2675 if (!config->numradiusservers)
2676 {
2677 log(0, 0, 0, 0, "No RADIUS servers defined!\n");
2678 }
2679
2680 config->num_radfds = 2 << RADIUS_SHIFT;
2681
2682 // Update plugins
2683 for (i = 0; i < MAXPLUGINS; i++)
2684 {
2685 if (strcmp(config->plugins[i], config->old_plugins[i]) == 0)
2686 continue;
2687 if (*config->plugins[i])
2688 {
2689 // Plugin added
2690 add_plugin(config->plugins[i]);
2691 }
2692 else if (*config->old_plugins[i])
2693 {
2694 // Plugin removed
2695 remove_plugin(config->old_plugins[i]);
2696 }
2697 }
2698 memcpy(config->old_plugins, config->plugins, sizeof(config->plugins));
2699 if (!config->cleanup_interval) config->cleanup_interval = 10;
2700 if (!config->multi_read_count) config->multi_read_count = 1;
2701 config->reload_config = 0;
2702 }
2703
2704 void read_config_file()
2705 {
2706 FILE *f;
2707
2708 if (!config->config_file) return;
2709 if (!(f = fopen(config->config_file, "r"))) {
2710 fprintf(stderr, "Can't open config file %s: %s\n", config->config_file, strerror(errno));
2711 return;
2712 }
2713
2714 log(3, 0, 0, 0, "Reading config file %s\n", config->config_file);
2715 cli_do_file(f);
2716 log(3, 0, 0, 0, "Done reading config file\n");
2717 fclose(f);
2718 update_config();
2719 }
2720
2721 int sessionsetup(tunnelidt t, sessionidt s, u8 routes)
2722 {
2723 // A session now exists, set it up
2724 ipt ip;
2725 char *user;
2726 sessionidt i;
2727 #ifdef STAT_CALLS
2728 STAT(call_sessionsetup);
2729 #endif
2730 log(3, session[s].ip, s, t, "Doing session setup for session\n");
2731 if (!session[s].ip) {
2732 log(0, session[s].ip, s, t, "VERY VERY BAD! sessionsetup() called with no session[s].ip\n");
2733 return 1;
2734 }
2735
2736 // Make sure this is right
2737 session[s].tunnel = t;
2738 // zap old sessions with same IP and/or username
2739 // Don't kill gardened sessions - doing so leads to a DoS
2740 // from someone who doesn't need to know the password
2741 ip = session[s].ip;
2742 user = session[s].user;
2743 for (i = 1; i < MAXSESSION; i++)
2744 {
2745 if (i == s) continue;
2746 if (ip == session[i].ip) sessionkill(i, "Duplicate IP address");
2747 if (!session[s].walled_garden && !session[i].walled_garden && strcasecmp(user, session[i].user) == 0)
2748 sessionkill(i, "Duplicate session for user");
2749 }
2750
2751 if (routes)
2752 {
2753 if (session[s].route[routes].ip && session[s].route[routes].mask)
2754 {
2755 log(2, session[s].ip, s, t, "Routing session\n");
2756 routeset(session[s].ip, 0, 0, 1);
2757 while (routes--)
2758 routeset(session[s].route[routes].ip, session[s].route[routes].mask,
2759 session[s].ip, 1);
2760 }
2761 }
2762 sessionsendarp(s);
2763 if (!session[s].sid)
2764 sendipcp(t, s);
2765
2766 // Force throttling on or off
2767 // This has the advantage of cleaning up after another throttled user who may have left
2768 // firewall rules lying around
2769 session[s].throttle = throttle_session(s, session[s].throttle);
2770
2771 {
2772 struct param_new_session data = { &tunnel[t], &session[s] };
2773 run_plugins(PLUGIN_NEW_SESSION, &data);
2774 }
2775
2776 if (!session[s].sid)
2777 session[s].sid = ++last_sid;
2778
2779 cache_sessionid(htonl(session[s].ip), s);
2780
2781 cluster_send_session(s);
2782 session[s].last_packet = time_now;
2783 {
2784 char *sessionip, *tunnelip;
2785 sessionip = strdup(inet_toa(ntohl(session[s].ip)));
2786 tunnelip = strdup(inet_toa(ntohl(tunnel[t].ip)));
2787 log(2, session[s].ip, s, t, "Login by %s at %s from %s (%s)\n",
2788 session[s].user, sessionip, tunnelip, tunnel[t].hostname);
2789 if (sessionip) free(sessionip);
2790 if (tunnelip) free(tunnelip);
2791 }
2792
2793 return 1; // RADIUS OK and IP allocated, done...
2794 }
2795
2796 #ifdef RINGBUFFER
2797 void ringbuffer_dump(FILE *stream)
2798 {
2799 int i = ringbuffer->head;
2800
2801 while (i != ringbuffer->tail)
2802 {
2803 if (*ringbuffer->buffer[i].message)
2804 fprintf(stream, "%d-%s", ringbuffer->buffer[i].level, ringbuffer->buffer[i].message);
2805 if (++i == ringbuffer->tail) break;
2806 if (i == RINGBUFFER_SIZE) i = 0;
2807 }
2808 }
2809 #endif
2810
2811 void initplugins()
2812 {
2813 int i;
2814
2815 loaded_plugins = ll_init();
2816 // Initialize the plugins to nothing
2817 for (i = 0; i < MAX_PLUGIN_TYPES; i++)
2818 plugins[i] = ll_init();
2819 }
2820
2821 void add_plugin(char *plugin_name)
2822 {
2823 void *p;
2824 int (*initfunc)(struct pluginfuncs *);
2825 char path[256] = {0};
2826 int i;
2827 struct pluginfuncs funcs;
2828
2829 funcs._log = _log;
2830 funcs._log_hex = _log_hex;
2831 funcs.inet_toa = inet_toa;
2832 funcs.get_session_by_username = sessionbyuser;
2833 funcs.get_session_by_id = sessiontbysessionidt;
2834 funcs.get_id_by_session = sessionidtbysessiont;
2835 funcs.sessionkill = sessionkill;
2836 funcs.radiusnew = radiusnew;
2837 funcs.radiussend = radiussend;
2838
2839 snprintf(path, 256, "%s/%s.so", LIBDIR, plugin_name);
2840
2841 log(2, 0, 0, 0, "Loading plugin from %s\n", path);
2842 p = dlopen(path, RTLD_NOW);
2843 if (!p)
2844 {
2845 log(1, 0, 0, 0, " Plugin load failed: %s\n", dlerror());
2846 return;
2847 }
2848
2849 if (ll_contains(loaded_plugins, p))
2850 {
2851 dlclose(p);
2852 return;
2853 }
2854
2855 {
2856 int *v = dlsym(p, "__plugin_api_version");
2857 if (!v || *v != PLUGIN_API_VERSION)
2858 {
2859 log(1, 0, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
2860 dlclose(p);
2861 return;
2862 }
2863 }
2864
2865 initfunc = dlsym(p, "plugin_init");
2866 if (!initfunc)
2867 {
2868 log(1, 0, 0, 0, " Plugin load failed: function plugin_init() does not exist: %s\n", dlerror());
2869 dlclose(p);
2870 return;
2871 }
2872
2873 if (!initfunc(&funcs))
2874 {
2875 log(1, 0, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
2876 dlclose(p);
2877 return;
2878 }
2879
2880 for (i = 0; i < max_plugin_functions; i++)
2881 {
2882 void *x;
2883 if (!plugin_functions[i]) continue;
2884 if ((x = dlsym(p, plugin_functions[i])))
2885 {
2886 log(3, 0, 0, 0, " Supports function \"%s\"\n", plugin_functions[i]);
2887 ll_push(plugins[i], x);
2888 }
2889 }
2890 log(2, 0, 0, 0, " Loaded plugin %s\n", plugin_name);
2891 }
2892
2893 void remove_plugin(char *plugin_name)
2894 {
2895 void *p;
2896 int (*donefunc)();
2897 char path[256] = {0};
2898 int i;
2899
2900 snprintf(path, 256, "%s/%s.so", LIBDIR, plugin_name);
2901
2902 log(2, 0, 0, 0, "Removing plugin %s\n", plugin_name);
2903 // Get the existing pointer
2904 p = dlopen(path, RTLD_LAZY);
2905 if (!p) return;
2906
2907 for (i = 0; i < max_plugin_functions; i++)
2908 {
2909 void *x;
2910 if (!plugin_functions[i]) continue;
2911 if ((x = dlsym(p, plugin_functions[i]))) ll_delete(plugins[i], x);
2912 }
2913
2914 if (ll_contains(loaded_plugins, p))
2915 {
2916 ll_delete(loaded_plugins, p);
2917
2918 donefunc = dlsym(p, "plugin_done");
2919 if (donefunc) donefunc();
2920 }
2921
2922 dlclose(p);
2923 dlclose(p);
2924 log(2, 0, 0, 0, "Removed plugin %s\n", plugin_name);
2925 }
2926
2927 int run_plugins(int plugin_type, void *data)
2928 {
2929 int (*func)(void *data);
2930 if (!plugins[plugin_type] || plugin_type > max_plugin_functions) return 1;
2931
2932 ll_reset(plugins[plugin_type]);
2933 while ((func = ll_next(plugins[plugin_type])))
2934 {
2935 int rc;
2936 rc = func(data);
2937 if (rc == PLUGIN_RET_STOP) return 1;
2938 if (rc == PLUGIN_RET_ERROR) return 0;
2939 }
2940 return 1;
2941 }
2942
2943 void processcontrol(u8 * buf, int len, struct sockaddr_in *addr)
2944 {
2945 char *resp;
2946 int l;
2947 struct param_control param = { buf, len, ntohl(addr->sin_addr.s_addr), ntohs(addr->sin_port), NULL, 0, 0 };
2948
2949 log(4, ntohl(addr->sin_addr.s_addr), 0, 0, "Received ");
2950 if (log_stream)
2951 dump_packet(buf, log_stream);
2952
2953 resp = calloc(1400, 1);
2954 l = new_packet(PKT_RESP_ERROR, resp);
2955 *(int *)(resp + 6) = *(int *)(buf + 6);
2956
2957 param.type = ntohs(*(short *)(buf + 2));
2958 param.id = ntohl(*(int *)(buf + 6));
2959 param.data_length = ntohs(*(short *)(buf + 4)) - 10;
2960 param.data = (param.data_length > 0) ? (char *)(buf + 10) : NULL;
2961 param.response = resp;
2962 param.response_length = l;
2963
2964 run_plugins(PLUGIN_CONTROL, &param);
2965
2966 if (param.send_response)
2967 {
2968 send_packet(controlfd, ntohl(addr->sin_addr.s_addr), ntohs(addr->sin_port), param.response, param.response_length);
2969 log(4, ntohl(addr->sin_addr.s_addr), 0, 0, "Sent Control packet response\n");
2970 }
2971
2972 free(resp);
2973 }
2974
2975 /*
2976 * HACK
2977 * Go through all of the tunnels and do some cleanups
2978 */
2979 void tunnel_clean()
2980 {
2981 int i;
2982
2983 log(1, 0, 0, 0, "Cleaning tunnels array\n");
2984
2985 for (i = 1; i < MAXTUNNEL; i++)
2986 {
2987 if (!tunnel[i].ip
2988 || !*tunnel[i].hostname
2989 || (tunnel[i].state == TUNNELDIE && tunnel[i].die >= time_now))
2990 {
2991 tunnelclear(i);
2992 }
2993 }
2994 }
2995
2996 void tunnelclear(tunnelidt t)
2997 {
2998 if (!t) return;
2999 memset(&tunnel[t], 0, sizeof(tunnel[t]));
3000 tunnel[t].state = TUNNELFREE;
3001 }
3002
3003 tunnelidt new_tunnel()
3004 {
3005 tunnelidt i;
3006 for (i = 1; i < MAXTUNNEL; i++)
3007 {
3008 if (tunnel[i].state == TUNNELFREE)
3009 {
3010 log(4, 0, 0, i, "Assigning tunnel ID %d\n", i);
3011 return i;
3012 }
3013 }
3014 log(0, 0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
3015 return 0;
3016 }
3017