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