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