82242756ffc04262d6026675974b96a801fb5ef9
[l2tpns.git] / l2tpns.c
1 // L2TP Network Server
2 // Adrian Kennard 2002
3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
5 // vim: sw=8 ts=8
6
7 char const *cvs_id_l2tpns = "$Id: l2tpns.c,v 1.176 2011/01/20 12:48:40 bodea Exp $";
8
9 #include <arpa/inet.h>
10 #include <assert.h>
11 #include <errno.h>
12 #include <fcntl.h>
13 #include <linux/if_tun.h>
14 #define SYSLOG_NAMES
15 #include <syslog.h>
16 #include <malloc.h>
17 #include <math.h>
18 #include <net/route.h>
19 #include <sys/mman.h>
20 #include <netdb.h>
21 #include <netinet/in.h>
22 #include <netinet/ip6.h>
23 #include <stdarg.h>
24 #include <stdlib.h>
25 #include <stdio.h>
26 #include <string.h>
27 #include <ctype.h>
28 #include <sys/ioctl.h>
29 #include <sys/socket.h>
30 #include <sys/stat.h>
31 #include <sys/time.h>
32 #include <sys/resource.h>
33 #include <sys/wait.h>
34 #include <linux/if.h>
35 #include <stddef.h>
36 #include <time.h>
37 #include <dlfcn.h>
38 #include <unistd.h>
39 #include <sched.h>
40 #include <sys/sysinfo.h>
41 #include <libcli.h>
42 #include <linux/netlink.h>
43 #include <linux/rtnetlink.h>
44
45 #include "md5.h"
46 #include "l2tpns.h"
47 #include "cluster.h"
48 #include "plugin.h"
49 #include "ll.h"
50 #include "constants.h"
51 #include "control.h"
52 #include "util.h"
53 #include "tbf.h"
54
55 #ifdef BGP
56 #include "bgp.h"
57 #endif
58
59 // Globals
60 configt *config = NULL; // all configuration
61 int nlfd = -1; // netlink socket
62 int tunfd = -1; // tun interface file handle. (network device)
63 int udpfd = -1; // UDP file handle
64 int controlfd = -1; // Control signal handle
65 int clifd = -1; // Socket listening for CLI connections.
66 int daefd = -1; // Socket listening for DAE connections.
67 int snoopfd = -1; // UDP file handle for sending out intercept data
68 int *radfds = NULL; // RADIUS requests file handles
69 int rand_fd = -1; // Random data source
70 int cluster_sockfd = -1; // Intra-cluster communications socket.
71 int epollfd = -1; // event polling
72 time_t basetime = 0; // base clock
73 char hostname[1000] = ""; // us.
74 static int tunidx; // ifr_ifindex of tun device
75 int nlseqnum = 0; // netlink sequence number
76 int min_initok_nlseqnum = 0; // minimun seq number for messages after init is ok
77 static int syslog_log = 0; // are we logging to syslog
78 static FILE *log_stream = 0; // file handle for direct logging (i.e. direct into file, not via syslog).
79 uint32_t last_id = 0; // Unique ID for radius accounting
80 // Guest change
81 char guest_users[10][32]; // Array of guest users
82 int guest_accounts_num = 0; // Number of guest users
83
84 // calculated from config->l2tp_mtu
85 uint16_t MRU = 0; // PPP MRU
86 uint16_t MSS = 0; // TCP MSS
87
88 struct cli_session_actions *cli_session_actions = NULL; // Pending session changes requested by CLI
89 struct cli_tunnel_actions *cli_tunnel_actions = NULL; // Pending tunnel changes required by CLI
90
91 union iphash {
92 sessionidt sess;
93 union iphash *idx;
94 } ip_hash[256]; // Mapping from IP address to session structures.
95
96 struct ipv6radix {
97 sessionidt sess;
98 struct ipv6radix *branch;
99 } ipv6_hash[256]; // Mapping from IPv6 address to session structures.
100
101 // Traffic counters.
102 static uint32_t udp_rx = 0, udp_rx_pkt = 0, udp_tx = 0;
103 static uint32_t eth_rx = 0, eth_rx_pkt = 0;
104 uint32_t eth_tx = 0;
105
106 static uint32_t ip_pool_size = 1; // Size of the pool of addresses used for dynamic address allocation.
107 time_t time_now = 0; // Current time in seconds since epoch.
108 static char time_now_string[64] = {0}; // Current time as a string.
109 static int time_changed = 0; // time_now changed
110 char main_quit = 0; // True if we're in the process of exiting.
111 static char main_reload = 0; // Re-load pending
112 linked_list *loaded_plugins;
113 linked_list *plugins[MAX_PLUGIN_TYPES];
114
115 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
116 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
117
118 config_descriptt config_values[] = {
119 CONFIG("debug", debug, INT),
120 CONFIG("log_file", log_filename, STRING),
121 CONFIG("pid_file", pid_file, STRING),
122 CONFIG("random_device", random_device, STRING),
123 CONFIG("l2tp_secret", l2tp_secret, STRING),
124 CONFIG("l2tp_mtu", l2tp_mtu, INT),
125 CONFIG("ppp_restart_time", ppp_restart_time, INT),
126 CONFIG("ppp_max_configure", ppp_max_configure, INT),
127 CONFIG("ppp_max_failure", ppp_max_failure, INT),
128 CONFIG("primary_dns", default_dns1, IPv4),
129 CONFIG("secondary_dns", default_dns2, IPv4),
130 CONFIG("primary_radius", radiusserver[0], IPv4),
131 CONFIG("secondary_radius", radiusserver[1], IPv4),
132 CONFIG("primary_radius_port", radiusport[0], SHORT),
133 CONFIG("secondary_radius_port", radiusport[1], SHORT),
134 CONFIG("radius_accounting", radius_accounting, BOOL),
135 CONFIG("radius_interim", radius_interim, INT),
136 CONFIG("radius_secret", radiussecret, STRING),
137 CONFIG("radius_authtypes", radius_authtypes_s, STRING),
138 CONFIG("radius_dae_port", radius_dae_port, SHORT),
139 CONFIG("radius_bind_min", radius_bind_min, SHORT),
140 CONFIG("radius_bind_max", radius_bind_max, SHORT),
141 CONFIG("allow_duplicate_users", allow_duplicate_users, BOOL),
142 CONFIG("kill_timedout_sessions", kill_timedout_sessions, BOOL),
143 CONFIG("guest_account", guest_user, STRING),
144 CONFIG("bind_address", bind_address, IPv4),
145 CONFIG("peer_address", peer_address, IPv4),
146 CONFIG("send_garp", send_garp, BOOL),
147 CONFIG("throttle_speed", rl_rate, UNSIGNED_LONG),
148 CONFIG("throttle_buckets", num_tbfs, INT),
149 CONFIG("accounting_dir", accounting_dir, STRING),
150 CONFIG("dump_speed", dump_speed, BOOL),
151 CONFIG("multi_read_count", multi_read_count, INT),
152 CONFIG("scheduler_fifo", scheduler_fifo, BOOL),
153 CONFIG("lock_pages", lock_pages, BOOL),
154 CONFIG("icmp_rate", icmp_rate, INT),
155 CONFIG("packet_limit", max_packets, INT),
156 CONFIG("cluster_address", cluster_address, IPv4),
157 CONFIG("cluster_interface", cluster_interface, STRING),
158 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl, INT),
159 CONFIG("cluster_hb_interval", cluster_hb_interval, INT),
160 CONFIG("cluster_hb_timeout", cluster_hb_timeout, INT),
161 CONFIG("cluster_master_min_adv", cluster_master_min_adv, INT),
162 CONFIG("ipv6_prefix", ipv6_prefix, IPv6),
163 { NULL, 0, 0, 0 },
164 };
165
166 static char *plugin_functions[] = {
167 NULL,
168 "plugin_pre_auth",
169 "plugin_post_auth",
170 "plugin_packet_rx",
171 "plugin_packet_tx",
172 "plugin_timer",
173 "plugin_new_session",
174 "plugin_kill_session",
175 "plugin_control",
176 "plugin_radius_response",
177 "plugin_radius_reset",
178 "plugin_radius_account",
179 "plugin_become_master",
180 "plugin_new_session_master",
181 };
182
183 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
184
185 // Counters for shutdown sessions
186 static sessiont shut_acct[8192];
187 static sessionidt shut_acct_n = 0;
188
189 tunnelt *tunnel = NULL; // Array of tunnel structures.
190 bundlet *bundle = NULL; // Array of bundle structures.
191 fragmentationt *frag = NULL; // Array of fragmentation structures.
192 sessiont *session = NULL; // Array of session structures.
193 sessionlocalt *sess_local = NULL; // Array of local per-session counters.
194 radiust *radius = NULL; // Array of radius structures.
195 ippoolt *ip_address_pool = NULL; // Array of dynamic IP addresses.
196 ip_filtert *ip_filters = NULL; // Array of named filters.
197 static controlt *controlfree = 0;
198 struct Tstats *_statistics = NULL;
199 #ifdef RINGBUFFER
200 struct Tringbuffer *ringbuffer = NULL;
201 #endif
202
203 static void cache_ipmap(in_addr_t ip, sessionidt s);
204 static void uncache_ipmap(in_addr_t ip);
205 static void cache_ipv6map(struct in6_addr ip, int prefixlen, sessionidt s);
206 static void free_ip_address(sessionidt s);
207 static void dump_acct_info(int all);
208 static void sighup_handler(int sig);
209 static void shutdown_handler(int sig);
210 static void sigchild_handler(int sig);
211 static void build_chap_response(uint8_t *challenge, uint8_t id, uint16_t challenge_length, uint8_t **challenge_response);
212 static void update_config(void);
213 static void read_config_file(void);
214 static void initplugins(void);
215 static int add_plugin(char *plugin_name);
216 static int remove_plugin(char *plugin_name);
217 static void plugins_done(void);
218 static void processcontrol(uint8_t *buf, int len, struct sockaddr_in *addr, int alen, struct in_addr *local);
219 static tunnelidt new_tunnel(void);
220 static void unhide_value(uint8_t *value, size_t len, uint16_t type, uint8_t *vector, size_t vec_len);
221 static void bundleclear(bundleidt b);
222
223 // on slaves, alow BGP to withdraw cleanly before exiting
224 #define QUIT_DELAY 5
225
226 // quit actions (master)
227 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
228 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
229
230 // return internal time (10ths since process startup), set f if given
231 // as a side-effect sets time_now, and time_changed
232 static clockt now(double *f)
233 {
234 struct timeval t;
235 gettimeofday(&t, 0);
236 if (f) *f = t.tv_sec + t.tv_usec / 1000000.0;
237 if (t.tv_sec != time_now)
238 {
239 time_now = t.tv_sec;
240 time_changed++;
241 }
242 return (t.tv_sec - basetime) * 10 + t.tv_usec / 100000 + 1;
243 }
244
245 // work out a retry time based on try number
246 // This is a straight bounded exponential backoff.
247 // Maximum re-try time is 32 seconds. (2^5).
248 clockt backoff(uint8_t try)
249 {
250 if (try > 5) try = 5; // max backoff
251 return now(NULL) + 10 * (1 << try);
252 }
253
254
255 //
256 // Log a debug message. Typically called via the LOG macro
257 //
258 void _log(int level, sessionidt s, tunnelidt t, const char *format, ...)
259 {
260 static char message[65536] = {0};
261 va_list ap;
262
263 #ifdef RINGBUFFER
264 if (ringbuffer)
265 {
266 if (++ringbuffer->tail >= RINGBUFFER_SIZE)
267 ringbuffer->tail = 0;
268 if (ringbuffer->tail == ringbuffer->head)
269 if (++ringbuffer->head >= RINGBUFFER_SIZE)
270 ringbuffer->head = 0;
271
272 ringbuffer->buffer[ringbuffer->tail].level = level;
273 ringbuffer->buffer[ringbuffer->tail].session = s;
274 ringbuffer->buffer[ringbuffer->tail].tunnel = t;
275 va_start(ap, format);
276 vsnprintf(ringbuffer->buffer[ringbuffer->tail].message, 4095, format, ap);
277 va_end(ap);
278 }
279 #endif
280
281 if (config->debug < level) return;
282
283 va_start(ap, format);
284 vsnprintf(message, sizeof(message), format, ap);
285
286 if (log_stream)
287 fprintf(log_stream, "%s %02d/%02d %s", time_now_string, t, s, message);
288 else if (syslog_log)
289 syslog(level + 2, "%02d/%02d %s", t, s, message); // We don't need LOG_EMERG or LOG_ALERT
290
291 va_end(ap);
292 }
293
294 void _log_hex(int level, const char *title, const uint8_t *data, int maxsize)
295 {
296 int i, j;
297 const uint8_t *d = data;
298
299 if (config->debug < level) return;
300
301 // No support for _log_hex to syslog
302 if (log_stream)
303 {
304 _log(level, 0, 0, "%s (%d bytes):\n", title, maxsize);
305 setvbuf(log_stream, NULL, _IOFBF, 16384);
306
307 for (i = 0; i < maxsize; )
308 {
309 fprintf(log_stream, "%4X: ", i);
310 for (j = i; j < maxsize && j < (i + 16); j++)
311 {
312 fprintf(log_stream, "%02X ", d[j]);
313 if (j == i + 7)
314 fputs(": ", log_stream);
315 }
316
317 for (; j < i + 16; j++)
318 {
319 fputs(" ", log_stream);
320 if (j == i + 7)
321 fputs(": ", log_stream);
322 }
323
324 fputs(" ", log_stream);
325 for (j = i; j < maxsize && j < (i + 16); j++)
326 {
327 if (d[j] >= 0x20 && d[j] < 0x7f && d[j] != 0x20)
328 fputc(d[j], log_stream);
329 else
330 fputc('.', log_stream);
331
332 if (j == i + 7)
333 fputs(" ", log_stream);
334 }
335
336 i = j;
337 fputs("\n", log_stream);
338 }
339
340 fflush(log_stream);
341 setbuf(log_stream, NULL);
342 }
343 }
344
345 // update a counter, accumulating 2^32 wraps
346 void increment_counter(uint32_t *counter, uint32_t *wrap, uint32_t delta)
347 {
348 uint32_t new = *counter + delta;
349 if (new < *counter)
350 (*wrap)++;
351
352 *counter = new;
353 }
354
355 // initialise the random generator
356 static void initrandom(char *source)
357 {
358 static char path[sizeof(config->random_device)] = "*undefined*";
359
360 // reinitialise only if we are forced to do so or if the config has changed
361 if (source && !strncmp(path, source, sizeof(path)))
362 return;
363
364 // close previous source, if any
365 if (rand_fd >= 0)
366 close(rand_fd);
367
368 rand_fd = -1;
369
370 if (source)
371 {
372 // register changes
373 snprintf(path, sizeof(path), "%s", source);
374
375 if (*path == '/')
376 {
377 rand_fd = open(path, O_RDONLY|O_NONBLOCK);
378 if (rand_fd < 0)
379 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
380 path, strerror(errno));
381 }
382 }
383 }
384
385 // fill buffer with random data
386 void random_data(uint8_t *buf, int len)
387 {
388 int n = 0;
389
390 CSTAT(random_data);
391 if (rand_fd >= 0)
392 {
393 n = read(rand_fd, buf, len);
394 if (n >= len) return;
395 if (n < 0)
396 {
397 if (errno != EAGAIN)
398 {
399 LOG(0, 0, 0, "Error reading from random source: %s\n",
400 strerror(errno));
401
402 // fall back to rand()
403 initrandom(NULL);
404 }
405
406 n = 0;
407 }
408 }
409
410 // append missing data
411 while (n < len)
412 // not using the low order bits from the prng stream
413 buf[n++] = (rand() >> 4) & 0xff;
414 }
415
416 // Add a route
417 //
418 // This adds it to the routing table, advertises it
419 // via BGP if enabled, and stuffs it into the
420 // 'sessionbyip' cache.
421 //
422 // 'ip' and 'mask' must be in _host_ order.
423 //
424 static void routeset(sessionidt s, in_addr_t ip, in_addr_t mask, in_addr_t gw, int add)
425 {
426 struct rtentry r;
427 int i;
428
429 if (!mask) mask = 0xffffffff;
430
431 ip &= mask; // Force the ip to be the first one in the route.
432
433 memset(&r, 0, sizeof(r));
434 r.rt_dev = config->tundevice;
435 r.rt_dst.sa_family = AF_INET;
436 *(uint32_t *) & (((struct sockaddr_in *) &r.rt_dst)->sin_addr.s_addr) = htonl(ip);
437 r.rt_gateway.sa_family = AF_INET;
438 *(uint32_t *) & (((struct sockaddr_in *) &r.rt_gateway)->sin_addr.s_addr) = htonl(gw);
439 r.rt_genmask.sa_family = AF_INET;
440 *(uint32_t *) & (((struct sockaddr_in *) &r.rt_genmask)->sin_addr.s_addr) = htonl(mask);
441 r.rt_flags = (RTF_UP | RTF_STATIC);
442 if (gw)
443 r.rt_flags |= RTF_GATEWAY;
444 else if (mask == 0xffffffff)
445 r.rt_flags |= RTF_HOST;
446
447 LOG(1, s, 0, "Route %s %s/%s%s%s\n", add ? "add" : "del",
448 fmtaddr(htonl(ip), 0), fmtaddr(htonl(mask), 1),
449 gw ? " via" : "", gw ? fmtaddr(htonl(gw), 2) : "");
450
451 if (ioctl(ifrfd, add ? SIOCADDRT : SIOCDELRT, (void *) &r) < 0)
452 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno));
453
454 #ifdef BGP
455 if (add)
456 bgp_add_route(htonl(ip), htonl(mask));
457 else
458 bgp_del_route(htonl(ip), htonl(mask));
459 #endif /* BGP */
460
461 // Add/Remove the IPs to the 'sessionbyip' cache.
462 // Note that we add the zero address in the case of
463 // a network route. Roll on CIDR.
464
465 // Note that 's == 0' implies this is the address pool.
466 // We still cache it here, because it will pre-fill
467 // the malloc'ed tree.
468
469 if (s)
470 {
471 if (!add) // Are we deleting a route?
472 s = 0; // Caching the session as '0' is the same as uncaching.
473
474 for (i = ip; (i&mask) == (ip&mask) ; ++i)
475 cache_ipmap(i, s);
476 }
477 }
478
479 void route6set(sessionidt s, struct in6_addr ip, int prefixlen, int add)
480 {
481 struct in6_rtmsg rt;
482 char ipv6addr[INET6_ADDRSTRLEN];
483
484 if (ifr6fd < 0)
485 {
486 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
487 return;
488 }
489
490 memset(&rt, 0, sizeof(rt));
491
492 memcpy(&rt.rtmsg_dst, &ip, sizeof(struct in6_addr));
493 rt.rtmsg_dst_len = prefixlen;
494 rt.rtmsg_metric = 1;
495 rt.rtmsg_flags = RTF_UP;
496 rt.rtmsg_ifindex = tunidx;
497
498 LOG(1, 0, 0, "Route %s %s/%d\n",
499 add ? "add" : "del",
500 inet_ntop(AF_INET6, &ip, ipv6addr, INET6_ADDRSTRLEN),
501 prefixlen);
502
503 if (ioctl(ifr6fd, add ? SIOCADDRT : SIOCDELRT, (void *) &rt) < 0)
504 LOG(0, 0, 0, "route6set() error in ioctl: %s\n",
505 strerror(errno));
506
507 // FIXME: need to add BGP routing (RFC2858)
508
509 if (s)
510 {
511 if (!add) // Are we deleting a route?
512 s = 0; // Caching the session as '0' is the same as uncaching.
513
514 cache_ipv6map(ip, prefixlen, s);
515 }
516
517 return;
518 }
519
520 //
521 // Set up netlink socket
522 static void initnetlink(void)
523 {
524 struct sockaddr_nl nladdr;
525
526 nlfd = socket(AF_NETLINK, SOCK_RAW, NETLINK_ROUTE);
527 if (nlfd < 0)
528 {
529 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno));
530 exit(1);
531 }
532
533 memset(&nladdr, 0, sizeof(nladdr));
534 nladdr.nl_family = AF_NETLINK;
535 nladdr.nl_pid = getpid();
536
537 if (bind(nlfd, (struct sockaddr *)&nladdr, sizeof(nladdr)) < 0)
538 {
539 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno));
540 exit(1);
541 }
542 }
543
544 static ssize_t netlink_send(struct nlmsghdr *nh)
545 {
546 struct sockaddr_nl nladdr;
547 struct iovec iov;
548 struct msghdr msg;
549
550 nh->nlmsg_pid = getpid();
551 nh->nlmsg_seq = ++nlseqnum;
552
553 // set kernel address
554 memset(&nladdr, 0, sizeof(nladdr));
555 nladdr.nl_family = AF_NETLINK;
556
557 iov = (struct iovec){ (void *)nh, nh->nlmsg_len };
558 msg = (struct msghdr){ (void *)&nladdr, sizeof(nladdr), &iov, 1, NULL, 0, 0 };
559
560 return sendmsg(nlfd, &msg, 0);
561 }
562
563 static ssize_t netlink_recv(void *buf, ssize_t len)
564 {
565 struct sockaddr_nl nladdr;
566 struct iovec iov;
567 struct msghdr msg;
568
569 // set kernel address
570 memset(&nladdr, 0, sizeof(nladdr));
571 nladdr.nl_family = AF_NETLINK;
572
573 iov = (struct iovec){ buf, len };
574 msg = (struct msghdr){ (void *)&nladdr, sizeof(nladdr), &iov, 1, NULL, 0, 0 };
575
576 return recvmsg(nlfd, &msg, 0);
577 }
578
579 // messages corresponding to different phases seq number
580 static char *tun_nl_phase_msg[] = {
581 "initialized",
582 "getting tun interface index",
583 "setting tun interface parameters",
584 "setting tun IPv4 address",
585 "setting tun LL IPv6 address",
586 "setting tun global IPv6 address",
587 };
588
589 //
590 // Set up TUN interface
591 static void inittun(void)
592 {
593 struct ifinfomsg ifinfo;
594 struct ifreq ifr;
595
596 memset(&ifr, 0, sizeof(ifr));
597 ifr.ifr_flags = IFF_TUN;
598
599 tunfd = open(TUNDEVICE, O_RDWR);
600 if (tunfd < 0)
601 { // fatal
602 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE, strerror(errno));
603 exit(1);
604 }
605 {
606 int flags = fcntl(tunfd, F_GETFL, 0);
607 fcntl(tunfd, F_SETFL, flags | O_NONBLOCK);
608 }
609 if (ioctl(tunfd, TUNSETIFF, (void *) &ifr) < 0)
610 {
611 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno));
612 exit(1);
613 }
614 assert(strlen(ifr.ifr_name) < sizeof(config->tundevice));
615 strncpy(config->tundevice, ifr.ifr_name, sizeof(config->tundevice) - 1);
616
617 {
618 // get the interface index
619 struct {
620 struct nlmsghdr nh;
621 struct ifinfomsg ifinfo __attribute__ ((aligned(NLMSG_ALIGNTO)));
622 struct rtattr ifname_rta __attribute__ ((aligned(RTA_ALIGNTO)));
623 char ifname[IFNAMSIZ];
624 } req;
625 char buf[4096];
626 ssize_t len;
627 struct nlmsghdr *resp_nh;
628
629 req.nh.nlmsg_type = RTM_GETLINK;
630 req.nh.nlmsg_flags = NLM_F_REQUEST;
631
632 req.ifinfo.ifi_family = AF_UNSPEC; // as the man says
633
634 req.ifname_rta.rta_len = RTA_LENGTH(strlen(config->tundevice)+1);
635 req.ifname_rta.rta_type = IFLA_IFNAME;
636 strncpy(req.ifname, config->tundevice, IFNAMSIZ-1);
637
638 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.ifinfo)
639 + req.ifname_rta.rta_len);
640
641 if(netlink_send(&req.nh) < 0 || (len = netlink_recv(buf, sizeof(buf))) < 0)
642 {
643 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno));
644 exit(1);
645 }
646
647 resp_nh = (struct nlmsghdr *)buf;
648 if (!NLMSG_OK (resp_nh, len))
649 {
650 LOG(0, 0, 0, "Malformed answer getting tun ifindex %ld\n", len);
651 exit(1);
652 }
653
654 memcpy(&ifinfo, NLMSG_DATA(resp_nh), sizeof(ifinfo));
655 // got index
656 tunidx = ifinfo.ifi_index;
657 }
658 {
659 struct {
660 // interface setting
661 struct nlmsghdr nh;
662 union {
663 struct ifinfomsg ifinfo;
664 struct ifaddrmsg ifaddr;
665 } ifmsg __attribute__ ((aligned(NLMSG_ALIGNTO)));
666 char rtdata[32]; // 32 should be enough
667 } req;
668 struct {
669 struct rtattr rta;
670 uint32_t u32 __attribute__ ((aligned(RTA_ALIGNTO)));;
671 } u32_attr;
672 struct {
673 struct rtattr rta;
674 struct in_addr addr __attribute__ ((aligned(RTA_ALIGNTO)));;
675 } ipv4_attr;
676 struct {
677 struct rtattr rta;
678 struct in6_addr addr6 __attribute__ ((aligned(RTA_ALIGNTO)));;
679 } ipv6_attr;
680 char *buf_ptr;
681
682 memset(&req, 0, sizeof(req));
683
684 req.nh.nlmsg_type = RTM_SETLINK;
685 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_MULTI;
686
687 req.ifmsg.ifinfo = ifinfo;
688 req.ifmsg.ifinfo.ifi_flags |= IFF_UP; // set interface up
689 req.ifmsg.ifinfo.ifi_change = IFF_UP; // only change this flag
690
691 buf_ptr = NLMSG_DATA(&req.nh) + sizeof(req.ifmsg.ifinfo);
692
693 u32_attr.rta.rta_len = RTA_LENGTH(sizeof(u32_attr.u32));
694 u32_attr.rta.rta_type = IFLA_TXQLEN;
695 /* Bump up the qlen to deal with bursts from the network */
696 u32_attr.u32 = 1000;
697 memcpy(buf_ptr, &u32_attr, sizeof(u32_attr));
698
699 buf_ptr += RTA_ALIGN(u32_attr.rta.rta_len);
700
701 u32_attr.rta.rta_len = RTA_LENGTH(sizeof(u32_attr.u32));
702 u32_attr.rta.rta_type = IFLA_MTU;
703 /* set MTU to modem MRU */
704 u32_attr.u32 = MRU;
705 memcpy(buf_ptr, &u32_attr, sizeof(u32_attr));
706
707 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.ifmsg.ifinfo)
708 + u32_attr.rta.rta_len * 2);
709
710 if (netlink_send(&req.nh) < 0)
711 {
712 LOG(0, 0, 0, "Error setting up tun device interface: %s\n", strerror(errno));
713 exit(1);
714 }
715
716 memset(&req, 0, sizeof(req));
717
718 req.nh.nlmsg_type = RTM_NEWADDR;
719 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_MULTI;
720
721 req.ifmsg.ifaddr.ifa_family = AF_INET;
722 req.ifmsg.ifaddr.ifa_prefixlen = 32;
723 req.ifmsg.ifaddr.ifa_index = ifinfo.ifi_index;
724
725 ipv4_attr.rta.rta_len = RTA_LENGTH(sizeof(ipv4_attr.addr));
726 ipv4_attr.rta.rta_type = IFA_LOCAL;
727 ipv4_attr.addr.s_addr = config->bind_address ?
728 config->bind_address : 0x01010101; // 1.1.1.1
729 memcpy(NLMSG_DATA(&req.nh) + sizeof(req.ifmsg.ifaddr), &ipv4_attr, sizeof(ipv4_attr));
730
731 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.ifmsg.ifaddr)
732 + ipv4_attr.rta.rta_len);
733
734 if (netlink_send(&req.nh) < 0)
735 {
736 LOG(0, 0, 0, "Error setting up tun device IPv4 address: %s\n", strerror(errno));
737 exit(1);
738 }
739
740 // Only setup IPv6 on the tun device if we have a configured prefix
741 if (config->ipv6_prefix.s6_addr[0]) {
742 memset(&req, 0, sizeof(req));
743
744 req.nh.nlmsg_type = RTM_NEWADDR;
745 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_MULTI;
746
747 req.ifmsg.ifaddr.ifa_family = AF_INET6;
748 req.ifmsg.ifaddr.ifa_prefixlen = 64;
749 req.ifmsg.ifaddr.ifa_scope = RT_SCOPE_LINK;
750 req.ifmsg.ifaddr.ifa_index = ifinfo.ifi_index;
751
752 ipv6_attr.rta.rta_len = RTA_LENGTH(sizeof(ipv6_attr.addr6));
753 ipv6_attr.rta.rta_type = IFA_LOCAL;
754 // Link local address is FE80::1
755 memset(&ipv6_attr.addr6, 0, sizeof(ipv6_attr.addr6));
756 ipv6_attr.addr6.s6_addr[0] = 0xFE;
757 ipv6_attr.addr6.s6_addr[1] = 0x80;
758 ipv6_attr.addr6.s6_addr[15] = 1;
759 memcpy(NLMSG_DATA(&req.nh) + sizeof(req.ifmsg.ifaddr), &ipv6_attr, sizeof(ipv6_attr));
760
761 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.ifmsg.ifaddr)
762 + ipv6_attr.rta.rta_len);
763
764 if (netlink_send(&req.nh) < 0)
765 {
766 LOG(0, 0, 0, "Error setting up tun device IPv6 LL address: %s\n", strerror(errno));
767 exit(1);
768 }
769
770 memset(&req, 0, sizeof(req));
771
772 req.nh.nlmsg_type = RTM_NEWADDR;
773 req.nh.nlmsg_flags = NLM_F_REQUEST | NLM_F_CREATE | NLM_F_MULTI;
774
775 req.ifmsg.ifaddr.ifa_family = AF_INET6;
776 req.ifmsg.ifaddr.ifa_prefixlen = 64;
777 req.ifmsg.ifaddr.ifa_scope = RT_SCOPE_UNIVERSE;
778 req.ifmsg.ifaddr.ifa_index = ifinfo.ifi_index;
779
780 ipv6_attr.rta.rta_len = RTA_LENGTH(sizeof(ipv6_attr.addr6));
781 ipv6_attr.rta.rta_type = IFA_LOCAL;
782 // Global address is prefix::1
783 ipv6_attr.addr6 = config->ipv6_prefix;
784 ipv6_attr.addr6.s6_addr[15] = 1;
785 memcpy(NLMSG_DATA(&req.nh) + sizeof(req.ifmsg.ifaddr), &ipv6_attr, sizeof(ipv6_attr));
786
787 req.nh.nlmsg_len = NLMSG_LENGTH(sizeof(req.ifmsg.ifaddr)
788 + ipv6_attr.rta.rta_len);
789
790 if (netlink_send(&req.nh) < 0)
791 {
792 LOG(0, 0, 0, "Error setting up tun device IPv6 global address: %s\n", strerror(errno));
793 exit(1);
794 }
795 }
796
797 memset(&req, 0, sizeof(req));
798
799 req.nh.nlmsg_type = NLMSG_DONE;
800 req.nh.nlmsg_len = NLMSG_LENGTH(0);
801
802 if (netlink_send(&req.nh) < 0)
803 {
804 LOG(0, 0, 0, "Error finishing setting up tun device: %s\n", strerror(errno));
805 exit(1);
806 }
807
808 // if we get an error for seqnum < min_initok_nlseqnum,
809 // we must exit as initialization went wrong
810 if (config->ipv6_prefix.s6_addr[0])
811 min_initok_nlseqnum = 5 + 1; // idx + if + addr + 2*addr6
812 else
813 min_initok_nlseqnum = 3 + 1; // idx + if + addr
814 }
815 }
816
817 // set up UDP ports
818 static void initudp(void)
819 {
820 int on = 1;
821 struct sockaddr_in addr;
822
823 // Tunnel
824 memset(&addr, 0, sizeof(addr));
825 addr.sin_family = AF_INET;
826 addr.sin_port = htons(L2TPPORT);
827 addr.sin_addr.s_addr = config->bind_address;
828 udpfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
829 setsockopt(udpfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
830 {
831 int flags = fcntl(udpfd, F_GETFL, 0);
832 fcntl(udpfd, F_SETFL, flags | O_NONBLOCK);
833 }
834 if (bind(udpfd, (struct sockaddr *) &addr, sizeof(addr)) < 0)
835 {
836 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno));
837 exit(1);
838 }
839
840 // Control
841 memset(&addr, 0, sizeof(addr));
842 addr.sin_family = AF_INET;
843 addr.sin_port = htons(NSCTL_PORT);
844 controlfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
845 setsockopt(controlfd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
846 setsockopt(controlfd, SOL_IP, IP_PKTINFO, &on, sizeof(on)); // recvfromto
847 if (bind(controlfd, (struct sockaddr *) &addr, sizeof(addr)) < 0)
848 {
849 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno));
850 exit(1);
851 }
852
853 // Dynamic Authorization Extensions to RADIUS
854 memset(&addr, 0, sizeof(addr));
855 addr.sin_family = AF_INET;
856 addr.sin_port = htons(config->radius_dae_port);
857 daefd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
858 setsockopt(daefd, SOL_SOCKET, SO_REUSEADDR, &on, sizeof(on));
859 setsockopt(daefd, SOL_IP, IP_PKTINFO, &on, sizeof(on)); // recvfromto
860 if (bind(daefd, (struct sockaddr *) &addr, sizeof(addr)) < 0)
861 {
862 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno));
863 exit(1);
864 }
865
866 // Intercept
867 snoopfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
868 }
869
870 //
871 // Find session by IP, < 1 for not found
872 //
873 // Confusingly enough, this 'ip' must be
874 // in _network_ order. This being the common
875 // case when looking it up from IP packet headers.
876 //
877 // We actually use this cache for two things.
878 // #1. For used IP addresses, this maps to the
879 // session ID that it's used by.
880 // #2. For un-used IP addresses, this maps to the
881 // index into the pool table that contains that
882 // IP address.
883 //
884
885 static sessionidt lookup_ipmap(in_addr_t ip)
886 {
887 uint8_t *a = (uint8_t *) &ip;
888 union iphash *h = ip_hash;
889
890 if (!(h = h[*a++].idx)) return 0;
891 if (!(h = h[*a++].idx)) return 0;
892 if (!(h = h[*a++].idx)) return 0;
893
894 return h[*a].sess;
895 }
896
897 static sessionidt lookup_ipv6map(struct in6_addr ip)
898 {
899 struct ipv6radix *curnode;
900 int i;
901 int s;
902 char ipv6addr[INET6_ADDRSTRLEN];
903
904 curnode = &ipv6_hash[ip.s6_addr[0]];
905 i = 1;
906 s = curnode->sess;
907
908 while (s == 0 && i < 15 && curnode->branch != NULL)
909 {
910 curnode = &curnode->branch[ip.s6_addr[i]];
911 s = curnode->sess;
912 i++;
913 }
914
915 LOG(4, s, session[s].tunnel, "Looking up address %s and got %d\n",
916 inet_ntop(AF_INET6, &ip, ipv6addr,
917 INET6_ADDRSTRLEN),
918 s);
919
920 return s;
921 }
922
923 sessionidt sessionbyip(in_addr_t ip)
924 {
925 sessionidt s = lookup_ipmap(ip);
926 CSTAT(sessionbyip);
927
928 if (s > 0 && s < MAXSESSION && session[s].opened)
929 return s;
930
931 return 0;
932 }
933
934 sessionidt sessionbyipv6(struct in6_addr ip)
935 {
936 sessionidt s;
937 CSTAT(sessionbyipv6);
938
939 if (!memcmp(&config->ipv6_prefix, &ip, 8) ||
940 (ip.s6_addr[0] == 0xFE &&
941 ip.s6_addr[1] == 0x80 &&
942 ip.s6_addr16[1] == 0 &&
943 ip.s6_addr16[2] == 0 &&
944 ip.s6_addr16[3] == 0)) {
945 s = lookup_ipmap(*(in_addr_t *) &ip.s6_addr[8]);
946 } else {
947 s = lookup_ipv6map(ip);
948 }
949
950 if (s > 0 && s < MAXSESSION && session[s].opened)
951 return s;
952
953 return 0;
954 }
955
956 //
957 // Take an IP address in HOST byte order and
958 // add it to the sessionid by IP cache.
959 //
960 // (It's actually cached in network order)
961 //
962 static void cache_ipmap(in_addr_t ip, sessionidt s)
963 {
964 in_addr_t nip = htonl(ip); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
965 uint8_t *a = (uint8_t *) &nip;
966 union iphash *h = ip_hash;
967 int i;
968
969 for (i = 0; i < 3; i++)
970 {
971 if (!(h[a[i]].idx || (h[a[i]].idx = calloc(256, sizeof(union iphash)))))
972 return;
973
974 h = h[a[i]].idx;
975 }
976
977 h[a[3]].sess = s;
978
979 if (s > 0)
980 LOG(4, s, session[s].tunnel, "Caching ip address %s\n", fmtaddr(nip, 0));
981
982 else if (s == 0)
983 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip, 0));
984 // else a map to an ip pool index.
985 }
986
987 static void uncache_ipmap(in_addr_t ip)
988 {
989 cache_ipmap(ip, 0); // Assign it to the NULL session.
990 }
991
992 static void cache_ipv6map(struct in6_addr ip, int prefixlen, sessionidt s)
993 {
994 int i;
995 int bytes;
996 struct ipv6radix *curnode;
997 char ipv6addr[INET6_ADDRSTRLEN];
998
999 curnode = &ipv6_hash[ip.s6_addr[0]];
1000
1001 bytes = prefixlen >> 3;
1002 i = 1;
1003 while (i < bytes) {
1004 if (curnode->branch == NULL)
1005 {
1006 if (!(curnode->branch = calloc(256,
1007 sizeof (struct ipv6radix))))
1008 return;
1009 }
1010 curnode = &curnode->branch[ip.s6_addr[i]];
1011 i++;
1012 }
1013
1014 curnode->sess = s;
1015
1016 if (s > 0)
1017 LOG(4, s, session[s].tunnel, "Caching ip address %s/%d\n",
1018 inet_ntop(AF_INET6, &ip, ipv6addr,
1019 INET6_ADDRSTRLEN),
1020 prefixlen);
1021 else if (s == 0)
1022 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1023 inet_ntop(AF_INET6, &ip, ipv6addr,
1024 INET6_ADDRSTRLEN),
1025 prefixlen);
1026 }
1027
1028 //
1029 // CLI list to dump current ipcache.
1030 //
1031 int cmd_show_ipcache(struct cli_def *cli, char *command, char **argv, int argc)
1032 {
1033 union iphash *d = ip_hash, *e, *f, *g;
1034 int i, j, k, l;
1035 int count = 0;
1036
1037 if (CLI_HELP_REQUESTED)
1038 return CLI_HELP_NO_ARGS;
1039
1040 cli_print(cli, "%7s %s", "Sess#", "IP Address");
1041
1042 for (i = 0; i < 256; ++i)
1043 {
1044 if (!d[i].idx)
1045 continue;
1046
1047 e = d[i].idx;
1048 for (j = 0; j < 256; ++j)
1049 {
1050 if (!e[j].idx)
1051 continue;
1052
1053 f = e[j].idx;
1054 for (k = 0; k < 256; ++k)
1055 {
1056 if (!f[k].idx)
1057 continue;
1058
1059 g = f[k].idx;
1060 for (l = 0; l < 256; ++l)
1061 {
1062 if (!g[l].sess)
1063 continue;
1064
1065 cli_print(cli, "%7d %d.%d.%d.%d", g[l].sess, i, j, k, l);
1066 ++count;
1067 }
1068 }
1069 }
1070 }
1071 cli_print(cli, "%d entries in cache", count);
1072 return CLI_OK;
1073 }
1074
1075
1076 // Find session by username, 0 for not found
1077 // walled garden users aren't authenticated, so the username is
1078 // reasonably useless. Ignore them to avoid incorrect actions
1079 //
1080 // This is VERY inefficent. Don't call it often. :)
1081 //
1082 sessionidt sessionbyuser(char *username)
1083 {
1084 int s;
1085 CSTAT(sessionbyuser);
1086
1087 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
1088 {
1089 if (!session[s].opened)
1090 continue;
1091
1092 if (session[s].walled_garden)
1093 continue; // Skip walled garden users.
1094
1095 if (!strncmp(session[s].user, username, 128))
1096 return s;
1097
1098 }
1099 return 0; // Not found.
1100 }
1101
1102 void send_garp(in_addr_t ip)
1103 {
1104 int s;
1105 struct ifreq ifr;
1106 uint8_t mac[6];
1107
1108 s = socket(PF_INET, SOCK_DGRAM, 0);
1109 if (s < 0)
1110 {
1111 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno));
1112 return;
1113 }
1114 memset(&ifr, 0, sizeof(ifr));
1115 strncpy(ifr.ifr_name, "eth0", sizeof(ifr.ifr_name) - 1);
1116 if (ioctl(s, SIOCGIFHWADDR, &ifr) < 0)
1117 {
1118 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno));
1119 close(s);
1120 return;
1121 }
1122 memcpy(mac, &ifr.ifr_hwaddr.sa_data, 6*sizeof(char));
1123 if (ioctl(s, SIOCGIFINDEX, &ifr) < 0)
1124 {
1125 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno));
1126 close(s);
1127 return;
1128 }
1129 close(s);
1130 sendarp(ifr.ifr_ifindex, mac, ip);
1131 }
1132
1133 static sessiont *sessiontbysessionidt(sessionidt s)
1134 {
1135 if (!s || s >= MAXSESSION) return NULL;
1136 return &session[s];
1137 }
1138
1139 static sessionidt sessionidtbysessiont(sessiont *s)
1140 {
1141 sessionidt val = s-session;
1142 if (s < session || val >= MAXSESSION) return 0;
1143 return val;
1144 }
1145
1146 // actually send a control message for a specific tunnel
1147 void tunnelsend(uint8_t * buf, uint16_t l, tunnelidt t)
1148 {
1149 struct sockaddr_in addr;
1150
1151 CSTAT(tunnelsend);
1152
1153 if (!t)
1154 {
1155 LOG(0, 0, t, "tunnelsend called with 0 as tunnel id\n");
1156 STAT(tunnel_tx_errors);
1157 return;
1158 }
1159
1160 if (!tunnel[t].ip)
1161 {
1162 LOG(1, 0, t, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1163 STAT(tunnel_tx_errors);
1164 return;
1165 }
1166
1167 memset(&addr, 0, sizeof(addr));
1168 addr.sin_family = AF_INET;
1169 *(uint32_t *) & addr.sin_addr = htonl(tunnel[t].ip);
1170 addr.sin_port = htons(tunnel[t].port);
1171
1172 // sequence expected, if sequence in message
1173 if (*buf & 0x08) *(uint16_t *) (buf + ((*buf & 0x40) ? 10 : 8)) = htons(tunnel[t].nr);
1174
1175 // If this is a control message, deal with retries
1176 if (*buf & 0x80)
1177 {
1178 tunnel[t].last = time_now; // control message sent
1179 tunnel[t].retry = backoff(tunnel[t].try); // when to resend
1180 if (tunnel[t].try)
1181 {
1182 STAT(tunnel_retries);
1183 LOG(3, 0, t, "Control message resend try %d\n", tunnel[t].try);
1184 }
1185 }
1186
1187 if (sendto(udpfd, buf, l, 0, (void *) &addr, sizeof(addr)) < 0)
1188 {
1189 LOG(0, ntohs((*(uint16_t *) (buf + 6))), t, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1190 strerror(errno), udpfd, buf, l, inet_ntoa(addr.sin_addr));
1191 STAT(tunnel_tx_errors);
1192 return;
1193 }
1194
1195 LOG_HEX(5, "Send Tunnel Data", buf, l);
1196 STAT(tunnel_tx_packets);
1197 INC_STAT(tunnel_tx_bytes, l);
1198 }
1199
1200 //
1201 // Tiny helper function to write data to
1202 // the 'tun' device.
1203 //
1204 int tun_write(uint8_t * data, int size)
1205 {
1206 return write(tunfd, data, size);
1207 }
1208
1209 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1210 void adjust_tcp_mss(sessionidt s, tunnelidt t, uint8_t *buf, int len, uint8_t *tcp)
1211 {
1212 int d = (tcp[12] >> 4) * 4;
1213 uint8_t *mss = 0;
1214 uint8_t *opts;
1215 uint8_t *data;
1216 uint16_t orig;
1217 uint32_t sum;
1218
1219 if ((tcp[13] & 0x3f) & ~(TCP_FLAG_SYN|TCP_FLAG_ACK)) // only want SYN and SYN,ACK
1220 return;
1221
1222 if (tcp + d > buf + len) // short?
1223 return;
1224
1225 opts = tcp + 20;
1226 data = tcp + d;
1227
1228 while (opts < data)
1229 {
1230 if (*opts == 2 && opts[1] == 4) // mss option (2), length 4
1231 {
1232 mss = opts + 2;
1233 if (mss + 2 > data) return; // short?
1234 break;
1235 }
1236
1237 if (*opts == 0) return; // end of options
1238 if (*opts == 1 || !opts[1]) // no op (one byte), or no length (prevent loop)
1239 opts++;
1240 else
1241 opts += opts[1]; // skip over option
1242 }
1243
1244 if (!mss) return; // not found
1245 orig = ntohs(*(uint16_t *) mss);
1246
1247 if (orig <= MSS) return; // mss OK
1248
1249 LOG(5, s, t, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1250 fmtaddr(*(in_addr_t *) (buf + 12), 0), ntohs(*(uint16_t *) tcp),
1251 fmtaddr(*(in_addr_t *) (buf + 16), 1), ntohs(*(uint16_t *) (tcp + 2)),
1252 (tcp[13] & TCP_FLAG_ACK) ? ",ACK" : "", orig, MSS);
1253
1254 // set mss
1255 *(int16_t *) mss = htons(MSS);
1256
1257 // adjust checksum (see rfc1141)
1258 sum = orig + (~MSS & 0xffff);
1259 sum += ntohs(*(uint16_t *) (tcp + 16));
1260 sum = (sum & 0xffff) + (sum >> 16);
1261 *(uint16_t *) (tcp + 16) = htons(sum + (sum >> 16));
1262 }
1263
1264 void processmpframe(sessionidt s, tunnelidt t, uint8_t *p, uint16_t l, uint8_t extra)
1265 {
1266 uint16_t proto;
1267 if (extra) {
1268 // Skip the four extra bytes
1269 p += 4;
1270 l -= 4;
1271 }
1272
1273 if (*p & 1)
1274 {
1275 proto = *p++;
1276 l--;
1277 }
1278 else
1279 {
1280 proto = ntohs(*(uint16_t *) p);
1281 p += 2;
1282 l -= 2;
1283 }
1284 if (proto == PPPIP)
1285 {
1286 if (session[s].die)
1287 {
1288 LOG(4, s, t, "MPPP: Session %d is closing. Don't process PPP packets\n", s);
1289 return; // closing session, PPP not processed
1290 }
1291 session[s].last_packet = session[s].last_data = time_now;
1292 processipin(s, t, p, l);
1293 }
1294 else if (proto == PPPIPV6 && config->ipv6_prefix.s6_addr[0])
1295 {
1296 if (session[s].die)
1297 {
1298 LOG(4, s, t, "MPPP: Session %d is closing. Don't process PPP packets\n", s);
1299 return; // closing session, PPP not processed
1300 }
1301
1302 session[s].last_packet = session[s].last_data = time_now;
1303 processipv6in(s, t, p, l);
1304 }
1305 else if (proto == PPPIPCP)
1306 {
1307 session[s].last_packet = session[s].last_data = time_now;
1308 processipcp(s, t, p, l);
1309 }
1310 else if (proto == PPPCCP)
1311 {
1312 session[s].last_packet = session[s].last_data = time_now;
1313 processccp(s, t, p, l);
1314 }
1315 else
1316 {
1317 LOG(2, s, t, "MPPP: Unsupported MP protocol 0x%04X received\n",proto);
1318 }
1319 }
1320
1321 static void update_session_out_stat(sessionidt s, sessiont *sp, int len)
1322 {
1323 increment_counter(&sp->cout, &sp->cout_wrap, len); // byte count
1324 sp->cout_delta += len;
1325 sp->pout++;
1326 sp->last_data = time_now;
1327
1328 sess_local[s].cout += len; // To send to master..
1329 sess_local[s].pout++;
1330 }
1331
1332 // process outgoing (to tunnel) IP
1333 //
1334 static void processipout(uint8_t *buf, int len)
1335 {
1336 sessionidt s;
1337 sessiont *sp;
1338 tunnelidt t;
1339 in_addr_t ip;
1340
1341 uint8_t *data = buf; // Keep a copy of the originals.
1342 int size = len;
1343
1344 uint8_t fragbuf[MAXETHER + 20];
1345
1346 CSTAT(processipout);
1347
1348 if (len < MIN_IP_SIZE)
1349 {
1350 LOG(1, 0, 0, "Short IP, %d bytes\n", len);
1351 STAT(tun_rx_errors);
1352 return;
1353 }
1354 if (len >= MAXETHER)
1355 {
1356 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len);
1357 STAT(tun_rx_errors);
1358 return;
1359 }
1360
1361 // Skip the tun header
1362 buf += 4;
1363 len -= 4;
1364
1365 // Got an IP header now
1366 if (*(uint8_t *)(buf) >> 4 != 4)
1367 {
1368 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1369 return;
1370 }
1371
1372 ip = *(uint32_t *)(buf + 16);
1373 if (!(s = sessionbyip(ip)))
1374 {
1375 // Is this a packet for a session that doesn't exist?
1376 static int rate = 0; // Number of ICMP packets we've sent this second.
1377 static int last = 0; // Last time we reset the ICMP packet counter 'rate'.
1378
1379 if (last != time_now)
1380 {
1381 last = time_now;
1382 rate = 0;
1383 }
1384
1385 if (rate++ < config->icmp_rate) // Only send a max of icmp_rate per second.
1386 {
1387 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t *)(buf + 12), 0));
1388 host_unreachable(*(in_addr_t *)(buf + 12), *(uint16_t *)(buf + 4),
1389 config->bind_address ? config->bind_address : my_address, buf, len);
1390 }
1391 return;
1392 }
1393
1394 t = session[s].tunnel;
1395 if (len > session[s].mru || (session[s].mrru && len > session[s].mrru))
1396 {
1397 LOG(3, s, t, "Packet size more than session MRU\n");
1398 return;
1399 }
1400
1401 sp = &session[s];
1402
1403 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1404 if (config->max_packets > 0)
1405 {
1406 if (sess_local[s].last_packet_out == TIME)
1407 {
1408 int max = config->max_packets;
1409
1410 // All packets for throttled sessions are handled by the
1411 // master, so further limit by using the throttle rate.
1412 // A bit of a kludge, since throttle rate is in kbps,
1413 // but should still be generous given our average DSL
1414 // packet size is 200 bytes: a limit of 28kbps equates
1415 // to around 180 packets per second.
1416 if (!config->cluster_iam_master && sp->throttle_out && sp->throttle_out < max)
1417 max = sp->throttle_out;
1418
1419 if (++sess_local[s].packets_out > max)
1420 {
1421 sess_local[s].packets_dropped++;
1422 return;
1423 }
1424 }
1425 else
1426 {
1427 if (sess_local[s].packets_dropped)
1428 {
1429 INC_STAT(tun_rx_dropped, sess_local[s].packets_dropped);
1430 LOG(3, s, t, "Dropped %u/%u packets to %s for %suser %s\n",
1431 sess_local[s].packets_dropped, sess_local[s].packets_out,
1432 fmtaddr(ip, 0), sp->throttle_out ? "throttled " : "",
1433 sp->user);
1434 }
1435
1436 sess_local[s].last_packet_out = TIME;
1437 sess_local[s].packets_out = 1;
1438 sess_local[s].packets_dropped = 0;
1439 }
1440 }
1441
1442 // run access-list if any
1443 if (session[s].filter_out && !ip_filter(buf, len, session[s].filter_out - 1))
1444 return;
1445
1446 // adjust MSS on SYN and SYN,ACK packets with options
1447 if ((ntohs(*(uint16_t *) (buf + 6)) & 0x1fff) == 0 && buf[9] == IPPROTO_TCP) // first tcp fragment
1448 {
1449 int ihl = (buf[0] & 0xf) * 4; // length of IP header
1450 if (len >= ihl + 20 && (buf[ihl + 13] & TCP_FLAG_SYN) && ((buf[ihl + 12] >> 4) > 5))
1451 adjust_tcp_mss(s, t, buf, len, buf + ihl);
1452 }
1453
1454 if (sp->tbf_out)
1455 {
1456 // Are we throttling this session?
1457 if (config->cluster_iam_master)
1458 tbf_queue_packet(sp->tbf_out, data, size);
1459 else
1460 master_throttle_packet(sp->tbf_out, data, size);
1461 return;
1462 }
1463
1464 if (sp->walled_garden && !config->cluster_iam_master)
1465 {
1466 // We are walled-gardening this
1467 master_garden_packet(s, data, size);
1468 return;
1469 }
1470
1471 // Add on L2TP header
1472 {
1473 bundleidt bid = 0;
1474 if(session[s].bundle != 0 && bundle[session[s].bundle].num_of_links > 1)
1475 {
1476 bid = session[s].bundle;
1477 s = bundle[bid].members[bundle[bid].current_ses = ++bundle[bid].current_ses % bundle[bid].num_of_links];
1478 t = session[s].tunnel;
1479 sp = &session[s];
1480 LOG(4, s, t, "MPPP: (1)Session number becomes: %d\n", s);
1481 if(len > MINFRAGLEN)
1482 {
1483 // Partition the packet to "bundle[b].num_of_links" fragments
1484 bundlet *b = &bundle[bid];
1485 uint32_t num_of_links = b->num_of_links;
1486 uint32_t fraglen = len / num_of_links;
1487 fraglen = (fraglen > session[s].mru ? session[s].mru : fraglen);
1488 uint32_t last_fraglen = fraglen + len % num_of_links;
1489 last_fraglen = (last_fraglen > session[s].mru ? len % num_of_links : last_fraglen);
1490 uint32_t remain = len;
1491
1492 // send the first packet
1493 uint8_t *p = makeppp(fragbuf, sizeof(fragbuf), buf, fraglen, s, t, PPPIP, 0, bid, MP_BEGIN);
1494 if (!p) return;
1495 tunnelsend(fragbuf, fraglen + (p-fragbuf), t); // send it...
1496 // statistics
1497 update_session_out_stat(s, sp, fraglen);
1498 remain -= fraglen;
1499 while (remain > last_fraglen)
1500 {
1501 s = b->members[b->current_ses = ++b->current_ses % num_of_links];
1502 t = session[s].tunnel;
1503 sp = &session[s];
1504 LOG(4, s, t, "MPPP: (2)Session number becomes: %d\n", s);
1505 p = makeppp(fragbuf, sizeof(fragbuf), buf+(len - remain), fraglen, s, t, PPPIP, 0, bid, 0);
1506 if (!p) return;
1507 tunnelsend(fragbuf, fraglen + (p-fragbuf), t); // send it...
1508 update_session_out_stat(s, sp, fraglen);
1509 remain -= fraglen;
1510 }
1511 // send the last fragment
1512 s = b->members[b->current_ses = ++b->current_ses % num_of_links];
1513 t = session[s].tunnel;
1514 sp = &session[s];
1515 LOG(4, s, t, "MPPP: (2)Session number becomes: %d\n", s);
1516 p = makeppp(fragbuf, sizeof(fragbuf), buf+(len - remain), remain, s, t, PPPIP, 0, bid, MP_END);
1517 if (!p) return;
1518 tunnelsend(fragbuf, remain + (p-fragbuf), t); // send it...
1519 update_session_out_stat(s, sp, remain);
1520 if (remain != last_fraglen)
1521 LOG(3, s, t, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain, last_fraglen);
1522 }
1523 else {
1524 // Send it as one frame
1525 uint8_t *p = makeppp(fragbuf, sizeof(fragbuf), buf, len, s, t, PPPIP, 0, bid, MP_BOTH_BITS);
1526 if (!p) return;
1527 tunnelsend(fragbuf, len + (p-fragbuf), t); // send it...
1528 LOG(4, s, t, "MPPP: packet sent as one frame\n");
1529 update_session_out_stat(s, sp, len);
1530 }
1531 }
1532 else
1533 {
1534 uint8_t *p = makeppp(fragbuf, sizeof(fragbuf), buf, len, s, t, PPPIP, 0, 0, 0);
1535 if (!p) return;
1536 tunnelsend(fragbuf, len + (p-fragbuf), t); // send it...
1537 update_session_out_stat(s, sp, len);
1538 }
1539 }
1540
1541 // Snooping this session, send it to intercept box
1542 if (sp->snoop_ip && sp->snoop_port)
1543 snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port);
1544
1545 udp_tx += len;
1546 }
1547
1548 // process outgoing (to tunnel) IPv6
1549 //
1550 static void processipv6out(uint8_t * buf, int len)
1551 {
1552 sessionidt s;
1553 sessiont *sp;
1554 tunnelidt t;
1555 in_addr_t ip;
1556 struct in6_addr ip6;
1557
1558 uint8_t *data = buf; // Keep a copy of the originals.
1559 int size = len;
1560
1561 uint8_t b[MAXETHER + 20];
1562
1563 CSTAT(processipv6out);
1564
1565 if (len < MIN_IP_SIZE)
1566 {
1567 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len);
1568 STAT(tunnel_tx_errors);
1569 return;
1570 }
1571 if (len >= MAXETHER)
1572 {
1573 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len);
1574 STAT(tunnel_tx_errors);
1575 return;
1576 }
1577
1578 // Skip the tun header
1579 buf += 4;
1580 len -= 4;
1581
1582 // Got an IP header now
1583 if (*(uint8_t *)(buf) >> 4 != 6)
1584 {
1585 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1586 return;
1587 }
1588
1589 ip6 = *(struct in6_addr *)(buf+24);
1590 s = sessionbyipv6(ip6);
1591
1592 if (s == 0)
1593 {
1594 ip = *(uint32_t *)(buf + 32);
1595 s = sessionbyip(ip);
1596 }
1597
1598 if (s == 0)
1599 {
1600 // Is this a packet for a session that doesn't exist?
1601 static int rate = 0; // Number of ICMP packets we've sent this second.
1602 static int last = 0; // Last time we reset the ICMP packet counter 'rate'.
1603
1604 if (last != time_now)
1605 {
1606 last = time_now;
1607 rate = 0;
1608 }
1609
1610 if (rate++ < config->icmp_rate) // Only send a max of icmp_rate per second.
1611 {
1612 // FIXME: Should send icmp6 host unreachable
1613 }
1614 return;
1615 }
1616 if (session[s].bundle && bundle[session[s].bundle].num_of_links > 1)
1617 {
1618 bundleidt bid = session[s].bundle;
1619 s = bundle[bid].members[bundle[bid].current_ses = ++bundle[bid].current_ses % bundle[bid].num_of_links];
1620 LOG(3, s, session[s].tunnel, "MPPP: Session number becomes: %u\n", s);
1621 }
1622 t = session[s].tunnel;
1623 sp = &session[s];
1624 sp->last_data = time_now;
1625
1626 // FIXME: add DoS prevention/filters?
1627
1628 if (sp->tbf_out)
1629 {
1630 // Are we throttling this session?
1631 if (config->cluster_iam_master)
1632 tbf_queue_packet(sp->tbf_out, data, size);
1633 else
1634 master_throttle_packet(sp->tbf_out, data, size);
1635 return;
1636 }
1637 else if (sp->walled_garden && !config->cluster_iam_master)
1638 {
1639 // We are walled-gardening this
1640 master_garden_packet(s, data, size);
1641 return;
1642 }
1643
1644 LOG(5, s, t, "Ethernet -> Tunnel (%d bytes)\n", len);
1645
1646 // Add on L2TP header
1647 {
1648 uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIPV6, 0, 0, 0);
1649 if (!p) return;
1650 tunnelsend(b, len + (p-b), t); // send it...
1651 }
1652
1653 // Snooping this session, send it to intercept box
1654 if (sp->snoop_ip && sp->snoop_port)
1655 snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port);
1656
1657 increment_counter(&sp->cout, &sp->cout_wrap, len); // byte count
1658 sp->cout_delta += len;
1659 sp->pout++;
1660 udp_tx += len;
1661
1662 sess_local[s].cout += len; // To send to master..
1663 sess_local[s].pout++;
1664 }
1665
1666 //
1667 // Helper routine for the TBF filters.
1668 // Used to send queued data in to the user!
1669 //
1670 static void send_ipout(sessionidt s, uint8_t *buf, int len)
1671 {
1672 sessiont *sp;
1673 tunnelidt t;
1674 in_addr_t ip;
1675
1676 uint8_t b[MAXETHER + 20];
1677
1678 if (len < 0 || len > MAXETHER)
1679 {
1680 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len);
1681 return;
1682 }
1683
1684 // Skip the tun header
1685 buf += 4;
1686 len -= 4;
1687
1688 ip = *(in_addr_t *)(buf + 16);
1689
1690 if (!session[s].ip)
1691 return;
1692
1693 t = session[s].tunnel;
1694 sp = &session[s];
1695
1696 LOG(5, s, t, "Ethernet -> Tunnel (%d bytes)\n", len);
1697
1698 // Add on L2TP header
1699 {
1700 uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIP, 0, 0, 0);
1701 if (!p) return;
1702 tunnelsend(b, len + (p-b), t); // send it...
1703 }
1704
1705 // Snooping this session.
1706 if (sp->snoop_ip && sp->snoop_port)
1707 snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port);
1708
1709 increment_counter(&sp->cout, &sp->cout_wrap, len); // byte count
1710 sp->cout_delta += len;
1711 sp->pout++;
1712 udp_tx += len;
1713
1714 sess_local[s].cout += len; // To send to master..
1715 sess_local[s].pout++;
1716 }
1717
1718 // add an AVP (16 bit)
1719 static void control16(controlt * c, uint16_t avp, uint16_t val, uint8_t m)
1720 {
1721 uint16_t l = (m ? 0x8008 : 0x0008);
1722 *(uint16_t *) (c->buf + c->length + 0) = htons(l);
1723 *(uint16_t *) (c->buf + c->length + 2) = htons(0);
1724 *(uint16_t *) (c->buf + c->length + 4) = htons(avp);
1725 *(uint16_t *) (c->buf + c->length + 6) = htons(val);
1726 c->length += 8;
1727 }
1728
1729 // add an AVP (32 bit)
1730 static void control32(controlt * c, uint16_t avp, uint32_t val, uint8_t m)
1731 {
1732 uint16_t l = (m ? 0x800A : 0x000A);
1733 *(uint16_t *) (c->buf + c->length + 0) = htons(l);
1734 *(uint16_t *) (c->buf + c->length + 2) = htons(0);
1735 *(uint16_t *) (c->buf + c->length + 4) = htons(avp);
1736 *(uint32_t *) (c->buf + c->length + 6) = htonl(val);
1737 c->length += 10;
1738 }
1739
1740 // add an AVP (string)
1741 static void controls(controlt * c, uint16_t avp, char *val, uint8_t m)
1742 {
1743 uint16_t l = ((m ? 0x8000 : 0) + strlen(val) + 6);
1744 *(uint16_t *) (c->buf + c->length + 0) = htons(l);
1745 *(uint16_t *) (c->buf + c->length + 2) = htons(0);
1746 *(uint16_t *) (c->buf + c->length + 4) = htons(avp);
1747 memcpy(c->buf + c->length + 6, val, strlen(val));
1748 c->length += 6 + strlen(val);
1749 }
1750
1751 // add a binary AVP
1752 static void controlb(controlt * c, uint16_t avp, uint8_t *val, unsigned int len, uint8_t m)
1753 {
1754 uint16_t l = ((m ? 0x8000 : 0) + len + 6);
1755 *(uint16_t *) (c->buf + c->length + 0) = htons(l);
1756 *(uint16_t *) (c->buf + c->length + 2) = htons(0);
1757 *(uint16_t *) (c->buf + c->length + 4) = htons(avp);
1758 memcpy(c->buf + c->length + 6, val, len);
1759 c->length += 6 + len;
1760 }
1761
1762 // new control connection
1763 static controlt *controlnew(uint16_t mtype)
1764 {
1765 controlt *c;
1766 if (!controlfree)
1767 c = malloc(sizeof(controlt));
1768 else
1769 {
1770 c = controlfree;
1771 controlfree = c->next;
1772 }
1773 assert(c);
1774 c->next = 0;
1775 *(uint16_t *) (c->buf + 0) = htons(0xC802); // flags/ver
1776 c->length = 12;
1777 control16(c, 0, mtype, 1);
1778 return c;
1779 }
1780
1781 // send zero block if nothing is waiting
1782 // (ZLB send).
1783 static void controlnull(tunnelidt t)
1784 {
1785 uint8_t buf[12];
1786 if (tunnel[t].controlc) // Messages queued; They will carry the ack.
1787 return;
1788
1789 *(uint16_t *) (buf + 0) = htons(0xC802); // flags/ver
1790 *(uint16_t *) (buf + 2) = htons(12); // length
1791 *(uint16_t *) (buf + 4) = htons(tunnel[t].far); // tunnel
1792 *(uint16_t *) (buf + 6) = htons(0); // session
1793 *(uint16_t *) (buf + 8) = htons(tunnel[t].ns); // sequence
1794 *(uint16_t *) (buf + 10) = htons(tunnel[t].nr); // sequence
1795 tunnelsend(buf, 12, t);
1796 }
1797
1798 // add a control message to a tunnel, and send if within window
1799 static void controladd(controlt *c, sessionidt far, tunnelidt t)
1800 {
1801 *(uint16_t *) (c->buf + 2) = htons(c->length); // length
1802 *(uint16_t *) (c->buf + 4) = htons(tunnel[t].far); // tunnel
1803 *(uint16_t *) (c->buf + 6) = htons(far); // session
1804 *(uint16_t *) (c->buf + 8) = htons(tunnel[t].ns); // sequence
1805 tunnel[t].ns++; // advance sequence
1806 // link in message in to queue
1807 if (tunnel[t].controlc)
1808 tunnel[t].controle->next = c;
1809 else
1810 tunnel[t].controls = c;
1811
1812 tunnel[t].controle = c;
1813 tunnel[t].controlc++;
1814
1815 // send now if space in window
1816 if (tunnel[t].controlc <= tunnel[t].window)
1817 {
1818 tunnel[t].try = 0; // first send
1819 tunnelsend(c->buf, c->length, t);
1820 }
1821 }
1822
1823 //
1824 // Throttle or Unthrottle a session
1825 //
1826 // Throttle the data from/to through a session to no more than
1827 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1828 // user).
1829 //
1830 // If either value is -1, the current value is retained for that
1831 // direction.
1832 //
1833 void throttle_session(sessionidt s, int rate_in, int rate_out)
1834 {
1835 if (!session[s].opened)
1836 return; // No-one home.
1837
1838 if (!*session[s].user)
1839 return; // User not logged in
1840
1841 if (rate_in >= 0)
1842 {
1843 int bytes = rate_in * 1024 / 8; // kbits to bytes
1844 if (session[s].tbf_in)
1845 free_tbf(session[s].tbf_in);
1846
1847 if (rate_in > 0)
1848 session[s].tbf_in = new_tbf(s, bytes * 2, bytes, send_ipin);
1849 else
1850 session[s].tbf_in = 0;
1851
1852 session[s].throttle_in = rate_in;
1853 }
1854
1855 if (rate_out >= 0)
1856 {
1857 int bytes = rate_out * 1024 / 8;
1858 if (session[s].tbf_out)
1859 free_tbf(session[s].tbf_out);
1860
1861 if (rate_out > 0)
1862 session[s].tbf_out = new_tbf(s, bytes * 2, bytes, send_ipout);
1863 else
1864 session[s].tbf_out = 0;
1865
1866 session[s].throttle_out = rate_out;
1867 }
1868 }
1869
1870 // add/remove filters from session (-1 = no change)
1871 void filter_session(sessionidt s, int filter_in, int filter_out)
1872 {
1873 if (!session[s].opened)
1874 return; // No-one home.
1875
1876 if (!*session[s].user)
1877 return; // User not logged in
1878
1879 // paranoia
1880 if (filter_in > MAXFILTER) filter_in = -1;
1881 if (filter_out > MAXFILTER) filter_out = -1;
1882 if (session[s].filter_in > MAXFILTER) session[s].filter_in = 0;
1883 if (session[s].filter_out > MAXFILTER) session[s].filter_out = 0;
1884
1885 if (filter_in >= 0)
1886 {
1887 if (session[s].filter_in)
1888 ip_filters[session[s].filter_in - 1].used--;
1889
1890 if (filter_in > 0)
1891 ip_filters[filter_in - 1].used++;
1892
1893 session[s].filter_in = filter_in;
1894 }
1895
1896 if (filter_out >= 0)
1897 {
1898 if (session[s].filter_out)
1899 ip_filters[session[s].filter_out - 1].used--;
1900
1901 if (filter_out > 0)
1902 ip_filters[filter_out - 1].used++;
1903
1904 session[s].filter_out = filter_out;
1905 }
1906 }
1907
1908 // start tidy shutdown of session
1909 void sessionshutdown(sessionidt s, char const *reason, int cdn_result, int cdn_error, int term_cause)
1910 {
1911 int walled_garden = session[s].walled_garden;
1912 bundleidt b = session[s].bundle;
1913 //delete routes only for last session in bundle (in case of MPPP)
1914 int del_routes = !b || (bundle[b].num_of_links == 1);
1915
1916 CSTAT(sessionshutdown);
1917
1918 if (!session[s].opened)
1919 {
1920 LOG(3, s, session[s].tunnel, "Called sessionshutdown on an unopened session.\n");
1921 return; // not a live session
1922 }
1923
1924 if (!session[s].die)
1925 {
1926 struct param_kill_session data = { &tunnel[session[s].tunnel], &session[s] };
1927 LOG(2, s, session[s].tunnel, "Shutting down session %u: %s\n", s, reason);
1928 run_plugins(PLUGIN_KILL_SESSION, &data);
1929 session[s].die = TIME + 150; // Clean up in 15 seconds
1930 }
1931
1932 if (session[s].ip && !walled_garden && !session[s].die)
1933 {
1934 // RADIUS Stop message
1935 uint16_t r = radiusnew(s);
1936 if (r)
1937 {
1938 // stop, if not already trying
1939 if (radius[r].state != RADIUSSTOP)
1940 {
1941 radius[r].term_cause = term_cause;
1942 radius[r].term_msg = reason;
1943 radiussend(r, RADIUSSTOP);
1944 }
1945 }
1946 else
1947 LOG(1, s, session[s].tunnel, "No free RADIUS sessions for Stop message\n");
1948
1949 // Save counters to dump to accounting file
1950 if (*config->accounting_dir && shut_acct_n < sizeof(shut_acct) / sizeof(*shut_acct))
1951 memcpy(&shut_acct[shut_acct_n++], &session[s], sizeof(session[s]));
1952 }
1953
1954 if (session[s].ip)
1955 { // IP allocated, clear and unroute
1956 int r;
1957 int routed = 0;
1958 for (r = 0; r < MAXROUTE && session[s].route[r].ip; r++)
1959 {
1960 if ((session[s].ip & session[s].route[r].mask) ==
1961 (session[s].route[r].ip & session[s].route[r].mask))
1962 routed++;
1963
1964 if (del_routes) routeset(s, session[s].route[r].ip, session[s].route[r].mask, 0, 0);
1965 session[s].route[r].ip = 0;
1966 }
1967
1968 if (session[s].ip_pool_index == -1) // static ip
1969 {
1970 if (!routed && del_routes) routeset(s, session[s].ip, 0, 0, 0);
1971 session[s].ip = 0;
1972 }
1973 else
1974 free_ip_address(s);
1975
1976 // unroute IPv6, if setup
1977 if (session[s].ppp.ipv6cp == Opened && session[s].ipv6prefixlen && del_routes)
1978 route6set(s, session[s].ipv6route, session[s].ipv6prefixlen, 0);
1979
1980 if (b)
1981 {
1982 // This session was part of a bundle
1983 bundle[b].num_of_links--;
1984 LOG(3, s, 0, "MPPP: Dropping member link: %d from bundle %d\n",s,b);
1985 if(bundle[b].num_of_links == 0)
1986 {
1987 bundleclear(b);
1988 LOG(3, s, 0, "MPPP: Kill bundle: %d (No remaing member links)\n",b);
1989 }
1990 else
1991 {
1992 // Adjust the members array to accomodate the new change
1993 uint8_t mem_num = 0;
1994 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
1995 if(bundle[b].members[bundle[b].num_of_links] != s)
1996 {
1997 uint8_t ml;
1998 for(ml = 0; ml<bundle[b].num_of_links; ml++)
1999 if(bundle[b].members[ml] == s)
2000 {
2001 mem_num = ml;
2002 break;
2003 }
2004 bundle[b].members[mem_num] = bundle[b].members[bundle[b].num_of_links];
2005 LOG(3, s, 0, "MPPP: Adjusted member links array\n");
2006 }
2007 }
2008 cluster_send_bundle(b);
2009 }
2010 }
2011
2012 if (session[s].throttle_in || session[s].throttle_out) // Unthrottle if throttled.
2013 throttle_session(s, 0, 0);
2014
2015 if (cdn_result)
2016 { // Send CDN
2017 controlt *c = controlnew(14); // sending CDN
2018 if (cdn_error)
2019 {
2020 uint8_t buf[4];
2021 *(uint16_t *) buf = htons(cdn_result);
2022 *(uint16_t *) (buf+2) = htons(cdn_error);
2023 controlb(c, 1, buf, 4, 1);
2024 }
2025 else
2026 control16(c, 1, cdn_result, 1);
2027
2028 control16(c, 14, s, 1); // assigned session (our end)
2029 controladd(c, session[s].far, session[s].tunnel); // send the message
2030 }
2031
2032 // update filter refcounts
2033 if (session[s].filter_in) ip_filters[session[s].filter_in - 1].used--;
2034 if (session[s].filter_out) ip_filters[session[s].filter_out - 1].used--;
2035
2036 // clear PPP state
2037 memset(&session[s].ppp, 0, sizeof(session[s].ppp));
2038 sess_local[s].lcp.restart = 0;
2039 sess_local[s].ipcp.restart = 0;
2040 sess_local[s].ipv6cp.restart = 0;
2041 sess_local[s].ccp.restart = 0;
2042
2043 cluster_send_session(s);
2044 }
2045
2046 void sendipcp(sessionidt s, tunnelidt t)
2047 {
2048 uint8_t buf[MAXETHER];
2049 uint8_t *q;
2050
2051 CSTAT(sendipcp);
2052 LOG(3, s, t, "IPCP: send ConfigReq\n");
2053
2054 if (!session[s].unique_id)
2055 {
2056 if (!++last_id) ++last_id; // skip zero
2057 session[s].unique_id = last_id;
2058 }
2059
2060 q = makeppp(buf, sizeof(buf), 0, 0, s, t, PPPIPCP, 0, 0, 0);
2061 if (!q) return;
2062
2063 *q = ConfigReq;
2064 q[1] = session[s].unique_id & 0xf; // ID, dont care, we only send one type of request
2065 *(uint16_t *) (q + 2) = htons(10); // packet length
2066 q[4] = 3; // ip address option
2067 q[5] = 6; // option length
2068 *(in_addr_t *) (q + 6) = config->peer_address ? config->peer_address :
2069 config->bind_address ? config->bind_address :
2070 my_address; // send my IP
2071
2072 tunnelsend(buf, 10 + (q - buf), t); // send it
2073 restart_timer(s, ipcp);
2074 }
2075
2076 void sendipv6cp(sessionidt s, tunnelidt t)
2077 {
2078 uint8_t buf[MAXETHER];
2079 uint8_t *q;
2080
2081 CSTAT(sendipv6cp);
2082 LOG(3, s, t, "IPV6CP: send ConfigReq\n");
2083
2084 q = makeppp(buf, sizeof(buf), 0, 0, s, t, PPPIPV6CP, 0, 0, 0);
2085 if (!q) return;
2086
2087 *q = ConfigReq;
2088 q[1] = session[s].unique_id & 0xf; // ID, don't care, we
2089 // only send one type
2090 // of request
2091 *(uint16_t *) (q + 2) = htons(14);
2092 q[4] = 1; // interface identifier option
2093 q[5] = 10; // option length
2094 *(uint32_t *) (q + 6) = 0; // We'll be prefix::1
2095 *(uint32_t *) (q + 10) = 0;
2096 q[13] = 1;
2097
2098 tunnelsend(buf, 14 + (q - buf), t); // send it
2099 restart_timer(s, ipv6cp);
2100 }
2101
2102 static void sessionclear(sessionidt s)
2103 {
2104 memset(&session[s], 0, sizeof(session[s]));
2105 memset(&sess_local[s], 0, sizeof(sess_local[s]));
2106 memset(&cli_session_actions[s], 0, sizeof(cli_session_actions[s]));
2107
2108 session[s].tunnel = T_FREE; // Mark it as free.
2109 session[s].next = sessionfree;
2110 sessionfree = s;
2111 }
2112
2113 // kill a session now
2114 void sessionkill(sessionidt s, char *reason)
2115 {
2116 CSTAT(sessionkill);
2117
2118 if (!session[s].opened) // not alive
2119 return;
2120
2121 if (session[s].next)
2122 {
2123 LOG(0, s, session[s].tunnel, "Tried to kill a session with next pointer set (%u)\n", session[s].next);
2124 return;
2125 }
2126
2127 if (!session[s].die)
2128 sessionshutdown(s, reason, CDN_ADMIN_DISC, TERM_ADMIN_RESET); // close radius/routes, etc.
2129
2130 if (sess_local[s].radius)
2131 radiusclear(sess_local[s].radius, s); // cant send clean accounting data, session is killed
2132
2133 LOG(2, s, session[s].tunnel, "Kill session %d (%s): %s\n", s, session[s].user, reason);
2134 sessionclear(s);
2135 cluster_send_session(s);
2136 }
2137
2138 static void tunnelclear(tunnelidt t)
2139 {
2140 if (!t) return;
2141 memset(&tunnel[t], 0, sizeof(tunnel[t]));
2142 tunnel[t].state = TUNNELFREE;
2143 }
2144
2145 static void bundleclear(bundleidt b)
2146 {
2147 if (!b) return;
2148 memset(&bundle[b], 0, sizeof(bundle[b]));
2149 bundle[b].state = BUNDLEFREE;
2150 }
2151
2152 // kill a tunnel now
2153 static void tunnelkill(tunnelidt t, char *reason)
2154 {
2155 sessionidt s;
2156 controlt *c;
2157
2158 CSTAT(tunnelkill);
2159
2160 tunnel[t].state = TUNNELDIE;
2161
2162 // free control messages
2163 while ((c = tunnel[t].controls))
2164 {
2165 controlt * n = c->next;
2166 tunnel[t].controls = n;
2167 tunnel[t].controlc--;
2168 c->next = controlfree;
2169 controlfree = c;
2170 }
2171 // kill sessions
2172 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
2173 if (session[s].tunnel == t)
2174 sessionkill(s, reason);
2175
2176 // free tunnel
2177 tunnelclear(t);
2178 LOG(1, 0, t, "Kill tunnel %u: %s\n", t, reason);
2179 cli_tunnel_actions[t].action = 0;
2180 cluster_send_tunnel(t);
2181 }
2182
2183 // shut down a tunnel cleanly
2184 static void tunnelshutdown(tunnelidt t, char *reason, int result, int error, char *msg)
2185 {
2186 sessionidt s;
2187
2188 CSTAT(tunnelshutdown);
2189
2190 if (!tunnel[t].last || !tunnel[t].far || tunnel[t].state == TUNNELFREE)
2191 {
2192 // never set up, can immediately kill
2193 tunnelkill(t, reason);
2194 return;
2195 }
2196 LOG(1, 0, t, "Shutting down tunnel %u (%s)\n", t, reason);
2197
2198 // close session
2199 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
2200 if (session[s].tunnel == t)
2201 sessionshutdown(s, reason, CDN_NONE, TERM_ADMIN_RESET);
2202
2203 tunnel[t].state = TUNNELDIE;
2204 tunnel[t].die = TIME + 700; // Clean up in 70 seconds
2205 cluster_send_tunnel(t);
2206 // TBA - should we wait for sessions to stop?
2207 if (result)
2208 {
2209 controlt *c = controlnew(4); // sending StopCCN
2210 if (error)
2211 {
2212 uint8_t buf[64];
2213 int l = 4;
2214 *(uint16_t *) buf = htons(result);
2215 *(uint16_t *) (buf+2) = htons(error);
2216 if (msg)
2217 {
2218 int m = strlen(msg);
2219 if (m + 4 > sizeof(buf))
2220 m = sizeof(buf) - 4;
2221
2222 memcpy(buf+4, msg, m);
2223 l += m;
2224 }
2225
2226 controlb(c, 1, buf, l, 1);
2227 }
2228 else
2229 control16(c, 1, result, 1);
2230
2231 control16(c, 9, t, 1); // assigned tunnel (our end)
2232 controladd(c, 0, t); // send the message
2233 }
2234 }
2235
2236 // read and process packet on tunnel (UDP)
2237 void processudp(uint8_t *buf, int len, struct sockaddr_in *addr)
2238 {
2239 uint8_t *chapresponse = NULL;
2240 uint16_t l = len, t = 0, s = 0, ns = 0, nr = 0;
2241 uint8_t *p = buf + 2;
2242
2243
2244 CSTAT(processudp);
2245
2246 udp_rx += len;
2247 udp_rx_pkt++;
2248 LOG_HEX(5, "UDP Data", buf, len);
2249 STAT(tunnel_rx_packets);
2250 INC_STAT(tunnel_rx_bytes, len);
2251 if (len < 6)
2252 {
2253 LOG(1, 0, 0, "Short UDP, %d bytes\n", len);
2254 STAT(tunnel_rx_errors);
2255 return;
2256 }
2257 if ((buf[1] & 0x0F) != 2)
2258 {
2259 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf[1] & 0x0F);
2260 STAT(tunnel_rx_errors);
2261 return;
2262 }
2263 if (*buf & 0x40)
2264 { // length
2265 l = ntohs(*(uint16_t *) p);
2266 p += 2;
2267 }
2268 t = ntohs(*(uint16_t *) p);
2269 p += 2;
2270 s = ntohs(*(uint16_t *) p);
2271 p += 2;
2272 if (s >= MAXSESSION)
2273 {
2274 LOG(1, s, t, "Received UDP packet with invalid session ID\n");
2275 STAT(tunnel_rx_errors);
2276 return;
2277 }
2278 if (t >= MAXTUNNEL)
2279 {
2280 LOG(1, s, t, "Received UDP packet with invalid tunnel ID\n");
2281 STAT(tunnel_rx_errors);
2282 return;
2283 }
2284 if (*buf & 0x08)
2285 { // ns/nr
2286 ns = ntohs(*(uint16_t *) p);
2287 p += 2;
2288 nr = ntohs(*(uint16_t *) p);
2289 p += 2;
2290 }
2291 if (*buf & 0x02)
2292 { // offset
2293 uint16_t o = ntohs(*(uint16_t *) p);
2294 p += o + 2;
2295 }
2296 if ((p - buf) > l)
2297 {
2298 LOG(1, s, t, "Bad length %d>%d\n", (int) (p - buf), l);
2299 STAT(tunnel_rx_errors);
2300 return;
2301 }
2302 l -= (p - buf);
2303
2304 // used to time out old tunnels
2305 if (t && tunnel[t].state == TUNNELOPEN)
2306 tunnel[t].lastrec = time_now;
2307
2308 if (*buf & 0x80)
2309 { // control
2310 uint16_t message = 0xFFFF; // message type
2311 uint8_t fatal = 0;
2312 uint8_t mandatory = 0;
2313 uint16_t asession = 0; // assigned session
2314 uint32_t amagic = 0; // magic number
2315 uint8_t aflags = 0; // flags from last LCF
2316 uint16_t version = 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2317 char called[MAXTEL] = ""; // called number
2318 char calling[MAXTEL] = ""; // calling number
2319
2320 if (!config->cluster_iam_master)
2321 {
2322 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port);
2323 return;
2324 }
2325
2326 // control messages must have bits 0x80|0x40|0x08
2327 // (type, length and sequence) set, and bits 0x02|0x01
2328 // (offset and priority) clear
2329 if ((*buf & 0xCB) != 0xC8)
2330 {
2331 LOG(1, s, t, "Bad control header %02X\n", *buf);
2332 STAT(tunnel_rx_errors);
2333 return;
2334 }
2335
2336 // check for duplicate tunnel open message
2337 if (!t && ns == 0)
2338 {
2339 int i;
2340
2341 //
2342 // Is this a duplicate of the first packet? (SCCRQ)
2343 //
2344 for (i = 1; i <= config->cluster_highest_tunnelid ; ++i)
2345 {
2346 if (tunnel[i].state != TUNNELOPENING ||
2347 tunnel[i].ip != ntohl(*(in_addr_t *) & addr->sin_addr) ||
2348 tunnel[i].port != ntohs(addr->sin_port) )
2349 continue;
2350 t = i;
2351 LOG(3, s, t, "Duplicate SCCRQ?\n");
2352 break;
2353 }
2354 }
2355
2356 LOG(3, s, t, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2357 l, tunnel[t].controlc, tunnel[t].ns, tunnel[t].nr, ns, nr);
2358
2359 // if no tunnel specified, assign one
2360 if (!t)
2361 {
2362 if (!(t = new_tunnel()))
2363 {
2364 LOG(1, 0, 0, "No more tunnels\n");
2365 STAT(tunnel_overflow);
2366 return;
2367 }
2368 tunnelclear(t);
2369 tunnel[t].ip = ntohl(*(in_addr_t *) & addr->sin_addr);
2370 tunnel[t].port = ntohs(addr->sin_port);
2371 tunnel[t].window = 4; // default window
2372 STAT(tunnel_created);
2373 LOG(1, 0, t, " New tunnel from %s:%u ID %u\n",
2374 fmtaddr(htonl(tunnel[t].ip), 0), tunnel[t].port, t);
2375 }
2376
2377 // If the 'ns' just received is not the 'nr' we're
2378 // expecting, just send an ack and drop it.
2379 //
2380 // if 'ns' is less, then we got a retransmitted packet.
2381 // if 'ns' is greater than missed a packet. Either way
2382 // we should ignore it.
2383 if (ns != tunnel[t].nr)
2384 {
2385 // is this the sequence we were expecting?
2386 STAT(tunnel_rx_errors);
2387 LOG(1, 0, t, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2388 t, ns, tunnel[t].nr);
2389
2390 if (l) // Is this not a ZLB?
2391 controlnull(t);
2392 return;
2393 }
2394
2395 // check sequence of this message
2396 {
2397 int skip = tunnel[t].window; // track how many in-window packets are still in queue
2398 // some to clear maybe?
2399 while (tunnel[t].controlc > 0 && (((tunnel[t].ns - tunnel[t].controlc) - nr) & 0x8000))
2400 {
2401 controlt *c = tunnel[t].controls;
2402 tunnel[t].controls = c->next;
2403 tunnel[t].controlc--;
2404 c->next = controlfree;
2405 controlfree = c;
2406 skip--;
2407 tunnel[t].try = 0; // we have progress
2408 }
2409
2410 // receiver advance (do here so quoted correctly in any sends below)
2411 if (l) tunnel[t].nr = (ns + 1);
2412 if (skip < 0) skip = 0;
2413 if (skip < tunnel[t].controlc)
2414 {
2415 // some control packets can now be sent that were previous stuck out of window
2416 int tosend = tunnel[t].window - skip;
2417 controlt *c = tunnel[t].controls;
2418 while (c && skip)
2419 {
2420 c = c->next;
2421 skip--;
2422 }
2423 while (c && tosend)
2424 {
2425 tunnel[t].try = 0; // first send
2426 tunnelsend(c->buf, c->length, t);
2427 c = c->next;
2428 tosend--;
2429 }
2430 }
2431 if (!tunnel[t].controlc)
2432 tunnel[t].retry = 0; // caught up
2433 }
2434 if (l)
2435 { // if not a null message
2436 int result = 0;
2437 int error = 0;
2438 char *msg = 0;
2439
2440 // Default disconnect cause/message on receipt of CDN. Set to
2441 // more specific value from attribute 1 (result code) or 46
2442 // (disconnect cause) if present below.
2443 int disc_cause_set = 0;
2444 int disc_cause = TERM_NAS_REQUEST;
2445 char const *disc_reason = "Closed (Received CDN).";
2446
2447 // process AVPs
2448 while (l && !(fatal & 0x80)) // 0x80 = mandatory AVP
2449 {
2450 uint16_t n = (ntohs(*(uint16_t *) p) & 0x3FF);
2451 uint8_t *b = p;
2452 uint8_t flags = *p;
2453 uint16_t mtype;
2454
2455 if (n > l)
2456 {
2457 LOG(1, s, t, "Invalid length in AVP\n");
2458 STAT(tunnel_rx_errors);
2459 return;
2460 }
2461 p += n; // next
2462 l -= n;
2463 if (flags & 0x3C) // reserved bits, should be clear
2464 {
2465 LOG(1, s, t, "Unrecognised AVP flags %02X\n", *b);
2466 fatal = flags;
2467 result = 2; // general error
2468 error = 3; // reserved field non-zero
2469 msg = 0;
2470 continue; // next
2471 }
2472 b += 2;
2473 if (*(uint16_t *) (b))
2474 {
2475 LOG(2, s, t, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b)));
2476 fatal = flags;
2477 result = 2; // general error
2478 error = 6; // generic vendor-specific error
2479 msg = "unsupported vendor-specific";
2480 continue; // next
2481 }
2482 b += 2;
2483 mtype = ntohs(*(uint16_t *) (b));
2484 b += 2;
2485 n -= 6;
2486
2487 if (flags & 0x40)
2488 {
2489 uint16_t orig_len;
2490
2491 // handle hidden AVPs
2492 if (!*config->l2tp_secret)
2493 {
2494 LOG(1, s, t, "Hidden AVP requested, but no L2TP secret.\n");
2495 fatal = flags;
2496 result = 2; // general error
2497 error = 6; // generic vendor-specific error
2498 msg = "secret not specified";
2499 continue;
2500 }
2501 if (!session[s].random_vector_length)
2502 {
2503 LOG(1, s, t, "Hidden AVP requested, but no random vector.\n");
2504 fatal = flags;
2505 result = 2; // general error
2506 error = 6; // generic
2507 msg = "no random vector";
2508 continue;
2509 }
2510 if (n < 8)
2511 {
2512 LOG(2, s, t, "Short hidden AVP.\n");
2513 fatal = flags;
2514 result = 2; // general error
2515 error = 2; // length is wrong
2516 msg = 0;
2517 continue;
2518 }
2519
2520 // Unhide the AVP
2521 unhide_value(b, n, mtype, session[s].random_vector, session[s].random_vector_length);
2522
2523 orig_len = ntohs(*(uint16_t *) b);
2524 if (orig_len > n + 2)
2525 {
2526 LOG(1, s, t, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2527 orig_len, n);
2528
2529 fatal = flags;
2530 result = 2; // general error
2531 error = 2; // length is wrong
2532 msg = 0;
2533 continue;
2534 }
2535
2536 b += 2;
2537 n = orig_len;
2538 }
2539
2540 LOG(4, s, t, " AVP %u (%s) len %d%s%s\n", mtype, l2tp_avp_name(mtype), n,
2541 flags & 0x40 ? ", hidden" : "", flags & 0x80 ? ", mandatory" : "");
2542
2543 switch (mtype)
2544 {
2545 case 0: // message type
2546 message = ntohs(*(uint16_t *) b);
2547 mandatory = flags & 0x80;
2548 LOG(4, s, t, " Message type = %u (%s)\n", *b, l2tp_code(message));
2549 break;
2550 case 1: // result code
2551 {
2552 uint16_t rescode = ntohs(*(uint16_t *) b);
2553 char const *resdesc = "(unknown)";
2554 char const *errdesc = NULL;
2555 int cause = 0;
2556
2557 if (message == 4)
2558 { /* StopCCN */
2559 resdesc = l2tp_stopccn_result_code(rescode);
2560 cause = TERM_LOST_SERVICE;
2561 }
2562 else if (message == 14)
2563 { /* CDN */
2564 resdesc = l2tp_cdn_result_code(rescode);
2565 if (rescode == 1)
2566 cause = TERM_LOST_CARRIER;
2567 else
2568 cause = TERM_ADMIN_RESET;
2569 }
2570
2571 LOG(4, s, t, " Result Code %u: %s\n", rescode, resdesc);
2572 if (n >= 4)
2573 {
2574 uint16_t errcode = ntohs(*(uint16_t *)(b + 2));
2575 errdesc = l2tp_error_code(errcode);
2576 LOG(4, s, t, " Error Code %u: %s\n", errcode, errdesc);
2577 }
2578 if (n > 4)
2579 LOG(4, s, t, " Error String: %.*s\n", n-4, b+4);
2580
2581 if (cause && disc_cause_set < mtype) // take cause from attrib 46 in preference
2582 {
2583 disc_cause_set = mtype;
2584 disc_reason = errdesc ? errdesc : resdesc;
2585 disc_cause = cause;
2586 }
2587
2588 break;
2589 }
2590 break;
2591 case 2: // protocol version
2592 {
2593 version = ntohs(*(uint16_t *) (b));
2594 LOG(4, s, t, " Protocol version = %u\n", version);
2595 if (version && version != 0x0100)
2596 { // allow 0.0 and 1.0
2597 LOG(1, s, t, " Bad protocol version %04X\n", version);
2598 fatal = flags;
2599 result = 5; // unspported protocol version
2600 error = 0x0100; // supported version
2601 msg = 0;
2602 continue; // next
2603 }
2604 }
2605 break;
2606 case 3: // framing capabilities
2607 break;
2608 case 4: // bearer capabilities
2609 break;
2610 case 5: // tie breaker
2611 // We never open tunnels, so we don't care about tie breakers
2612 continue;
2613 case 6: // firmware revision
2614 break;
2615 case 7: // host name
2616 memset(tunnel[t].hostname, 0, sizeof(tunnel[t].hostname));
2617 memcpy(tunnel[t].hostname, b, (n < sizeof(tunnel[t].hostname)) ? n : sizeof(tunnel[t].hostname) - 1);
2618 LOG(4, s, t, " Tunnel hostname = \"%s\"\n", tunnel[t].hostname);
2619 // TBA - to send to RADIUS
2620 break;
2621 case 8: // vendor name
2622 memset(tunnel[t].vendor, 0, sizeof(tunnel[t].vendor));
2623 memcpy(tunnel[t].vendor, b, (n < sizeof(tunnel[t].vendor)) ? n : sizeof(tunnel[t].vendor) - 1);
2624 LOG(4, s, t, " Vendor name = \"%s\"\n", tunnel[t].vendor);
2625 break;
2626 case 9: // assigned tunnel
2627 tunnel[t].far = ntohs(*(uint16_t *) (b));
2628 LOG(4, s, t, " Remote tunnel id = %u\n", tunnel[t].far);
2629 break;
2630 case 10: // rx window
2631 tunnel[t].window = ntohs(*(uint16_t *) (b));
2632 if (!tunnel[t].window)
2633 tunnel[t].window = 1; // window of 0 is silly
2634 LOG(4, s, t, " rx window = %u\n", tunnel[t].window);
2635 break;
2636 case 11: // Challenge
2637 {
2638 LOG(4, s, t, " LAC requested CHAP authentication for tunnel\n");
2639 build_chap_response(b, 2, n, &chapresponse);
2640 }
2641 break;
2642 case 13: // Response
2643 // Why did they send a response? We never challenge.
2644 LOG(2, s, t, " received unexpected challenge response\n");
2645 break;
2646
2647 case 14: // assigned session
2648 asession = session[s].far = ntohs(*(uint16_t *) (b));
2649 LOG(4, s, t, " assigned session = %u\n", asession);
2650 break;
2651 case 15: // call serial number
2652 LOG(4, s, t, " call serial number = %u\n", ntohl(*(uint32_t *)b));
2653 break;
2654 case 18: // bearer type
2655 LOG(4, s, t, " bearer type = %u\n", ntohl(*(uint32_t *)b));
2656 // TBA - for RADIUS
2657 break;
2658 case 19: // framing type
2659 LOG(4, s, t, " framing type = %u\n", ntohl(*(uint32_t *)b));
2660 // TBA
2661 break;
2662 case 21: // called number
2663 memset(called, 0, sizeof(called));
2664 memcpy(called, b, (n < sizeof(called)) ? n : sizeof(called) - 1);
2665 LOG(4, s, t, " Called <%s>\n", called);
2666 break;
2667 case 22: // calling number
2668 memset(calling, 0, sizeof(calling));
2669 memcpy(calling, b, (n < sizeof(calling)) ? n : sizeof(calling) - 1);
2670 LOG(4, s, t, " Calling <%s>\n", calling);
2671 break;
2672 case 23: // subtype
2673 break;
2674 case 24: // tx connect speed
2675 if (n == 4)
2676 {
2677 session[s].tx_connect_speed = ntohl(*(uint32_t *)b);
2678 }
2679 else
2680 {
2681 // AS5300s send connect speed as a string
2682 char tmp[30];
2683 memset(tmp, 0, sizeof(tmp));
2684 memcpy(tmp, b, (n < sizeof(tmp)) ? n : sizeof(tmp) - 1);
2685 session[s].tx_connect_speed = atol(tmp);
2686 }
2687 LOG(4, s, t, " TX connect speed <%u>\n", session[s].tx_connect_speed);
2688 break;
2689 case 38: // rx connect speed
2690 if (n == 4)
2691 {
2692 session[s].rx_connect_speed = ntohl(*(uint32_t *)b);
2693 }
2694 else
2695 {
2696 // AS5300s send connect speed as a string
2697 char tmp[30];
2698 memset(tmp, 0, sizeof(tmp));
2699 memcpy(tmp, b, (n < sizeof(tmp)) ? n : sizeof(tmp) - 1);
2700 session[s].rx_connect_speed = atol(tmp);
2701 }
2702 LOG(4, s, t, " RX connect speed <%u>\n", session[s].rx_connect_speed);
2703 break;
2704 case 25: // Physical Channel ID
2705 {
2706 uint32_t tmp = ntohl(*(uint32_t *) b);
2707 LOG(4, s, t, " Physical Channel ID <%X>\n", tmp);
2708 break;
2709 }
2710 case 29: // Proxy Authentication Type
2711 {
2712 uint16_t atype = ntohs(*(uint16_t *)b);
2713 LOG(4, s, t, " Proxy Auth Type %u (%s)\n", atype, ppp_auth_type(atype));
2714 break;
2715 }
2716 case 30: // Proxy Authentication Name
2717 {
2718 char authname[64];
2719 memset(authname, 0, sizeof(authname));
2720 memcpy(authname, b, (n < sizeof(authname)) ? n : sizeof(authname) - 1);
2721 LOG(4, s, t, " Proxy Auth Name (%s)\n",
2722 authname);
2723 break;
2724 }
2725 case 31: // Proxy Authentication Challenge
2726 {
2727 LOG(4, s, t, " Proxy Auth Challenge\n");
2728 break;
2729 }
2730 case 32: // Proxy Authentication ID
2731 {
2732 uint16_t authid = ntohs(*(uint16_t *)(b));
2733 LOG(4, s, t, " Proxy Auth ID (%u)\n", authid);
2734 break;
2735 }
2736 case 33: // Proxy Authentication Response
2737 LOG(4, s, t, " Proxy Auth Response\n");
2738 break;
2739 case 27: // last sent lcp
2740 { // find magic number
2741 uint8_t *p = b, *e = p + n;
2742 while (p + 1 < e && p[1] && p + p[1] <= e)
2743 {
2744 if (*p == 5 && p[1] == 6) // Magic-Number
2745 amagic = ntohl(*(uint32_t *) (p + 2));
2746 else if (*p == 7) // Protocol-Field-Compression
2747 aflags |= SESSION_PFC;
2748 else if (*p == 8) // Address-and-Control-Field-Compression
2749 aflags |= SESSION_ACFC;
2750 p += p[1];
2751 }
2752 }
2753 break;
2754 case 28: // last recv lcp confreq
2755 break;
2756 case 26: // Initial Received LCP CONFREQ
2757 break;
2758 case 39: // seq required - we control it as an LNS anyway...
2759 break;
2760 case 36: // Random Vector
2761 LOG(4, s, t, " Random Vector received. Enabled AVP Hiding.\n");
2762 memset(session[s].random_vector, 0, sizeof(session[s].random_vector));
2763 if (n > sizeof(session[s].random_vector))
2764 n = sizeof(session[s].random_vector);
2765 memcpy(session[s].random_vector, b, n);
2766 session[s].random_vector_length = n;
2767 break;
2768 case 46: // ppp disconnect cause
2769 if (n >= 5)
2770 {
2771 uint16_t code = ntohs(*(uint16_t *) b);
2772 uint16_t proto = ntohs(*(uint16_t *) (b + 2));
2773 uint8_t dir = *(b + 4);
2774
2775 LOG(4, s, t, " PPP disconnect cause "
2776 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2777 code, proto, dir, n - 5, b + 5);
2778
2779 disc_cause_set = mtype;
2780
2781 switch (code)
2782 {
2783 case 1: // admin disconnect
2784 disc_cause = TERM_ADMIN_RESET;
2785 disc_reason = "Administrative disconnect";
2786 break;
2787 case 3: // lcp terminate
2788 if (dir != 2) break; // 1=peer (LNS), 2=local (LAC)
2789 disc_cause = TERM_USER_REQUEST;
2790 disc_reason = "Normal disconnection";
2791 break;
2792 case 4: // compulsory encryption unavailable
2793 if (dir != 1) break; // 1=refused by peer, 2=local
2794 disc_cause = TERM_USER_ERROR;
2795 disc_reason = "Compulsory encryption refused";
2796 break;
2797 case 5: // lcp: fsm timeout
2798 disc_cause = TERM_PORT_ERROR;
2799 disc_reason = "LCP: FSM timeout";
2800 break;
2801 case 6: // lcp: no recognisable lcp packets received
2802 disc_cause = TERM_PORT_ERROR;
2803 disc_reason = "LCP: no recognisable LCP packets";
2804 break;
2805 case 7: // lcp: magic-no error (possibly looped back)
2806 disc_cause = TERM_PORT_ERROR;
2807 disc_reason = "LCP: magic-no error (possible loop)";
2808 break;
2809 case 8: // lcp: echo request timeout
2810 disc_cause = TERM_PORT_ERROR;
2811 disc_reason = "LCP: echo request timeout";
2812 break;
2813 case 13: // auth: fsm timeout
2814 disc_cause = TERM_SERVICE_UNAVAILABLE;
2815 disc_reason = "Authentication: FSM timeout";
2816 break;
2817 case 15: // auth: unacceptable auth protocol
2818 disc_cause = TERM_SERVICE_UNAVAILABLE;
2819 disc_reason = "Unacceptable authentication protocol";
2820 break;
2821 case 16: // auth: authentication failed
2822 disc_cause = TERM_SERVICE_UNAVAILABLE;
2823 disc_reason = "Authentication failed";
2824 break;
2825 case 17: // ncp: fsm timeout
2826 disc_cause = TERM_SERVICE_UNAVAILABLE;
2827 disc_reason = "NCP: FSM timeout";
2828 break;
2829 case 18: // ncp: no ncps available
2830 disc_cause = TERM_SERVICE_UNAVAILABLE;
2831 disc_reason = "NCP: no NCPs available";
2832 break;
2833 case 19: // ncp: failure to converge on acceptable address
2834 disc_cause = TERM_SERVICE_UNAVAILABLE;
2835 disc_reason = (dir == 1)
2836 ? "NCP: too many Configure-Naks received from peer"
2837 : "NCP: too many Configure-Naks sent to peer";
2838 break;
2839 case 20: // ncp: user not permitted to use any address
2840 disc_cause = TERM_SERVICE_UNAVAILABLE;
2841 disc_reason = (dir == 1)
2842 ? "NCP: local link address not acceptable to peer"
2843 : "NCP: remote link address not acceptable";
2844 break;
2845 }
2846 }
2847 break;
2848 default:
2849 {
2850 static char e[] = "unknown AVP 0xXXXX";
2851 LOG(2, s, t, " Unknown AVP type %u\n", mtype);
2852 fatal = flags;
2853 result = 2; // general error
2854 error = 8; // unknown mandatory AVP
2855 sprintf((msg = e) + 14, "%04x", mtype);
2856 continue; // next
2857 }
2858 }
2859 }
2860 // process message
2861 if (fatal & 0x80)
2862 tunnelshutdown(t, "Invalid mandatory AVP", result, error, msg);
2863 else
2864 switch (message)
2865 {
2866 case 1: // SCCRQ - Start Control Connection Request
2867 tunnel[t].state = TUNNELOPENING;
2868 if (main_quit != QUIT_SHUTDOWN)
2869 {
2870 controlt *c = controlnew(2); // sending SCCRP
2871 control16(c, 2, version, 1); // protocol version
2872 control32(c, 3, 3, 1); // framing
2873 controls(c, 7, hostname, 1); // host name
2874 if (chapresponse) controlb(c, 13, chapresponse, 16, 1); // Challenge response
2875 control16(c, 9, t, 1); // assigned tunnel
2876 controladd(c, 0, t); // send the resply
2877 }
2878 else
2879 {
2880 tunnelshutdown(t, "Shutting down", 6, 0, 0);
2881 }
2882 break;
2883 case 2: // SCCRP
2884 tunnel[t].state = TUNNELOPEN;
2885 tunnel[t].lastrec = time_now;
2886 break;
2887 case 3: // SCCN
2888 tunnel[t].state = TUNNELOPEN;
2889 tunnel[t].lastrec = time_now;
2890 controlnull(t); // ack
2891 break;
2892 case 4: // StopCCN
2893 controlnull(t); // ack
2894 tunnelshutdown(t, "Stopped", 0, 0, 0); // Shut down cleanly
2895 break;
2896 case 6: // HELLO
2897 controlnull(t); // simply ACK
2898 break;
2899 case 7: // OCRQ
2900 // TBA
2901 break;
2902 case 8: // OCRO
2903 // TBA
2904 break;
2905 case 9: // OCCN
2906 // TBA
2907 break;
2908 case 10: // ICRQ
2909 if (sessionfree && main_quit != QUIT_SHUTDOWN)
2910 {
2911 controlt *c = controlnew(11); // ICRP
2912
2913 s = sessionfree;
2914 sessionfree = session[s].next;
2915 memset(&session[s], 0, sizeof(session[s]));
2916
2917 if (s > config->cluster_highest_sessionid)
2918 config->cluster_highest_sessionid = s;
2919
2920 session[s].opened = time_now;
2921 session[s].tunnel = t;
2922 session[s].far = asession;
2923 session[s].last_packet = session[s].last_data = time_now;
2924 LOG(3, s, t, "New session (%u/%u)\n", tunnel[t].far, session[s].far);
2925 control16(c, 14, s, 1); // assigned session
2926 controladd(c, asession, t); // send the reply
2927
2928 strncpy(session[s].called, called, sizeof(session[s].called) - 1);
2929 strncpy(session[s].calling, calling, sizeof(session[s].calling) - 1);
2930
2931 session[s].ppp.phase = Establish;
2932 session[s].ppp.lcp = Starting;
2933
2934 STAT(session_created);
2935 break;
2936 }
2937
2938 {
2939 controlt *c = controlnew(14); // CDN
2940 if (!sessionfree)
2941 {
2942 STAT(session_overflow);
2943 LOG(1, 0, t, "No free sessions\n");
2944 control16(c, 1, 4, 0); // temporary lack of resources
2945 }
2946 else
2947 control16(c, 1, 2, 7); // shutting down, try another
2948
2949 controladd(c, asession, t); // send the message
2950 }
2951 return;
2952 case 11: // ICRP
2953 // TBA
2954 break;
2955 case 12: // ICCN
2956 if (amagic == 0) amagic = time_now;
2957 session[s].magic = amagic; // set magic number
2958 session[s].flags = aflags; // set flags received
2959 session[s].mru = PPPoE_MRU; // default
2960 controlnull(t); // ack
2961
2962 // start LCP
2963 sess_local[s].lcp_authtype = config->radius_authprefer;
2964 sess_local[s].ppp_mru = MRU;
2965
2966 // Set multilink options before sending initial LCP packet
2967 sess_local[s].mp_mrru = 1614;
2968 sess_local[s].mp_epdis = config->bind_address ? config->bind_address : my_address;
2969
2970 sendlcp(s, t);
2971 change_state(s, lcp, RequestSent);
2972 break;
2973
2974 case 14: // CDN
2975 controlnull(t); // ack
2976 sessionshutdown(s, disc_reason, CDN_NONE, disc_cause);
2977 break;
2978 case 0xFFFF:
2979 LOG(1, s, t, "Missing message type\n");
2980 break;
2981 default:
2982 STAT(tunnel_rx_errors);
2983 if (mandatory)
2984 tunnelshutdown(t, "Unknown message type", 2, 6, "unknown message type");
2985 else
2986 LOG(1, s, t, "Unknown message type %u\n", message);
2987 break;
2988 }
2989 if (chapresponse) free(chapresponse);
2990 cluster_send_tunnel(t);
2991 }
2992 else
2993 {
2994 LOG(4, s, t, " Got a ZLB ack\n");
2995 }
2996 }
2997 else
2998 { // data
2999 uint16_t proto;
3000
3001 LOG_HEX(5, "Receive Tunnel Data", p, l);
3002 if (l > 2 && p[0] == 0xFF && p[1] == 0x03)
3003 { // HDLC address header, discard
3004 p += 2;
3005 l -= 2;
3006 }
3007 if (l < 2)
3008 {
3009 LOG(1, s, t, "Short ppp length %d\n", l);
3010 STAT(tunnel_rx_errors);
3011 return;
3012 }
3013 if (*p & 1)
3014 {
3015 proto = *p++;
3016 l--;
3017 }
3018 else
3019 {
3020 proto = ntohs(*(uint16_t *) p);
3021 p += 2;
3022 l -= 2;
3023 }
3024
3025 if (s && !session[s].opened) // Is something wrong??
3026 {
3027 if (!config->cluster_iam_master)
3028 {
3029 // Pass it off to the master to deal with..
3030 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port);
3031 return;
3032 }
3033
3034
3035 LOG(1, s, t, "UDP packet contains session which is not opened. Dropping packet.\n");
3036 STAT(tunnel_rx_errors);
3037 return;
3038 }
3039
3040 if (proto == PPPPAP)
3041 {
3042 session[s].last_packet = time_now;
3043 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
3044 processpap(s, t, p, l);
3045 }
3046 else if (proto == PPPCHAP)
3047 {
3048 session[s].last_packet = time_now;
3049 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
3050 processchap(s, t, p, l);
3051 }
3052 else if (proto == PPPLCP)
3053 {
3054 session[s].last_packet = time_now;
3055 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
3056 processlcp(s, t, p, l);
3057 }
3058 else if (proto == PPPIPCP)
3059 {
3060 session[s].last_packet = time_now;
3061 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
3062 processipcp(s, t, p, l);
3063 }
3064 else if (proto == PPPIPV6CP && config->ipv6_prefix.s6_addr[0])
3065 {
3066 session[s].last_packet = time_now;
3067 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
3068 processipv6cp(s, t, p, l);
3069 }
3070 else if (proto == PPPCCP)
3071 {
3072 session[s].last_packet = time_now;
3073 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
3074 processccp(s, t, p, l);
3075 }
3076 else if (proto == PPPIP)
3077 {
3078 if (session[s].die)
3079 {
3080 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3081 return; // closing session, PPP not processed
3082 }
3083
3084 session[s].last_packet = session[s].last_data = time_now;
3085 if (session[s].walled_garden && !config->cluster_iam_master)
3086 {
3087 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port);
3088 return;
3089 }
3090
3091 processipin(s, t, p, l);
3092 }
3093 else if (proto == PPPMP)
3094 {
3095 if (session[s].die)
3096 {
3097 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3098 return; // closing session, PPP not processed
3099 }
3100
3101 session[s].last_packet = session[s].last_data = time_now;
3102 if (session[s].walled_garden && !config->cluster_iam_master)
3103 {
3104 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port);
3105 return;
3106 }
3107
3108 processmpin(s, t, p, l);
3109 }
3110 else if (proto == PPPIPV6 && config->ipv6_prefix.s6_addr[0])
3111 {
3112 if (session[s].die)
3113 {
3114 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3115 return; // closing session, PPP not processed
3116 }
3117
3118 session[s].last_packet = session[s].last_data = time_now;
3119 if (session[s].walled_garden && !config->cluster_iam_master)
3120 {
3121 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port);
3122 return;
3123 }
3124
3125 processipv6in(s, t, p, l);
3126 }
3127 else if (session[s].ppp.lcp == Opened)
3128 {
3129 session[s].last_packet = time_now;
3130 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port); return; }
3131 protoreject(s, t, p, l, proto);
3132 }
3133 else
3134 {
3135 LOG(2, s, t, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3136 proto, ppp_state(session[s].ppp.lcp));
3137 }
3138 }
3139 }
3140
3141 // read and process packet on tun
3142 static void processtun(uint8_t * buf, int len)
3143 {
3144 LOG_HEX(5, "Receive TUN Data", buf, len);
3145 STAT(tun_rx_packets);
3146 INC_STAT(tun_rx_bytes, len);
3147
3148 CSTAT(processtun);
3149
3150 eth_rx_pkt++;
3151 eth_rx += len;
3152 if (len < 22)
3153 {
3154 LOG(1, 0, 0, "Short tun packet %d bytes\n", len);
3155 STAT(tun_rx_errors);
3156 return;
3157 }
3158
3159 if (*(uint16_t *) (buf + 2) == htons(PKTIP)) // IPv4
3160 processipout(buf, len);
3161 else if (*(uint16_t *) (buf + 2) == htons(PKTIPV6) // IPV6
3162 && config->ipv6_prefix.s6_addr[0])
3163 processipv6out(buf, len);
3164
3165 // Else discard.
3166 }
3167
3168 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3169 // that we look at the whole of the tunnel, radius and session tables
3170 // every second
3171 static void regular_cleanups(double period)
3172 {
3173 // Next tunnel, radius and session to check for actions on.
3174 static tunnelidt t = 0;
3175 static int r = 0;
3176 static sessionidt s = 0;
3177
3178 int t_actions = 0;
3179 int r_actions = 0;
3180 int s_actions = 0;
3181
3182 int t_slice;
3183 int r_slice;
3184 int s_slice;
3185
3186 int i;
3187 int a;
3188
3189 // divide up tables into slices based on the last run
3190 t_slice = config->cluster_highest_tunnelid * period;
3191 r_slice = (MAXRADIUS - 1) * period;
3192 s_slice = config->cluster_highest_sessionid * period;
3193
3194 if (t_slice < 1)
3195 t_slice = 1;
3196 else if (t_slice > config->cluster_highest_tunnelid)
3197 t_slice = config->cluster_highest_tunnelid;
3198
3199 if (r_slice < 1)
3200 r_slice = 1;
3201 else if (r_slice > (MAXRADIUS - 1))
3202 r_slice = MAXRADIUS - 1;
3203
3204 if (s_slice < 1)
3205 s_slice = 1;
3206 else if (s_slice > config->cluster_highest_sessionid)
3207 s_slice = config->cluster_highest_sessionid;
3208
3209 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period);
3210
3211 for (i = 0; i < t_slice; i++)
3212 {
3213 t++;
3214 if (t > config->cluster_highest_tunnelid)
3215 t = 1;
3216
3217 // check for expired tunnels
3218 if (tunnel[t].die && tunnel[t].die <= TIME)
3219 {
3220 STAT(tunnel_timeout);
3221 tunnelkill(t, "Expired");
3222 t_actions++;
3223 continue;
3224 }
3225 // check for message resend
3226 if (tunnel[t].retry && tunnel[t].controlc)
3227 {
3228 // resend pending messages as timeout on reply
3229 if (tunnel[t].retry <= TIME)
3230 {
3231 controlt *c = tunnel[t].controls;
3232 uint16_t w = tunnel[t].window;
3233 tunnel[t].try++; // another try
3234 if (tunnel[t].try > 5)
3235 tunnelkill(t, "Timeout on control message"); // game over
3236 else
3237 while (c && w--)
3238 {
3239 tunnelsend(c->buf, c->length, t);
3240 c = c->next;
3241 }
3242
3243 t_actions++;
3244 }
3245 }
3246 // Send hello
3247 if (tunnel[t].state == TUNNELOPEN && !tunnel[t].controlc && (time_now - tunnel[t].lastrec) > 60)
3248 {
3249 controlt *c = controlnew(6); // sending HELLO
3250 controladd(c, 0, t); // send the message
3251 LOG(3, 0, t, "Sending HELLO message\n");
3252 t_actions++;
3253 }
3254
3255 // Check for tunnel changes requested from the CLI
3256 if ((a = cli_tunnel_actions[t].action))
3257 {
3258 cli_tunnel_actions[t].action = 0;
3259 if (a & CLI_TUN_KILL)
3260 {
3261 LOG(2, 0, t, "Dropping tunnel by CLI\n");
3262 tunnelshutdown(t, "Requested by administrator", 1, 0, 0);
3263 t_actions++;
3264 }
3265 }
3266 }
3267
3268 for (i = 0; i < r_slice; i++)
3269 {
3270 r++;
3271 if (r >= MAXRADIUS)
3272 r = 1;
3273
3274 if (!radius[r].state)
3275 continue;
3276
3277 if (radius[r].retry <= TIME)
3278 {
3279 radiusretry(r);
3280 r_actions++;
3281 }
3282 }
3283
3284 for (i = 0; i < s_slice; i++)
3285 {
3286 s++;
3287 if (s > config->cluster_highest_sessionid)
3288 s = 1;
3289
3290 if (!session[s].opened) // Session isn't in use
3291 continue;
3292
3293 // check for expired sessions
3294 if (session[s].die)
3295 {
3296 if (session[s].die <= TIME)
3297 {
3298 sessionkill(s, "Expired");
3299 s_actions++;
3300 }
3301 continue;
3302 }
3303
3304 // PPP timeouts
3305 if (sess_local[s].lcp.restart <= time_now)
3306 {
3307 int next_state = session[s].ppp.lcp;
3308 switch (session[s].ppp.lcp)
3309 {
3310 case RequestSent:
3311 case AckReceived:
3312 next_state = RequestSent;
3313
3314 case AckSent:
3315 if (sess_local[s].lcp.conf_sent < config->ppp_max_configure)
3316 {
3317 LOG(3, s, session[s].tunnel, "No ACK for LCP ConfigReq... resending\n");
3318 sendlcp(s, session[s].tunnel);
3319 change_state(s, lcp, next_state);
3320 }
3321 else
3322 {
3323 sessionshutdown(s, "No response to LCP ConfigReq.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3324 STAT(session_timeout);
3325 }
3326
3327 s_actions++;
3328 }
3329
3330 if (session[s].die)
3331 continue;
3332 }
3333
3334 if (sess_local[s].ipcp.restart <= time_now)
3335 {
3336 int next_state = session[s].ppp.ipcp;
3337 switch (session[s].ppp.ipcp)
3338 {
3339 case RequestSent:
3340 case AckReceived:
3341 next_state = RequestSent;
3342
3343 case AckSent:
3344 if (sess_local[s].ipcp.conf_sent < config->ppp_max_configure)
3345 {
3346 LOG(3, s, session[s].tunnel, "No ACK for IPCP ConfigReq... resending\n");
3347 sendipcp(s, session[s].tunnel);
3348 change_state(s, ipcp, next_state);
3349 }
3350 else
3351 {
3352 sessionshutdown(s, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3353 STAT(session_timeout);
3354 }
3355
3356 s_actions++;
3357 }
3358
3359 if (session[s].die)
3360 continue;
3361 }
3362
3363 if (sess_local[s].ipv6cp.restart <= time_now)
3364 {
3365 int next_state = session[s].ppp.ipv6cp;
3366 switch (session[s].ppp.ipv6cp)
3367 {
3368 case RequestSent:
3369 case AckReceived:
3370 next_state = RequestSent;
3371
3372 case AckSent:
3373 if (sess_local[s].ipv6cp.conf_sent < config->ppp_max_configure)
3374 {
3375 LOG(3, s, session[s].tunnel, "No ACK for IPV6CP ConfigReq... resending\n");
3376 sendipv6cp(s, session[s].tunnel);
3377 change_state(s, ipv6cp, next_state);
3378 }
3379 else
3380 {
3381 LOG(3, s, session[s].tunnel, "No ACK for IPV6CP ConfigReq\n");
3382 change_state(s, ipv6cp, Stopped);
3383 }
3384
3385 s_actions++;
3386 }
3387 }
3388
3389 if (sess_local[s].ccp.restart <= time_now)
3390 {
3391 int next_state = session[s].ppp.ccp;
3392 switch (session[s].ppp.ccp)
3393 {
3394 case RequestSent:
3395 case AckReceived:
3396 next_state = RequestSent;
3397
3398 case AckSent:
3399 if (sess_local[s].ccp.conf_sent < config->ppp_max_configure)
3400 {
3401 LOG(3, s, session[s].tunnel, "No ACK for CCP ConfigReq... resending\n");
3402 sendccp(s, session[s].tunnel);
3403 change_state(s, ccp, next_state);
3404 }
3405 else
3406 {
3407 LOG(3, s, session[s].tunnel, "No ACK for CCP ConfigReq\n");
3408 change_state(s, ccp, Stopped);
3409 }
3410
3411 s_actions++;
3412 }
3413 }
3414
3415 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3416 if (session[s].last_packet && (time_now - session[s].last_packet >= IDLE_TIMEOUT))
3417 {
3418 sessionshutdown(s, "No response to LCP ECHO requests.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3419 STAT(session_timeout);
3420 s_actions++;
3421 continue;
3422 }
3423
3424 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3425 if (session[s].ppp.phase >= Establish && (time_now - session[s].last_packet >= ECHO_TIMEOUT) &&
3426 (time_now - sess_local[s].last_echo >= ECHO_TIMEOUT))
3427 {
3428 uint8_t b[MAXETHER];
3429
3430 uint8_t *q = makeppp(b, sizeof(b), 0, 0, s, session[s].tunnel, PPPLCP, 1, 0, 0);
3431 if (!q) continue;
3432
3433 *q = EchoReq;
3434 *(uint8_t *)(q + 1) = (time_now % 255); // ID
3435 *(uint16_t *)(q + 2) = htons(8); // Length
3436 *(uint32_t *)(q + 4) = session[s].ppp.lcp == Opened ? htonl(session[s].magic) : 0; // Magic Number
3437
3438 LOG(4, s, session[s].tunnel, "No data in %d seconds, sending LCP ECHO\n",
3439 (int)(time_now - session[s].last_packet));
3440 tunnelsend(b, 24, session[s].tunnel); // send it
3441 sess_local[s].last_echo = time_now;
3442 s_actions++;
3443 }
3444
3445 // Drop sessions who have reached session_timeout seconds
3446 if (session[s].session_timeout)
3447 {
3448 bundleidt bid = session[s].bundle;
3449 if (bid)
3450 {
3451 if (time_now - bundle[bid].last_check >= 1)
3452 {
3453 bundle[bid].online_time += (time_now - bundle[bid].last_check) * bundle[bid].num_of_links;
3454 bundle[bid].last_check = time_now;
3455 if (bundle[bid].online_time >= session[s].session_timeout)
3456 {
3457 int ses;
3458 for (ses = bundle[bid].num_of_links - 1; ses >= 0; ses--)
3459 {
3460 sessionshutdown(bundle[bid].members[ses], "Session timeout", CDN_ADMIN_DISC, TERM_SESSION_TIMEOUT);
3461 s_actions++;
3462 continue;
3463 }
3464 }
3465 }
3466 }
3467 else if (time_now - session[s].opened >= session[s].session_timeout)
3468 {
3469 sessionshutdown(s, "Session timeout", CDN_ADMIN_DISC, TERM_SESSION_TIMEOUT);
3470 s_actions++;
3471 continue;
3472 }
3473 }
3474
3475 // Drop sessions who have reached idle_timeout seconds
3476 if (session[s].last_data && session[s].idle_timeout && (time_now - session[s].last_data >= session[s].idle_timeout))
3477 {
3478 sessionshutdown(s, "Idle Timeout Reached", CDN_ADMIN_DISC, TERM_IDLE_TIMEOUT);
3479 STAT(session_timeout);
3480 s_actions++;
3481 continue;
3482 }
3483
3484 // Check for actions requested from the CLI
3485 if ((a = cli_session_actions[s].action))
3486 {
3487 int send = 0;
3488
3489 cli_session_actions[s].action = 0;
3490 if (a & CLI_SESS_KILL)
3491 {
3492 LOG(2, s, session[s].tunnel, "Dropping session by CLI\n");
3493 sessionshutdown(s, "Requested by administrator.", CDN_ADMIN_DISC, TERM_ADMIN_RESET);
3494 a = 0; // dead, no need to check for other actions
3495 s_actions++;
3496 }
3497
3498 if (a & CLI_SESS_NOSNOOP)
3499 {
3500 LOG(2, s, session[s].tunnel, "Unsnooping session by CLI\n");
3501 session[s].snoop_ip = 0;
3502 session[s].snoop_port = 0;
3503 s_actions++;
3504 send++;
3505 }
3506 else if (a & CLI_SESS_SNOOP)
3507 {
3508 LOG(2, s, session[s].tunnel, "Snooping session by CLI (to %s:%u)\n",
3509 fmtaddr(cli_session_actions[s].snoop_ip, 0),
3510 cli_session_actions[s].snoop_port);
3511
3512 session[s].snoop_ip = cli_session_actions[s].snoop_ip;
3513 session[s].snoop_port = cli_session_actions[s].snoop_port;
3514 s_actions++;
3515 send++;
3516 }
3517
3518 if (a & CLI_SESS_NOTHROTTLE)
3519 {
3520 LOG(2, s, session[s].tunnel, "Un-throttling session by CLI\n");
3521 throttle_session(s, 0, 0);
3522 s_actions++;
3523 send++;
3524 }
3525 else if (a & CLI_SESS_THROTTLE)
3526 {
3527 LOG(2, s, session[s].tunnel, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3528 cli_session_actions[s].throttle_in,
3529 cli_session_actions[s].throttle_out);
3530
3531 throttle_session(s, cli_session_actions[s].throttle_in, cli_session_actions[s].throttle_out);
3532 s_actions++;
3533 send++;
3534 }
3535
3536 if (a & CLI_SESS_NOFILTER)
3537 {
3538 LOG(2, s, session[s].tunnel, "Un-filtering session by CLI\n");
3539 filter_session(s, 0, 0);
3540 s_actions++;
3541 send++;
3542 }
3543 else if (a & CLI_SESS_FILTER)
3544 {
3545 LOG(2, s, session[s].tunnel, "Filtering session by CLI (in=%d, out=%d)\n",
3546 cli_session_actions[s].filter_in,
3547 cli_session_actions[s].filter_out);
3548
3549 filter_session(s, cli_session_actions[s].filter_in, cli_session_actions[s].filter_out);
3550 s_actions++;
3551 send++;
3552 }
3553
3554 if (send)
3555 cluster_send_session(s);
3556 }
3557
3558 // RADIUS interim accounting
3559 if (config->radius_accounting && config->radius_interim > 0
3560 && session[s].ip && !session[s].walled_garden
3561 && !sess_local[s].radius // RADIUS already in progress
3562 && time_now - sess_local[s].last_interim >= config->radius_interim
3563 && session[s].flags & SESSION_STARTED)
3564 {
3565 int rad = radiusnew(s);
3566 if (!rad)
3567 {
3568 LOG(1, s, session[s].tunnel, "No free RADIUS sessions for Interim message\n");
3569 STAT(radius_overflow);
3570 continue;
3571 }
3572
3573 LOG(3, s, session[s].tunnel, "Sending RADIUS Interim for %s (%u)\n",
3574 session[s].user, session[s].unique_id);
3575
3576 radiussend(rad, RADIUSINTERIM);
3577 sess_local[s].last_interim = time_now;
3578 s_actions++;
3579 }
3580 }
3581
3582 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3583 t_slice, r_slice, s_slice, t_actions, r_actions, s_actions);
3584 }
3585
3586 //
3587 // Are we in the middle of a tunnel update, or radius
3588 // requests??
3589 //
3590 static int still_busy(void)
3591 {
3592 int i;
3593 static clockt last_talked = 0;
3594 static clockt start_busy_wait = 0;
3595
3596 if (!config->cluster_iam_master)
3597 {
3598 #ifdef BGP
3599 static time_t stopped_bgp = 0;
3600 if (bgp_configured)
3601 {
3602 if (!stopped_bgp)
3603 {
3604 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY);
3605
3606 for (i = 0; i < BGP_NUM_PEERS; i++)
3607 if (bgp_peers[i].state == Established)
3608 bgp_stop(&bgp_peers[i]);
3609
3610 stopped_bgp = time_now;
3611
3612 // we don't want to become master
3613 cluster_send_ping(0);
3614
3615 return 1;
3616 }
3617
3618 if (time_now < (stopped_bgp + QUIT_DELAY))
3619 return 1;
3620 }
3621 #endif /* BGP */
3622
3623 return 0;
3624 }
3625
3626 if (main_quit == QUIT_SHUTDOWN)
3627 {
3628 static int dropped = 0;
3629 if (!dropped)
3630 {
3631 int i;
3632
3633 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3634 for (i = 1; i < MAXTUNNEL; i++)
3635 if (tunnel[i].ip || tunnel[i].state)
3636 tunnelshutdown(i, "L2TPNS Closing", 6, 0, 0);
3637
3638 dropped = 1;
3639 }
3640 }
3641
3642 if (start_busy_wait == 0)
3643 start_busy_wait = TIME;
3644
3645 for (i = config->cluster_highest_tunnelid ; i > 0 ; --i)
3646 {
3647 if (!tunnel[i].controlc)
3648 continue;
3649
3650 if (last_talked != TIME)
3651 {
3652 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i);
3653 last_talked = TIME;
3654 }
3655 return 1;
3656 }
3657
3658 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3659 if (abs(TIME - start_busy_wait) > BUSY_WAIT_TIME)
3660 {
3661 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3662 return 0;
3663 }
3664
3665 for (i = 1; i < MAXRADIUS; i++)
3666 {
3667 if (radius[i].state == RADIUSNULL)
3668 continue;
3669 if (radius[i].state == RADIUSWAIT)
3670 continue;
3671
3672 if (last_talked != TIME)
3673 {
3674 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i, radius[i].session);
3675 last_talked = TIME;
3676 }
3677 return 1;
3678 }
3679
3680 return 0;
3681 }
3682
3683 #ifdef HAVE_EPOLL
3684 # include <sys/epoll.h>
3685 #else
3686 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3687 # include "fake_epoll.h"
3688 #endif
3689
3690 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3691 #define BASE_FDS 7
3692
3693 // additional polled fds
3694 #ifdef BGP
3695 # define EXTRA_FDS BGP_NUM_PEERS
3696 #else
3697 # define EXTRA_FDS 0
3698 #endif
3699
3700 // main loop - gets packets on tun or udp and processes them
3701 static void mainloop(void)
3702 {
3703 int i;
3704 uint8_t buf[65536];
3705 clockt next_cluster_ping = 0; // send initial ping immediately
3706 struct epoll_event events[BASE_FDS + RADIUS_FDS + EXTRA_FDS];
3707 int maxevent = sizeof(events)/sizeof(*events);
3708
3709 if ((epollfd = epoll_create(maxevent)) < 0)
3710 {
3711 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno));
3712 exit(1);
3713 }
3714
3715 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3716 clifd, cluster_sockfd, tunfd, udpfd, controlfd, daefd, nlfd);
3717
3718 /* setup our fds to poll for input */
3719 {
3720 static struct event_data d[BASE_FDS];
3721 struct epoll_event e;
3722
3723 e.events = EPOLLIN;
3724 i = 0;
3725
3726 if (clifd >= 0)
3727 {
3728 d[i].type = FD_TYPE_CLI;
3729 e.data.ptr = &d[i++];
3730 epoll_ctl(epollfd, EPOLL_CTL_ADD, clifd, &e);
3731 }
3732
3733 d[i].type = FD_TYPE_CLUSTER;
3734 e.data.ptr = &d[i++];
3735 epoll_ctl(epollfd, EPOLL_CTL_ADD, cluster_sockfd, &e);
3736
3737 d[i].type = FD_TYPE_TUN;
3738 e.data.ptr = &d[i++];
3739 epoll_ctl(epollfd, EPOLL_CTL_ADD, tunfd, &e);
3740
3741 d[i].type = FD_TYPE_UDP;
3742 e.data.ptr = &d[i++];
3743 epoll_ctl(epollfd, EPOLL_CTL_ADD, udpfd, &e);
3744
3745 d[i].type = FD_TYPE_CONTROL;
3746 e.data.ptr = &d[i++];
3747 epoll_ctl(epollfd, EPOLL_CTL_ADD, controlfd, &e);
3748
3749 d[i].type = FD_TYPE_DAE;
3750 e.data.ptr = &d[i++];
3751 epoll_ctl(epollfd, EPOLL_CTL_ADD, daefd, &e);
3752
3753 d[i].type = FD_TYPE_NETLINK;
3754 e.data.ptr = &d[i++];
3755 epoll_ctl(epollfd, EPOLL_CTL_ADD, nlfd, &e);
3756 }
3757
3758 #ifdef BGP
3759 signal(SIGPIPE, SIG_IGN);
3760 bgp_setup(config->as_number);
3761 if (config->bind_address)
3762 bgp_add_route(config->bind_address, 0xffffffff);
3763
3764 for (i = 0; i < BGP_NUM_PEERS; i++)
3765 {
3766 if (config->neighbour[i].name[0])
3767 bgp_start(&bgp_peers[i], config->neighbour[i].name,
3768 config->neighbour[i].as, config->neighbour[i].keepalive,
3769 config->neighbour[i].hold, 0); /* 0 = routing disabled */
3770 }
3771 #endif /* BGP */
3772
3773 while (!main_quit || still_busy())
3774 {
3775 int more = 0;
3776 int n;
3777
3778
3779 if (main_reload)
3780 {
3781 main_reload = 0;
3782 read_config_file();
3783 config->reload_config++;
3784 }
3785
3786 if (config->reload_config)
3787 {
3788 config->reload_config = 0;
3789 update_config();
3790 }
3791
3792 #ifdef BGP
3793 bgp_set_poll();
3794 #endif /* BGP */
3795
3796 n = epoll_wait(epollfd, events, maxevent, 100); // timeout 100ms (1/10th sec)
3797 STAT(select_called);
3798
3799 TIME = now(NULL);
3800 if (n < 0)
3801 {
3802 if (errno == EINTR ||
3803 errno == ECHILD) // EINTR was clobbered by sigchild_handler()
3804 continue;
3805
3806 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno));
3807 break; // exit
3808 }
3809
3810 if (n)
3811 {
3812 struct sockaddr_in addr;
3813 struct in_addr local;
3814 socklen_t alen;
3815 int c, s;
3816 int udp_ready = 0;
3817 int tun_ready = 0;
3818 int cluster_ready = 0;
3819 int udp_pkts = 0;
3820 int tun_pkts = 0;
3821 int cluster_pkts = 0;
3822 #ifdef BGP
3823 uint32_t bgp_events[BGP_NUM_PEERS];
3824 memset(bgp_events, 0, sizeof(bgp_events));
3825 #endif /* BGP */
3826
3827 for (c = n, i = 0; i < c; i++)
3828 {
3829 struct event_data *d = events[i].data.ptr;
3830
3831 switch (d->type)
3832 {
3833 case FD_TYPE_CLI: // CLI connections
3834 {
3835 int cli;
3836
3837 alen = sizeof(addr);
3838 if ((cli = accept(clifd, (struct sockaddr *)&addr, &alen)) >= 0)
3839 {
3840 cli_do(cli);
3841 close(cli);
3842 }
3843 else
3844 LOG(0, 0, 0, "accept error: %s\n", strerror(errno));
3845
3846 n--;
3847 break;
3848 }
3849
3850 // these are handled below, with multiple interleaved reads
3851 case FD_TYPE_CLUSTER: cluster_ready++; break;
3852 case FD_TYPE_TUN: tun_ready++; break;
3853 case FD_TYPE_UDP: udp_ready++; break;
3854
3855 case FD_TYPE_CONTROL: // nsctl commands
3856 alen = sizeof(addr);
3857 s = recvfromto(controlfd, buf, sizeof(buf), MSG_WAITALL, (struct sockaddr *) &addr, &alen, &local);
3858 if (s > 0) processcontrol(buf, s, &addr, alen, &local);
3859 n--;
3860 break;
3861
3862 case FD_TYPE_DAE: // DAE requests
3863 alen = sizeof(addr);
3864 s = recvfromto(daefd, buf, sizeof(buf), MSG_WAITALL, (struct sockaddr *) &addr, &alen, &local);
3865 if (s > 0) processdae(buf, s, &addr, alen, &local);
3866 n--;
3867 break;
3868
3869 case FD_TYPE_RADIUS: // RADIUS response
3870 alen = sizeof(addr);
3871 s = recvfrom(radfds[d->index], buf, sizeof(buf), MSG_WAITALL, (struct sockaddr *) &addr, &alen);
3872 if (s >= 0 && config->cluster_iam_master)
3873 {
3874 if (addr.sin_addr.s_addr == config->radiusserver[0] ||
3875 addr.sin_addr.s_addr == config->radiusserver[1])
3876 processrad(buf, s, d->index);
3877 else
3878 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3879 fmtaddr(addr.sin_addr.s_addr, 0));
3880 }
3881
3882 n--;
3883 break;
3884
3885 #ifdef BGP
3886 case FD_TYPE_BGP:
3887 bgp_events[d->index] = events[i].events;
3888 n--;
3889 break;
3890 #endif /* BGP */
3891
3892 case FD_TYPE_NETLINK:
3893 {
3894 struct nlmsghdr *nh = (struct nlmsghdr *)buf;
3895 s = netlink_recv(buf, sizeof(buf));
3896 if (nh->nlmsg_type == NLMSG_ERROR)
3897 {
3898 struct nlmsgerr *errmsg = NLMSG_DATA(nh);
3899 if (errmsg->error)
3900 {
3901 if (errmsg->msg.nlmsg_seq < min_initok_nlseqnum)
3902 {
3903 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg[nh->nlmsg_seq], strerror(-errmsg->error));
3904 exit(1);
3905 }
3906 else
3907
3908 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg->error));
3909 }
3910 // else it's a ack
3911 }
3912 else
3913 LOG(1, 0, 0, "Got a unknown netlink message: type %d seq %d flags %d\n", nh->nlmsg_type, nh->nlmsg_seq, nh->nlmsg_flags);
3914 n--;
3915 break;
3916 }
3917
3918 default:
3919 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d->type);
3920 }
3921 }
3922
3923 #ifdef BGP
3924 bgp_process(bgp_events);
3925 #endif /* BGP */
3926
3927 for (c = 0; n && c < config->multi_read_count; c++)
3928 {
3929 // L2TP
3930 if (udp_ready)
3931 {
3932 alen = sizeof(addr);
3933 if ((s = recvfrom(udpfd, buf, sizeof(buf), 0, (void *) &addr, &alen)) > 0)
3934 {
3935 processudp(buf, s, &addr);
3936 udp_pkts++;
3937 }
3938 else
3939 {
3940 udp_ready = 0;
3941 n--;
3942 }
3943 }
3944
3945 // incoming IP
3946 if (tun_ready)
3947 {
3948 if ((s = read(tunfd, buf, sizeof(buf))) > 0)
3949 {
3950 processtun(buf, s);
3951 tun_pkts++;
3952 }
3953 else
3954 {
3955 tun_ready = 0;
3956 n--;
3957 }
3958 }
3959
3960 // cluster
3961 if (cluster_ready)
3962 {
3963 alen = sizeof(addr);
3964 if ((s = recvfrom(cluster_sockfd, buf, sizeof(buf), MSG_WAITALL, (void *) &addr, &alen)) > 0)
3965 {
3966 processcluster(buf, s, addr.sin_addr.s_addr);
3967 cluster_pkts++;
3968 }
3969 else
3970 {
3971 cluster_ready = 0;
3972 n--;
3973 }
3974 }
3975 }
3976
3977 if (udp_pkts > 1 || tun_pkts > 1 || cluster_pkts > 1)
3978 STAT(multi_read_used);
3979
3980 if (c >= config->multi_read_count)
3981 {
3982 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3983 config->multi_read_count, udp_pkts, tun_pkts, cluster_pkts);
3984
3985 STAT(multi_read_exceeded);
3986 more++;
3987 }
3988 }
3989
3990 if (time_changed)
3991 {
3992 double Mbps = 1024.0 * 1024.0 / 8 * time_changed;
3993
3994 // Log current traffic stats
3995 snprintf(config->bandwidth, sizeof(config->bandwidth),
3996 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3997 (udp_rx / Mbps), (eth_tx / Mbps), (eth_rx / Mbps), (udp_tx / Mbps),
3998 ((udp_tx + udp_rx + eth_tx + eth_rx) / Mbps),
3999 udp_rx_pkt / time_changed, eth_rx_pkt / time_changed);
4000
4001 udp_tx = udp_rx = 0;
4002 udp_rx_pkt = eth_rx_pkt = 0;
4003 eth_tx = eth_rx = 0;
4004 time_changed = 0;
4005
4006 if (config->dump_speed)
4007 printf("%s\n", config->bandwidth);
4008
4009 // Update the internal time counter
4010 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
4011
4012 {
4013 // Run timer hooks
4014 struct param_timer p = { time_now };
4015 run_plugins(PLUGIN_TIMER, &p);
4016 }
4017 }
4018
4019 // Runs on every machine (master and slaves).
4020 if (next_cluster_ping <= TIME)
4021 {
4022 // Check to see which of the cluster is still alive..
4023
4024 cluster_send_ping(basetime); // Only does anything if we're a slave
4025 cluster_check_master(); // ditto.
4026
4027 cluster_heartbeat(); // Only does anything if we're a master.
4028 cluster_check_slaves(); // ditto.
4029
4030 master_update_counts(); // If we're a slave, send our byte counters to our master.
4031
4032 if (config->cluster_iam_master && !config->cluster_iam_uptodate)
4033 next_cluster_ping = TIME + 1; // out-of-date slaves, do fast updates
4034 else
4035 next_cluster_ping = TIME + config->cluster_hb_interval;
4036 }
4037
4038 if (!config->cluster_iam_master)
4039 continue;
4040
4041 // Run token bucket filtering queue..
4042 // Only run it every 1/10th of a second.
4043 {
4044 static clockt last_run = 0;
4045 if (last_run != TIME)
4046 {
4047 last_run = TIME;
4048 tbf_run_timer();
4049 }
4050 }
4051
4052 // Handle timeouts, retries etc.
4053 {
4054 static double last_clean = 0;
4055 double this_clean;
4056 double diff;
4057
4058 TIME = now(&this_clean);
4059 diff = this_clean - last_clean;
4060
4061 // Run during idle time (after we've handled
4062 // all incoming packets) or every 1/10th sec
4063 if (!more || diff > 0.1)
4064 {
4065 regular_cleanups(diff);
4066 last_clean = this_clean;
4067 }
4068 }
4069
4070 if (*config->accounting_dir)
4071 {
4072 static clockt next_acct = 0;
4073 static clockt next_shut_acct = 0;
4074
4075 if (next_acct <= TIME)
4076 {
4077 // Dump accounting data
4078 next_acct = TIME + ACCT_TIME;
4079 next_shut_acct = TIME + ACCT_SHUT_TIME;
4080 dump_acct_info(1);
4081 }
4082 else if (next_shut_acct <= TIME)
4083 {
4084 // Dump accounting data for shutdown sessions
4085 next_shut_acct = TIME + ACCT_SHUT_TIME;
4086 if (shut_acct_n)
4087 dump_acct_info(0);
4088 }
4089 }
4090 }
4091
4092 // Are we the master and shutting down??
4093 if (config->cluster_iam_master)
4094 cluster_heartbeat(); // Flush any queued changes..
4095
4096 // Ok. Notify everyone we're shutting down. If we're
4097 // the master, this will force an election.
4098 cluster_send_ping(0);
4099
4100 //
4101 // Important!!! We MUST not process any packets past this point!
4102 LOG(1, 0, 0, "Shutdown complete\n");
4103 }
4104
4105 static void stripdomain(char *host)
4106 {
4107 char *p;
4108
4109 if ((p = strchr(host, '.')))
4110 {
4111 char *domain = 0;
4112 char _domain[1024];
4113
4114 // strip off domain
4115 FILE *resolv = fopen("/etc/resolv.conf", "r");
4116 if (resolv)
4117 {
4118 char buf[1024];
4119 char *b;
4120
4121 while (fgets(buf, sizeof(buf), resolv))
4122 {
4123 if (strncmp(buf, "domain", 6) && strncmp(buf, "search", 6))
4124 continue;
4125
4126 if (!isspace(buf[6]))
4127 continue;
4128
4129 b = buf + 7;
4130 while (isspace(*b)) b++;
4131
4132 if (*b)
4133 {
4134 char *d = b;
4135 while (*b && !isspace(*b)) b++;
4136 *b = 0;
4137 if (buf[0] == 'd') // domain is canonical
4138 {
4139 domain = d;
4140 break;
4141 }
4142
4143 // first search line
4144 if (!domain)
4145 {
4146 // hold, may be subsequent domain line
4147 strncpy(_domain, d, sizeof(_domain))[sizeof(_domain)-1] = 0;
4148 domain = _domain;
4149 }
4150 }
4151 }
4152
4153 fclose(resolv);
4154 }
4155
4156 if (domain)
4157 {
4158 int hl = strlen(host);
4159 int dl = strlen(domain);
4160 if (dl < hl && host[hl - dl - 1] == '.' && !strcmp(host + hl - dl, domain))
4161 host[hl -dl - 1] = 0;
4162 }
4163 else
4164 {
4165 *p = 0; // everything after first dot
4166 }
4167 }
4168 }
4169
4170 // Init data structures
4171 static void initdata(int optdebug, char *optconfig)
4172 {
4173 int i;
4174
4175 if (!(config = shared_malloc(sizeof(configt))))
4176 {
4177 fprintf(stderr, "Error doing malloc for configuration: %s\n", strerror(errno));
4178 exit(1);
4179 }
4180
4181 memset(config, 0, sizeof(configt));
4182 time(&config->start_time);
4183 strncpy(config->config_file, optconfig, strlen(optconfig));
4184 config->debug = optdebug;
4185 config->num_tbfs = MAXTBFS;
4186 config->rl_rate = 28; // 28kbps
4187 config->cluster_mcast_ttl = 1;
4188 config->cluster_master_min_adv = 1;
4189 config->ppp_restart_time = 3;
4190 config->ppp_max_configure = 10;
4191 config->ppp_max_failure = 5;
4192 config->kill_timedout_sessions = 1;
4193 strcpy(config->random_device, RANDOMDEVICE);
4194
4195 log_stream = stderr;
4196
4197 #ifdef RINGBUFFER
4198 if (!(ringbuffer = shared_malloc(sizeof(struct Tringbuffer))))
4199 {
4200 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno));
4201 exit(1);
4202 }
4203 memset(ringbuffer, 0, sizeof(struct Tringbuffer));
4204 #endif
4205
4206 if (!(_statistics = shared_malloc(sizeof(struct Tstats))))
4207 {
4208 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno));
4209 exit(1);
4210 }
4211 if (!(tunnel = shared_malloc(sizeof(tunnelt) * MAXTUNNEL)))
4212 {
4213 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno));
4214 exit(1);
4215 }
4216 if (!(bundle = shared_malloc(sizeof(bundlet) * MAXBUNDLE)))
4217 {
4218 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno));
4219 exit(1);
4220 }
4221 if (!(frag = shared_malloc(sizeof(fragmentationt) * MAXBUNDLE)))
4222 {
4223 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno));
4224 exit(1);
4225 }
4226 if (!(session = shared_malloc(sizeof(sessiont) * MAXSESSION)))
4227 {
4228 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno));
4229 exit(1);
4230 }
4231
4232 if (!(sess_local = shared_malloc(sizeof(sessionlocalt) * MAXSESSION)))
4233 {
4234 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno));
4235 exit(1);
4236 }
4237
4238 if (!(radius = shared_malloc(sizeof(radiust) * MAXRADIUS)))
4239 {
4240 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno));
4241 exit(1);
4242 }
4243
4244 if (!(ip_address_pool = shared_malloc(sizeof(ippoolt) * MAXIPPOOL)))
4245 {
4246 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno));
4247 exit(1);
4248 }
4249
4250 if (!(ip_filters = shared_malloc(sizeof(ip_filtert) * MAXFILTER)))
4251 {
4252 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno));
4253 exit(1);
4254 }
4255 memset(ip_filters, 0, sizeof(ip_filtert) * MAXFILTER);
4256
4257 if (!(cli_session_actions = shared_malloc(sizeof(struct cli_session_actions) * MAXSESSION)))
4258 {
4259 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno));
4260 exit(1);
4261 }
4262 memset(cli_session_actions, 0, sizeof(struct cli_session_actions) * MAXSESSION);
4263
4264 if (!(cli_tunnel_actions = shared_malloc(sizeof(struct cli_tunnel_actions) * MAXSESSION)))
4265 {
4266 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno));
4267 exit(1);
4268 }
4269 memset(cli_tunnel_actions, 0, sizeof(struct cli_tunnel_actions) * MAXSESSION);
4270
4271 memset(tunnel, 0, sizeof(tunnelt) * MAXTUNNEL);
4272 memset(bundle, 0, sizeof(bundlet) * MAXBUNDLE);
4273 memset(session, 0, sizeof(sessiont) * MAXSESSION);
4274 memset(radius, 0, sizeof(radiust) * MAXRADIUS);
4275 memset(ip_address_pool, 0, sizeof(ippoolt) * MAXIPPOOL);
4276
4277 // Put all the sessions on the free list marked as undefined.
4278 for (i = 1; i < MAXSESSION; i++)
4279 {
4280 session[i].next = i + 1;
4281 session[i].tunnel = T_UNDEF; // mark it as not filled in.
4282 }
4283 session[MAXSESSION - 1].next = 0;
4284 sessionfree = 1;
4285
4286 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4287 for (i = 1; i < MAXTUNNEL; i++)
4288 tunnel[i].state = TUNNELUNDEF; // mark it as not filled in.
4289
4290 for (i = 1; i < MAXBUNDLE; i++) {
4291 bundle[i].state = BUNDLEUNDEF;
4292 }
4293
4294 if (!*hostname)
4295 {
4296 // Grab my hostname unless it's been specified
4297 gethostname(hostname, sizeof(hostname));
4298 stripdomain(hostname);
4299 }
4300
4301 _statistics->start_time = _statistics->last_reset = time(NULL);
4302
4303 #ifdef BGP
4304 if (!(bgp_peers = shared_malloc(sizeof(struct bgp_peer) * BGP_NUM_PEERS)))
4305 {
4306 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno));
4307 exit(1);
4308 }
4309 #endif /* BGP */
4310 }
4311
4312 static int assign_ip_address(sessionidt s)
4313 {
4314 uint32_t i;
4315 int best = -1;
4316 time_t best_time = time_now;
4317 char *u = session[s].user;
4318 char reuse = 0;
4319
4320
4321 CSTAT(assign_ip_address);
4322
4323 for (i = 1; i < ip_pool_size; i++)
4324 {
4325 if (!ip_address_pool[i].address || ip_address_pool[i].assigned)
4326 continue;
4327
4328 if (!session[s].walled_garden && ip_address_pool[i].user[0] && !strcmp(u, ip_address_pool[i].user))
4329 {
4330 best = i;
4331 reuse = 1;
4332 break;
4333 }
4334
4335 if (ip_address_pool[i].last < best_time)
4336 {
4337 best = i;
4338 if (!(best_time = ip_address_pool[i].last))
4339 break; // never used, grab this one
4340 }
4341 }
4342
4343 if (best < 0)
4344 {
4345 LOG(0, s, session[s].tunnel, "assign_ip_address(): out of addresses\n");
4346 return 0;
4347 }
4348
4349 session[s].ip = ip_address_pool[best].address;
4350 session[s].ip_pool_index = best;
4351 ip_address_pool[best].assigned = 1;
4352 ip_address_pool[best].last = time_now;
4353 ip_address_pool[best].session = s;
4354 if (session[s].walled_garden)
4355 /* Don't track addresses of users in walled garden (note: this
4356 means that their address isn't "sticky" even if they get
4357 un-gardened). */
4358 ip_address_pool[best].user[0] = 0;
4359 else
4360 strncpy(ip_address_pool[best].user, u, sizeof(ip_address_pool[best].user) - 1);
4361
4362 STAT(ip_allocated);
4363 LOG(4, s, session[s].tunnel, "assign_ip_address(): %s ip address %d from pool\n",
4364 reuse ? "Reusing" : "Allocating", best);
4365
4366 return 1;
4367 }
4368
4369 static void free_ip_address(sessionidt s)
4370 {
4371 int i = session[s].ip_pool_index;
4372
4373
4374 CSTAT(free_ip_address);
4375
4376 if (!session[s].ip)
4377 return; // what the?
4378
4379 if (i < 0) // Is this actually part of the ip pool?
4380 i = 0;
4381
4382 STAT(ip_freed);
4383 cache_ipmap(session[s].ip, -i); // Change the mapping to point back to the ip pool index.
4384 session[s].ip = 0;
4385 ip_address_pool[i].assigned = 0;
4386 ip_address_pool[i].session = 0;
4387 ip_address_pool[i].last = time_now;
4388 }
4389
4390 //
4391 // Fsck the address pool against the session table.
4392 // Normally only called when we become a master.
4393 //
4394 // This isn't perfect: We aren't keep tracking of which
4395 // users used to have an IP address.
4396 //
4397 void rebuild_address_pool(void)
4398 {
4399 int i;
4400
4401 //
4402 // Zero the IP pool allocation, and build
4403 // a map from IP address to pool index.
4404 for (i = 1; i < MAXIPPOOL; ++i)
4405 {
4406 ip_address_pool[i].assigned = 0;
4407 ip_address_pool[i].session = 0;
4408 if (!ip_address_pool[i].address)
4409 continue;
4410
4411 cache_ipmap(ip_address_pool[i].address, -i); // Map pool IP to pool index.
4412 }
4413
4414 for (i = 0; i < MAXSESSION; ++i)
4415 {
4416 int ipid;
4417 if (!(session[i].opened && session[i].ip))
4418 continue;
4419
4420 ipid = - lookup_ipmap(htonl(session[i].ip));
4421
4422 if (session[i].ip_pool_index < 0)
4423 {
4424 // Not allocated out of the pool.
4425 if (ipid < 1) // Not found in the pool either? good.
4426 continue;
4427
4428 LOG(0, i, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4429 i, fmtaddr(session[i].ip, 0), ipid);
4430
4431 // Fall through and process it as part of the pool.
4432 }
4433
4434
4435 if (ipid > MAXIPPOOL || ipid < 0)
4436 {
4437 LOG(0, i, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i, ipid);
4438 ipid = -1;
4439 session[i].ip_pool_index = ipid;
4440 continue;
4441 }
4442
4443 ip_address_pool[ipid].assigned = 1;
4444 ip_address_pool[ipid].session = i;
4445 ip_address_pool[ipid].last = time_now;
4446 strncpy(ip_address_pool[ipid].user, session[i].user, sizeof(ip_address_pool[ipid].user) - 1);
4447 session[i].ip_pool_index = ipid;
4448 cache_ipmap(session[i].ip, i); // Fix the ip map.
4449 }
4450 }
4451
4452 //
4453 // Fix the address pool to match a changed session.
4454 // (usually when the master sends us an update).
4455 static void fix_address_pool(int sid)
4456 {
4457 int ipid;
4458
4459 ipid = session[sid].ip_pool_index;
4460
4461 if (ipid > ip_pool_size)
4462 return; // Ignore it. rebuild_address_pool will fix it up.
4463
4464 if (ip_address_pool[ipid].address != session[sid].ip)
4465 return; // Just ignore it. rebuild_address_pool will take care of it.
4466
4467 ip_address_pool[ipid].assigned = 1;
4468 ip_address_pool[ipid].session = sid;
4469 ip_address_pool[ipid].last = time_now;
4470 strncpy(ip_address_pool[ipid].user, session[sid].user, sizeof(ip_address_pool[ipid].user) - 1);
4471 }
4472
4473 //
4474 // Add a block of addresses to the IP pool to hand out.
4475 //
4476 static void add_to_ip_pool(in_addr_t addr, in_addr_t mask)
4477 {
4478 int i;
4479 if (mask == 0)
4480 mask = 0xffffffff; // Host route only.
4481
4482 addr &= mask;
4483
4484 if (ip_pool_size >= MAXIPPOOL) // Pool is full!
4485 return ;
4486
4487 for (i = addr ;(i & mask) == addr; ++i)
4488 {
4489 if ((i & 0xff) == 0 || (i&0xff) == 255)
4490 continue; // Skip 0 and broadcast addresses.
4491
4492 ip_address_pool[ip_pool_size].address = i;
4493 ip_address_pool[ip_pool_size].assigned = 0;
4494 ++ip_pool_size;
4495 if (ip_pool_size >= MAXIPPOOL)
4496 {
4497 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr), 0));
4498 return;
4499 }
4500 }
4501 }
4502
4503 // Initialize the IP address pool
4504 static void initippool()
4505 {
4506 FILE *f;
4507 char *p;
4508 char buf[4096];
4509 memset(ip_address_pool, 0, sizeof(ip_address_pool));
4510
4511 if (!(f = fopen(IPPOOLFILE, "r")))
4512 {
4513 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE ": %s\n", strerror(errno));
4514 exit(1);
4515 }
4516
4517 while (ip_pool_size < MAXIPPOOL && fgets(buf, 4096, f))
4518 {
4519 char *pool = buf;
4520 buf[4095] = 0; // Force it to be zero terminated/
4521
4522 if (*buf == '#' || *buf == '\n')
4523 continue; // Skip comments / blank lines
4524 if ((p = (char *)strrchr(buf, '\n'))) *p = 0;
4525 if ((p = (char *)strchr(buf, ':')))
4526 {
4527 in_addr_t src;
4528 *p = '\0';
4529 src = inet_addr(buf);
4530 if (src == INADDR_NONE)
4531 {
4532 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf);
4533 exit(1);
4534 }
4535 // This entry is for a specific IP only
4536 if (src != config->bind_address)
4537 continue;
4538 *p = ':';
4539 pool = p+1;
4540 }
4541 if ((p = (char *)strchr(pool, '/')))
4542 {
4543 // It's a range
4544 int numbits = 0;
4545 in_addr_t start = 0, mask = 0;
4546
4547 LOG(2, 0, 0, "Adding IP address range %s\n", buf);
4548 *p++ = 0;
4549 if (!*p || !(numbits = atoi(p)))
4550 {
4551 LOG(0, 0, 0, "Invalid pool range %s\n", buf);
4552 continue;
4553 }
4554 start = ntohl(inet_addr(pool));
4555 mask = (in_addr_t) (pow(2, numbits) - 1) << (32 - numbits);
4556
4557 // Add a static route for this pool
4558 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
4559 fmtaddr(htonl(start), 0), 32 + mask);
4560
4561 routeset(0, start, mask, 0, 1);
4562
4563 add_to_ip_pool(start, mask);
4564 }
4565 else
4566 {
4567 // It's a single ip address
4568 add_to_ip_pool(ntohl(inet_addr(pool)), 0);
4569 }
4570 }
4571 fclose(f);
4572 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size - 1);
4573 }
4574
4575 void snoop_send_packet(uint8_t *packet, uint16_t size, in_addr_t destination, uint16_t port)
4576 {
4577 struct sockaddr_in snoop_addr = {0};
4578 if (!destination || !port || snoopfd <= 0 || size <= 0 || !packet)
4579 return;
4580
4581 snoop_addr.sin_family = AF_INET;
4582 snoop_addr.sin_addr.s_addr = destination;
4583 snoop_addr.sin_port = ntohs(port);
4584
4585 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size,
4586 fmtaddr(snoop_addr.sin_addr.s_addr, 0),
4587 htons(snoop_addr.sin_port));
4588
4589 if (sendto(snoopfd, packet, size, MSG_DONTWAIT | MSG_NOSIGNAL, (void *) &snoop_addr, sizeof(snoop_addr)) < 0)
4590 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno));
4591
4592 STAT(packets_snooped);
4593 }
4594
4595 static int dump_session(FILE **f, sessiont *s)
4596 {
4597 if (!s->opened || !s->ip || !(s->cin_delta || s->cout_delta) || !*s->user || s->walled_garden)
4598 return 1;
4599
4600 if (!*f)
4601 {
4602 char filename[1024];
4603 char timestr[64];
4604 time_t now = time(NULL);
4605
4606 strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&now));
4607 snprintf(filename, sizeof(filename), "%s/%s", config->accounting_dir, timestr);
4608
4609 if (!(*f = fopen(filename, "w")))
4610 {
4611 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename, strerror(errno));
4612 return 0;
4613 }
4614
4615 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename);
4616 fprintf(*f, "# dslwatch.pl dump file V1.01\n"
4617 "# host: %s\n"
4618 "# endpoint: %s\n"
4619 "# time: %ld\n"
4620 "# uptime: %ld\n"
4621 "# format: username ip qos uptxoctets downrxoctets\n",
4622 hostname,
4623 fmtaddr(config->bind_address ? config->bind_address : my_address, 0),
4624 now,
4625 now - basetime);
4626 }
4627
4628 LOG(4, 0, 0, "Dumping accounting information for %s\n", s->user);
4629 fprintf(*f, "%s %s %d %u %u\n",
4630 s->user, // username
4631 fmtaddr(htonl(s->ip), 0), // ip
4632 (s->throttle_in || s->throttle_out) ? 2 : 1, // qos
4633 (uint32_t) s->cin_delta, // uptxoctets
4634 (uint32_t) s->cout_delta); // downrxoctets
4635
4636 s->cin_delta = s->cout_delta = 0;
4637
4638 return 1;
4639 }
4640
4641 static void dump_acct_info(int all)
4642 {
4643 int i;
4644 FILE *f = NULL;
4645
4646
4647 CSTAT(dump_acct_info);
4648
4649 if (shut_acct_n)
4650 {
4651 for (i = 0; i < shut_acct_n; i++)
4652 dump_session(&f, &shut_acct[i]);
4653
4654 shut_acct_n = 0;
4655 }
4656
4657 if (all)
4658 for (i = 1; i <= config->cluster_highest_sessionid; i++)
4659 dump_session(&f, &session[i]);
4660
4661 if (f)
4662 fclose(f);
4663 }
4664
4665 // Main program
4666 int main(int argc, char *argv[])
4667 {
4668 int i;
4669 int optdebug = 0;
4670 char *optconfig = CONFIGFILE;
4671
4672 time(&basetime); // start clock
4673
4674 // scan args
4675 while ((i = getopt(argc, argv, "dvc:h:")) >= 0)
4676 {
4677 switch (i)
4678 {
4679 case 'd':
4680 if (fork()) exit(0);
4681 setsid();
4682 freopen("/dev/null", "r", stdin);
4683 freopen("/dev/null", "w", stdout);
4684 freopen("/dev/null", "w", stderr);
4685 break;
4686 case 'v':
4687 optdebug++;
4688 break;
4689 case 'c':
4690 optconfig = optarg;
4691 break;
4692 case 'h':
4693 snprintf(hostname, sizeof(hostname), "%s", optarg);
4694 break;
4695 default:
4696 printf("Args are:\n"
4697 "\t-d\t\tDetach from terminal\n"
4698 "\t-c <file>\tConfig file\n"
4699 "\t-h <hostname>\tForce hostname\n"
4700 "\t-v\t\tDebug\n");
4701
4702 return (0);
4703 break;
4704 }
4705 }
4706
4707 // Start the timer routine off
4708 time(&time_now);
4709 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
4710
4711 initplugins();
4712 initdata(optdebug, optconfig);
4713
4714 init_cli(hostname);
4715 read_config_file();
4716 update_config();
4717 init_tbf(config->num_tbfs);
4718
4719 LOG(0, 0, 0, "L2TPNS version " VERSION "\n");
4720 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4721 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4722 {
4723 struct rlimit rlim;
4724 rlim.rlim_cur = RLIM_INFINITY;
4725 rlim.rlim_max = RLIM_INFINITY;
4726 // Remove the maximum core size
4727 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
4728 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno));
4729
4730 // Make core dumps go to /tmp
4731 chdir("/tmp");
4732 }
4733
4734 if (config->scheduler_fifo)
4735 {
4736 int ret;
4737 struct sched_param params = {0};
4738 params.sched_priority = 1;
4739
4740 if (get_nprocs() < 2)
4741 {
4742 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4743 config->scheduler_fifo = 0;
4744 }
4745 else
4746 {
4747 if ((ret = sched_setscheduler(0, SCHED_FIFO, &params)) == 0)
4748 {
4749 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4750 }
4751 else
4752 {
4753 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno));
4754 config->scheduler_fifo = 0;
4755 }
4756 }
4757 }
4758
4759 initnetlink();
4760
4761 /* Set up the cluster communications port. */
4762 if (cluster_init() < 0)
4763 exit(1);
4764
4765 inittun();
4766 LOG(1, 0, 0, "Set up on interface %s\n", config->tundevice);
4767
4768 initudp();
4769 initrad();
4770 initippool();
4771
4772 // seed prng
4773 {
4774 unsigned seed = time_now ^ getpid();
4775 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed);
4776 srand(seed);
4777 }
4778
4779 signal(SIGHUP, sighup_handler);
4780 signal(SIGCHLD, sigchild_handler);
4781 signal(SIGTERM, shutdown_handler);
4782 signal(SIGINT, shutdown_handler);
4783 signal(SIGQUIT, shutdown_handler);
4784
4785 // Prevent us from getting paged out
4786 if (config->lock_pages)
4787 {
4788 if (!mlockall(MCL_CURRENT))
4789 LOG(1, 0, 0, "Locking pages into memory\n");
4790 else
4791 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno));
4792 }
4793
4794 mainloop();
4795
4796 /* remove plugins (so cleanup code gets run) */
4797 plugins_done();
4798
4799 // Remove the PID file if we wrote it
4800 if (config->wrote_pid && *config->pid_file == '/')
4801 unlink(config->pid_file);
4802
4803 /* kill CLI children */
4804 signal(SIGTERM, SIG_IGN);
4805 kill(0, SIGTERM);
4806 return 0;
4807 }
4808
4809 static void sighup_handler(int sig)
4810 {
4811 main_reload++;
4812 }
4813
4814 static void shutdown_handler(int sig)
4815 {
4816 main_quit = (sig == SIGQUIT) ? QUIT_SHUTDOWN : QUIT_FAILOVER;
4817 }
4818
4819 static void sigchild_handler(int sig)
4820 {
4821 while (waitpid(-1, NULL, WNOHANG) > 0)
4822 ;
4823 }
4824
4825 static void build_chap_response(uint8_t *challenge, uint8_t id, uint16_t challenge_length, uint8_t **challenge_response)
4826 {
4827 MD5_CTX ctx;
4828 *challenge_response = NULL;
4829
4830 if (!*config->l2tp_secret)
4831 {
4832 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4833 return;
4834 }
4835
4836 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4837
4838 *challenge_response = calloc(17, 1);
4839
4840 MD5_Init(&ctx);
4841 MD5_Update(&ctx, &id, 1);
4842 MD5_Update(&ctx, config->l2tp_secret, strlen(config->l2tp_secret));
4843 MD5_Update(&ctx, challenge, challenge_length);
4844 MD5_Final(*challenge_response, &ctx);
4845
4846 return;
4847 }
4848
4849 static int facility_value(char *name)
4850 {
4851 int i;
4852 for (i = 0; facilitynames[i].c_name; i++)
4853 {
4854 if (strcmp(facilitynames[i].c_name, name) == 0)
4855 return facilitynames[i].c_val;
4856 }
4857 return 0;
4858 }
4859
4860 static void update_config()
4861 {
4862 int i;
4863 char *p;
4864 static int timeout = 0;
4865 static int interval = 0;
4866
4867 // Update logging
4868 closelog();
4869 syslog_log = 0;
4870 if (log_stream)
4871 {
4872 if (log_stream != stderr)
4873 fclose(log_stream);
4874
4875 log_stream = NULL;
4876 }
4877
4878 if (*config->log_filename)
4879 {
4880 if (strstr(config->log_filename, "syslog:") == config->log_filename)
4881 {
4882 char *p = config->log_filename + 7;
4883 if (*p)
4884 {
4885 openlog("l2tpns", LOG_PID, facility_value(p));
4886 syslog_log = 1;
4887 }
4888 }
4889 else if (strchr(config->log_filename, '/') == config->log_filename)
4890 {
4891 if ((log_stream = fopen((char *)(config->log_filename), "a")))
4892 {
4893 fseek(log_stream, 0, SEEK_END);
4894 setbuf(log_stream, NULL);
4895 }
4896 else
4897 {
4898 log_stream = stderr;
4899 setbuf(log_stream, NULL);
4900 }
4901 }
4902 }
4903 else
4904 {
4905 log_stream = stderr;
4906 setbuf(log_stream, NULL);
4907 }
4908
4909 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4910 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4911
4912 if (config->l2tp_mtu <= 0) config->l2tp_mtu = 1500; // ethernet default
4913 else if (config->l2tp_mtu < MINMTU) config->l2tp_mtu = MINMTU;
4914 else if (config->l2tp_mtu > MAXMTU) config->l2tp_mtu = MAXMTU;
4915
4916 // reset MRU/MSS globals
4917 MRU = config->l2tp_mtu - L2TP_HDRS;
4918 if (MRU > PPPoE_MRU)
4919 MRU = PPPoE_MRU;
4920
4921 MSS = MRU - TCP_HDRS;
4922
4923 // Update radius
4924 config->numradiusservers = 0;
4925 for (i = 0; i < MAXRADSERVER; i++)
4926 if (config->radiusserver[i])
4927 {
4928 config->numradiusservers++;
4929 // Set radius port: if not set, take the port from the
4930 // first radius server. For the first radius server,
4931 // take the #defined default value from l2tpns.h
4932
4933 // test twice, In case someone works with
4934 // a secondary radius server without defining
4935 // a primary one, this will work even then.
4936 if (i > 0 && !config->radiusport[i])
4937 config->radiusport[i] = config->radiusport[i-1];
4938 if (!config->radiusport[i])
4939 config->radiusport[i] = RADPORT;
4940 }
4941
4942 if (!config->numradiusservers)
4943 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4944
4945 // parse radius_authtypes_s
4946 config->radius_authtypes = config->radius_authprefer = 0;
4947 p = config->radius_authtypes_s;
4948 while (p && *p)
4949 {
4950 char *s = strpbrk(p, " \t,");
4951 int type = 0;
4952
4953 if (s)
4954 {
4955 *s++ = 0;
4956 while (*s == ' ' || *s == '\t')
4957 s++;
4958
4959 if (!*s)
4960 s = 0;
4961 }
4962
4963 if (!strncasecmp("chap", p, strlen(p)))
4964 type = AUTHCHAP;
4965 else if (!strncasecmp("pap", p, strlen(p)))
4966 type = AUTHPAP;
4967 else
4968 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p);
4969
4970 config->radius_authtypes |= type;
4971 if (!config->radius_authprefer)
4972 config->radius_authprefer = type;
4973
4974 p = s;
4975 }
4976
4977 if (!config->radius_authtypes)
4978 {
4979 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4980 config->radius_authtypes = config->radius_authprefer = AUTHPAP;
4981 }
4982
4983 // normalise radius_authtypes_s
4984 if (config->radius_authprefer == AUTHPAP)
4985 {
4986 strcpy(config->radius_authtypes_s, "pap");
4987 if (config->radius_authtypes & AUTHCHAP)
4988 strcat(config->radius_authtypes_s, ", chap");
4989 }
4990 else
4991 {
4992 strcpy(config->radius_authtypes_s, "chap");
4993 if (config->radius_authtypes & AUTHPAP)
4994 strcat(config->radius_authtypes_s, ", pap");
4995 }
4996
4997 if (!config->radius_dae_port)
4998 config->radius_dae_port = DAEPORT;
4999
5000 // re-initialise the random number source
5001 initrandom(config->random_device);
5002
5003 // Update plugins
5004 for (i = 0; i < MAXPLUGINS; i++)
5005 {
5006 if (strcmp(config->plugins[i], config->old_plugins[i]) == 0)
5007 continue;
5008
5009 if (*config->plugins[i])
5010 {
5011 // Plugin added
5012 add_plugin(config->plugins[i]);
5013 }
5014 else if (*config->old_plugins[i])
5015 {
5016 // Plugin removed
5017 remove_plugin(config->old_plugins[i]);
5018 }
5019 }
5020
5021 // Guest change
5022 guest_accounts_num = 0;
5023 char *p2 = config->guest_user;
5024 while (p2 && *p2)
5025 {
5026 char *s = strpbrk(p2, " \t,");
5027 if (s)
5028 {
5029 *s++ = 0;
5030 while (*s == ' ' || *s == '\t')
5031 s++;
5032
5033 if (!*s)
5034 s = 0;
5035 }
5036
5037 strcpy(guest_users[guest_accounts_num], p2);
5038 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num, guest_users[guest_accounts_num]);
5039 guest_accounts_num++;
5040 p2 = s;
5041 }
5042 // Rebuild the guest_user array
5043 strcpy(config->guest_user, "");
5044 int ui = 0;
5045 for (ui=0; ui<guest_accounts_num; ui++)
5046 {
5047 strcat(config->guest_user, guest_users[ui]);
5048 if (ui<guest_accounts_num-1)
5049 {
5050 strcat(config->guest_user, ",");
5051 }
5052 }
5053
5054
5055 memcpy(config->old_plugins, config->plugins, sizeof(config->plugins));
5056 if (!config->multi_read_count) config->multi_read_count = 10;
5057 if (!config->cluster_address) config->cluster_address = inet_addr(DEFAULT_MCAST_ADDR);
5058 if (!*config->cluster_interface)
5059 strncpy(config->cluster_interface, DEFAULT_MCAST_INTERFACE, sizeof(config->cluster_interface) - 1);
5060
5061 if (!config->cluster_hb_interval)
5062 config->cluster_hb_interval = PING_INTERVAL; // Heartbeat every 0.5 seconds.
5063
5064 if (!config->cluster_hb_timeout)
5065 config->cluster_hb_timeout = HB_TIMEOUT; // 10 missed heartbeat triggers an election.
5066
5067 if (interval != config->cluster_hb_interval || timeout != config->cluster_hb_timeout)
5068 {
5069 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5070 // late, ensure we're sufficiently larger than that
5071 int t = 4 * config->cluster_hb_interval + 11;
5072
5073 if (config->cluster_hb_timeout < t)
5074 {
5075 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config->cluster_hb_timeout, t);
5076 config->cluster_hb_timeout = t;
5077 }
5078
5079 // Push timing changes to the slaves immediately if we're the master
5080 if (config->cluster_iam_master)
5081 cluster_heartbeat();
5082
5083 interval = config->cluster_hb_interval;
5084 timeout = config->cluster_hb_timeout;
5085 }
5086
5087 // Write PID file
5088 if (*config->pid_file == '/' && !config->wrote_pid)
5089 {
5090 FILE *f;
5091 if ((f = fopen(config->pid_file, "w")))
5092 {
5093 fprintf(f, "%d\n", getpid());
5094 fclose(f);
5095 config->wrote_pid = 1;
5096 }
5097 else
5098 {
5099 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config->pid_file, strerror(errno));
5100 }
5101 }
5102 }
5103
5104 static void read_config_file()
5105 {
5106 FILE *f;
5107
5108 if (!config->config_file) return;
5109 if (!(f = fopen(config->config_file, "r")))
5110 {
5111 fprintf(stderr, "Can't open config file %s: %s\n", config->config_file, strerror(errno));
5112 return;
5113 }
5114
5115 LOG(3, 0, 0, "Reading config file %s\n", config->config_file);
5116 cli_do_file(f);
5117 LOG(3, 0, 0, "Done reading config file\n");
5118 fclose(f);
5119 }
5120
5121 int sessionsetup(sessionidt s, tunnelidt t)
5122 {
5123 // A session now exists, set it up
5124 in_addr_t ip;
5125 char *user;
5126 sessionidt i;
5127 int r;
5128
5129 CSTAT(sessionsetup);
5130
5131 LOG(3, s, t, "Doing session setup for session\n");
5132
5133 // Join a bundle if the MRRU option is accepted
5134 if(session[s].mrru > 0 && session[s].bundle == 0)
5135 {
5136 LOG(3, s, t, "This session can be part of multilink bundle\n");
5137 if (join_bundle(s) > 0)
5138 cluster_send_bundle(session[s].bundle);
5139 else
5140 {
5141 LOG(0, s, t, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5142 sessionshutdown(s, "Mismaching mssf option.", CDN_NONE, TERM_SERVICE_UNAVAILABLE);
5143 return 0;
5144 }
5145 }
5146
5147 if (!session[s].ip)
5148 {
5149 assign_ip_address(s);
5150 if (!session[s].ip)
5151 {
5152 LOG(0, s, t, " No IP allocated. The IP address pool is FULL!\n");
5153 sessionshutdown(s, "No IP addresses available.", CDN_TRY_ANOTHER, TERM_SERVICE_UNAVAILABLE);
5154 return 0;
5155 }
5156 LOG(3, s, t, " No IP allocated. Assigned %s from pool\n",
5157 fmtaddr(htonl(session[s].ip), 0));
5158 }
5159
5160
5161 // Make sure this is right
5162 session[s].tunnel = t;
5163
5164 // zap old sessions with same IP and/or username
5165 // Don't kill gardened sessions - doing so leads to a DoS
5166 // from someone who doesn't need to know the password
5167 {
5168 ip = session[s].ip;
5169 user = session[s].user;
5170 for (i = 1; i <= config->cluster_highest_sessionid; i++)
5171 {
5172 if (i == s) continue;
5173 if (!session[s].opened) continue;
5174 // Allow duplicate sessions for multilink ones of the same bundle.
5175 if (session[s].bundle && session[i].bundle && session[s].bundle == session[i].bundle)
5176 continue;
5177 if (ip == session[i].ip)
5178 {
5179 sessionkill(i, "Duplicate IP address");
5180 continue;
5181 }
5182
5183 if (config->allow_duplicate_users) continue;
5184 if (session[s].walled_garden || session[i].walled_garden) continue;
5185 // Guest change
5186 int found = 0;
5187 int gu;
5188 for (gu = 0; gu < guest_accounts_num; gu++)
5189 {
5190 if (!strcasecmp(user, guest_users[gu]))
5191 {
5192 found = 1;
5193 break;
5194 }
5195 }
5196 if (found) continue;
5197
5198 // Drop the new session in case of duplicate sessionss, not the old one.
5199 if (!strcasecmp(user, session[i].user))
5200 sessionkill(i, "Duplicate session for users");
5201 }
5202 }
5203
5204 // no need to set a route for the same IP address of the bundle
5205 if (!session[s].bundle || (bundle[session[s].bundle].num_of_links == 1))
5206 {
5207 int routed = 0;
5208
5209 // Add the route for this session.
5210 for (r = 0; r < MAXROUTE && session[s].route[r].ip; r++)
5211 {
5212 if ((session[s].ip & session[s].route[r].mask) ==
5213 (session[s].route[r].ip & session[s].route[r].mask))
5214 routed++;
5215
5216 routeset(s, session[s].route[r].ip, session[s].route[r].mask, 0, 1);
5217 }
5218
5219 // Static IPs need to be routed if not already
5220 // convered by a Framed-Route. Anything else is part
5221 // of the IP address pool and is already routed, it
5222 // just needs to be added to the IP cache.
5223 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5224 if (session[s].ip_pool_index == -1) // static ip
5225 {
5226 if (!routed) routeset(s, session[s].ip, 0, 0, 1);
5227 }
5228 else
5229 cache_ipmap(session[s].ip, s);
5230 }
5231
5232 sess_local[s].lcp_authtype = 0; // RADIUS authentication complete
5233 lcp_open(s, t); // transition to Network phase and send initial IPCP
5234
5235 // Run the plugin's against this new session.
5236 {
5237 struct param_new_session data = { &tunnel[t], &session[s] };
5238 run_plugins(PLUGIN_NEW_SESSION, &data);
5239 }
5240
5241 // Allocate TBFs if throttled
5242 if (session[s].throttle_in || session[s].throttle_out)
5243 throttle_session(s, session[s].throttle_in, session[s].throttle_out);
5244
5245 session[s].last_packet = session[s].last_data = time_now;
5246
5247 LOG(2, s, t, "Login by %s at %s from %s (%s)\n", session[s].user,
5248 fmtaddr(htonl(session[s].ip), 0),
5249 fmtaddr(htonl(tunnel[t].ip), 1), tunnel[t].hostname);
5250
5251 cluster_send_session(s); // Mark it as dirty, and needing to the flooded to the cluster.
5252
5253 return 1; // RADIUS OK and IP allocated, done...
5254 }
5255
5256 //
5257 // This session just got dropped on us by the master or something.
5258 // Make sure our tables up up to date...
5259 //
5260 int load_session(sessionidt s, sessiont *new)
5261 {
5262 int i;
5263 int newip = 0;
5264
5265 // Sanity checks.
5266 if (new->ip_pool_index >= MAXIPPOOL ||
5267 new->tunnel >= MAXTUNNEL)
5268 {
5269 LOG(0, s, 0, "Strange session update received!\n");
5270 // FIXME! What to do here?
5271 return 0;
5272 }
5273
5274 //
5275 // Ok. All sanity checks passed. Now we're committed to
5276 // loading the new session.
5277 //
5278
5279 session[s].tunnel = new->tunnel; // For logging in cache_ipmap
5280
5281 // See if routes/ip cache need updating
5282 if (new->ip != session[s].ip)
5283 newip++;
5284
5285 for (i = 0; !newip && i < MAXROUTE && (session[s].route[i].ip || new->route[i].ip); i++)
5286 if (new->route[i].ip != session[s].route[i].ip ||
5287 new->route[i].mask != session[s].route[i].mask)
5288 newip++;
5289
5290 // needs update
5291 if (newip)
5292 {
5293 int routed = 0;
5294
5295 // remove old routes...
5296 for (i = 0; i < MAXROUTE && session[s].route[i].ip; i++)
5297 {
5298 if ((session[s].ip & session[s].route[i].mask) ==
5299 (session[s].route[i].ip & session[s].route[i].mask))
5300 routed++;
5301
5302 routeset(s, session[s].route[i].ip, session[s].route[i].mask, 0, 0);
5303 }
5304
5305 // ...ip
5306 if (session[s].ip)
5307 {
5308 if (session[s].ip_pool_index == -1) // static IP
5309 {
5310 if (!routed) routeset(s, session[s].ip, 0, 0, 0);
5311 }
5312 else // It's part of the IP pool, remove it manually.
5313 uncache_ipmap(session[s].ip);
5314 }
5315
5316 routed = 0;
5317
5318 // add new routes...
5319 for (i = 0; i < MAXROUTE && new->route[i].ip; i++)
5320 {
5321 if ((new->ip & new->route[i].mask) ==
5322 (new->route[i].ip & new->route[i].mask))
5323 routed++;
5324
5325 routeset(s, new->route[i].ip, new->route[i].mask, 0, 1);
5326 }
5327
5328 // ...ip
5329 if (new->ip)
5330 {
5331 // If there's a new one, add it.
5332 if (new->ip_pool_index == -1)
5333 {
5334 if (!routed) routeset(s, new->ip, 0, 0, 1);
5335 }
5336 else
5337 cache_ipmap(new->ip, s);
5338 }
5339 }
5340
5341 // check v6 routing
5342 if (new->ipv6prefixlen && new->ppp.ipv6cp == Opened && session[s].ppp.ipv6cp != Opened)
5343 route6set(s, new->ipv6route, new->ipv6prefixlen, 1);
5344
5345 // check filters
5346 if (new->filter_in && (new->filter_in > MAXFILTER || !ip_filters[new->filter_in - 1].name[0]))
5347 {
5348 LOG(2, s, session[s].tunnel, "Dropping invalid input filter %u\n", (int) new->filter_in);
5349 new->filter_in = 0;
5350 }
5351
5352 if (new->filter_out && (new->filter_out > MAXFILTER || !ip_filters[new->filter_out - 1].name[0]))
5353 {
5354 LOG(2, s, session[s].tunnel, "Dropping invalid output filter %u\n", (int) new->filter_out);
5355 new->filter_out = 0;
5356 }
5357
5358 if (new->filter_in != session[s].filter_in)
5359 {
5360 if (session[s].filter_in) ip_filters[session[s].filter_in - 1].used--;
5361 if (new->filter_in) ip_filters[new->filter_in - 1].used++;
5362 }
5363
5364 if (new->filter_out != session[s].filter_out)
5365 {
5366 if (session[s].filter_out) ip_filters[session[s].filter_out - 1].used--;
5367 if (new->filter_out) ip_filters[new->filter_out - 1].used++;
5368 }
5369
5370 if (new->tunnel && s > config->cluster_highest_sessionid) // Maintain this in the slave. It's used
5371 // for walking the sessions to forward byte counts to the master.
5372 config->cluster_highest_sessionid = s;
5373
5374 memcpy(&session[s], new, sizeof(session[s])); // Copy over..
5375
5376 // Do fixups into address pool.
5377 if (new->ip_pool_index != -1)
5378 fix_address_pool(s);
5379
5380 return 1;
5381 }
5382
5383 static void initplugins()
5384 {
5385 int i;
5386
5387 loaded_plugins = ll_init();
5388 // Initialize the plugins to nothing
5389 for (i = 0; i < MAX_PLUGIN_TYPES; i++)
5390 plugins[i] = ll_init();
5391 }
5392
5393 static void *open_plugin(char *plugin_name, int load)
5394 {
5395 char path[256] = "";
5396
5397 snprintf(path, 256, PLUGINDIR "/%s.so", plugin_name);
5398 LOG(2, 0, 0, "%soading plugin from %s\n", load ? "L" : "Un-l", path);
5399 return dlopen(path, RTLD_NOW);
5400 }
5401
5402 // plugin callback to get a config value
5403 static void *getconfig(char *key, enum config_typet type)
5404 {
5405 int i;
5406
5407 for (i = 0; config_values[i].key; i++)
5408 {
5409 if (!strcmp(config_values[i].key, key))
5410 {
5411 if (config_values[i].type == type)
5412 return ((void *) config) + config_values[i].offset;
5413
5414 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5415 key, type, config_values[i].type);
5416
5417 return 0;
5418 }
5419 }
5420
5421 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key);
5422 return 0;
5423 }
5424
5425 static int add_plugin(char *plugin_name)
5426 {
5427 static struct pluginfuncs funcs = {
5428 _log,
5429 _log_hex,
5430 fmtaddr,
5431 sessionbyuser,
5432 sessiontbysessionidt,
5433 sessionidtbysessiont,
5434 radiusnew,
5435 radiussend,
5436 getconfig,
5437 sessionshutdown,
5438 sessionkill,
5439 throttle_session,
5440 cluster_send_session,
5441 };
5442
5443 void *p = open_plugin(plugin_name, 1);
5444 int (*initfunc)(struct pluginfuncs *);
5445 int i;
5446
5447 if (!p)
5448 {
5449 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5450 return -1;
5451 }
5452
5453 if (ll_contains(loaded_plugins, p))
5454 {
5455 dlclose(p);
5456 return 0; // already loaded
5457 }
5458
5459 {
5460 int *v = dlsym(p, "plugin_api_version");
5461 if (!v || *v != PLUGIN_API_VERSION)
5462 {
5463 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5464 dlclose(p);
5465 return -1;
5466 }
5467 }
5468
5469 if ((initfunc = dlsym(p, "plugin_init")))
5470 {
5471 if (!initfunc(&funcs))
5472 {
5473 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5474 dlclose(p);
5475 return -1;
5476 }
5477 }
5478
5479 ll_push(loaded_plugins, p);
5480
5481 for (i = 0; i < max_plugin_functions; i++)
5482 {
5483 void *x;
5484 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
5485 {
5486 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions[i]);
5487 ll_push(plugins[i], x);
5488 }
5489 }
5490
5491 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name);
5492 return 1;
5493 }
5494
5495 static void run_plugin_done(void *plugin)
5496 {
5497 int (*donefunc)(void) = dlsym(plugin, "plugin_done");
5498
5499 if (donefunc)
5500 donefunc();
5501 }
5502
5503 static int remove_plugin(char *plugin_name)
5504 {
5505 void *p = open_plugin(plugin_name, 0);
5506 int loaded = 0;
5507
5508 if (!p)
5509 return -1;
5510
5511 if (ll_contains(loaded_plugins, p))
5512 {
5513 int i;
5514 for (i = 0; i < max_plugin_functions; i++)
5515 {
5516 void *x;
5517 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
5518 ll_delete(plugins[i], x);
5519 }
5520
5521 ll_delete(loaded_plugins, p);
5522 run_plugin_done(p);
5523 loaded = 1;
5524 }
5525
5526 dlclose(p);
5527 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name);
5528 return loaded;
5529 }
5530
5531 int run_plugins(int plugin_type, void *data)
5532 {
5533 int (*func)(void *data);
5534
5535 if (!plugins[plugin_type] || plugin_type > max_plugin_functions)
5536 return PLUGIN_RET_ERROR;
5537
5538 ll_reset(plugins[plugin_type]);
5539 while ((func = ll_next(plugins[plugin_type])))
5540 {
5541 int r = func(data);
5542
5543 if (r != PLUGIN_RET_OK)
5544 return r; // stop here
5545 }
5546
5547 return PLUGIN_RET_OK;
5548 }
5549
5550 static void plugins_done()
5551 {
5552 void *p;
5553
5554 ll_reset(loaded_plugins);
5555 while ((p = ll_next(loaded_plugins)))
5556 run_plugin_done(p);
5557 }
5558
5559 static void processcontrol(uint8_t *buf, int len, struct sockaddr_in *addr, int alen, struct in_addr *local)
5560 {
5561 struct nsctl request;
5562 struct nsctl response;
5563 int type = unpack_control(&request, buf, len);
5564 int r;
5565 void *p;
5566
5567 if (log_stream && config->debug >= 4)
5568 {
5569 if (type < 0)
5570 {
5571 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5572 fmtaddr(addr->sin_addr.s_addr, 0), type);
5573 }
5574 else
5575 {
5576 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
5577 dump_control(&request, log_stream);
5578 }
5579 }
5580
5581 switch (type)
5582 {
5583 case NSCTL_REQ_LOAD:
5584 if (request.argc != 1)
5585 {
5586 response.type = NSCTL_RES_ERR;
5587 response.argc = 1;
5588 response.argv[0] = "name of plugin required";
5589 }
5590 else if ((r = add_plugin(request.argv[0])) < 1)
5591 {
5592 response.type = NSCTL_RES_ERR;
5593 response.argc = 1;
5594 response.argv[0] = !r
5595 ? "plugin already loaded"
5596 : "error loading plugin";
5597 }
5598 else
5599 {
5600 response.type = NSCTL_RES_OK;
5601 response.argc = 0;
5602 }
5603
5604 break;
5605
5606 case NSCTL_REQ_UNLOAD:
5607 if (request.argc != 1)
5608 {
5609 response.type = NSCTL_RES_ERR;
5610 response.argc = 1;
5611 response.argv[0] = "name of plugin required";
5612 }
5613 else if ((r = remove_plugin(request.argv[0])) < 1)
5614 {
5615 response.type = NSCTL_RES_ERR;
5616 response.argc = 1;
5617 response.argv[0] = !r
5618 ? "plugin not loaded"
5619 : "plugin not found";
5620 }
5621 else
5622 {
5623 response.type = NSCTL_RES_OK;
5624 response.argc = 0;
5625 }
5626
5627 break;
5628
5629 case NSCTL_REQ_HELP:
5630 response.type = NSCTL_RES_OK;
5631 response.argc = 0;
5632
5633 ll_reset(loaded_plugins);
5634 while ((p = ll_next(loaded_plugins)))
5635 {
5636 char **help = dlsym(p, "plugin_control_help");
5637 while (response.argc < 0xff && help && *help)
5638 response.argv[response.argc++] = *help++;
5639 }
5640
5641 break;
5642
5643 case NSCTL_REQ_CONTROL:
5644 {
5645 struct param_control param = {
5646 config->cluster_iam_master,
5647 request.argc,
5648 request.argv,
5649 0,
5650 NULL,
5651 };
5652
5653 int r = run_plugins(PLUGIN_CONTROL, &param);
5654
5655 if (r == PLUGIN_RET_ERROR)
5656 {
5657 response.type = NSCTL_RES_ERR;
5658 response.argc = 1;
5659 response.argv[0] = param.additional
5660 ? param.additional
5661 : "error returned by plugin";
5662 }
5663 else if (r == PLUGIN_RET_NOTMASTER)
5664 {
5665 static char msg[] = "must be run on master: 000.000.000.000";
5666
5667 response.type = NSCTL_RES_ERR;
5668 response.argc = 1;
5669 if (config->cluster_master_address)
5670 {
5671 strcpy(msg + 23, fmtaddr(config->cluster_master_address, 0));
5672 response.argv[0] = msg;
5673 }
5674 else
5675 {
5676 response.argv[0] = "must be run on master: none elected";
5677 }
5678 }
5679 else if (!(param.response & NSCTL_RESPONSE))
5680 {
5681 response.type = NSCTL_RES_ERR;
5682 response.argc = 1;
5683 response.argv[0] = param.response
5684 ? "unrecognised response value from plugin"
5685 : "unhandled action";
5686 }
5687 else
5688 {
5689 response.type = param.response;
5690 response.argc = 0;
5691 if (param.additional)
5692 {
5693 response.argc = 1;
5694 response.argv[0] = param.additional;
5695 }
5696 }
5697 }
5698
5699 break;
5700
5701 default:
5702 response.type = NSCTL_RES_ERR;
5703 response.argc = 1;
5704 response.argv[0] = "error unpacking control packet";
5705 }
5706
5707 buf = calloc(NSCTL_MAX_PKT_SZ, 1);
5708 if (!buf)
5709 {
5710 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5711 return;
5712 }
5713
5714 r = pack_control(buf, NSCTL_MAX_PKT_SZ, response.type, response.argc, response.argv);
5715 if (r > 0)
5716 {
5717 sendtofrom(controlfd, buf, r, 0, (const struct sockaddr *) addr, alen, local);
5718 if (log_stream && config->debug >= 4)
5719 {
5720 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
5721 dump_control(&response, log_stream);
5722 }
5723 }
5724 else
5725 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5726 fmtaddr(addr->sin_addr.s_addr, 0), r);
5727
5728 free(buf);
5729 }
5730
5731 static tunnelidt new_tunnel()
5732 {
5733 tunnelidt i;
5734 for (i = 1; i < MAXTUNNEL; i++)
5735 {
5736 if (tunnel[i].state == TUNNELFREE)
5737 {
5738 LOG(4, 0, i, "Assigning tunnel ID %u\n", i);
5739 if (i > config->cluster_highest_tunnelid)
5740 config->cluster_highest_tunnelid = i;
5741 return i;
5742 }
5743 }
5744 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5745 return 0;
5746 }
5747
5748 //
5749 // We're becoming the master. Do any required setup..
5750 //
5751 // This is principally telling all the plugins that we're
5752 // now a master, and telling them about all the sessions
5753 // that are active too..
5754 //
5755 void become_master(void)
5756 {
5757 int s, i;
5758 static struct event_data d[RADIUS_FDS];
5759 struct epoll_event e;
5760
5761 run_plugins(PLUGIN_BECOME_MASTER, NULL);
5762
5763 // running a bunch of iptables commands is slow and can cause
5764 // the master to drop tunnels on takeover--kludge around the
5765 // problem by forking for the moment (note: race)
5766 if (!fork_and_close())
5767 {
5768 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
5769 {
5770 if (!session[s].opened) // Not an in-use session.
5771 continue;
5772
5773 run_plugins(PLUGIN_NEW_SESSION_MASTER, &session[s]);
5774 }
5775 exit(0);
5776 }
5777
5778 // add radius fds
5779 e.events = EPOLLIN;
5780 for (i = 0; i < RADIUS_FDS; i++)
5781 {
5782 d[i].type = FD_TYPE_RADIUS;
5783 d[i].index = i;
5784 e.data.ptr = &d[i];
5785
5786 epoll_ctl(epollfd, EPOLL_CTL_ADD, radfds[i], &e);
5787 }
5788 }
5789
5790 int cmd_show_hist_idle(struct cli_def *cli, char *command, char **argv, int argc)
5791 {
5792 int s, i;
5793 int count = 0;
5794 int buckets[64];
5795
5796 if (CLI_HELP_REQUESTED)
5797 return CLI_HELP_NO_ARGS;
5798
5799 time(&time_now);
5800 for (i = 0; i < 64;++i) buckets[i] = 0;
5801
5802 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
5803 {
5804 int idle;
5805 if (!session[s].opened)
5806 continue;
5807
5808 idle = time_now - session[s].last_data;
5809 idle /= 5 ; // In multiples of 5 seconds.
5810 if (idle < 0)
5811 idle = 0;
5812 if (idle > 63)
5813 idle = 63;
5814
5815 ++count;
5816 ++buckets[idle];
5817 }
5818
5819 for (i = 0; i < 63; ++i)
5820 {
5821 cli_print(cli, "%3d seconds : %7.2f%% (%6d)", i * 5, (double) buckets[i] * 100.0 / count , buckets[i]);
5822 }
5823 cli_print(cli, "lots of secs : %7.2f%% (%6d)", (double) buckets[63] * 100.0 / count , buckets[i]);
5824 cli_print(cli, "%d total sessions open.", count);
5825 return CLI_OK;
5826 }
5827
5828 int cmd_show_hist_open(struct cli_def *cli, char *command, char **argv, int argc)
5829 {
5830 int s, i;
5831 int count = 0;
5832 int buckets[64];
5833
5834 if (CLI_HELP_REQUESTED)
5835 return CLI_HELP_NO_ARGS;
5836
5837 time(&time_now);
5838 for (i = 0; i < 64;++i) buckets[i] = 0;
5839
5840 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
5841 {
5842 int open = 0, d;
5843 if (!session[s].opened)
5844 continue;
5845
5846 d = time_now - session[s].opened;
5847 if (d < 0)
5848 d = 0;
5849 while (d > 1 && open < 32)
5850 {
5851 ++open;
5852 d >>= 1; // half.
5853 }
5854 ++count;
5855 ++buckets[open];
5856 }
5857
5858 s = 1;
5859 for (i = 0; i < 30; ++i)
5860 {
5861 cli_print(cli, " < %8d seconds : %7.2f%% (%6d)", s, (double) buckets[i] * 100.0 / count , buckets[i]);
5862 s <<= 1;
5863 }
5864 cli_print(cli, "%d total sessions open.", count);
5865 return CLI_OK;
5866 }
5867
5868 /* Unhide an avp.
5869 *
5870 * This unencodes the AVP using the L2TP secret and the previously
5871 * stored random vector. It overwrites the hidden data with the
5872 * unhidden AVP subformat.
5873 */
5874 static void unhide_value(uint8_t *value, size_t len, uint16_t type, uint8_t *vector, size_t vec_len)
5875 {
5876 MD5_CTX ctx;
5877 uint8_t digest[16];
5878 uint8_t *last;
5879 size_t d = 0;
5880 uint16_t m = htons(type);
5881
5882 // Compute initial pad
5883 MD5_Init(&ctx);
5884 MD5_Update(&ctx, (unsigned char *) &m, 2);
5885 MD5_Update(&ctx, config->l2tp_secret, strlen(config->l2tp_secret));
5886 MD5_Update(&ctx, vector, vec_len);
5887 MD5_Final(digest, &ctx);
5888
5889 // pointer to last decoded 16 octets
5890 last = value;
5891
5892 while (len > 0)
5893 {
5894 // calculate a new pad based on the last decoded block
5895 if (d >= sizeof(digest))
5896 {
5897 MD5_Init(&ctx);
5898 MD5_Update(&ctx, config->l2tp_secret, strlen(config->l2tp_secret));
5899 MD5_Update(&ctx, last, sizeof(digest));
5900 MD5_Final(digest, &ctx);
5901
5902 d = 0;
5903 last = value;
5904 }
5905
5906 *value++ ^= digest[d++];
5907 len--;
5908 }
5909 }
5910
5911 int find_filter(char const *name, size_t len)
5912 {
5913 int free = -1;
5914 int i;
5915
5916 for (i = 0; i < MAXFILTER; i++)
5917 {
5918 if (!*ip_filters[i].name)
5919 {
5920 if (free < 0)
5921 free = i;
5922
5923 continue;
5924 }
5925
5926 if (strlen(ip_filters[i].name) != len)
5927 continue;
5928
5929 if (!strncmp(ip_filters[i].name, name, len))
5930 return i;
5931 }
5932
5933 return free;
5934 }
5935
5936 static int ip_filter_port(ip_filter_portt *p, uint16_t port)
5937 {
5938 switch (p->op)
5939 {
5940 case FILTER_PORT_OP_EQ: return port == p->port;
5941 case FILTER_PORT_OP_NEQ: return port != p->port;
5942 case FILTER_PORT_OP_GT: return port > p->port;
5943 case FILTER_PORT_OP_LT: return port < p->port;
5944 case FILTER_PORT_OP_RANGE: return port >= p->port && port <= p->port2;
5945 }
5946
5947 return 0;
5948 }
5949
5950 static int ip_filter_flag(uint8_t op, uint8_t sflags, uint8_t cflags, uint8_t flags)
5951 {
5952 switch (op)
5953 {
5954 case FILTER_FLAG_OP_ANY:
5955 return (flags & sflags) || (~flags & cflags);
5956
5957 case FILTER_FLAG_OP_ALL:
5958 return (flags & sflags) == sflags && (~flags & cflags) == cflags;
5959
5960 case FILTER_FLAG_OP_EST:
5961 return (flags & (TCP_FLAG_ACK|TCP_FLAG_RST)) && (~flags & TCP_FLAG_SYN);
5962 }
5963
5964 return 0;
5965 }
5966
5967 int ip_filter(uint8_t *buf, int len, uint8_t filter)
5968 {
5969 uint16_t frag_offset;
5970 uint8_t proto;
5971 in_addr_t src_ip;
5972 in_addr_t dst_ip;
5973 uint16_t src_port = 0;
5974 uint16_t dst_port = 0;
5975 uint8_t flags = 0;
5976 ip_filter_rulet *rule;
5977
5978 if (len < 20) // up to end of destination address
5979 return 0;
5980
5981 if ((*buf >> 4) != 4) // IPv4
5982 return 0;
5983
5984 frag_offset = ntohs(*(uint16_t *) (buf + 6)) & 0x1fff;
5985 proto = buf[9];
5986 src_ip = *(in_addr_t *) (buf + 12);
5987 dst_ip = *(in_addr_t *) (buf + 16);
5988
5989 if (frag_offset == 0 && (proto == IPPROTO_TCP || proto == IPPROTO_UDP))
5990 {
5991 int l = (buf[0] & 0xf) * 4; // length of IP header
5992 if (len < l + 4) // ports
5993 return 0;
5994
5995 src_port = ntohs(*(uint16_t *) (buf + l));
5996 dst_port = ntohs(*(uint16_t *) (buf + l + 2));
5997 if (proto == IPPROTO_TCP)
5998 {
5999 if (len < l + 14) // flags
6000 return 0;
6001
6002 flags = buf[l + 13] & 0x3f;
6003 }
6004 }
6005
6006 for (rule = ip_filters[filter].rules; rule->action; rule++)
6007 {
6008 if (rule->proto != IPPROTO_IP && proto != rule->proto)
6009 continue;
6010
6011 if (rule->src_wild != INADDR_BROADCAST &&
6012 (src_ip & ~rule->src_wild) != (rule->src_ip & ~rule->src_wild))
6013 continue;
6014
6015 if (rule->dst_wild != INADDR_BROADCAST &&
6016 (dst_ip & ~rule->dst_wild) != (rule->dst_ip & ~rule->dst_wild))
6017 continue;
6018
6019 if (frag_offset)
6020 {
6021 // layer 4 deny rules are skipped
6022 if (rule->action == FILTER_ACTION_DENY &&
6023 (rule->src_ports.op || rule->dst_ports.op || rule->tcp_flag_op))
6024 continue;
6025 }
6026 else
6027 {
6028 if (rule->frag)
6029 continue;
6030
6031 if (proto == IPPROTO_TCP || proto == IPPROTO_UDP)
6032 {
6033 if (rule->src_ports.op && !ip_filter_port(&rule->src_ports, src_port))
6034 continue;
6035
6036 if (rule->dst_ports.op && !ip_filter_port(&rule->dst_ports, dst_port))
6037 continue;
6038
6039 if (proto == IPPROTO_TCP && rule->tcp_flag_op &&
6040 !ip_filter_flag(rule->tcp_flag_op, rule->tcp_sflags, rule->tcp_cflags, flags))
6041 continue;
6042 }
6043 }
6044
6045 // matched
6046 rule->counter++;
6047 return rule->action == FILTER_ACTION_PERMIT;
6048 }
6049
6050 // default deny
6051 return 0;
6052 }