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