Change log level
[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 if (n == 0)
2720 {
2721 // if continue a infinity loop is created.
2722 LOG(1, s, t, "It's infinite loop protection %02X\n", *b);
2723 return;
2724 }
2725 else
2726 continue; // next
2727 }
2728 b += 2;
2729 if (*(uint16_t *) (b))
2730 {
2731 LOG(2, s, t, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b)));
2732 fatal = flags;
2733 result = 2; // general error
2734 error = 6; // generic vendor-specific error
2735 msg = "unsupported vendor-specific";
2736 if (n == 0)
2737 {
2738 // if continue a infinity loop is created.
2739 LOG(1, s, t, "It's infinite loop protection %02X\n", *b);
2740 return;
2741 }
2742 else
2743 continue; // next
2744 }
2745 b += 2;
2746 mtype = ntohs(*(uint16_t *) (b));
2747 b += 2;
2748 n -= 6;
2749
2750 if (flags & 0x40)
2751 {
2752 uint16_t orig_len;
2753
2754 // handle hidden AVPs
2755 if (!*config->l2tp_secret)
2756 {
2757 LOG(1, s, t, "Hidden AVP requested, but no L2TP secret.\n");
2758 fatal = flags;
2759 result = 2; // general error
2760 error = 6; // generic vendor-specific error
2761 msg = "secret not specified";
2762 continue;
2763 }
2764 if (!session[s].random_vector_length)
2765 {
2766 LOG(1, s, t, "Hidden AVP requested, but no random vector.\n");
2767 fatal = flags;
2768 result = 2; // general error
2769 error = 6; // generic
2770 msg = "no random vector";
2771 continue;
2772 }
2773 if (n < 8)
2774 {
2775 LOG(2, s, t, "Short hidden AVP.\n");
2776 fatal = flags;
2777 result = 2; // general error
2778 error = 2; // length is wrong
2779 msg = 0;
2780 continue;
2781 }
2782
2783 // Unhide the AVP
2784 unhide_value(b, n, mtype, session[s].random_vector, session[s].random_vector_length);
2785
2786 orig_len = ntohs(*(uint16_t *) b);
2787 if (orig_len > n + 2)
2788 {
2789 LOG(1, s, t, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2790 orig_len, n);
2791
2792 fatal = flags;
2793 result = 2; // general error
2794 error = 2; // length is wrong
2795 msg = 0;
2796 continue;
2797 }
2798
2799 b += 2;
2800 n = orig_len;
2801 }
2802
2803 LOG(3, s, t, " AVP %u (%s) len %d%s%s\n", mtype, l2tp_avp_name(mtype), n,
2804 flags & 0x40 ? ", hidden" : "", flags & 0x80 ? ", mandatory" : "");
2805
2806 switch (mtype)
2807 {
2808 case 0: // message type
2809 message = ntohs(*(uint16_t *) b);
2810 mandatory = flags & 0x80;
2811 LOG(3, s, t, " Message type = %u (%s)\n", message, l2tp_code(message));
2812 break;
2813 case 1: // result code
2814 {
2815 uint16_t rescode = ntohs(*(uint16_t *) b);
2816 char const *resdesc = "(unknown)";
2817 char const *errdesc = NULL;
2818 int cause = 0;
2819
2820 if (message == 4)
2821 { /* StopCCN */
2822 resdesc = l2tp_stopccn_result_code(rescode);
2823 cause = TERM_LOST_SERVICE;
2824 }
2825 else if (message == 14)
2826 { /* CDN */
2827 resdesc = l2tp_cdn_result_code(rescode);
2828 if (rescode == 1)
2829 cause = TERM_LOST_CARRIER;
2830 else
2831 cause = TERM_ADMIN_RESET;
2832 }
2833
2834 LOG(3, s, t, " Result Code %u: %s\n", rescode, resdesc);
2835 if (n >= 4)
2836 {
2837 uint16_t errcode = ntohs(*(uint16_t *)(b + 2));
2838 errdesc = l2tp_error_code(errcode);
2839 LOG(3, s, t, " Error Code %u: %s\n", errcode, errdesc);
2840 }
2841 if (n > 4)
2842 LOG(3, s, t, " Error String: %.*s\n", n-4, b+4);
2843
2844 if (cause && disc_cause_set < mtype) // take cause from attrib 46 in preference
2845 {
2846 disc_cause_set = mtype;
2847 disc_reason = errdesc ? errdesc : resdesc;
2848 disc_cause = cause;
2849 }
2850
2851 break;
2852 }
2853 break;
2854 case 2: // protocol version
2855 {
2856 version = ntohs(*(uint16_t *) (b));
2857 LOG(3, s, t, " Protocol version = %u\n", version);
2858 if (version && version != 0x0100)
2859 { // allow 0.0 and 1.0
2860 LOG(1, s, t, " Bad protocol version %04X\n", version);
2861 fatal = flags;
2862 result = 5; // unspported protocol version
2863 error = 0x0100; // supported version
2864 msg = 0;
2865 continue; // next
2866 }
2867 }
2868 break;
2869 case 3: // framing capabilities
2870 break;
2871 case 4: // bearer capabilities
2872 break;
2873 case 5: // tie breaker
2874 // We never open tunnels, so we don't care about tie breakers
2875 continue;
2876 case 6: // firmware revision
2877 break;
2878 case 7: // host name
2879 memset(tunnel[t].hostname, 0, sizeof(tunnel[t].hostname));
2880 memcpy(tunnel[t].hostname, b, (n < sizeof(tunnel[t].hostname)) ? n : sizeof(tunnel[t].hostname) - 1);
2881 LOG(3, s, t, " Tunnel hostname = \"%s\"\n", tunnel[t].hostname);
2882 // TBA - to send to RADIUS
2883 break;
2884 case 8: // vendor name
2885 memset(tunnel[t].vendor, 0, sizeof(tunnel[t].vendor));
2886 memcpy(tunnel[t].vendor, b, (n < sizeof(tunnel[t].vendor)) ? n : sizeof(tunnel[t].vendor) - 1);
2887 LOG(3, s, t, " Vendor name = \"%s\"\n", tunnel[t].vendor);
2888 break;
2889 case 9: // assigned tunnel
2890 tunnel[t].far = ntohs(*(uint16_t *) (b));
2891 LOG(3, s, t, " Remote tunnel id = %u\n", tunnel[t].far);
2892 break;
2893 case 10: // rx window
2894 tunnel[t].window = ntohs(*(uint16_t *) (b));
2895 if (!tunnel[t].window)
2896 tunnel[t].window = 1; // window of 0 is silly
2897 LOG(3, s, t, " rx window = %u\n", tunnel[t].window);
2898 break;
2899 case 11: // Request Challenge
2900 {
2901 LOG(3, s, t, " LAC requested CHAP authentication for tunnel\n");
2902 if (message == 1)
2903 build_chap_response(b, 2, n, &sendchalresponse);
2904 else if (message == 2)
2905 build_chap_response(b, 3, n, &sendchalresponse);
2906 }
2907 break;
2908 case 13: // receive challenge Response
2909 if (tunnel[t].isremotelns)
2910 {
2911 recvchalresponse = calloc(17, 1);
2912 memcpy(recvchalresponse, b, (n < 17) ? n : 16);
2913 LOG(3, s, t, "received challenge response from REMOTE LNS\n");
2914 }
2915 else
2916 // Why did they send a response? We never challenge.
2917 LOG(2, s, t, " received unexpected challenge response\n");
2918 break;
2919
2920 case 14: // assigned session
2921 asession = session[s].far = ntohs(*(uint16_t *) (b));
2922 LOG(3, s, t, " assigned session = %u\n", asession);
2923 break;
2924 case 15: // call serial number
2925 LOG(3, s, t, " call serial number = %u\n", ntohl(*(uint32_t *)b));
2926 break;
2927 case 18: // bearer type
2928 LOG(3, s, t, " bearer type = %u\n", ntohl(*(uint32_t *)b));
2929 // TBA - for RADIUS
2930 break;
2931 case 19: // framing type
2932 LOG(3, s, t, " framing type = %u\n", ntohl(*(uint32_t *)b));
2933 // TBA
2934 break;
2935 case 21: // called number
2936 memset(called, 0, sizeof(called));
2937 memcpy(called, b, (n < sizeof(called)) ? n : sizeof(called) - 1);
2938 LOG(3, s, t, " Called <%s>\n", called);
2939 break;
2940 case 22: // calling number
2941 memset(calling, 0, sizeof(calling));
2942 memcpy(calling, b, (n < sizeof(calling)) ? n : sizeof(calling) - 1);
2943 LOG(3, s, t, " Calling <%s>\n", calling);
2944 break;
2945 case 23: // subtype
2946 break;
2947 case 24: // tx connect speed
2948 if (n == 4)
2949 {
2950 session[s].tx_connect_speed = ntohl(*(uint32_t *)b);
2951 }
2952 else
2953 {
2954 // AS5300s send connect speed as a string
2955 char tmp[30];
2956 memset(tmp, 0, sizeof(tmp));
2957 memcpy(tmp, b, (n < sizeof(tmp)) ? n : sizeof(tmp) - 1);
2958 session[s].tx_connect_speed = atol(tmp);
2959 }
2960 LOG(3, s, t, " TX connect speed <%u>\n", session[s].tx_connect_speed);
2961 break;
2962 case 38: // rx connect speed
2963 if (n == 4)
2964 {
2965 session[s].rx_connect_speed = ntohl(*(uint32_t *)b);
2966 }
2967 else
2968 {
2969 // AS5300s send connect speed as a string
2970 char tmp[30];
2971 memset(tmp, 0, sizeof(tmp));
2972 memcpy(tmp, b, (n < sizeof(tmp)) ? n : sizeof(tmp) - 1);
2973 session[s].rx_connect_speed = atol(tmp);
2974 }
2975 LOG(3, s, t, " RX connect speed <%u>\n", session[s].rx_connect_speed);
2976 break;
2977 case 25: // Physical Channel ID
2978 {
2979 uint32_t tmp = ntohl(*(uint32_t *) b);
2980 LOG(3, s, t, " Physical Channel ID <%X>\n", tmp);
2981 break;
2982 }
2983 case 29: // Proxy Authentication Type
2984 {
2985 uint16_t atype = ntohs(*(uint16_t *)b);
2986 LOG(3, s, t, " Proxy Auth Type %u (%s)\n", atype, ppp_auth_type(atype));
2987 break;
2988 }
2989 case 30: // Proxy Authentication Name
2990 {
2991 char authname[64];
2992 memset(authname, 0, sizeof(authname));
2993 memcpy(authname, b, (n < sizeof(authname)) ? n : sizeof(authname) - 1);
2994 LOG(3, s, t, " Proxy Auth Name (%s)\n",
2995 authname);
2996 break;
2997 }
2998 case 31: // Proxy Authentication Challenge
2999 {
3000 LOG(3, s, t, " Proxy Auth Challenge\n");
3001 break;
3002 }
3003 case 32: // Proxy Authentication ID
3004 {
3005 uint16_t authid = ntohs(*(uint16_t *)(b));
3006 LOG(3, s, t, " Proxy Auth ID (%u)\n", authid);
3007 break;
3008 }
3009 case 33: // Proxy Authentication Response
3010 LOG(3, s, t, " Proxy Auth Response\n");
3011 break;
3012 case 27: // last sent lcp
3013 { // find magic number
3014 uint8_t *p = b, *e = p + n;
3015 while (p + 1 < e && p[1] && p + p[1] <= e)
3016 {
3017 if (*p == 5 && p[1] == 6) // Magic-Number
3018 amagic = ntohl(*(uint32_t *) (p + 2));
3019 else if (*p == 7) // Protocol-Field-Compression
3020 aflags |= SESSION_PFC;
3021 else if (*p == 8) // Address-and-Control-Field-Compression
3022 aflags |= SESSION_ACFC;
3023 p += p[1];
3024 }
3025 }
3026 break;
3027 case 28: // last recv lcp confreq
3028 break;
3029 case 26: // Initial Received LCP CONFREQ
3030 break;
3031 case 39: // seq required - we control it as an LNS anyway...
3032 break;
3033 case 36: // Random Vector
3034 LOG(3, s, t, " Random Vector received. Enabled AVP Hiding.\n");
3035 memset(session[s].random_vector, 0, sizeof(session[s].random_vector));
3036 if (n > sizeof(session[s].random_vector))
3037 n = sizeof(session[s].random_vector);
3038 memcpy(session[s].random_vector, b, n);
3039 session[s].random_vector_length = n;
3040 break;
3041 case 46: // ppp disconnect cause
3042 if (n >= 5)
3043 {
3044 uint16_t code = ntohs(*(uint16_t *) b);
3045 uint16_t proto = ntohs(*(uint16_t *) (b + 2));
3046 uint8_t dir = *(b + 4);
3047
3048 LOG(3, s, t, " PPP disconnect cause "
3049 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
3050 code, proto, dir, n - 5, b + 5);
3051
3052 disc_cause_set = mtype;
3053
3054 switch (code)
3055 {
3056 case 1: // admin disconnect
3057 disc_cause = TERM_ADMIN_RESET;
3058 disc_reason = "Administrative disconnect";
3059 break;
3060 case 3: // lcp terminate
3061 if (dir != 2) break; // 1=peer (LNS), 2=local (LAC)
3062 disc_cause = TERM_USER_REQUEST;
3063 disc_reason = "Normal disconnection";
3064 break;
3065 case 4: // compulsory encryption unavailable
3066 if (dir != 1) break; // 1=refused by peer, 2=local
3067 disc_cause = TERM_USER_ERROR;
3068 disc_reason = "Compulsory encryption refused";
3069 break;
3070 case 5: // lcp: fsm timeout
3071 disc_cause = TERM_PORT_ERROR;
3072 disc_reason = "LCP: FSM timeout";
3073 break;
3074 case 6: // lcp: no recognisable lcp packets received
3075 disc_cause = TERM_PORT_ERROR;
3076 disc_reason = "LCP: no recognisable LCP packets";
3077 break;
3078 case 7: // lcp: magic-no error (possibly looped back)
3079 disc_cause = TERM_PORT_ERROR;
3080 disc_reason = "LCP: magic-no error (possible loop)";
3081 break;
3082 case 8: // lcp: echo request timeout
3083 disc_cause = TERM_PORT_ERROR;
3084 disc_reason = "LCP: echo request timeout";
3085 break;
3086 case 13: // auth: fsm timeout
3087 disc_cause = TERM_SERVICE_UNAVAILABLE;
3088 disc_reason = "Authentication: FSM timeout";
3089 break;
3090 case 15: // auth: unacceptable auth protocol
3091 disc_cause = TERM_SERVICE_UNAVAILABLE;
3092 disc_reason = "Unacceptable authentication protocol";
3093 break;
3094 case 16: // auth: authentication failed
3095 disc_cause = TERM_SERVICE_UNAVAILABLE;
3096 disc_reason = "Authentication failed";
3097 break;
3098 case 17: // ncp: fsm timeout
3099 disc_cause = TERM_SERVICE_UNAVAILABLE;
3100 disc_reason = "NCP: FSM timeout";
3101 break;
3102 case 18: // ncp: no ncps available
3103 disc_cause = TERM_SERVICE_UNAVAILABLE;
3104 disc_reason = "NCP: no NCPs available";
3105 break;
3106 case 19: // ncp: failure to converge on acceptable address
3107 disc_cause = TERM_SERVICE_UNAVAILABLE;
3108 disc_reason = (dir == 1)
3109 ? "NCP: too many Configure-Naks received from peer"
3110 : "NCP: too many Configure-Naks sent to peer";
3111 break;
3112 case 20: // ncp: user not permitted to use any address
3113 disc_cause = TERM_SERVICE_UNAVAILABLE;
3114 disc_reason = (dir == 1)
3115 ? "NCP: local link address not acceptable to peer"
3116 : "NCP: remote link address not acceptable";
3117 break;
3118 }
3119 }
3120 break;
3121 default:
3122 {
3123 static char e[] = "unknown AVP 0xXXXX";
3124 LOG(2, s, t, " Unknown AVP type %u\n", mtype);
3125 fatal = flags;
3126 result = 2; // general error
3127 error = 8; // unknown mandatory AVP
3128 sprintf((msg = e) + 14, "%04x", mtype);
3129 continue; // next
3130 }
3131 }
3132 }
3133 // process message
3134 if (fatal & 0x80)
3135 tunnelshutdown(t, "Invalid mandatory AVP", result, error, msg);
3136 else
3137 switch (message)
3138 {
3139 case 1: // SCCRQ - Start Control Connection Request
3140 tunnel[t].state = TUNNELOPENING;
3141 LOG(3, s, t, "Received SCCRQ\n");
3142 if (main_quit != QUIT_SHUTDOWN)
3143 {
3144 LOG(3, s, t, "sending SCCRP\n");
3145 controlt *c = controlnew(2); // sending SCCRP
3146 control16(c, 2, version, 1); // protocol version
3147 control32(c, 3, 3, 1); // framing
3148 controls(c, 7, config->multi_n_hostname[tunnel[t].indexudp][0]?config->multi_n_hostname[tunnel[t].indexudp]:hostname, 1); // host name
3149 if (sendchalresponse) controlb(c, 13, sendchalresponse, 16, 1); // Send Challenge response
3150 control16(c, 9, t, 1); // assigned tunnel
3151 controladd(c, 0, t); // send the resply
3152 }
3153 else
3154 {
3155 tunnelshutdown(t, "Shutting down", 6, 0, 0);
3156 }
3157 break;
3158 case 2: // SCCRP
3159 tunnel[t].state = TUNNELOPEN;
3160 tunnel[t].lastrec = time_now;
3161 LOG(3, s, t, "Received SCCRP\n");
3162 if (main_quit != QUIT_SHUTDOWN)
3163 {
3164 if (tunnel[t].isremotelns && recvchalresponse)
3165 {
3166 hasht hash;
3167
3168 lac_calc_rlns_auth(t, 2, hash); // id = 2 (SCCRP)
3169 // check authenticator
3170 if (memcmp(hash, recvchalresponse, 16) == 0)
3171 {
3172 LOG(3, s, t, "sending SCCCN to REMOTE LNS\n");
3173 controlt *c = controlnew(3); // sending SCCCN
3174 controls(c, 7, config->multi_n_hostname[tunnel[t].indexudp][0]?config->multi_n_hostname[tunnel[t].indexudp]:hostname, 1); // host name
3175 controls(c, 8, Vendor_name, 1); // Vendor name
3176 control16(c, 2, version, 1); // protocol version
3177 control32(c, 3, 3, 1); // framing Capabilities
3178 if (sendchalresponse) controlb(c, 13, sendchalresponse, 16, 1); // Challenge response
3179 control16(c, 9, t, 1); // assigned tunnel
3180 controladd(c, 0, t); // send
3181 }
3182 else
3183 {
3184 tunnelshutdown(t, "Bad chap response from REMOTE LNS", 4, 0, 0);
3185 }
3186 }
3187 }
3188 else
3189 {
3190 tunnelshutdown(t, "Shutting down", 6, 0, 0);
3191 }
3192 break;
3193 case 3: // SCCN
3194 LOG(3, s, t, "Received SCCN\n");
3195 tunnel[t].state = TUNNELOPEN;
3196 tunnel[t].lastrec = time_now;
3197 controlnull(t); // ack
3198 break;
3199 case 4: // StopCCN
3200 LOG(3, s, t, "Received StopCCN\n");
3201 controlnull(t); // ack
3202 tunnelshutdown(t, "Stopped", 0, 0, 0); // Shut down cleanly
3203 break;
3204 case 6: // HELLO
3205 LOG(3, s, t, "Received HELLO\n");
3206 controlnull(t); // simply ACK
3207 break;
3208 case 7: // OCRQ
3209 // TBA
3210 LOG(3, s, t, "Received OCRQ\n");
3211 break;
3212 case 8: // OCRO
3213 // TBA
3214 LOG(3, s, t, "Received OCRO\n");
3215 break;
3216 case 9: // OCCN
3217 // TBA
3218 LOG(3, s, t, "Received OCCN\n");
3219 break;
3220 case 10: // ICRQ
3221 LOG(3, s, t, "Received ICRQ\n");
3222 if (sessionfree && main_quit != QUIT_SHUTDOWN)
3223 {
3224 controlt *c = controlnew(11); // ICRP
3225
3226 LOG(3, s, t, "Sending ICRP\n");
3227
3228 s = sessionfree;
3229 sessionfree = session[s].next;
3230 memset(&session[s], 0, sizeof(session[s]));
3231
3232 if (s > config->cluster_highest_sessionid)
3233 config->cluster_highest_sessionid = s;
3234
3235 session[s].opened = time_now;
3236 session[s].tunnel = t;
3237 session[s].far = asession;
3238 session[s].last_packet = session[s].last_data = time_now;
3239 LOG(3, s, t, "New session (%u/%u)\n", tunnel[t].far, session[s].far);
3240 control16(c, 14, s, 1); // assigned session
3241 controladd(c, asession, t); // send the reply
3242
3243 strncpy(session[s].called, called, sizeof(session[s].called) - 1);
3244 strncpy(session[s].calling, calling, sizeof(session[s].calling) - 1);
3245
3246 session[s].ppp.phase = Establish;
3247 session[s].ppp.lcp = Starting;
3248
3249 STAT(session_created);
3250 break;
3251 }
3252
3253 {
3254 controlt *c = controlnew(14); // CDN
3255 LOG(3, s, t, "Sending CDN\n");
3256 if (!sessionfree)
3257 {
3258 STAT(session_overflow);
3259 LOG(1, 0, t, "No free sessions\n");
3260 control16(c, 1, 4, 0); // temporary lack of resources
3261 }
3262 else
3263 control16(c, 1, 2, 7); // shutting down, try another
3264
3265 controladd(c, asession, t); // send the message
3266 }
3267 return;
3268 case 11: // ICRP
3269 LOG(3, s, t, "Received ICRP\n");
3270 if (session[s].forwardtosession)
3271 {
3272 controlt *c = controlnew(12); // ICCN
3273
3274 session[s].opened = time_now;
3275 session[s].tunnel = t;
3276 session[s].far = asession;
3277 session[s].last_packet = session[s].last_data = time_now;
3278
3279 control32(c, 19, 1, 1); // Framing Type
3280 control32(c, 24, 10000000, 1); // Tx Connect Speed
3281 controladd(c, asession, t); // send the message
3282 LOG(3, s, t, "Sending ICCN\n");
3283 }
3284 break;
3285 case 12: // ICCN
3286 LOG(3, s, t, "Received ICCN\n");
3287 if (amagic == 0) amagic = time_now;
3288 session[s].magic = amagic; // set magic number
3289 session[s].flags = aflags; // set flags received
3290 session[s].mru = PPPoE_MRU; // default
3291 controlnull(t); // ack
3292
3293 // start LCP
3294 sess_local[s].lcp_authtype = config->radius_authprefer;
3295 sess_local[s].ppp_mru = MRU;
3296
3297 // Set multilink options before sending initial LCP packet
3298 sess_local[s].mp_mrru = 1614;
3299 sess_local[s].mp_epdis = ntohl(config->iftun_address ? config->iftun_address : my_address);
3300
3301 sendlcp(s, t);
3302 change_state(s, lcp, RequestSent);
3303 break;
3304
3305 case 14: // CDN
3306 LOG(3, s, t, "Received CDN\n");
3307 controlnull(t); // ack
3308 sessionshutdown(s, disc_reason, CDN_NONE, disc_cause);
3309 break;
3310 case 0xFFFF:
3311 LOG(1, s, t, "Missing message type\n");
3312 break;
3313 default:
3314 STAT(tunnel_rx_errors);
3315 if (mandatory)
3316 tunnelshutdown(t, "Unknown message type", 2, 6, "unknown message type");
3317 else
3318 LOG(1, s, t, "Unknown message type %u\n", message);
3319 break;
3320 }
3321 if (sendchalresponse) free(sendchalresponse);
3322 if (recvchalresponse) free(recvchalresponse);
3323 cluster_send_tunnel(t);
3324 }
3325 else
3326 {
3327 LOG(4, s, t, " Got a ZLB ack\n");
3328 }
3329 }
3330 else
3331 { // data
3332 uint16_t proto;
3333
3334 LOG_HEX(5, "Receive Tunnel Data", p, l);
3335 if (l > 2 && p[0] == 0xFF && p[1] == 0x03)
3336 { // HDLC address header, discard
3337 p += 2;
3338 l -= 2;
3339 }
3340 if (l < 2)
3341 {
3342 LOG(1, s, t, "Short ppp length %d\n", l);
3343 STAT(tunnel_rx_errors);
3344 return;
3345 }
3346 if (*p & 1)
3347 {
3348 proto = *p++;
3349 l--;
3350 }
3351 else
3352 {
3353 proto = ntohs(*(uint16_t *) p);
3354 p += 2;
3355 l -= 2;
3356 }
3357
3358 if (session[s].forwardtosession)
3359 {
3360 LOG(5, s, t, "Forwarding data session to session %u\n", session[s].forwardtosession);
3361 // Forward to LAC/BAS or Remote LNS session
3362 lac_session_forward(buf, len, s, proto, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3363 return;
3364 }
3365 else if (config->auth_tunnel_change_addr_src)
3366 {
3367 if (tunnel[t].ip != ntohl(addr->sin_addr.s_addr) &&
3368 tunnel[t].port == ntohs(addr->sin_port))
3369 {
3370 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3371 LOG(5, s, t, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3372 fmtaddr(htonl(tunnel[t].ip), 0), fmtaddr(addr->sin_addr.s_addr, 0));
3373
3374 tunnel[t].ip = ntohl(addr->sin_addr.s_addr);
3375 }
3376 }
3377
3378 if (s && !session[s].opened) // Is something wrong??
3379 {
3380 if (!config->cluster_iam_master)
3381 {
3382 // Pass it off to the master to deal with..
3383 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3384 return;
3385 }
3386
3387 LOG(1, s, t, "UDP packet contains session which is not opened. Dropping packet.\n");
3388 STAT(tunnel_rx_errors);
3389 return;
3390 }
3391
3392 if (proto == PPPPAP)
3393 {
3394 session[s].last_packet = time_now;
3395 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3396 processpap(s, t, p, l);
3397 }
3398 else if (proto == PPPCHAP)
3399 {
3400 session[s].last_packet = time_now;
3401 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3402 processchap(s, t, p, l);
3403 }
3404 else if (proto == PPPLCP)
3405 {
3406 session[s].last_packet = time_now;
3407 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3408 processlcp(s, t, p, l);
3409 }
3410 else if (proto == PPPIPCP)
3411 {
3412 session[s].last_packet = time_now;
3413 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3414 processipcp(s, t, p, l);
3415 }
3416 else if (proto == PPPIPV6CP && config->ipv6_prefix.s6_addr[0])
3417 {
3418 session[s].last_packet = time_now;
3419 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3420 processipv6cp(s, t, p, l);
3421 }
3422 else if (proto == PPPCCP)
3423 {
3424 session[s].last_packet = time_now;
3425 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3426 processccp(s, t, p, l);
3427 }
3428 else if (proto == PPPIP)
3429 {
3430 if (session[s].die)
3431 {
3432 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3433 return; // closing session, PPP not processed
3434 }
3435
3436 session[s].last_packet = session[s].last_data = time_now;
3437 if (session[s].walled_garden && !config->cluster_iam_master)
3438 {
3439 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3440 return;
3441 }
3442
3443 processipin(s, t, p, l);
3444 }
3445 else if (proto == PPPMP)
3446 {
3447 if (session[s].die)
3448 {
3449 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3450 return; // closing session, PPP not processed
3451 }
3452
3453 session[s].last_packet = session[s].last_data = time_now;
3454 if (!config->cluster_iam_master)
3455 {
3456 // The fragments reconstruction is managed by the Master.
3457 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3458 return;
3459 }
3460
3461 processmpin(s, t, p, l);
3462 }
3463 else if (proto == PPPIPV6 && config->ipv6_prefix.s6_addr[0])
3464 {
3465 if (session[s].die)
3466 {
3467 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3468 return; // closing session, PPP not processed
3469 }
3470
3471 session[s].last_packet = session[s].last_data = time_now;
3472 if (session[s].walled_garden && !config->cluster_iam_master)
3473 {
3474 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3475 return;
3476 }
3477
3478 if (!config->cluster_iam_master)
3479 {
3480 // Check if DhcpV6, IP dst: FF02::1:2, Src Port 0x0222 (546), Dst Port 0x0223 (547)
3481 if (*(p + 6) == 17 && *(p + 24) == 0xFF && *(p + 25) == 2 &&
3482 *(uint32_t *)(p + 26) == 0 && *(uint32_t *)(p + 30) == 0 &&
3483 *(uint16_t *)(p + 34) == 0 && *(p + 36) == 0 && *(p + 37) == 1 && *(p + 38) == 0 && *(p + 39) == 2 &&
3484 *(p + 40) == 2 && *(p + 41) == 0x22 && *(p + 42) == 2 && *(p + 43) == 0x23)
3485 {
3486 // DHCPV6 must be managed by the Master.
3487 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3488 return;
3489 }
3490 }
3491
3492 processipv6in(s, t, p, l);
3493 }
3494 else if (session[s].ppp.lcp == Opened)
3495 {
3496 session[s].last_packet = time_now;
3497 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3498 protoreject(s, t, p, l, proto);
3499 }
3500 else
3501 {
3502 LOG(2, s, t, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3503 proto, ppp_state(session[s].ppp.lcp));
3504 }
3505 }
3506 }
3507
3508 // read and process packet on tun
3509 // (i.e. this routine writes to buf[-8]).
3510 static void processtun(uint8_t * buf, int len)
3511 {
3512 LOG_HEX(5, "Receive TUN Data", buf, len);
3513 STAT(tun_rx_packets);
3514 INC_STAT(tun_rx_bytes, len);
3515
3516 CSTAT(processtun);
3517
3518 eth_rx_pkt++;
3519 eth_rx += len;
3520 if (len < 22)
3521 {
3522 LOG(1, 0, 0, "Short tun packet %d bytes\n", len);
3523 STAT(tun_rx_errors);
3524 return;
3525 }
3526
3527 if (*(uint16_t *) (buf + 2) == htons(PKTIP)) // IPv4
3528 processipout(buf, len);
3529 else if (*(uint16_t *) (buf + 2) == htons(PKTIPV6) // IPV6
3530 && config->ipv6_prefix.s6_addr[0])
3531 processipv6out(buf, len);
3532
3533 // Else discard.
3534 }
3535
3536 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3537 // that we look at the whole of the tunnel, radius and session tables
3538 // every second
3539 static void regular_cleanups(double period)
3540 {
3541 // Next tunnel, radius and session to check for actions on.
3542 static tunnelidt t = 0;
3543 static int r = 0;
3544 static sessionidt s = 0;
3545
3546 int t_actions = 0;
3547 int r_actions = 0;
3548 int s_actions = 0;
3549
3550 int t_slice;
3551 int r_slice;
3552 int s_slice;
3553
3554 int i;
3555 int a;
3556
3557 // divide up tables into slices based on the last run
3558 t_slice = config->cluster_highest_tunnelid * period;
3559 r_slice = (MAXRADIUS - 1) * period;
3560 s_slice = config->cluster_highest_sessionid * period;
3561
3562 if (t_slice < 1)
3563 t_slice = 1;
3564 else if (t_slice > config->cluster_highest_tunnelid)
3565 t_slice = config->cluster_highest_tunnelid;
3566
3567 if (r_slice < 1)
3568 r_slice = 1;
3569 else if (r_slice > (MAXRADIUS - 1))
3570 r_slice = MAXRADIUS - 1;
3571
3572 if (s_slice < 1)
3573 s_slice = 1;
3574 else if (s_slice > config->cluster_highest_sessionid)
3575 s_slice = config->cluster_highest_sessionid;
3576
3577 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period);
3578
3579 for (i = 0; i < t_slice; i++)
3580 {
3581 t++;
3582 if (t > config->cluster_highest_tunnelid)
3583 t = 1;
3584
3585 if (t == TUNNEL_ID_PPPOE)
3586 continue;
3587
3588 // check for expired tunnels
3589 if (tunnel[t].die && tunnel[t].die <= TIME)
3590 {
3591 STAT(tunnel_timeout);
3592 tunnelkill(t, "Expired");
3593 t_actions++;
3594 continue;
3595 }
3596 // check for message resend
3597 if (tunnel[t].retry && tunnel[t].controlc)
3598 {
3599 // resend pending messages as timeout on reply
3600 if (tunnel[t].retry <= TIME)
3601 {
3602 controlt *c = tunnel[t].controls;
3603 uint16_t w = tunnel[t].window;
3604 tunnel[t].try++; // another try
3605 if (tunnel[t].try > 5)
3606 tunnelkill(t, "Timeout on control message"); // game over
3607 else
3608 while (c && w--)
3609 {
3610 tunnelsend(c->buf, c->length, t);
3611 c = c->next;
3612 }
3613
3614 t_actions++;
3615 }
3616 }
3617 // Send hello
3618 if (tunnel[t].state == TUNNELOPEN && !tunnel[t].controlc && (time_now - tunnel[t].lastrec) > 60)
3619 {
3620 if (!config->disable_sending_hello)
3621 {
3622 controlt *c = controlnew(6); // sending HELLO
3623 controladd(c, 0, t); // send the message
3624 LOG(3, 0, t, "Sending HELLO message\n");
3625 t_actions++;
3626 }
3627 }
3628
3629 // Check for tunnel changes requested from the CLI
3630 if ((a = cli_tunnel_actions[t].action))
3631 {
3632 cli_tunnel_actions[t].action = 0;
3633 if (a & CLI_TUN_KILL)
3634 {
3635 LOG(2, 0, t, "Dropping tunnel by CLI\n");
3636 tunnelshutdown(t, "Requested by administrator", 1, 0, 0);
3637 t_actions++;
3638 }
3639 }
3640 }
3641
3642 for (i = 0; i < r_slice; i++)
3643 {
3644 r++;
3645 if (r >= MAXRADIUS)
3646 r = 1;
3647
3648 if (!radius[r].state)
3649 continue;
3650
3651 if (radius[r].retry <= TIME)
3652 {
3653 radiusretry(r);
3654 r_actions++;
3655 }
3656 }
3657
3658 for (i = 0; i < s_slice; i++)
3659 {
3660 s++;
3661 if (s > config->cluster_highest_sessionid)
3662 s = 1;
3663
3664 if (!session[s].opened) // Session isn't in use
3665 continue;
3666
3667 // check for expired sessions
3668 if (session[s].die)
3669 {
3670 if (session[s].die <= TIME)
3671 {
3672 sessionkill(s, "Expired");
3673 s_actions++;
3674 }
3675 continue;
3676 }
3677
3678 // PPP timeouts
3679 if (sess_local[s].lcp.restart <= time_now)
3680 {
3681 int next_state = session[s].ppp.lcp;
3682 switch (session[s].ppp.lcp)
3683 {
3684 case RequestSent:
3685 case AckReceived:
3686 next_state = RequestSent;
3687
3688 case AckSent:
3689 if (sess_local[s].lcp.conf_sent < config->ppp_max_configure)
3690 {
3691 LOG(3, s, session[s].tunnel, "No ACK for LCP ConfigReq... resending\n");
3692 sendlcp(s, session[s].tunnel);
3693 change_state(s, lcp, next_state);
3694 }
3695 else
3696 {
3697 sessionshutdown(s, "No response to LCP ConfigReq.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3698 STAT(session_timeout);
3699 }
3700
3701 s_actions++;
3702 }
3703
3704 if (session[s].die)
3705 continue;
3706 }
3707
3708 if (sess_local[s].ipcp.restart <= time_now)
3709 {
3710 int next_state = session[s].ppp.ipcp;
3711 switch (session[s].ppp.ipcp)
3712 {
3713 case RequestSent:
3714 case AckReceived:
3715 next_state = RequestSent;
3716
3717 case AckSent:
3718 if (sess_local[s].ipcp.conf_sent < config->ppp_max_configure)
3719 {
3720 LOG(3, s, session[s].tunnel, "No ACK for IPCP ConfigReq... resending\n");
3721 sendipcp(s, session[s].tunnel);
3722 change_state(s, ipcp, next_state);
3723 }
3724 else
3725 {
3726 sessionshutdown(s, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3727 STAT(session_timeout);
3728 }
3729
3730 s_actions++;
3731 }
3732
3733 if (session[s].die)
3734 continue;
3735 }
3736
3737 if (sess_local[s].ipv6cp.restart <= time_now)
3738 {
3739 int next_state = session[s].ppp.ipv6cp;
3740 switch (session[s].ppp.ipv6cp)
3741 {
3742 case RequestSent:
3743 case AckReceived:
3744 next_state = RequestSent;
3745
3746 case AckSent:
3747 if (sess_local[s].ipv6cp.conf_sent < config->ppp_max_configure)
3748 {
3749 LOG(3, s, session[s].tunnel, "No ACK for IPV6CP ConfigReq... resending\n");
3750 sendipv6cp(s, session[s].tunnel);
3751 change_state(s, ipv6cp, next_state);
3752 }
3753 else
3754 {
3755 LOG(3, s, session[s].tunnel, "No ACK for IPV6CP ConfigReq\n");
3756 change_state(s, ipv6cp, Stopped);
3757 }
3758
3759 s_actions++;
3760 }
3761 }
3762
3763 if (sess_local[s].ccp.restart <= time_now)
3764 {
3765 int next_state = session[s].ppp.ccp;
3766 switch (session[s].ppp.ccp)
3767 {
3768 case RequestSent:
3769 case AckReceived:
3770 next_state = RequestSent;
3771
3772 case AckSent:
3773 if (sess_local[s].ccp.conf_sent < config->ppp_max_configure)
3774 {
3775 LOG(3, s, session[s].tunnel, "No ACK for CCP ConfigReq... resending\n");
3776 sendccp(s, session[s].tunnel);
3777 change_state(s, ccp, next_state);
3778 }
3779 else
3780 {
3781 LOG(3, s, session[s].tunnel, "No ACK for CCP ConfigReq\n");
3782 change_state(s, ccp, Stopped);
3783 }
3784
3785 s_actions++;
3786 }
3787 }
3788
3789 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3790 if (session[s].last_packet && (time_now - session[s].last_packet >= config->idle_echo_timeout))
3791 {
3792 sessionshutdown(s, "No response to LCP ECHO requests.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3793 STAT(session_timeout);
3794 s_actions++;
3795 continue;
3796 }
3797
3798 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3799 if (session[s].ppp.phase >= Establish &&
3800 ((!config->ppp_keepalive) ||
3801 (time_now - session[s].last_packet >= config->echo_timeout)) &&
3802 (time_now - sess_local[s].last_echo >= ECHO_TIMEOUT))
3803 {
3804 uint8_t b[MAXETHER];
3805
3806 uint8_t *q = makeppp(b, sizeof(b), 0, 0, s, session[s].tunnel, PPPLCP, 1, 0, 0);
3807 if (!q) continue;
3808
3809 *q = EchoReq;
3810 *(uint8_t *)(q + 1) = (time_now % 255); // ID
3811 *(uint16_t *)(q + 2) = htons(8); // Length
3812 *(uint32_t *)(q + 4) = session[s].ppp.lcp == Opened ? htonl(session[s].magic) : 0; // Magic Number
3813
3814 LOG(4, s, session[s].tunnel, "No data in %d seconds, sending LCP ECHO\n",
3815 (int)(time_now - session[s].last_packet));
3816
3817 tunnelsend(b, (q - b) + 8, session[s].tunnel); // send it
3818 sess_local[s].last_echo = time_now;
3819 s_actions++;
3820 }
3821
3822 // Drop sessions who have reached session_timeout seconds
3823 if (session[s].session_timeout)
3824 {
3825 bundleidt bid = session[s].bundle;
3826 if (bid)
3827 {
3828 if (time_now - bundle[bid].last_check >= 1)
3829 {
3830 bundle[bid].online_time += (time_now - bundle[bid].last_check) * bundle[bid].num_of_links;
3831 bundle[bid].last_check = time_now;
3832 if (bundle[bid].online_time >= session[s].session_timeout)
3833 {
3834 int ses;
3835 for (ses = bundle[bid].num_of_links - 1; ses >= 0; ses--)
3836 {
3837 sessionshutdown(bundle[bid].members[ses], "Session timeout", CDN_ADMIN_DISC, TERM_SESSION_TIMEOUT);
3838 s_actions++;
3839 continue;
3840 }
3841 }
3842 }
3843 }
3844 else if (time_now - session[s].opened >= session[s].session_timeout)
3845 {
3846 sessionshutdown(s, "Session timeout", CDN_ADMIN_DISC, TERM_SESSION_TIMEOUT);
3847 s_actions++;
3848 continue;
3849 }
3850 }
3851
3852 // Drop sessions who have reached idle_timeout seconds
3853 if (session[s].last_data && session[s].idle_timeout && (time_now - session[s].last_data >= session[s].idle_timeout))
3854 {
3855 sessionshutdown(s, "Idle Timeout Reached", CDN_ADMIN_DISC, TERM_IDLE_TIMEOUT);
3856 STAT(session_timeout);
3857 s_actions++;
3858 continue;
3859 }
3860
3861 // Check for actions requested from the CLI
3862 if ((a = cli_session_actions[s].action))
3863 {
3864 int send = 0;
3865
3866 cli_session_actions[s].action = 0;
3867 if (a & CLI_SESS_KILL)
3868 {
3869 LOG(2, s, session[s].tunnel, "Dropping session by CLI\n");
3870 sessionshutdown(s, "Requested by administrator.", CDN_ADMIN_DISC, TERM_ADMIN_RESET);
3871 a = 0; // dead, no need to check for other actions
3872 s_actions++;
3873 }
3874
3875 if (a & CLI_SESS_NOSNOOP)
3876 {
3877 LOG(2, s, session[s].tunnel, "Unsnooping session by CLI\n");
3878 session[s].snoop_ip = 0;
3879 session[s].snoop_port = 0;
3880 s_actions++;
3881 send++;
3882 }
3883 else if (a & CLI_SESS_SNOOP)
3884 {
3885 LOG(2, s, session[s].tunnel, "Snooping session by CLI (to %s:%u)\n",
3886 fmtaddr(cli_session_actions[s].snoop_ip, 0),
3887 cli_session_actions[s].snoop_port);
3888
3889 session[s].snoop_ip = cli_session_actions[s].snoop_ip;
3890 session[s].snoop_port = cli_session_actions[s].snoop_port;
3891 s_actions++;
3892 send++;
3893 }
3894
3895 if (a & CLI_SESS_NOTHROTTLE)
3896 {
3897 LOG(2, s, session[s].tunnel, "Un-throttling session by CLI\n");
3898 throttle_session(s, 0, 0);
3899 s_actions++;
3900 send++;
3901 }
3902 else if (a & CLI_SESS_THROTTLE)
3903 {
3904 LOG(2, s, session[s].tunnel, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3905 cli_session_actions[s].throttle_in,
3906 cli_session_actions[s].throttle_out);
3907
3908 throttle_session(s, cli_session_actions[s].throttle_in, cli_session_actions[s].throttle_out);
3909 s_actions++;
3910 send++;
3911 }
3912
3913 if (a & CLI_SESS_NOFILTER)
3914 {
3915 LOG(2, s, session[s].tunnel, "Un-filtering session by CLI\n");
3916 filter_session(s, 0, 0);
3917 s_actions++;
3918 send++;
3919 }
3920 else if (a & CLI_SESS_FILTER)
3921 {
3922 LOG(2, s, session[s].tunnel, "Filtering session by CLI (in=%d, out=%d)\n",
3923 cli_session_actions[s].filter_in,
3924 cli_session_actions[s].filter_out);
3925
3926 filter_session(s, cli_session_actions[s].filter_in, cli_session_actions[s].filter_out);
3927 s_actions++;
3928 send++;
3929 }
3930
3931 if (send)
3932 cluster_send_session(s);
3933 }
3934
3935 // RADIUS interim accounting
3936 if (config->radius_accounting && config->radius_interim > 0
3937 && session[s].ip && !session[s].walled_garden
3938 && !sess_local[s].radius // RADIUS already in progress
3939 && time_now - sess_local[s].last_interim >= config->radius_interim
3940 && session[s].flags & SESSION_STARTED)
3941 {
3942 int rad = radiusnew(s);
3943 if (!rad)
3944 {
3945 LOG(1, s, session[s].tunnel, "No free RADIUS sessions for Interim message\n");
3946 STAT(radius_overflow);
3947 continue;
3948 }
3949
3950 LOG(3, s, session[s].tunnel, "Sending RADIUS Interim for %s (%u)\n",
3951 session[s].user, session[s].unique_id);
3952
3953 radiussend(rad, RADIUSINTERIM);
3954 sess_local[s].last_interim = time_now;
3955 s_actions++;
3956 }
3957 }
3958
3959 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3960 t_slice, r_slice, s_slice, t_actions, r_actions, s_actions);
3961 }
3962
3963 //
3964 // Are we in the middle of a tunnel update, or radius
3965 // requests??
3966 //
3967 static int still_busy(void)
3968 {
3969 int i;
3970 static clockt last_talked = 0;
3971 static clockt start_busy_wait = 0;
3972
3973 #ifdef BGP
3974 static time_t stopped_bgp = 0;
3975 if (bgp_configured)
3976 {
3977 if (!stopped_bgp)
3978 {
3979 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY);
3980
3981 for (i = 0; i < BGP_NUM_PEERS; i++)
3982 if (bgp_peers[i].state == Established)
3983 bgp_stop(&bgp_peers[i]);
3984
3985 stopped_bgp = time_now;
3986
3987 if (!config->cluster_iam_master)
3988 {
3989 // we don't want to become master
3990 cluster_send_ping(0);
3991
3992 return 1;
3993 }
3994 }
3995
3996 if (!config->cluster_iam_master && time_now < (stopped_bgp + QUIT_DELAY))
3997 return 1;
3998 }
3999 #endif /* BGP */
4000
4001 if (!config->cluster_iam_master)
4002 return 0;
4003
4004 if (main_quit == QUIT_SHUTDOWN)
4005 {
4006 static int dropped = 0;
4007 if (!dropped)
4008 {
4009 int i;
4010
4011 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
4012 for (i = 1; i < MAXTUNNEL; i++)
4013 if (tunnel[i].ip || tunnel[i].state)
4014 tunnelshutdown(i, "L2TPNS Closing", 6, 0, 0);
4015
4016 dropped = 1;
4017 }
4018 }
4019
4020 if (start_busy_wait == 0)
4021 start_busy_wait = TIME;
4022
4023 for (i = config->cluster_highest_tunnelid ; i > 0 ; --i)
4024 {
4025 if (!tunnel[i].controlc)
4026 continue;
4027
4028 if (last_talked != TIME)
4029 {
4030 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i);
4031 last_talked = TIME;
4032 }
4033 return 1;
4034 }
4035
4036 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
4037 if (abs(TIME - start_busy_wait) > BUSY_WAIT_TIME)
4038 {
4039 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
4040 return 0;
4041 }
4042
4043 for (i = 1; i < MAXRADIUS; i++)
4044 {
4045 if (radius[i].state == RADIUSNULL)
4046 continue;
4047 if (radius[i].state == RADIUSWAIT)
4048 continue;
4049
4050 if (last_talked != TIME)
4051 {
4052 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i, radius[i].session);
4053 last_talked = TIME;
4054 }
4055 return 1;
4056 }
4057
4058 return 0;
4059 }
4060
4061 #ifdef HAVE_EPOLL
4062 # include <sys/epoll.h>
4063 #else
4064 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
4065 # include "fake_epoll.h"
4066 #endif
4067
4068 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
4069 #define BASE_FDS (9 + MAX_UDPFD)
4070
4071 // additional polled fds
4072 #ifdef BGP
4073 # define EXTRA_FDS BGP_NUM_PEERS
4074 #else
4075 # define EXTRA_FDS 0
4076 #endif
4077
4078 // main loop - gets packets on tun or udp and processes them
4079 static void mainloop(void)
4080 {
4081 int i, j;
4082 uint8_t buf[65536];
4083 uint8_t *p = buf + 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4084 // and the forwarded pppoe session
4085 int size_bufp = sizeof(buf) - 32;
4086 clockt next_cluster_ping = 0; // send initial ping immediately
4087 struct epoll_event events[BASE_FDS + RADIUS_FDS + EXTRA_FDS];
4088 int maxevent = sizeof(events)/sizeof(*events);
4089
4090 if ((epollfd = epoll_create(maxevent)) < 0)
4091 {
4092 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno));
4093 exit(1);
4094 }
4095
4096 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",
4097 clifd, cluster_sockfd, tunfd, udpfd[0], controlfd, daefd, nlfd, udplacfd, pppoediscfd, pppoesessfd);
4098
4099 /* setup our fds to poll for input */
4100 {
4101 static struct event_data d[BASE_FDS];
4102 struct epoll_event e;
4103
4104 e.events = EPOLLIN;
4105 i = 0;
4106
4107 if (clifd >= 0)
4108 {
4109 d[i].type = FD_TYPE_CLI;
4110 e.data.ptr = &d[i++];
4111 epoll_ctl(epollfd, EPOLL_CTL_ADD, clifd, &e);
4112 }
4113
4114 d[i].type = FD_TYPE_CLUSTER;
4115 e.data.ptr = &d[i++];
4116 epoll_ctl(epollfd, EPOLL_CTL_ADD, cluster_sockfd, &e);
4117
4118 d[i].type = FD_TYPE_TUN;
4119 e.data.ptr = &d[i++];
4120 epoll_ctl(epollfd, EPOLL_CTL_ADD, tunfd, &e);
4121
4122 d[i].type = FD_TYPE_CONTROL;
4123 e.data.ptr = &d[i++];
4124 epoll_ctl(epollfd, EPOLL_CTL_ADD, controlfd, &e);
4125
4126 d[i].type = FD_TYPE_DAE;
4127 e.data.ptr = &d[i++];
4128 epoll_ctl(epollfd, EPOLL_CTL_ADD, daefd, &e);
4129
4130 d[i].type = FD_TYPE_NETLINK;
4131 e.data.ptr = &d[i++];
4132 epoll_ctl(epollfd, EPOLL_CTL_ADD, nlfd, &e);
4133
4134 d[i].type = FD_TYPE_PPPOEDISC;
4135 e.data.ptr = &d[i++];
4136 epoll_ctl(epollfd, EPOLL_CTL_ADD, pppoediscfd, &e);
4137
4138 d[i].type = FD_TYPE_PPPOESESS;
4139 e.data.ptr = &d[i++];
4140 epoll_ctl(epollfd, EPOLL_CTL_ADD, pppoesessfd, &e);
4141
4142 for (j = 0; j < config->nbudpfd; j++)
4143 {
4144 d[i].type = FD_TYPE_UDP;
4145 d[i].index = j;
4146 e.data.ptr = &d[i++];
4147 epoll_ctl(epollfd, EPOLL_CTL_ADD, udpfd[j], &e);
4148 }
4149 }
4150
4151 #ifdef BGP
4152 signal(SIGPIPE, SIG_IGN);
4153 bgp_setup(config->as_number);
4154 if (config->bind_address)
4155 bgp_add_route(config->bind_address, 0xffffffff);
4156
4157 for (i = 0; i < BGP_NUM_PEERS; i++)
4158 {
4159 if (config->neighbour[i].name[0])
4160 bgp_start(&bgp_peers[i], config->neighbour[i].name,
4161 config->neighbour[i].as, config->neighbour[i].keepalive,
4162 config->neighbour[i].hold, config->neighbour[i].update_source,
4163 0); /* 0 = routing disabled */
4164 }
4165 #endif /* BGP */
4166
4167 while (!main_quit || still_busy())
4168 {
4169 int more = 0;
4170 int n;
4171
4172
4173 if (main_reload)
4174 {
4175 main_reload = 0;
4176 read_config_file();
4177 config->reload_config++;
4178 }
4179
4180 if (config->reload_config)
4181 {
4182 config->reload_config = 0;
4183 update_config();
4184 }
4185
4186 #ifdef BGP
4187 bgp_set_poll();
4188 #endif /* BGP */
4189
4190 n = epoll_wait(epollfd, events, maxevent, 100); // timeout 100ms (1/10th sec)
4191 STAT(select_called);
4192
4193 TIME = now(NULL);
4194 if (n < 0)
4195 {
4196 if (errno == EINTR ||
4197 errno == ECHILD) // EINTR was clobbered by sigchild_handler()
4198 continue;
4199
4200 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno));
4201 break; // exit
4202 }
4203
4204 if (n)
4205 {
4206 struct sockaddr_in addr;
4207 struct in_addr local;
4208 socklen_t alen;
4209 int c, s;
4210 int udp_ready[MAX_UDPFD + 1] = INIT_TABUDPVAR;
4211 int pppoesess_ready = 0;
4212 int pppoesess_pkts = 0;
4213 int tun_ready = 0;
4214 int cluster_ready = 0;
4215 int udp_pkts[MAX_UDPFD + 1] = INIT_TABUDPVAR;
4216 int tun_pkts = 0;
4217 int cluster_pkts = 0;
4218 #ifdef BGP
4219 uint32_t bgp_events[BGP_NUM_PEERS];
4220 memset(bgp_events, 0, sizeof(bgp_events));
4221 #endif /* BGP */
4222
4223 for (c = n, i = 0; i < c; i++)
4224 {
4225 struct event_data *d = events[i].data.ptr;
4226
4227 switch (d->type)
4228 {
4229 case FD_TYPE_CLI: // CLI connections
4230 {
4231 int cli;
4232
4233 alen = sizeof(addr);
4234 if ((cli = accept(clifd, (struct sockaddr *)&addr, &alen)) >= 0)
4235 {
4236 cli_do(cli);
4237 close(cli);
4238 }
4239 else
4240 LOG(0, 0, 0, "accept error: %s\n", strerror(errno));
4241
4242 n--;
4243 break;
4244 }
4245
4246 // these are handled below, with multiple interleaved reads
4247 case FD_TYPE_CLUSTER: cluster_ready++; break;
4248 case FD_TYPE_TUN: tun_ready++; break;
4249 case FD_TYPE_UDP: udp_ready[d->index]++; break;
4250 case FD_TYPE_PPPOESESS: pppoesess_ready++; break;
4251
4252 case FD_TYPE_PPPOEDISC: // pppoe discovery
4253 s = read(pppoediscfd, p, size_bufp);
4254 if (s > 0) process_pppoe_disc(p, s);
4255 n--;
4256 break;
4257
4258 case FD_TYPE_CONTROL: // nsctl commands
4259 alen = sizeof(addr);
4260 s = recvfromto(controlfd, p, size_bufp, MSG_WAITALL, (struct sockaddr *) &addr, &alen, &local);
4261 if (s > 0) processcontrol(p, s, &addr, alen, &local);
4262 n--;
4263 break;
4264
4265 case FD_TYPE_DAE: // DAE requests
4266 alen = sizeof(addr);
4267 s = recvfromto(daefd, p, size_bufp, MSG_WAITALL, (struct sockaddr *) &addr, &alen, &local);
4268 if (s > 0) processdae(p, s, &addr, alen, &local);
4269 n--;
4270 break;
4271
4272 case FD_TYPE_RADIUS: // RADIUS response
4273 alen = sizeof(addr);
4274 s = recvfrom(radfds[d->index], p, size_bufp, MSG_WAITALL, (struct sockaddr *) &addr, &alen);
4275 if (s >= 0 && config->cluster_iam_master)
4276 {
4277 if (addr.sin_addr.s_addr == config->radiusserver[0] ||
4278 addr.sin_addr.s_addr == config->radiusserver[1])
4279 processrad(p, s, d->index);
4280 else
4281 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4282 fmtaddr(addr.sin_addr.s_addr, 0));
4283 }
4284
4285 n--;
4286 break;
4287
4288 #ifdef BGP
4289 case FD_TYPE_BGP:
4290 bgp_events[d->index] = events[i].events;
4291 n--;
4292 break;
4293 #endif /* BGP */
4294
4295 case FD_TYPE_NETLINK:
4296 {
4297 struct nlmsghdr *nh = (struct nlmsghdr *)p;
4298 s = netlink_recv(p, size_bufp);
4299 if (nh->nlmsg_type == NLMSG_ERROR)
4300 {
4301 struct nlmsgerr *errmsg = NLMSG_DATA(nh);
4302 if (errmsg->error)
4303 {
4304 if (errmsg->msg.nlmsg_seq < min_initok_nlseqnum)
4305 {
4306 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg[nh->nlmsg_seq], strerror(-errmsg->error));
4307 exit(1);
4308 }
4309 else
4310 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg->error));
4311 }
4312 // else it's a ack
4313 }
4314 else
4315 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);
4316 n--;
4317 break;
4318 }
4319
4320 default:
4321 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d->type);
4322 }
4323 }
4324
4325 #ifdef BGP
4326 bgp_process(bgp_events);
4327 #endif /* BGP */
4328
4329 for (c = 0; n && c < config->multi_read_count; c++)
4330 {
4331 for (j = 0; j < config->nbudpfd; j++)
4332 {
4333 // L2TP and L2TP REMOTE LNS
4334 if (udp_ready[j])
4335 {
4336 alen = sizeof(addr);
4337 if ((s = recvfrom(udpfd[j], p, size_bufp, 0, (void *) &addr, &alen)) > 0)
4338 {
4339 processudp(p, s, &addr, j);
4340 udp_pkts[j]++;
4341 }
4342 else
4343 {
4344 udp_ready[j] = 0;
4345 n--;
4346 }
4347 }
4348 }
4349
4350 // incoming IP
4351 if (tun_ready)
4352 {
4353 if ((s = read(tunfd, p, size_bufp)) > 0)
4354 {
4355 processtun(p, s);
4356 tun_pkts++;
4357 }
4358 else
4359 {
4360 tun_ready = 0;
4361 n--;
4362 }
4363 }
4364
4365 // pppoe session
4366 if (pppoesess_ready)
4367 {
4368 if ((s = read(pppoesessfd, p, size_bufp)) > 0)
4369 {
4370 process_pppoe_sess(p, s);
4371 pppoesess_pkts++;
4372 }
4373 else
4374 {
4375 pppoesess_ready = 0;
4376 n--;
4377 }
4378 }
4379
4380 // cluster
4381 if (cluster_ready)
4382 {
4383 alen = sizeof(addr);
4384 if ((s = recvfrom(cluster_sockfd, p, size_bufp, MSG_WAITALL, (void *) &addr, &alen)) > 0)
4385 {
4386 processcluster(p, s, addr.sin_addr.s_addr);
4387 cluster_pkts++;
4388 }
4389 else
4390 {
4391 cluster_ready = 0;
4392 n--;
4393 }
4394 }
4395 }
4396
4397 if (udp_pkts[0] > 1 || tun_pkts > 1 || cluster_pkts > 1)
4398 STAT(multi_read_used);
4399
4400 if (c >= config->multi_read_count)
4401 {
4402 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4403 config->multi_read_count, udp_pkts[0], tun_pkts, cluster_pkts, pppoesess_pkts);
4404 STAT(multi_read_exceeded);
4405 more++;
4406 }
4407 }
4408 #ifdef BGP
4409 else
4410 /* no event received, but timers could still have expired */
4411 bgp_process_peers_timers();
4412 #endif /* BGP */
4413
4414 if (time_changed)
4415 {
4416 double Mbps = 1024.0 * 1024.0 / 8 * time_changed;
4417
4418 // Log current traffic stats
4419 snprintf(config->bandwidth, sizeof(config->bandwidth),
4420 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4421 (udp_rx / Mbps), (eth_tx / Mbps), (eth_rx / Mbps), (udp_tx / Mbps),
4422 ((udp_tx + udp_rx + eth_tx + eth_rx) / Mbps),
4423 udp_rx_pkt / time_changed, eth_rx_pkt / time_changed);
4424
4425 udp_tx = udp_rx = 0;
4426 udp_rx_pkt = eth_rx_pkt = 0;
4427 eth_tx = eth_rx = 0;
4428 time_changed = 0;
4429
4430 if (config->dump_speed)
4431 printf("%s\n", config->bandwidth);
4432
4433 // Update the internal time counter
4434 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
4435
4436 {
4437 // Run timer hooks
4438 struct param_timer p = { time_now };
4439 run_plugins(PLUGIN_TIMER, &p);
4440 }
4441 }
4442
4443 // Runs on every machine (master and slaves).
4444 if (next_cluster_ping <= TIME)
4445 {
4446 // Check to see which of the cluster is still alive..
4447
4448 cluster_send_ping(basetime); // Only does anything if we're a slave
4449 cluster_check_master(); // ditto.
4450
4451 cluster_heartbeat(); // Only does anything if we're a master.
4452 cluster_check_slaves(); // ditto.
4453
4454 master_update_counts(); // If we're a slave, send our byte counters to our master.
4455
4456 if (config->cluster_iam_master && !config->cluster_iam_uptodate)
4457 next_cluster_ping = TIME + 1; // out-of-date slaves, do fast updates
4458 else
4459 next_cluster_ping = TIME + config->cluster_hb_interval;
4460 }
4461
4462 if (!config->cluster_iam_master)
4463 continue;
4464
4465 // Run token bucket filtering queue..
4466 // Only run it every 1/10th of a second.
4467 {
4468 static clockt last_run = 0;
4469 if (last_run != TIME)
4470 {
4471 last_run = TIME;
4472 tbf_run_timer();
4473 }
4474 }
4475
4476 // Handle timeouts, retries etc.
4477 {
4478 static double last_clean = 0;
4479 double this_clean;
4480 double diff;
4481
4482 TIME = now(&this_clean);
4483 diff = this_clean - last_clean;
4484
4485 // Run during idle time (after we've handled
4486 // all incoming packets) or every 1/10th sec
4487 if (!more || diff > 0.1)
4488 {
4489 regular_cleanups(diff);
4490 last_clean = this_clean;
4491 }
4492 }
4493
4494 if (*config->accounting_dir)
4495 {
4496 static clockt next_acct = 0;
4497 static clockt next_shut_acct = 0;
4498
4499 if (next_acct <= TIME)
4500 {
4501 // Dump accounting data
4502 next_acct = TIME + ACCT_TIME;
4503 next_shut_acct = TIME + ACCT_SHUT_TIME;
4504 dump_acct_info(1);
4505 }
4506 else if (next_shut_acct <= TIME)
4507 {
4508 // Dump accounting data for shutdown sessions
4509 next_shut_acct = TIME + ACCT_SHUT_TIME;
4510 if (shut_acct_n)
4511 dump_acct_info(0);
4512 }
4513 }
4514 }
4515
4516 // Are we the master and shutting down??
4517 if (config->cluster_iam_master)
4518 cluster_heartbeat(); // Flush any queued changes..
4519
4520 // Ok. Notify everyone we're shutting down. If we're
4521 // the master, this will force an election.
4522 cluster_send_ping(0);
4523
4524 //
4525 // Important!!! We MUST not process any packets past this point!
4526 LOG(1, 0, 0, "Shutdown complete\n");
4527 }
4528
4529 static void stripdomain(char *host)
4530 {
4531 char *p;
4532
4533 if ((p = strchr(host, '.')))
4534 {
4535 char *domain = 0;
4536 char _domain[1024];
4537
4538 // strip off domain
4539 FILE *resolv = fopen("/etc/resolv.conf", "r");
4540 if (resolv)
4541 {
4542 char buf[1024];
4543 char *b;
4544
4545 while (fgets(buf, sizeof(buf), resolv))
4546 {
4547 if (strncmp(buf, "domain", 6) && strncmp(buf, "search", 6))
4548 continue;
4549
4550 if (!isspace(buf[6]))
4551 continue;
4552
4553 b = buf + 7;
4554 while (isspace(*b)) b++;
4555
4556 if (*b)
4557 {
4558 char *d = b;
4559 while (*b && !isspace(*b)) b++;
4560 *b = 0;
4561 if (buf[0] == 'd') // domain is canonical
4562 {
4563 domain = d;
4564 break;
4565 }
4566
4567 // first search line
4568 if (!domain)
4569 {
4570 // hold, may be subsequent domain line
4571 strncpy(_domain, d, sizeof(_domain))[sizeof(_domain)-1] = 0;
4572 domain = _domain;
4573 }
4574 }
4575 }
4576
4577 fclose(resolv);
4578 }
4579
4580 if (domain)
4581 {
4582 int hl = strlen(host);
4583 int dl = strlen(domain);
4584 if (dl < hl && host[hl - dl - 1] == '.' && !strcmp(host + hl - dl, domain))
4585 host[hl -dl - 1] = 0;
4586 }
4587 else
4588 {
4589 *p = 0; // everything after first dot
4590 }
4591 }
4592 }
4593
4594 // Init data structures
4595 static void initdata(int optdebug, char *optconfig)
4596 {
4597 int i;
4598
4599 if (!(config = shared_malloc(sizeof(configt))))
4600 {
4601 fprintf(stderr, "Error doing malloc for configuration: %s\n", strerror(errno));
4602 exit(1);
4603 }
4604
4605 memset(config, 0, sizeof(configt));
4606 time(&config->start_time);
4607 strncpy(config->config_file, optconfig, strlen(optconfig));
4608 config->debug = optdebug;
4609 config->num_tbfs = MAXTBFS;
4610 config->rl_rate = 28; // 28kbps
4611 config->cluster_mcast_ttl = 1;
4612 config->cluster_master_min_adv = 1;
4613 config->ppp_restart_time = 3;
4614 config->ppp_max_configure = 10;
4615 config->ppp_max_failure = 5;
4616 config->kill_timedout_sessions = 1;
4617 strcpy(config->random_device, RANDOMDEVICE);
4618 // Set default value echo_timeout and idle_echo_timeout
4619 config->echo_timeout = ECHO_TIMEOUT;
4620 config->idle_echo_timeout = IDLE_ECHO_TIMEOUT;
4621 config->ppp_keepalive = 1;
4622 // Set default RDNSS lifetime
4623 config->dns6_lifetime = 1200;
4624
4625 log_stream = stderr;
4626
4627 #ifdef RINGBUFFER
4628 if (!(ringbuffer = shared_malloc(sizeof(struct Tringbuffer))))
4629 {
4630 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno));
4631 exit(1);
4632 }
4633 memset(ringbuffer, 0, sizeof(struct Tringbuffer));
4634 #endif
4635
4636 if (!(_statistics = shared_malloc(sizeof(struct Tstats))))
4637 {
4638 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno));
4639 exit(1);
4640 }
4641 if (!(tunnel = shared_malloc(sizeof(tunnelt) * MAXTUNNEL)))
4642 {
4643 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno));
4644 exit(1);
4645 }
4646 if (!(bundle = shared_malloc(sizeof(bundlet) * MAXBUNDLE)))
4647 {
4648 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno));
4649 exit(1);
4650 }
4651 if (!(frag = shared_malloc(sizeof(fragmentationt) * MAXBUNDLE)))
4652 {
4653 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno));
4654 exit(1);
4655 }
4656 if (!(session = shared_malloc(sizeof(sessiont) * MAXSESSION)))
4657 {
4658 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno));
4659 exit(1);
4660 }
4661
4662 if (!(sess_local = shared_malloc(sizeof(sessionlocalt) * MAXSESSION)))
4663 {
4664 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno));
4665 exit(1);
4666 }
4667
4668 if (!(radius = shared_malloc(sizeof(radiust) * MAXRADIUS)))
4669 {
4670 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno));
4671 exit(1);
4672 }
4673
4674 if (!(ip_address_pool = shared_malloc(sizeof(ippoolt) * MAXIPPOOL)))
4675 {
4676 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno));
4677 exit(1);
4678 }
4679
4680 if (!(ip_filters = shared_malloc(sizeof(ip_filtert) * MAXFILTER)))
4681 {
4682 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno));
4683 exit(1);
4684 }
4685 memset(ip_filters, 0, sizeof(ip_filtert) * MAXFILTER);
4686
4687 if (!(cli_session_actions = shared_malloc(sizeof(struct cli_session_actions) * MAXSESSION)))
4688 {
4689 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno));
4690 exit(1);
4691 }
4692 memset(cli_session_actions, 0, sizeof(struct cli_session_actions) * MAXSESSION);
4693
4694 if (!(cli_tunnel_actions = shared_malloc(sizeof(struct cli_tunnel_actions) * MAXSESSION)))
4695 {
4696 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno));
4697 exit(1);
4698 }
4699 memset(cli_tunnel_actions, 0, sizeof(struct cli_tunnel_actions) * MAXSESSION);
4700
4701 memset(tunnel, 0, sizeof(tunnelt) * MAXTUNNEL);
4702 memset(bundle, 0, sizeof(bundlet) * MAXBUNDLE);
4703 memset(session, 0, sizeof(sessiont) * MAXSESSION);
4704 memset(radius, 0, sizeof(radiust) * MAXRADIUS);
4705 memset(ip_address_pool, 0, sizeof(ippoolt) * MAXIPPOOL);
4706
4707 // Put all the sessions on the free list marked as undefined.
4708 for (i = 1; i < MAXSESSION; i++)
4709 {
4710 session[i].next = i + 1;
4711 session[i].tunnel = T_UNDEF; // mark it as not filled in.
4712 }
4713 session[MAXSESSION - 1].next = 0;
4714 sessionfree = 1;
4715
4716 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4717 for (i = 1; i < MAXTUNNEL; i++)
4718 tunnel[i].state = TUNNELUNDEF; // mark it as not filled in.
4719
4720 for (i = 1; i < MAXBUNDLE; i++) {
4721 bundle[i].state = BUNDLEUNDEF;
4722 }
4723
4724 if (!*hostname)
4725 {
4726 // Grab my hostname unless it's been specified
4727 gethostname(hostname, sizeof(hostname));
4728 stripdomain(hostname);
4729 }
4730
4731 _statistics->start_time = _statistics->last_reset = time(NULL);
4732
4733 #ifdef BGP
4734 if (!(bgp_peers = shared_malloc(sizeof(struct bgp_peer) * BGP_NUM_PEERS)))
4735 {
4736 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno));
4737 exit(1);
4738 }
4739 #endif /* BGP */
4740
4741 lac_initremotelnsdata();
4742 }
4743
4744 static int assign_ip_address(sessionidt s)
4745 {
4746 uint32_t i;
4747 int best = -1;
4748 time_t best_time = time_now;
4749 char *u = session[s].user;
4750 char reuse = 0;
4751
4752
4753 CSTAT(assign_ip_address);
4754
4755 for (i = 1; i < ip_pool_size; i++)
4756 {
4757 if (!ip_address_pool[i].address || ip_address_pool[i].assigned)
4758 continue;
4759
4760 if (!session[s].walled_garden && ip_address_pool[i].user[0] && !strcmp(u, ip_address_pool[i].user))
4761 {
4762 best = i;
4763 reuse = 1;
4764 break;
4765 }
4766
4767 if (ip_address_pool[i].last < best_time)
4768 {
4769 best = i;
4770 if (!(best_time = ip_address_pool[i].last))
4771 break; // never used, grab this one
4772 }
4773 }
4774
4775 if (best < 0)
4776 {
4777 LOG(0, s, session[s].tunnel, "assign_ip_address(): out of addresses\n");
4778 return 0;
4779 }
4780
4781 session[s].ip = ip_address_pool[best].address;
4782 session[s].ip_pool_index = best;
4783 ip_address_pool[best].assigned = 1;
4784 ip_address_pool[best].last = time_now;
4785 ip_address_pool[best].session = s;
4786 if (session[s].walled_garden)
4787 /* Don't track addresses of users in walled garden (note: this
4788 means that their address isn't "sticky" even if they get
4789 un-gardened). */
4790 ip_address_pool[best].user[0] = 0;
4791 else
4792 strncpy(ip_address_pool[best].user, u, sizeof(ip_address_pool[best].user) - 1);
4793
4794 STAT(ip_allocated);
4795 LOG(4, s, session[s].tunnel, "assign_ip_address(): %s ip address %d from pool\n",
4796 reuse ? "Reusing" : "Allocating", best);
4797
4798 return 1;
4799 }
4800
4801 static void free_ip_address(sessionidt s)
4802 {
4803 int i = session[s].ip_pool_index;
4804
4805
4806 CSTAT(free_ip_address);
4807
4808 if (!session[s].ip)
4809 return; // what the?
4810
4811 if (i < 0) // Is this actually part of the ip pool?
4812 i = 0;
4813
4814 STAT(ip_freed);
4815 cache_ipmap(session[s].ip, -i); // Change the mapping to point back to the ip pool index.
4816 session[s].ip = 0;
4817 ip_address_pool[i].assigned = 0;
4818 ip_address_pool[i].session = 0;
4819 ip_address_pool[i].last = time_now;
4820 }
4821
4822 //
4823 // Fsck the address pool against the session table.
4824 // Normally only called when we become a master.
4825 //
4826 // This isn't perfect: We aren't keep tracking of which
4827 // users used to have an IP address.
4828 //
4829 void rebuild_address_pool(void)
4830 {
4831 int i;
4832
4833 //
4834 // Zero the IP pool allocation, and build
4835 // a map from IP address to pool index.
4836 for (i = 1; i < MAXIPPOOL; ++i)
4837 {
4838 ip_address_pool[i].assigned = 0;
4839 ip_address_pool[i].session = 0;
4840 if (!ip_address_pool[i].address)
4841 continue;
4842
4843 cache_ipmap(ip_address_pool[i].address, -i); // Map pool IP to pool index.
4844 }
4845
4846 for (i = 0; i < MAXSESSION; ++i)
4847 {
4848 int ipid;
4849 if (!(session[i].opened && session[i].ip))
4850 continue;
4851
4852 ipid = - lookup_ipmap(htonl(session[i].ip));
4853
4854 if (session[i].ip_pool_index < 0)
4855 {
4856 // Not allocated out of the pool.
4857 if (ipid < 1) // Not found in the pool either? good.
4858 continue;
4859
4860 LOG(0, i, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4861 i, fmtaddr(session[i].ip, 0), ipid);
4862
4863 // Fall through and process it as part of the pool.
4864 }
4865
4866
4867 if (ipid > MAXIPPOOL || ipid < 0)
4868 {
4869 LOG(0, i, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i, ipid);
4870 ipid = -1;
4871 session[i].ip_pool_index = ipid;
4872 continue;
4873 }
4874
4875 ip_address_pool[ipid].assigned = 1;
4876 ip_address_pool[ipid].session = i;
4877 ip_address_pool[ipid].last = time_now;
4878 strncpy(ip_address_pool[ipid].user, session[i].user, sizeof(ip_address_pool[ipid].user) - 1);
4879 session[i].ip_pool_index = ipid;
4880 cache_ipmap(session[i].ip, i); // Fix the ip map.
4881 }
4882 }
4883
4884 //
4885 // Fix the address pool to match a changed session.
4886 // (usually when the master sends us an update).
4887 static void fix_address_pool(int sid)
4888 {
4889 int ipid;
4890
4891 ipid = session[sid].ip_pool_index;
4892
4893 if (ipid > ip_pool_size)
4894 return; // Ignore it. rebuild_address_pool will fix it up.
4895
4896 if (ip_address_pool[ipid].address != session[sid].ip)
4897 return; // Just ignore it. rebuild_address_pool will take care of it.
4898
4899 ip_address_pool[ipid].assigned = 1;
4900 ip_address_pool[ipid].session = sid;
4901 ip_address_pool[ipid].last = time_now;
4902 strncpy(ip_address_pool[ipid].user, session[sid].user, sizeof(ip_address_pool[ipid].user) - 1);
4903 }
4904
4905 //
4906 // Add a block of addresses to the IP pool to hand out.
4907 //
4908 static void add_to_ip_pool(in_addr_t addr, int prefixlen)
4909 {
4910 int i;
4911 if (prefixlen == 0)
4912 prefixlen = 32; // Host route only.
4913
4914 addr &= 0xffffffff << (32 - prefixlen);
4915
4916 if (ip_pool_size >= MAXIPPOOL) // Pool is full!
4917 return ;
4918
4919 for (i = addr ; i < addr+(1<<(32-prefixlen)); ++i)
4920 {
4921 if ((i & 0xff) == 0 || (i&0xff) == 255)
4922 continue; // Skip 0 and broadcast addresses.
4923
4924 ip_address_pool[ip_pool_size].address = i;
4925 ip_address_pool[ip_pool_size].assigned = 0;
4926 ++ip_pool_size;
4927 if (ip_pool_size >= MAXIPPOOL)
4928 {
4929 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr), 0));
4930 return;
4931 }
4932 }
4933 }
4934
4935 // Initialize the IP address pool
4936 static void initippool()
4937 {
4938 FILE *f;
4939 char *p;
4940 char buf[4096];
4941 memset(ip_address_pool, 0, sizeof(ip_address_pool));
4942
4943 if (!(f = fopen(IPPOOLFILE, "r")))
4944 {
4945 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE ": %s\n", strerror(errno));
4946 exit(1);
4947 }
4948
4949 while (ip_pool_size < MAXIPPOOL && fgets(buf, 4096, f))
4950 {
4951 char *pool = buf;
4952 buf[4095] = 0; // Force it to be zero terminated/
4953
4954 if (*buf == '#' || *buf == '\n')
4955 continue; // Skip comments / blank lines
4956 if ((p = (char *)strrchr(buf, '\n'))) *p = 0;
4957 if ((p = (char *)strchr(buf, ':')))
4958 {
4959 in_addr_t src;
4960 *p = '\0';
4961 src = inet_addr(buf);
4962 if (src == INADDR_NONE)
4963 {
4964 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf);
4965 exit(1);
4966 }
4967 // This entry is for a specific IP only
4968 if (src != config->bind_address)
4969 continue;
4970 *p = ':';
4971 pool = p+1;
4972 }
4973 if ((p = (char *)strchr(pool, '/')))
4974 {
4975 // It's a range
4976 int numbits = 0;
4977 in_addr_t start = 0;
4978
4979 LOG(2, 0, 0, "Adding IP address range %s\n", buf);
4980 *p++ = 0;
4981 if (!*p || !(numbits = atoi(p)))
4982 {
4983 LOG(0, 0, 0, "Invalid pool range %s\n", buf);
4984 continue;
4985 }
4986 start = ntohl(inet_addr(pool));
4987
4988 // Add a static route for this pool
4989 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4990 fmtaddr(htonl(start), 0), numbits);
4991
4992 routeset(0, start, numbits, 0, 1);
4993
4994 add_to_ip_pool(start, numbits);
4995 }
4996 else
4997 {
4998 // It's a single ip address
4999 add_to_ip_pool(ntohl(inet_addr(pool)), 0);
5000 }
5001 }
5002 fclose(f);
5003 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size - 1);
5004 }
5005
5006 void snoop_send_packet(uint8_t *packet, uint16_t size, in_addr_t destination, uint16_t port)
5007 {
5008 struct sockaddr_in snoop_addr = {0};
5009 if (!destination || !port || snoopfd <= 0 || size <= 0 || !packet)
5010 return;
5011
5012 snoop_addr.sin_family = AF_INET;
5013 snoop_addr.sin_addr.s_addr = destination;
5014 snoop_addr.sin_port = ntohs(port);
5015
5016 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size,
5017 fmtaddr(snoop_addr.sin_addr.s_addr, 0),
5018 htons(snoop_addr.sin_port));
5019
5020 if (sendto(snoopfd, packet, size, MSG_DONTWAIT | MSG_NOSIGNAL, (void *) &snoop_addr, sizeof(snoop_addr)) < 0)
5021 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno));
5022
5023 STAT(packets_snooped);
5024 }
5025
5026 static int dump_session(FILE **f, sessiont *s)
5027 {
5028 if (!s->opened || (!s->ip && !s->forwardtosession) || !(s->cin_delta || s->cout_delta) || !*s->user || s->walled_garden)
5029 return 1;
5030
5031 if (!*f)
5032 {
5033 char filename[1024];
5034 char timestr[64];
5035 time_t now = time(NULL);
5036
5037 strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&now));
5038 snprintf(filename, sizeof(filename), "%s/%s", config->accounting_dir, timestr);
5039
5040 if (!(*f = fopen(filename, "w")))
5041 {
5042 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename, strerror(errno));
5043 return 0;
5044 }
5045
5046 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename);
5047 if(config->account_all_origin)
5048 {
5049 fprintf(*f, "# dslwatch.pl dump file V1.01\n"
5050 "# host: %s\n"
5051 "# endpoint: %s\n"
5052 "# time: %ld\n"
5053 "# uptime: %ld\n"
5054 "# format: username ip qos uptxoctets downrxoctets origin(L=LAC, R=Remote LNS, P=PPPOE)\n",
5055 hostname,
5056 fmtaddr(config->iftun_n_address[tunnel[s->tunnel].indexudp] ? config->iftun_n_address[tunnel[s->tunnel].indexudp] : my_address, 0),
5057 now,
5058 now - basetime);
5059 }
5060 else
5061 {
5062 fprintf(*f, "# dslwatch.pl dump file V1.01\n"
5063 "# host: %s\n"
5064 "# endpoint: %s\n"
5065 "# time: %ld\n"
5066 "# uptime: %ld\n"
5067 "# format: username ip qos uptxoctets downrxoctets\n",
5068 hostname,
5069 fmtaddr(config->iftun_n_address[tunnel[s->tunnel].indexudp] ? config->iftun_n_address[tunnel[s->tunnel].indexudp] : my_address, 0),
5070 now,
5071 now - basetime);
5072 }
5073 }
5074
5075 LOG(4, 0, 0, "Dumping accounting information for %s\n", s->user);
5076 if(config->account_all_origin)
5077 {
5078 fprintf(*f, "%s %s %d %u %u %s\n",
5079 s->user, // username
5080 fmtaddr(htonl(s->ip), 0), // ip
5081 (s->throttle_in || s->throttle_out) ? 2 : 1, // qos
5082 (uint32_t) s->cin_delta, // uptxoctets
5083 (uint32_t) s->cout_delta, // downrxoctets
5084 (s->tunnel == TUNNEL_ID_PPPOE)?"P":(tunnel[s->tunnel].isremotelns?"R":"L")); // Origin
5085 }
5086 else if (!tunnel[s->tunnel].isremotelns && (s->tunnel != TUNNEL_ID_PPPOE))
5087 {
5088 fprintf(*f, "%s %s %d %u %u\n",
5089 s->user, // username
5090 fmtaddr(htonl(s->ip), 0), // ip
5091 (s->throttle_in || s->throttle_out) ? 2 : 1, // qos
5092 (uint32_t) s->cin_delta, // uptxoctets
5093 (uint32_t) s->cout_delta); // downrxoctets
5094 }
5095
5096 s->cin_delta = s->cout_delta = 0;
5097
5098 return 1;
5099 }
5100
5101 static void dump_acct_info(int all)
5102 {
5103 int i;
5104 FILE *f = NULL;
5105
5106
5107 CSTAT(dump_acct_info);
5108
5109 if (shut_acct_n)
5110 {
5111 for (i = 0; i < shut_acct_n; i++)
5112 dump_session(&f, &shut_acct[i]);
5113
5114 shut_acct_n = 0;
5115 }
5116
5117 if (all)
5118 for (i = 1; i <= config->cluster_highest_sessionid; i++)
5119 dump_session(&f, &session[i]);
5120
5121 if (f)
5122 fclose(f);
5123 }
5124
5125 // Main program
5126 int main(int argc, char *argv[])
5127 {
5128 int i;
5129 int optdebug = 0;
5130 char *optconfig = CONFIGFILE;
5131
5132 time(&basetime); // start clock
5133
5134 // scan args
5135 while ((i = getopt(argc, argv, "dvc:h:")) >= 0)
5136 {
5137 switch (i)
5138 {
5139 case 'd':
5140 if (fork()) exit(0);
5141 setsid();
5142 if(!freopen("/dev/null", "r", stdin)) LOG(0, 0, 0, "Error freopen stdin: %s\n", strerror(errno));
5143 if(!freopen("/dev/null", "w", stdout)) LOG(0, 0, 0, "Error freopen stdout: %s\n", strerror(errno));
5144 if(!freopen("/dev/null", "w", stderr)) LOG(0, 0, 0, "Error freopen stderr: %s\n", strerror(errno));
5145 break;
5146 case 'v':
5147 optdebug++;
5148 break;
5149 case 'c':
5150 optconfig = optarg;
5151 break;
5152 case 'h':
5153 snprintf(hostname, sizeof(hostname), "%s", optarg);
5154 break;
5155 default:
5156 printf("Args are:\n"
5157 "\t-d\t\tDetach from terminal\n"
5158 "\t-c <file>\tConfig file\n"
5159 "\t-h <hostname>\tForce hostname\n"
5160 "\t-v\t\tDebug\n");
5161
5162 return (0);
5163 break;
5164 }
5165 }
5166
5167 // Start the timer routine off
5168 time(&time_now);
5169 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
5170
5171 initplugins();
5172 initdata(optdebug, optconfig);
5173
5174 init_cli();
5175 read_config_file();
5176 /* set hostname /after/ having read the config file */
5177 if (*config->hostname)
5178 strcpy(hostname, config->hostname);
5179 cli_init_complete(hostname);
5180 update_config();
5181 init_tbf(config->num_tbfs);
5182
5183 LOG(0, 0, 0, "L2TPNS version " VERSION "\n");
5184 LOG(0, 0, 0, "Copyright (c) 2012, 2013, 2014 ISP FDN & SAMESWIRELESS\n");
5185 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5186 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5187 {
5188 struct rlimit rlim;
5189 rlim.rlim_cur = RLIM_INFINITY;
5190 rlim.rlim_max = RLIM_INFINITY;
5191 // Remove the maximum core size
5192 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
5193 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno));
5194
5195 // Make core dumps go to /tmp
5196 if(chdir("/tmp")) LOG(0, 0, 0, "Error chdir /tmp: %s\n", strerror(errno));
5197 }
5198
5199 if (config->scheduler_fifo)
5200 {
5201 int ret;
5202 struct sched_param params = {0};
5203 params.sched_priority = 1;
5204
5205 if (get_nprocs() < 2)
5206 {
5207 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5208 config->scheduler_fifo = 0;
5209 }
5210 else
5211 {
5212 if ((ret = sched_setscheduler(0, SCHED_FIFO, &params)) == 0)
5213 {
5214 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5215 }
5216 else
5217 {
5218 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno));
5219 config->scheduler_fifo = 0;
5220 }
5221 }
5222 }
5223
5224 initnetlink();
5225
5226 /* Set up the cluster communications port. */
5227 if (cluster_init() < 0)
5228 exit(1);
5229
5230 inittun();
5231 LOG(1, 0, 0, "Set up on interface %s\n", config->tundevicename);
5232
5233 if (*config->pppoe_if_to_bind)
5234 {
5235 init_pppoe();
5236 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config->pppoe_if_to_bind);
5237 }
5238
5239 if (!config->nbmultiaddress)
5240 {
5241 config->bind_n_address[0] = config->bind_address;
5242 config->nbmultiaddress++;
5243 }
5244 config->nbudpfd = config->nbmultiaddress;
5245 for (i = 0; i < config->nbudpfd; i++)
5246 initudp(&udpfd[i], config->bind_n_address[i]);
5247 initlacudp();
5248 config->indexlacudpfd = config->nbudpfd;
5249 udpfd[config->indexlacudpfd] = udplacfd;
5250 config->nbudpfd++;
5251
5252 initcontrol();
5253 initdae();
5254
5255 // Intercept
5256 snoopfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
5257
5258 initrad();
5259 initippool();
5260 dhcpv6_init();
5261
5262 // seed prng
5263 {
5264 unsigned seed = time_now ^ getpid();
5265 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed);
5266 srand(seed);
5267 }
5268
5269 signal(SIGHUP, sighup_handler);
5270 signal(SIGCHLD, sigchild_handler);
5271 signal(SIGTERM, shutdown_handler);
5272 signal(SIGINT, shutdown_handler);
5273 signal(SIGQUIT, shutdown_handler);
5274
5275 // Prevent us from getting paged out
5276 if (config->lock_pages)
5277 {
5278 if (!mlockall(MCL_CURRENT))
5279 LOG(1, 0, 0, "Locking pages into memory\n");
5280 else
5281 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno));
5282 }
5283
5284 mainloop();
5285
5286 /* remove plugins (so cleanup code gets run) */
5287 plugins_done();
5288
5289 // Remove the PID file if we wrote it
5290 if (config->wrote_pid && *config->pid_file == '/')
5291 unlink(config->pid_file);
5292
5293 /* kill CLI children */
5294 signal(SIGTERM, SIG_IGN);
5295 kill(0, SIGTERM);
5296 return 0;
5297 }
5298
5299 static void sighup_handler(int sig)
5300 {
5301 main_reload++;
5302 }
5303
5304 static void shutdown_handler(int sig)
5305 {
5306 main_quit = (sig == SIGQUIT) ? QUIT_SHUTDOWN : QUIT_FAILOVER;
5307 }
5308
5309 static void sigchild_handler(int sig)
5310 {
5311 while (waitpid(-1, NULL, WNOHANG) > 0)
5312 ;
5313 }
5314
5315 static void build_chap_response(uint8_t *challenge, uint8_t id, uint16_t challenge_length, uint8_t **challenge_response)
5316 {
5317 MD5_CTX ctx;
5318 *challenge_response = NULL;
5319
5320 if (!*config->l2tp_secret)
5321 {
5322 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5323 return;
5324 }
5325
5326 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5327
5328 *challenge_response = calloc(17, 1);
5329
5330 MD5_Init(&ctx);
5331 MD5_Update(&ctx, &id, 1);
5332 MD5_Update(&ctx, config->l2tp_secret, strlen(config->l2tp_secret));
5333 MD5_Update(&ctx, challenge, challenge_length);
5334 MD5_Final(*challenge_response, &ctx);
5335
5336 return;
5337 }
5338
5339 static int facility_value(char *name)
5340 {
5341 int i;
5342 for (i = 0; facilitynames[i].c_name; i++)
5343 {
5344 if (strcmp(facilitynames[i].c_name, name) == 0)
5345 return facilitynames[i].c_val;
5346 }
5347 return 0;
5348 }
5349
5350 static void update_config()
5351 {
5352 int i;
5353 char *p;
5354 static int timeout = 0;
5355 static int interval = 0;
5356
5357 // Update logging
5358 closelog();
5359 syslog_log = 0;
5360 if (log_stream)
5361 {
5362 if (log_stream != stderr)
5363 fclose(log_stream);
5364
5365 log_stream = NULL;
5366 }
5367
5368 if (*config->log_filename)
5369 {
5370 if (strstr(config->log_filename, "syslog:") == config->log_filename)
5371 {
5372 char *p = config->log_filename + 7;
5373 if (*p)
5374 {
5375 openlog("l2tpns", LOG_PID, facility_value(p));
5376 syslog_log = 1;
5377 }
5378 }
5379 else if (strchr(config->log_filename, '/') == config->log_filename)
5380 {
5381 if ((log_stream = fopen((char *)(config->log_filename), "a")))
5382 {
5383 fseek(log_stream, 0, SEEK_END);
5384 setbuf(log_stream, NULL);
5385 }
5386 else
5387 {
5388 log_stream = stderr;
5389 setbuf(log_stream, NULL);
5390 }
5391 }
5392 }
5393 else
5394 {
5395 log_stream = stderr;
5396 setbuf(log_stream, NULL);
5397 }
5398
5399 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5400 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5401
5402 if (config->l2tp_mtu <= 0) config->l2tp_mtu = 1500; // ethernet default
5403 else if (config->l2tp_mtu < MINMTU) config->l2tp_mtu = MINMTU;
5404 else if (config->l2tp_mtu > MAXMTU) config->l2tp_mtu = MAXMTU;
5405
5406 // reset MRU/MSS globals
5407 MRU = config->l2tp_mtu - L2TP_HDRS;
5408 if (MRU > PPPoE_MRU)
5409 MRU = PPPoE_MRU;
5410
5411 MSS = MRU - TCP_HDRS;
5412
5413 // Update radius
5414 config->numradiusservers = 0;
5415 for (i = 0; i < MAXRADSERVER; i++)
5416 if (config->radiusserver[i])
5417 {
5418 config->numradiusservers++;
5419 // Set radius port: if not set, take the port from the
5420 // first radius server. For the first radius server,
5421 // take the #defined default value from l2tpns.h
5422
5423 // test twice, In case someone works with
5424 // a secondary radius server without defining
5425 // a primary one, this will work even then.
5426 if (i > 0 && !config->radiusport[i])
5427 config->radiusport[i] = config->radiusport[i-1];
5428 if (!config->radiusport[i])
5429 config->radiusport[i] = RADPORT;
5430 }
5431
5432 if (!config->numradiusservers)
5433 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5434
5435 // parse radius_authtypes_s
5436 config->radius_authtypes = config->radius_authprefer = 0;
5437 p = config->radius_authtypes_s;
5438 while (p && *p)
5439 {
5440 char *s = strpbrk(p, " \t,");
5441 int type = 0;
5442
5443 if (s)
5444 {
5445 *s++ = 0;
5446 while (*s == ' ' || *s == '\t')
5447 s++;
5448
5449 if (!*s)
5450 s = 0;
5451 }
5452
5453 if (!strncasecmp("chap", p, strlen(p)))
5454 type = AUTHCHAP;
5455 else if (!strncasecmp("pap", p, strlen(p)))
5456 type = AUTHPAP;
5457 else
5458 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p);
5459
5460 config->radius_authtypes |= type;
5461 if (!config->radius_authprefer)
5462 config->radius_authprefer = type;
5463
5464 p = s;
5465 }
5466
5467 if (!config->radius_authtypes)
5468 {
5469 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5470 config->radius_authtypes = config->radius_authprefer = AUTHPAP;
5471 }
5472
5473 // normalise radius_authtypes_s
5474 if (config->radius_authprefer == AUTHPAP)
5475 {
5476 strcpy(config->radius_authtypes_s, "pap");
5477 if (config->radius_authtypes & AUTHCHAP)
5478 strcat(config->radius_authtypes_s, ", chap");
5479 }
5480 else
5481 {
5482 strcpy(config->radius_authtypes_s, "chap");
5483 if (config->radius_authtypes & AUTHPAP)
5484 strcat(config->radius_authtypes_s, ", pap");
5485 }
5486
5487 if (!config->radius_dae_port)
5488 config->radius_dae_port = DAEPORT;
5489
5490 if(!config->bind_portremotelns)
5491 config->bind_portremotelns = L2TPLACPORT;
5492 if(!config->bind_address_remotelns)
5493 config->bind_address_remotelns = INADDR_ANY;
5494
5495 if (*config->bind_multi_address)
5496 {
5497 char *sip = config->bind_multi_address;
5498 char *n = sip;
5499 char *e = config->bind_multi_address + strlen(config->bind_multi_address);
5500 config->nbmultiaddress = 0;
5501
5502 while (*sip && (sip < e))
5503 {
5504 in_addr_t ip = 0;
5505 uint8_t u = 0;
5506
5507 while (n < e && (*n == ',' || *n == ' ')) n++;
5508
5509 while (n < e && (isdigit(*n) || *n == '.'))
5510 {
5511 if (*n == '.')
5512 {
5513 ip = (ip << 8) + u;
5514 u = 0;
5515 }
5516 else
5517 u = u * 10 + *n - '0';
5518 n++;
5519 }
5520 ip = (ip << 8) + u;
5521 n++;
5522
5523 if (ip)
5524 {
5525 config->bind_n_address[config->nbmultiaddress] = htonl(ip);
5526 config->iftun_n_address[config->nbmultiaddress] = htonl(ip);
5527 config->nbmultiaddress++;
5528 LOG(1, 0, 0, "Bind address %s\n", fmtaddr(htonl(ip), 0));
5529
5530 if (config->nbmultiaddress >= MAX_BINDADDR) break;
5531 }
5532
5533 sip = n;
5534 }
5535
5536 if (config->nbmultiaddress >= 1)
5537 {
5538 config->bind_address = config->bind_n_address[0];
5539 config->iftun_address = config->bind_address;
5540 }
5541 }
5542
5543 if(!config->iftun_address)
5544 {
5545 config->iftun_address = config->bind_address;
5546 config->iftun_n_address[0] = config->iftun_address;
5547 }
5548
5549 if (*config->multi_hostname)
5550 {
5551 char *shost = config->multi_hostname;
5552 char *n = shost;
5553 char *e = config->multi_hostname + strlen(config->multi_hostname);
5554 config->nbmultihostname = 0;
5555
5556 while (*shost && (shost < e))
5557 {
5558 while ((n < e) && (*n == ' ' || *n == ',' || *n == '\t')) n++;
5559
5560 i = 0;
5561 while (n < e && (*n != ',') && (*n != '\t'))
5562 {
5563 config->multi_n_hostname[config->nbmultihostname][i] = *n;
5564 n++;i++;
5565 }
5566
5567 if (i > 0)
5568 {
5569 config->multi_n_hostname[config->nbmultihostname][i] = 0;
5570 LOG(1, 0, 0, "Bind Hostname %s\n", config->multi_n_hostname[config->nbmultihostname]);
5571 config->nbmultihostname++;
5572 if (config->nbmultihostname >= MAX_NBHOSTNAME) break;
5573 }
5574
5575 shost = n;
5576 }
5577
5578 if (config->nbmultihostname >= 1)
5579 {
5580 strcpy(hostname, config->multi_n_hostname[0]);
5581 strcpy(config->hostname, hostname);
5582 }
5583 }
5584
5585 if (!*config->pppoe_ac_name)
5586 strncpy(config->pppoe_ac_name, DEFAULT_PPPOE_AC_NAME, sizeof(config->pppoe_ac_name) - 1);
5587
5588 // re-initialise the random number source
5589 initrandom(config->random_device);
5590
5591 // Update plugins
5592 for (i = 0; i < MAXPLUGINS; i++)
5593 {
5594 if (strcmp(config->plugins[i], config->old_plugins[i]) == 0)
5595 continue;
5596
5597 if (*config->plugins[i])
5598 {
5599 // Plugin added
5600 add_plugin(config->plugins[i]);
5601 }
5602 else if (*config->old_plugins[i])
5603 {
5604 // Plugin removed
5605 remove_plugin(config->old_plugins[i]);
5606 }
5607 }
5608
5609 // Guest change
5610 guest_accounts_num = 0;
5611 char *p2 = config->guest_user;
5612 while (p2 && *p2)
5613 {
5614 char *s = strpbrk(p2, " \t,");
5615 if (s)
5616 {
5617 *s++ = 0;
5618 while (*s == ' ' || *s == '\t')
5619 s++;
5620
5621 if (!*s)
5622 s = 0;
5623 }
5624
5625 strcpy(guest_users[guest_accounts_num], p2);
5626 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num, guest_users[guest_accounts_num]);
5627 guest_accounts_num++;
5628 p2 = s;
5629 }
5630 // Rebuild the guest_user array
5631 strcpy(config->guest_user, "");
5632 int ui = 0;
5633 for (ui=0; ui<guest_accounts_num; ui++)
5634 {
5635 strcat(config->guest_user, guest_users[ui]);
5636 if (ui<guest_accounts_num-1)
5637 {
5638 strcat(config->guest_user, ",");
5639 }
5640 }
5641
5642
5643 memcpy(config->old_plugins, config->plugins, sizeof(config->plugins));
5644 if (!config->multi_read_count) config->multi_read_count = 10;
5645 if (!config->cluster_address) config->cluster_address = inet_addr(DEFAULT_MCAST_ADDR);
5646 if (!config->cluster_port) config->cluster_port = CLUSTERPORT;
5647 if (!*config->cluster_interface)
5648 strncpy(config->cluster_interface, DEFAULT_MCAST_INTERFACE, sizeof(config->cluster_interface) - 1);
5649
5650 if (!config->cluster_hb_interval)
5651 config->cluster_hb_interval = PING_INTERVAL; // Heartbeat every 0.5 seconds.
5652
5653 if (!config->cluster_hb_timeout)
5654 config->cluster_hb_timeout = HB_TIMEOUT; // 10 missed heartbeat triggers an election.
5655
5656 if (interval != config->cluster_hb_interval || timeout != config->cluster_hb_timeout)
5657 {
5658 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5659 // late, ensure we're sufficiently larger than that
5660 int t = 4 * config->cluster_hb_interval + 11;
5661
5662 if (config->cluster_hb_timeout < t)
5663 {
5664 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config->cluster_hb_timeout, t);
5665 config->cluster_hb_timeout = t;
5666 }
5667
5668 // Push timing changes to the slaves immediately if we're the master
5669 if (config->cluster_iam_master)
5670 cluster_heartbeat();
5671
5672 interval = config->cluster_hb_interval;
5673 timeout = config->cluster_hb_timeout;
5674 }
5675
5676 // Write PID file
5677 if (*config->pid_file == '/' && !config->wrote_pid)
5678 {
5679 FILE *f;
5680 if ((f = fopen(config->pid_file, "w")))
5681 {
5682 fprintf(f, "%d\n", getpid());
5683 fclose(f);
5684 config->wrote_pid = 1;
5685 }
5686 else
5687 {
5688 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config->pid_file, strerror(errno));
5689 }
5690 }
5691 }
5692
5693 static void read_config_file()
5694 {
5695 FILE *f;
5696
5697 if (!config->config_file) return;
5698 if (!(f = fopen(config->config_file, "r")))
5699 {
5700 fprintf(stderr, "Can't open config file %s: %s\n", config->config_file, strerror(errno));
5701 return;
5702 }
5703
5704 LOG(3, 0, 0, "Reading config file %s\n", config->config_file);
5705 cli_do_file(f);
5706 LOG(3, 0, 0, "Done reading config file\n");
5707 fclose(f);
5708 }
5709
5710 int sessionsetup(sessionidt s, tunnelidt t)
5711 {
5712 // A session now exists, set it up
5713 in_addr_t ip;
5714 char *user;
5715 sessionidt i;
5716 int r;
5717
5718 CSTAT(sessionsetup);
5719
5720 LOG(3, s, t, "Doing session setup for session\n");
5721
5722 // Join a bundle if the MRRU option is accepted
5723 if(session[s].mrru > 0 && session[s].bundle == 0)
5724 {
5725 LOG(3, s, t, "This session can be part of multilink bundle\n");
5726 if (join_bundle(s) > 0)
5727 cluster_send_bundle(session[s].bundle);
5728 else
5729 {
5730 LOG(0, s, t, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5731 sessionshutdown(s, "Mismaching mssf option.", CDN_NONE, TERM_SERVICE_UNAVAILABLE);
5732 return 0;
5733 }
5734 }
5735
5736 if (!session[s].ip)
5737 {
5738 assign_ip_address(s);
5739 if (!session[s].ip)
5740 {
5741 LOG(0, s, t, " No IP allocated. The IP address pool is FULL!\n");
5742 sessionshutdown(s, "No IP addresses available.", CDN_TRY_ANOTHER, TERM_SERVICE_UNAVAILABLE);
5743 return 0;
5744 }
5745 LOG(3, s, t, " No IP allocated. Assigned %s from pool\n",
5746 fmtaddr(htonl(session[s].ip), 0));
5747 }
5748
5749 // Make sure this is right
5750 session[s].tunnel = t;
5751
5752 // zap old sessions with same IP and/or username
5753 // Don't kill gardened sessions - doing so leads to a DoS
5754 // from someone who doesn't need to know the password
5755 {
5756 ip = session[s].ip;
5757 user = session[s].user;
5758 for (i = 1; i <= config->cluster_highest_sessionid; i++)
5759 {
5760 if (i == s) continue;
5761 if (!session[s].opened) break;
5762 // Allow duplicate sessions for multilink ones of the same bundle.
5763 if (session[s].bundle && session[i].bundle && session[s].bundle == session[i].bundle) continue;
5764
5765 if (ip == session[i].ip)
5766 {
5767 sessionshutdown(i, "Duplicate IP address", CDN_ADMIN_DISC, TERM_ADMIN_RESET); // close radius/routes, etc.
5768 continue;
5769 }
5770
5771 if (config->allow_duplicate_users) continue;
5772 if (session[s].walled_garden || session[i].walled_garden) continue;
5773 // Guest change
5774 int found = 0;
5775 int gu;
5776 for (gu = 0; gu < guest_accounts_num; gu++)
5777 {
5778 if (!strcasecmp(user, guest_users[gu]))
5779 {
5780 found = 1;
5781 break;
5782 }
5783 }
5784 if (found) continue;
5785
5786 // Drop the new session in case of duplicate sessionss, not the old one.
5787 if (!strcasecmp(user, session[i].user))
5788 sessionshutdown(i, "Duplicate session for users", CDN_ADMIN_DISC, TERM_ADMIN_RESET); // close radius/routes, etc.
5789 }
5790 }
5791
5792 // no need to set a route for the same IP address of the bundle
5793 if (!session[s].bundle || (bundle[session[s].bundle].num_of_links == 1))
5794 {
5795 int routed = 0;
5796
5797 // Add the route for this session.
5798 for (r = 0; r < MAXROUTE && session[s].route[r].ip; r++)
5799 {
5800 if ((session[s].ip >> (32-session[s].route[r].prefixlen)) ==
5801 (session[s].route[r].ip >> (32-session[s].route[r].prefixlen)))
5802 routed++;
5803
5804 routeset(s, session[s].route[r].ip, session[s].route[r].prefixlen, 0, 1);
5805 }
5806
5807 // Static IPs need to be routed if not already
5808 // convered by a Framed-Route. Anything else is part
5809 // of the IP address pool and is already routed, it
5810 // just needs to be added to the IP cache.
5811 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5812 if (session[s].ip_pool_index == -1) // static ip
5813 {
5814 if (!routed) routeset(s, session[s].ip, 0, 0, 1);
5815 }
5816 else
5817 cache_ipmap(session[s].ip, s);
5818 }
5819
5820 sess_local[s].lcp_authtype = 0; // RADIUS authentication complete
5821 lcp_open(s, t); // transition to Network phase and send initial IPCP
5822
5823 // Run the plugin's against this new session.
5824 {
5825 struct param_new_session data = { &tunnel[t], &session[s] };
5826 run_plugins(PLUGIN_NEW_SESSION, &data);
5827 }
5828
5829 // Allocate TBFs if throttled
5830 if (session[s].throttle_in || session[s].throttle_out)
5831 throttle_session(s, session[s].throttle_in, session[s].throttle_out);
5832
5833 session[s].last_packet = session[s].last_data = time_now;
5834
5835 LOG(2, s, t, "Login by %s at %s from %s (%s)\n", session[s].user,
5836 fmtaddr(htonl(session[s].ip), 0),
5837 fmtaddr(htonl(tunnel[t].ip), 1), tunnel[t].hostname);
5838
5839 cluster_send_session(s); // Mark it as dirty, and needing to the flooded to the cluster.
5840
5841 return 1; // RADIUS OK and IP allocated, done...
5842 }
5843
5844 //
5845 // This session just got dropped on us by the master or something.
5846 // Make sure our tables up up to date...
5847 //
5848 int load_session(sessionidt s, sessiont *new)
5849 {
5850 int i;
5851 int newip = 0;
5852
5853 // Sanity checks.
5854 if (new->ip_pool_index >= MAXIPPOOL ||
5855 new->tunnel >= MAXTUNNEL)
5856 {
5857 LOG(0, s, 0, "Strange session update received!\n");
5858 // FIXME! What to do here?
5859 return 0;
5860 }
5861
5862 //
5863 // Ok. All sanity checks passed. Now we're committed to
5864 // loading the new session.
5865 //
5866
5867 session[s].tunnel = new->tunnel; // For logging in cache_ipmap
5868
5869 // See if routes/ip cache need updating
5870 if (new->ip != session[s].ip)
5871 newip++;
5872
5873 for (i = 0; !newip && i < MAXROUTE && (session[s].route[i].ip || new->route[i].ip); i++)
5874 if (new->route[i].ip != session[s].route[i].ip ||
5875 new->route[i].prefixlen != session[s].route[i].prefixlen)
5876 newip++;
5877
5878 // needs update
5879 if (newip)
5880 {
5881 int routed = 0;
5882
5883 // remove old routes...
5884 for (i = 0; i < MAXROUTE && session[s].route[i].ip; i++)
5885 {
5886 if ((session[s].ip >> (32-session[s].route[i].prefixlen)) ==
5887 (session[s].route[i].ip >> (32-session[s].route[i].prefixlen)))
5888 routed++;
5889
5890 routeset(s, session[s].route[i].ip, session[s].route[i].prefixlen, 0, 0);
5891 }
5892
5893 // ...ip
5894 if (session[s].ip)
5895 {
5896 if (session[s].ip_pool_index == -1) // static IP
5897 {
5898 if (!routed) routeset(s, session[s].ip, 0, 0, 0);
5899 }
5900 else // It's part of the IP pool, remove it manually.
5901 uncache_ipmap(session[s].ip);
5902 }
5903
5904 // remove old IPV6 routes...
5905 for (i = 0; i < MAXROUTE6 && session[s].route6[i].ipv6route.s6_addr[0] && session[s].route6[i].ipv6prefixlen; i++)
5906 {
5907 route6set(s, session[s].route6[i].ipv6route, session[s].route6[i].ipv6prefixlen, 0);
5908 }
5909
5910 if (session[s].ipv6address.s6_addr[0])
5911 {
5912 route6set(s, session[s].ipv6address, 128, 0);
5913 }
5914
5915 routed = 0;
5916
5917 // add new routes...
5918 for (i = 0; i < MAXROUTE && new->route[i].ip; i++)
5919 {
5920 if ((new->ip >> (32-new->route[i].prefixlen)) ==
5921 (new->route[i].ip >> (32-new->route[i].prefixlen)))
5922 routed++;
5923
5924 routeset(s, new->route[i].ip, new->route[i].prefixlen, 0, 1);
5925 }
5926
5927 // ...ip
5928 if (new->ip)
5929 {
5930 // If there's a new one, add it.
5931 if (new->ip_pool_index == -1)
5932 {
5933 if (!routed) routeset(s, new->ip, 0, 0, 1);
5934 }
5935 else
5936 cache_ipmap(new->ip, s);
5937 }
5938 }
5939
5940 // check v6 routing
5941 if (new->ppp.ipv6cp == Opened && session[s].ppp.ipv6cp != Opened)
5942 {
5943 for (i = 0; i < MAXROUTE6 && new->route6[i].ipv6prefixlen; i++)
5944 {
5945 route6set(s, new->route6[i].ipv6route, new->route6[i].ipv6prefixlen, 1);
5946 }
5947 }
5948
5949 if (new->ipv6address.s6_addr[0] && new->ppp.ipv6cp == Opened && session[s].ppp.ipv6cp != Opened)
5950 {
5951 // Check if included in prefix
5952 if (sessionbyipv6(new->ipv6address) != s)
5953 route6set(s, new->ipv6address, 128, 1);
5954 }
5955
5956 // check filters
5957 if (new->filter_in && (new->filter_in > MAXFILTER || !ip_filters[new->filter_in - 1].name[0]))
5958 {
5959 LOG(2, s, session[s].tunnel, "Dropping invalid input filter %u\n", (int) new->filter_in);
5960 new->filter_in = 0;
5961 }
5962
5963 if (new->filter_out && (new->filter_out > MAXFILTER || !ip_filters[new->filter_out - 1].name[0]))
5964 {
5965 LOG(2, s, session[s].tunnel, "Dropping invalid output filter %u\n", (int) new->filter_out);
5966 new->filter_out = 0;
5967 }
5968
5969 if (new->filter_in != session[s].filter_in)
5970 {
5971 if (session[s].filter_in) ip_filters[session[s].filter_in - 1].used--;
5972 if (new->filter_in) ip_filters[new->filter_in - 1].used++;
5973 }
5974
5975 if (new->filter_out != session[s].filter_out)
5976 {
5977 if (session[s].filter_out) ip_filters[session[s].filter_out - 1].used--;
5978 if (new->filter_out) ip_filters[new->filter_out - 1].used++;
5979 }
5980
5981 if (new->tunnel && s > config->cluster_highest_sessionid) // Maintain this in the slave. It's used
5982 // for walking the sessions to forward byte counts to the master.
5983 config->cluster_highest_sessionid = s;
5984
5985 memcpy(&session[s], new, sizeof(session[s])); // Copy over..
5986
5987 // Do fixups into address pool.
5988 if (new->ip_pool_index != -1)
5989 fix_address_pool(s);
5990
5991 return 1;
5992 }
5993
5994 static void initplugins()
5995 {
5996 int i;
5997
5998 loaded_plugins = ll_init();
5999 // Initialize the plugins to nothing
6000 for (i = 0; i < MAX_PLUGIN_TYPES; i++)
6001 plugins[i] = ll_init();
6002 }
6003
6004 static void *open_plugin(char *plugin_name, int load)
6005 {
6006 char path[256] = "";
6007
6008 snprintf(path, 256, PLUGINDIR "/%s.so", plugin_name);
6009 LOG(2, 0, 0, "%soading plugin from %s\n", load ? "L" : "Un-l", path);
6010 return dlopen(path, RTLD_NOW);
6011 }
6012
6013 // plugin callback to get a config value
6014 static void *getconfig(char *key, enum config_typet type)
6015 {
6016 int i;
6017
6018 for (i = 0; config_values[i].key; i++)
6019 {
6020 if (!strcmp(config_values[i].key, key))
6021 {
6022 if (config_values[i].type == type)
6023 return ((void *) config) + config_values[i].offset;
6024
6025 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
6026 key, type, config_values[i].type);
6027
6028 return 0;
6029 }
6030 }
6031
6032 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key);
6033 return 0;
6034 }
6035
6036 static int add_plugin(char *plugin_name)
6037 {
6038 static struct pluginfuncs funcs = {
6039 _log,
6040 _log_hex,
6041 fmtaddr,
6042 sessionbyuser,
6043 sessiontbysessionidt,
6044 sessionidtbysessiont,
6045 radiusnew,
6046 radiussend,
6047 getconfig,
6048 sessionshutdown,
6049 sessionkill,
6050 throttle_session,
6051 cluster_send_session,
6052 };
6053
6054 void *p = open_plugin(plugin_name, 1);
6055 int (*initfunc)(struct pluginfuncs *);
6056 int i;
6057
6058 if (!p)
6059 {
6060 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
6061 return -1;
6062 }
6063
6064 if (ll_contains(loaded_plugins, p))
6065 {
6066 dlclose(p);
6067 return 0; // already loaded
6068 }
6069
6070 {
6071 int *v = dlsym(p, "plugin_api_version");
6072 if (!v || *v != PLUGIN_API_VERSION)
6073 {
6074 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
6075 dlclose(p);
6076 return -1;
6077 }
6078 }
6079
6080 if ((initfunc = dlsym(p, "plugin_init")))
6081 {
6082 if (!initfunc(&funcs))
6083 {
6084 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
6085 dlclose(p);
6086 return -1;
6087 }
6088 }
6089
6090 ll_push(loaded_plugins, p);
6091
6092 for (i = 0; i < max_plugin_functions; i++)
6093 {
6094 void *x;
6095 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
6096 {
6097 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions[i]);
6098 ll_push(plugins[i], x);
6099 }
6100 }
6101
6102 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name);
6103 return 1;
6104 }
6105
6106 static void run_plugin_done(void *plugin)
6107 {
6108 int (*donefunc)(void) = dlsym(plugin, "plugin_done");
6109
6110 if (donefunc)
6111 donefunc();
6112 }
6113
6114 static int remove_plugin(char *plugin_name)
6115 {
6116 void *p = open_plugin(plugin_name, 0);
6117 int loaded = 0;
6118
6119 if (!p)
6120 return -1;
6121
6122 if (ll_contains(loaded_plugins, p))
6123 {
6124 int i;
6125 for (i = 0; i < max_plugin_functions; i++)
6126 {
6127 void *x;
6128 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
6129 ll_delete(plugins[i], x);
6130 }
6131
6132 ll_delete(loaded_plugins, p);
6133 run_plugin_done(p);
6134 loaded = 1;
6135 }
6136
6137 dlclose(p);
6138 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name);
6139 return loaded;
6140 }
6141
6142 int run_plugins(int plugin_type, void *data)
6143 {
6144 int (*func)(void *data);
6145
6146 if (!plugins[plugin_type] || plugin_type > max_plugin_functions)
6147 return PLUGIN_RET_ERROR;
6148
6149 ll_reset(plugins[plugin_type]);
6150 while ((func = ll_next(plugins[plugin_type])))
6151 {
6152 int r = func(data);
6153
6154 if (r != PLUGIN_RET_OK)
6155 return r; // stop here
6156 }
6157
6158 return PLUGIN_RET_OK;
6159 }
6160
6161 static void plugins_done()
6162 {
6163 void *p;
6164
6165 ll_reset(loaded_plugins);
6166 while ((p = ll_next(loaded_plugins)))
6167 run_plugin_done(p);
6168 }
6169
6170 static void processcontrol(uint8_t *buf, int len, struct sockaddr_in *addr, int alen, struct in_addr *local)
6171 {
6172 struct nsctl request;
6173 struct nsctl response;
6174 int type = unpack_control(&request, buf, len);
6175 int r;
6176 void *p;
6177
6178 if (log_stream && config->debug >= 4)
6179 {
6180 if (type < 0)
6181 {
6182 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6183 fmtaddr(addr->sin_addr.s_addr, 0), type);
6184 }
6185 else
6186 {
6187 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
6188 dump_control(&request, log_stream);
6189 }
6190 }
6191
6192 switch (type)
6193 {
6194 case NSCTL_REQ_LOAD:
6195 if (request.argc != 1)
6196 {
6197 response.type = NSCTL_RES_ERR;
6198 response.argc = 1;
6199 response.argv[0] = "name of plugin required";
6200 }
6201 else if ((r = add_plugin(request.argv[0])) < 1)
6202 {
6203 response.type = NSCTL_RES_ERR;
6204 response.argc = 1;
6205 response.argv[0] = !r
6206 ? "plugin already loaded"
6207 : "error loading plugin";
6208 }
6209 else
6210 {
6211 response.type = NSCTL_RES_OK;
6212 response.argc = 0;
6213 }
6214
6215 break;
6216
6217 case NSCTL_REQ_UNLOAD:
6218 if (request.argc != 1)
6219 {
6220 response.type = NSCTL_RES_ERR;
6221 response.argc = 1;
6222 response.argv[0] = "name of plugin required";
6223 }
6224 else if ((r = remove_plugin(request.argv[0])) < 1)
6225 {
6226 response.type = NSCTL_RES_ERR;
6227 response.argc = 1;
6228 response.argv[0] = !r
6229 ? "plugin not loaded"
6230 : "plugin not found";
6231 }
6232 else
6233 {
6234 response.type = NSCTL_RES_OK;
6235 response.argc = 0;
6236 }
6237
6238 break;
6239
6240 case NSCTL_REQ_HELP:
6241 response.type = NSCTL_RES_OK;
6242 response.argc = 0;
6243
6244 ll_reset(loaded_plugins);
6245 while ((p = ll_next(loaded_plugins)))
6246 {
6247 char **help = dlsym(p, "plugin_control_help");
6248 while (response.argc < 0xff && help && *help)
6249 response.argv[response.argc++] = *help++;
6250 }
6251
6252 break;
6253
6254 case NSCTL_REQ_CONTROL:
6255 {
6256 struct param_control param = {
6257 config->cluster_iam_master,
6258 request.argc,
6259 request.argv,
6260 0,
6261 NULL,
6262 };
6263
6264 int r = run_plugins(PLUGIN_CONTROL, &param);
6265
6266 if (r == PLUGIN_RET_ERROR)
6267 {
6268 response.type = NSCTL_RES_ERR;
6269 response.argc = 1;
6270 response.argv[0] = param.additional
6271 ? param.additional
6272 : "error returned by plugin";
6273 }
6274 else if (r == PLUGIN_RET_NOTMASTER)
6275 {
6276 static char msg[] = "must be run on master: 000.000.000.000";
6277
6278 response.type = NSCTL_RES_ERR;
6279 response.argc = 1;
6280 if (config->cluster_master_address)
6281 {
6282 strcpy(msg + 23, fmtaddr(config->cluster_master_address, 0));
6283 response.argv[0] = msg;
6284 }
6285 else
6286 {
6287 response.argv[0] = "must be run on master: none elected";
6288 }
6289 }
6290 else if (!(param.response & NSCTL_RESPONSE))
6291 {
6292 response.type = NSCTL_RES_ERR;
6293 response.argc = 1;
6294 response.argv[0] = param.response
6295 ? "unrecognised response value from plugin"
6296 : "unhandled action";
6297 }
6298 else
6299 {
6300 response.type = param.response;
6301 response.argc = 0;
6302 if (param.additional)
6303 {
6304 response.argc = 1;
6305 response.argv[0] = param.additional;
6306 }
6307 }
6308 }
6309
6310 break;
6311
6312 default:
6313 response.type = NSCTL_RES_ERR;
6314 response.argc = 1;
6315 response.argv[0] = "error unpacking control packet";
6316 }
6317
6318 buf = calloc(NSCTL_MAX_PKT_SZ, 1);
6319 if (!buf)
6320 {
6321 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6322 return;
6323 }
6324
6325 r = pack_control(buf, NSCTL_MAX_PKT_SZ, response.type, response.argc, response.argv);
6326 if (r > 0)
6327 {
6328 sendtofrom(controlfd, buf, r, 0, (const struct sockaddr *) addr, alen, local);
6329 if (log_stream && config->debug >= 4)
6330 {
6331 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
6332 dump_control(&response, log_stream);
6333 }
6334 }
6335 else
6336 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6337 fmtaddr(addr->sin_addr.s_addr, 0), r);
6338
6339 free(buf);
6340 }
6341
6342 static tunnelidt new_tunnel()
6343 {
6344 tunnelidt i;
6345 for (i = 1; i < MAXTUNNEL; i++)
6346 {
6347 if ((tunnel[i].state == TUNNELFREE) && (i != TUNNEL_ID_PPPOE))
6348 {
6349 LOG(4, 0, i, "Assigning tunnel ID %u\n", i);
6350 if (i > config->cluster_highest_tunnelid)
6351 config->cluster_highest_tunnelid = i;
6352 return i;
6353 }
6354 }
6355 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6356 return 0;
6357 }
6358
6359 //
6360 // We're becoming the master. Do any required setup..
6361 //
6362 // This is principally telling all the plugins that we're
6363 // now a master, and telling them about all the sessions
6364 // that are active too..
6365 //
6366 void become_master(void)
6367 {
6368 int s, i;
6369 static struct event_data d[RADIUS_FDS];
6370 struct epoll_event e;
6371
6372 run_plugins(PLUGIN_BECOME_MASTER, NULL);
6373
6374 // running a bunch of iptables commands is slow and can cause
6375 // the master to drop tunnels on takeover--kludge around the
6376 // problem by forking for the moment (note: race)
6377 if (!fork_and_close())
6378 {
6379 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
6380 {
6381 if (!session[s].opened) // Not an in-use session.
6382 continue;
6383
6384 run_plugins(PLUGIN_NEW_SESSION_MASTER, &session[s]);
6385 }
6386 exit(0);
6387 }
6388
6389 // add radius fds
6390 e.events = EPOLLIN;
6391 for (i = 0; i < RADIUS_FDS; i++)
6392 {
6393 d[i].type = FD_TYPE_RADIUS;
6394 d[i].index = i;
6395 e.data.ptr = &d[i];
6396
6397 epoll_ctl(epollfd, EPOLL_CTL_ADD, radfds[i], &e);
6398 }
6399 }
6400
6401 int cmd_show_hist_idle(struct cli_def *cli, const char *command, char **argv, int argc)
6402 {
6403 int s, i;
6404 int count = 0;
6405 int buckets[64];
6406
6407 if (CLI_HELP_REQUESTED)
6408 return CLI_HELP_NO_ARGS;
6409
6410 time(&time_now);
6411 for (i = 0; i < 64;++i) buckets[i] = 0;
6412
6413 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
6414 {
6415 int idle;
6416 if (!session[s].opened)
6417 continue;
6418
6419 idle = time_now - session[s].last_data;
6420 idle /= 5 ; // In multiples of 5 seconds.
6421 if (idle < 0)
6422 idle = 0;
6423 if (idle > 63)
6424 idle = 63;
6425
6426 ++count;
6427 ++buckets[idle];
6428 }
6429
6430 for (i = 0; i < 63; ++i)
6431 {
6432 cli_print(cli, "%3d seconds : %7.2f%% (%6d)", i * 5, (double) buckets[i] * 100.0 / count , buckets[i]);
6433 }
6434 cli_print(cli, "lots of secs : %7.2f%% (%6d)", (double) buckets[63] * 100.0 / count , buckets[i]);
6435 cli_print(cli, "%d total sessions open.", count);
6436 return CLI_OK;
6437 }
6438
6439 int cmd_show_hist_open(struct cli_def *cli, const char *command, char **argv, int argc)
6440 {
6441 int s, i;
6442 int count = 0;
6443 int buckets[64];
6444
6445 if (CLI_HELP_REQUESTED)
6446 return CLI_HELP_NO_ARGS;
6447
6448 time(&time_now);
6449 for (i = 0; i < 64;++i) buckets[i] = 0;
6450
6451 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
6452 {
6453 int open = 0, d;
6454 if (!session[s].opened)
6455 continue;
6456
6457 d = time_now - session[s].opened;
6458 if (d < 0)
6459 d = 0;
6460 while (d > 1 && open < 32)
6461 {
6462 ++open;
6463 d >>= 1; // half.
6464 }
6465 ++count;
6466 ++buckets[open];
6467 }
6468
6469 s = 1;
6470 for (i = 0; i < 30; ++i)
6471 {
6472 cli_print(cli, " < %8d seconds : %7.2f%% (%6d)", s, (double) buckets[i] * 100.0 / count , buckets[i]);
6473 s <<= 1;
6474 }
6475 cli_print(cli, "%d total sessions open.", count);
6476 return CLI_OK;
6477 }
6478
6479 /* Unhide an avp.
6480 *
6481 * This unencodes the AVP using the L2TP secret and the previously
6482 * stored random vector. It overwrites the hidden data with the
6483 * unhidden AVP subformat.
6484 */
6485 static void unhide_value(uint8_t *value, size_t len, uint16_t type, uint8_t *vector, size_t vec_len)
6486 {
6487 MD5_CTX ctx;
6488 uint8_t digest[16];
6489 uint8_t *last;
6490 size_t d = 0;
6491 uint16_t m = htons(type);
6492
6493 // Compute initial pad
6494 MD5_Init(&ctx);
6495 MD5_Update(&ctx, (unsigned char *) &m, 2);
6496 MD5_Update(&ctx, config->l2tp_secret, strlen(config->l2tp_secret));
6497 MD5_Update(&ctx, vector, vec_len);
6498 MD5_Final(digest, &ctx);
6499
6500 // pointer to last decoded 16 octets
6501 last = value;
6502
6503 while (len > 0)
6504 {
6505 // calculate a new pad based on the last decoded block
6506 if (d >= sizeof(digest))
6507 {
6508 MD5_Init(&ctx);
6509 MD5_Update(&ctx, config->l2tp_secret, strlen(config->l2tp_secret));
6510 MD5_Update(&ctx, last, sizeof(digest));
6511 MD5_Final(digest, &ctx);
6512
6513 d = 0;
6514 last = value;
6515 }
6516
6517 *value++ ^= digest[d++];
6518 len--;
6519 }
6520 }
6521
6522 int find_filter(char const *name, size_t len)
6523 {
6524 int free = -1;
6525 int i;
6526
6527 for (i = 0; i < MAXFILTER; i++)
6528 {
6529 if (!*ip_filters[i].name)
6530 {
6531 if (free < 0)
6532 free = i;
6533
6534 continue;
6535 }
6536
6537 if (strlen(ip_filters[i].name) != len)
6538 continue;
6539
6540 if (!strncmp(ip_filters[i].name, name, len))
6541 return i;
6542 }
6543
6544 return free;
6545 }
6546
6547 static int ip_filter_port(ip_filter_portt *p, uint16_t port)
6548 {
6549 switch (p->op)
6550 {
6551 case FILTER_PORT_OP_EQ: return port == p->port;
6552 case FILTER_PORT_OP_NEQ: return port != p->port;
6553 case FILTER_PORT_OP_GT: return port > p->port;
6554 case FILTER_PORT_OP_LT: return port < p->port;
6555 case FILTER_PORT_OP_RANGE: return port >= p->port && port <= p->port2;
6556 }
6557
6558 return 0;
6559 }
6560
6561 static int ip_filter_flag(uint8_t op, uint8_t sflags, uint8_t cflags, uint8_t flags)
6562 {
6563 switch (op)
6564 {
6565 case FILTER_FLAG_OP_ANY:
6566 return (flags & sflags) || (~flags & cflags);
6567
6568 case FILTER_FLAG_OP_ALL:
6569 return (flags & sflags) == sflags && (~flags & cflags) == cflags;
6570
6571 case FILTER_FLAG_OP_EST:
6572 return (flags & (TCP_FLAG_ACK|TCP_FLAG_RST)) && (~flags & TCP_FLAG_SYN);
6573 }
6574
6575 return 0;
6576 }
6577
6578 int ip_filter(uint8_t *buf, int len, uint8_t filter)
6579 {
6580 uint16_t frag_offset;
6581 uint8_t proto;
6582 in_addr_t src_ip;
6583 in_addr_t dst_ip;
6584 uint16_t src_port = 0;
6585 uint16_t dst_port = 0;
6586 uint8_t flags = 0;
6587 ip_filter_rulet *rule;
6588
6589 if (len < 20) // up to end of destination address
6590 return 0;
6591
6592 if ((*buf >> 4) != 4) // IPv4
6593 return 0;
6594
6595 frag_offset = ntohs(*(uint16_t *) (buf + 6)) & 0x1fff;
6596 proto = buf[9];
6597 src_ip = *(in_addr_t *) (buf + 12);
6598 dst_ip = *(in_addr_t *) (buf + 16);
6599
6600 if (frag_offset == 0 && (proto == IPPROTO_TCP || proto == IPPROTO_UDP))
6601 {
6602 int l = (buf[0] & 0xf) * 4; // length of IP header
6603 if (len < l + 4) // ports
6604 return 0;
6605
6606 src_port = ntohs(*(uint16_t *) (buf + l));
6607 dst_port = ntohs(*(uint16_t *) (buf + l + 2));
6608 if (proto == IPPROTO_TCP)
6609 {
6610 if (len < l + 14) // flags
6611 return 0;
6612
6613 flags = buf[l + 13] & 0x3f;
6614 }
6615 }
6616
6617 for (rule = ip_filters[filter].rules; rule->action; rule++)
6618 {
6619 if (rule->proto != IPPROTO_IP && proto != rule->proto)
6620 continue;
6621
6622 if (rule->src_wild != INADDR_BROADCAST &&
6623 (src_ip & ~rule->src_wild) != (rule->src_ip & ~rule->src_wild))
6624 continue;
6625
6626 if (rule->dst_wild != INADDR_BROADCAST &&
6627 (dst_ip & ~rule->dst_wild) != (rule->dst_ip & ~rule->dst_wild))
6628 continue;
6629
6630 if (frag_offset)
6631 {
6632 // layer 4 deny rules are skipped
6633 if (rule->action == FILTER_ACTION_DENY &&
6634 (rule->src_ports.op || rule->dst_ports.op || rule->tcp_flag_op))
6635 continue;
6636 }
6637 else
6638 {
6639 if (rule->frag)
6640 continue;
6641
6642 if (proto == IPPROTO_TCP || proto == IPPROTO_UDP)
6643 {
6644 if (rule->src_ports.op && !ip_filter_port(&rule->src_ports, src_port))
6645 continue;
6646
6647 if (rule->dst_ports.op && !ip_filter_port(&rule->dst_ports, dst_port))
6648 continue;
6649
6650 if (proto == IPPROTO_TCP && rule->tcp_flag_op &&
6651 !ip_filter_flag(rule->tcp_flag_op, rule->tcp_sflags, rule->tcp_cflags, flags))
6652 continue;
6653 }
6654 }
6655
6656 // matched
6657 rule->counter++;
6658 return rule->action == FILTER_ACTION_PERMIT;
6659 }
6660
6661 // default deny
6662 return 0;
6663 }
6664
6665 tunnelidt lac_new_tunnel()
6666 {
6667 return new_tunnel();
6668 }
6669
6670 void lac_tunnelclear(tunnelidt t)
6671 {
6672 tunnelclear(t);
6673 }
6674
6675 void lac_send_SCCRQ(tunnelidt t, uint8_t * auth, unsigned int auth_len)
6676 {
6677 uint16_t version = 0x0100; // protocol version
6678
6679 tunnel[t].state = TUNNELOPENING;
6680
6681 // Sent SCCRQ - Start Control Connection Request
6682 controlt *c = controlnew(1); // sending SCCRQ
6683 controls(c, 7, config->multi_n_hostname[tunnel[t].indexudp][0]?config->multi_n_hostname[tunnel[t].indexudp]:hostname, 1); // host name
6684 controls(c, 8, Vendor_name, 1); // Vendor name
6685 control16(c, 2, version, 1); // protocol version
6686 control32(c, 3, 3, 1); // framing Capabilities
6687 control16(c, 9, t, 1); // assigned tunnel
6688 controlb(c, 11, (uint8_t *) auth, auth_len, 1); // CHAP Challenge
6689 LOG(3, 0, t, "Sent SCCRQ to REMOTE LNS\n");
6690 controladd(c, 0, t); // send
6691 }
6692
6693 void lac_send_ICRQ(tunnelidt t, sessionidt s)
6694 {
6695 // Sent ICRQ Incoming-call-request
6696 controlt *c = controlnew(10); // ICRQ
6697
6698 control16(c, 14, s, 1); // assigned sesion
6699 call_serial_number++;
6700 control32(c, 15, call_serial_number, 1); // call serial number
6701 LOG(3, s, t, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel[t].far);
6702 controladd(c, 0, t); // send
6703 }
6704
6705 void lac_tunnelshutdown(tunnelidt t, char *reason, int result, int error, char *msg)
6706 {
6707 tunnelshutdown(t, reason, result, error, msg);
6708 }
6709