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