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