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