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