Merge branch 'master' into samesversion
[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->pout++;
1398 sp->last_data = time_now;
1399
1400 sess_local[s].cout += len; // To send to master..
1401 sess_local[s].pout++;
1402 }
1403
1404 // process outgoing (to tunnel) IP
1405 //
1406 // (i.e. this routine writes to data[-8]).
1407 void processipout(uint8_t *buf, int len)
1408 {
1409 sessionidt s;
1410 groupidt g;
1411 sessiont *sp;
1412 tunnelidt t;
1413 in_addr_t ip;
1414
1415 uint8_t *data = buf; // Keep a copy of the originals.
1416 int size = len;
1417
1418 uint8_t fragbuf[MAXETHER + 20];
1419
1420 CSTAT(processipout);
1421
1422 if (len < MIN_IP_SIZE)
1423 {
1424 LOG(1, 0, 0, "Short IP, %d bytes\n", len);
1425 STAT(tun_rx_errors);
1426 return;
1427 }
1428 if (len >= MAXETHER)
1429 {
1430 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len);
1431 STAT(tun_rx_errors);
1432 return;
1433 }
1434
1435 // Skip the tun header
1436 buf += 4;
1437 len -= 4;
1438
1439 // Got an IP header now
1440 if (*(uint8_t *)(buf) >> 4 != 4)
1441 {
1442 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1443 return;
1444 }
1445
1446 ip = *(uint32_t *)(buf + 16);
1447 if ((g = grp_groupbyip(ip)))
1448 {
1449 s = grp_getnextsession(g, ip);
1450 if (!s)
1451 {
1452 // Is this a packet for a session that doesn't exist?
1453 static int rate = 0; // Number of ICMP packets we've sent this second.
1454 static int last = 0; // Last time we reset the ICMP packet counter 'rate'.
1455
1456 if (last != time_now)
1457 {
1458 last = time_now;
1459 rate = 0;
1460 }
1461
1462 if (rate++ < config->icmp_rate) // Only send a max of icmp_rate per second.
1463 {
1464 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t *)(buf + 12), 0));
1465 host_unreachable(*(in_addr_t *)(buf + 12), *(uint16_t *)(buf + 4),
1466 config->bind_address ? config->bind_address : my_address, buf, len);
1467 }
1468 return;
1469 }
1470 }
1471 else if (!(s = sessionbyip(ip)))
1472 {
1473 // Is this a packet for a session that doesn't exist?
1474 static int rate = 0; // Number of ICMP packets we've sent this second.
1475 static int last = 0; // Last time we reset the ICMP packet counter 'rate'.
1476
1477 if (last != time_now)
1478 {
1479 last = time_now;
1480 rate = 0;
1481 }
1482
1483 if (rate++ < config->icmp_rate) // Only send a max of icmp_rate per second.
1484 {
1485 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t *)(buf + 12), 0));
1486 host_unreachable(*(in_addr_t *)(buf + 12), *(uint16_t *)(buf + 4),
1487 config->bind_address ? config->bind_address : my_address, buf, len);
1488 }
1489 return;
1490 }
1491
1492 t = session[s].tunnel;
1493 if (len > session[s].mru || (session[s].mrru && len > session[s].mrru))
1494 {
1495 LOG(3, s, t, "Packet size more than session MRU\n");
1496 return;
1497 }
1498
1499 sp = &session[s];
1500
1501 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1502 if (config->max_packets > 0)
1503 {
1504 if (sess_local[s].last_packet_out == TIME)
1505 {
1506 int max = config->max_packets;
1507
1508 // All packets for throttled sessions are handled by the
1509 // master, so further limit by using the throttle rate.
1510 // A bit of a kludge, since throttle rate is in kbps,
1511 // but should still be generous given our average DSL
1512 // packet size is 200 bytes: a limit of 28kbps equates
1513 // to around 180 packets per second.
1514 if (!config->cluster_iam_master && sp->throttle_out && sp->throttle_out < max)
1515 max = sp->throttle_out;
1516
1517 if (++sess_local[s].packets_out > max)
1518 {
1519 sess_local[s].packets_dropped++;
1520 return;
1521 }
1522 }
1523 else
1524 {
1525 if (sess_local[s].packets_dropped)
1526 {
1527 INC_STAT(tun_rx_dropped, sess_local[s].packets_dropped);
1528 LOG(3, s, t, "Dropped %u/%u packets to %s for %suser %s\n",
1529 sess_local[s].packets_dropped, sess_local[s].packets_out,
1530 fmtaddr(ip, 0), sp->throttle_out ? "throttled " : "",
1531 sp->user);
1532 }
1533
1534 sess_local[s].last_packet_out = TIME;
1535 sess_local[s].packets_out = 1;
1536 sess_local[s].packets_dropped = 0;
1537 }
1538 }
1539
1540 // run access-list if any
1541 if (session[s].filter_out && !ip_filter(buf, len, session[s].filter_out - 1))
1542 return;
1543
1544 // adjust MSS on SYN and SYN,ACK packets with options
1545 if ((ntohs(*(uint16_t *) (buf + 6)) & 0x1fff) == 0 && buf[9] == IPPROTO_TCP) // first tcp fragment
1546 {
1547 int ihl = (buf[0] & 0xf) * 4; // length of IP header
1548 if (len >= ihl + 20 && (buf[ihl + 13] & TCP_FLAG_SYN) && ((buf[ihl + 12] >> 4) > 5))
1549 adjust_tcp_mss(s, t, buf, len, buf + ihl);
1550 }
1551
1552 if (sp->tbf_out)
1553 {
1554 // Are we throttling this session?
1555 if (config->cluster_iam_master)
1556 tbf_queue_packet(sp->tbf_out, data, size);
1557 else
1558 master_throttle_packet(sp->tbf_out, data, size);
1559 return;
1560 }
1561
1562 if (sp->walled_garden && !config->cluster_iam_master)
1563 {
1564 // We are walled-gardening this
1565 master_garden_packet(s, data, size);
1566 return;
1567 }
1568
1569 if(session[s].bundle != 0 && bundle[session[s].bundle].num_of_links > 1)
1570 {
1571
1572 if (!config->cluster_iam_master)
1573 {
1574 // The MPPP packets must be managed by the Master.
1575 master_forward_mppp_packet(s, data, size);
1576 return;
1577 }
1578
1579 // Add on L2TP header
1580 sessionidt members[MAXBUNDLESES];
1581 bundleidt bid = session[s].bundle;
1582 bundlet *b = &bundle[bid];
1583 uint32_t num_of_links, nb_opened;
1584 int i;
1585
1586 num_of_links = b->num_of_links;
1587 nb_opened = 0;
1588 for (i = 0;i < num_of_links;i++)
1589 {
1590 s = b->members[i];
1591 if (session[s].ppp.lcp == Opened)
1592 {
1593 members[nb_opened] = s;
1594 nb_opened++;
1595 }
1596 }
1597
1598 if (nb_opened < 1)
1599 {
1600 LOG(3, s, t, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid);
1601 return;
1602 }
1603
1604 num_of_links = nb_opened;
1605 b->current_ses = (b->current_ses + 1) % num_of_links;
1606 s = members[b->current_ses];
1607 t = session[s].tunnel;
1608 sp = &session[s];
1609 LOG(4, s, t, "MPPP: (1)Session number becomes: %d\n", s);
1610
1611 if (num_of_links > 1)
1612 {
1613 if(len > MINFRAGLEN)
1614 {
1615 //for rotate traffic among the member links
1616 uint32_t divisor = num_of_links;
1617 if (divisor > 2)
1618 divisor = divisor/2 + (divisor & 1);
1619
1620 // Partition the packet to "num_of_links" fragments
1621 uint32_t fraglen = len / divisor;
1622 uint32_t last_fraglen = fraglen + len % divisor;
1623 uint32_t remain = len;
1624
1625 // send the first packet
1626 uint8_t *p = makeppp(fragbuf, sizeof(fragbuf), buf, fraglen, s, t, PPPIP, 0, bid, MP_BEGIN);
1627 if (!p) return;
1628 tunnelsend(fragbuf, fraglen + (p-fragbuf), t); // send it...
1629
1630 // statistics
1631 update_session_out_stat(s, sp, fraglen);
1632
1633 remain -= fraglen;
1634 while (remain > last_fraglen)
1635 {
1636 b->current_ses = (b->current_ses + 1) % num_of_links;
1637 s = members[b->current_ses];
1638 t = session[s].tunnel;
1639 sp = &session[s];
1640 LOG(4, s, t, "MPPP: (2)Session number becomes: %d\n", s);
1641 p = makeppp(fragbuf, sizeof(fragbuf), buf+(len - remain), fraglen, s, t, PPPIP, 0, bid, 0);
1642 if (!p) return;
1643 tunnelsend(fragbuf, fraglen + (p-fragbuf), t); // send it...
1644 update_session_out_stat(s, sp, fraglen);
1645 remain -= fraglen;
1646 }
1647 // send the last fragment
1648 b->current_ses = (b->current_ses + 1) % num_of_links;
1649 s = members[b->current_ses];
1650 t = session[s].tunnel;
1651 sp = &session[s];
1652 LOG(4, s, t, "MPPP: (2)Session number becomes: %d\n", s);
1653 p = makeppp(fragbuf, sizeof(fragbuf), buf+(len - remain), remain, s, t, PPPIP, 0, bid, MP_END);
1654 if (!p) return;
1655 tunnelsend(fragbuf, remain + (p-fragbuf), t); // send it...
1656 update_session_out_stat(s, sp, remain);
1657 if (remain != last_fraglen)
1658 LOG(3, s, t, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain, last_fraglen);
1659 }
1660 else
1661 {
1662 // Send it as one frame
1663 uint8_t *p = makeppp(fragbuf, sizeof(fragbuf), buf, len, s, t, PPPIP, 0, bid, MP_BOTH_BITS);
1664 if (!p) return;
1665 tunnelsend(fragbuf, len + (p-fragbuf), t); // send it...
1666 LOG(4, s, t, "MPPP: packet sent as one frame\n");
1667 update_session_out_stat(s, sp, len);
1668 }
1669 }
1670 else
1671 {
1672 // Send it as one frame (NO MPPP Frame)
1673 uint8_t *p = opt_makeppp(buf, len, s, t, PPPIP, 0, 0, 0);
1674 tunnelsend(p, len + (buf-p), t); // send it...
1675 update_session_out_stat(s, sp, len);
1676 }
1677 }
1678 else
1679 {
1680 uint8_t *p = opt_makeppp(buf, len, s, t, PPPIP, 0, 0, 0);
1681 tunnelsend(p, len + (buf-p), t); // send it...
1682 update_session_out_stat(s, sp, len);
1683 }
1684
1685 // Snooping this session, send it to intercept box
1686 if (sp->snoop_ip && sp->snoop_port)
1687 snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port);
1688
1689 udp_tx += len;
1690 }
1691
1692 // process outgoing (to tunnel) IPv6
1693 //
1694 static void processipv6out(uint8_t * buf, int len)
1695 {
1696 sessionidt s;
1697 sessiont *sp;
1698 tunnelidt t;
1699 in_addr_t ip;
1700 struct in6_addr ip6;
1701
1702 uint8_t *data = buf; // Keep a copy of the originals.
1703 int size = len;
1704
1705 uint8_t b[MAXETHER + 20];
1706
1707 CSTAT(processipv6out);
1708
1709 if (len < MIN_IP_SIZE)
1710 {
1711 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len);
1712 STAT(tunnel_tx_errors);
1713 return;
1714 }
1715 if (len >= MAXETHER)
1716 {
1717 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len);
1718 STAT(tunnel_tx_errors);
1719 return;
1720 }
1721
1722 // Skip the tun header
1723 buf += 4;
1724 len -= 4;
1725
1726 // Got an IP header now
1727 if (*(uint8_t *)(buf) >> 4 != 6)
1728 {
1729 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1730 return;
1731 }
1732
1733 ip6 = *(struct in6_addr *)(buf+24);
1734 s = sessionbyipv6(ip6);
1735
1736 if (s == 0)
1737 {
1738 ip = *(uint32_t *)(buf + 32);
1739 s = sessionbyip(ip);
1740 }
1741
1742 if (s == 0)
1743 {
1744 // Is this a packet for a session that doesn't exist?
1745 static int rate = 0; // Number of ICMP packets we've sent this second.
1746 static int last = 0; // Last time we reset the ICMP packet counter 'rate'.
1747
1748 if (last != time_now)
1749 {
1750 last = time_now;
1751 rate = 0;
1752 }
1753
1754 if (rate++ < config->icmp_rate) // Only send a max of icmp_rate per second.
1755 {
1756 // FIXME: Should send icmp6 host unreachable
1757 }
1758 return;
1759 }
1760 if (session[s].bundle && bundle[session[s].bundle].num_of_links > 1)
1761 {
1762 bundleidt bid = session[s].bundle;
1763 bundlet *b = &bundle[bid];
1764
1765 b->current_ses = (b->current_ses + 1) % b->num_of_links;
1766 s = b->members[b->current_ses];
1767 LOG(3, s, session[s].tunnel, "MPPP: Session number becomes: %u\n", s);
1768 }
1769 t = session[s].tunnel;
1770 sp = &session[s];
1771 sp->last_data = time_now;
1772
1773 // FIXME: add DoS prevention/filters?
1774
1775 if (sp->tbf_out)
1776 {
1777 // Are we throttling this session?
1778 if (config->cluster_iam_master)
1779 tbf_queue_packet(sp->tbf_out, data, size);
1780 else
1781 master_throttle_packet(sp->tbf_out, data, size);
1782 return;
1783 }
1784 else if (sp->walled_garden && !config->cluster_iam_master)
1785 {
1786 // We are walled-gardening this
1787 master_garden_packet(s, data, size);
1788 return;
1789 }
1790
1791 LOG(5, s, t, "Ethernet -> Tunnel (%d bytes)\n", len);
1792
1793 // Add on L2TP header
1794 {
1795 uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIPV6, 0, 0, 0);
1796 if (!p) return;
1797 tunnelsend(b, len + (p-b), t); // send it...
1798 }
1799
1800 // Snooping this session, send it to intercept box
1801 if (sp->snoop_ip && sp->snoop_port)
1802 snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port);
1803
1804 increment_counter(&sp->cout, &sp->cout_wrap, len); // byte count
1805 sp->cout_delta += len;
1806 sp->pout++;
1807 udp_tx += len;
1808
1809 sess_local[s].cout += len; // To send to master..
1810 sess_local[s].pout++;
1811 }
1812
1813 //
1814 // Helper routine for the TBF filters.
1815 // Used to send queued data in to the user!
1816 //
1817 static void send_ipout(sessionidt s, uint8_t *buf, int len)
1818 {
1819 sessiont *sp;
1820 tunnelidt t;
1821
1822 uint8_t b[MAXETHER + 20];
1823
1824 if (len < 0 || len > MAXETHER)
1825 {
1826 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len);
1827 return;
1828 }
1829
1830 // Skip the tun header
1831 buf += 4;
1832 len -= 4;
1833
1834 if (!session[s].ip)
1835 return;
1836
1837 t = session[s].tunnel;
1838 sp = &session[s];
1839
1840 LOG(5, s, t, "Ethernet -> Tunnel (%d bytes)\n", len);
1841
1842 // Add on L2TP header
1843 {
1844 uint8_t *p = makeppp(b, sizeof(b), buf, len, s, t, PPPIP, 0, 0, 0);
1845 if (!p) return;
1846 tunnelsend(b, len + (p-b), t); // send it...
1847 }
1848
1849 // Snooping this session.
1850 if (sp->snoop_ip && sp->snoop_port)
1851 snoop_send_packet(buf, len, sp->snoop_ip, sp->snoop_port);
1852
1853 increment_counter(&sp->cout, &sp->cout_wrap, len); // byte count
1854 sp->cout_delta += len;
1855 sp->pout++;
1856 udp_tx += len;
1857
1858 sess_local[s].cout += len; // To send to master..
1859 sess_local[s].pout++;
1860 }
1861
1862 // add an AVP (16 bit)
1863 static void control16(controlt * c, uint16_t avp, uint16_t val, uint8_t m)
1864 {
1865 uint16_t l = (m ? 0x8008 : 0x0008);
1866 *(uint16_t *) (c->buf + c->length + 0) = htons(l);
1867 *(uint16_t *) (c->buf + c->length + 2) = htons(0);
1868 *(uint16_t *) (c->buf + c->length + 4) = htons(avp);
1869 *(uint16_t *) (c->buf + c->length + 6) = htons(val);
1870 c->length += 8;
1871 }
1872
1873 // add an AVP (32 bit)
1874 static void control32(controlt * c, uint16_t avp, uint32_t val, uint8_t m)
1875 {
1876 uint16_t l = (m ? 0x800A : 0x000A);
1877 *(uint16_t *) (c->buf + c->length + 0) = htons(l);
1878 *(uint16_t *) (c->buf + c->length + 2) = htons(0);
1879 *(uint16_t *) (c->buf + c->length + 4) = htons(avp);
1880 *(uint32_t *) (c->buf + c->length + 6) = htonl(val);
1881 c->length += 10;
1882 }
1883
1884 // add an AVP (string)
1885 static void controls(controlt * c, uint16_t avp, char *val, uint8_t m)
1886 {
1887 uint16_t l = ((m ? 0x8000 : 0) + strlen(val) + 6);
1888 *(uint16_t *) (c->buf + c->length + 0) = htons(l);
1889 *(uint16_t *) (c->buf + c->length + 2) = htons(0);
1890 *(uint16_t *) (c->buf + c->length + 4) = htons(avp);
1891 memcpy(c->buf + c->length + 6, val, strlen(val));
1892 c->length += 6 + strlen(val);
1893 }
1894
1895 // add a binary AVP
1896 static void controlb(controlt * c, uint16_t avp, uint8_t *val, unsigned int len, uint8_t m)
1897 {
1898 uint16_t l = ((m ? 0x8000 : 0) + len + 6);
1899 *(uint16_t *) (c->buf + c->length + 0) = htons(l);
1900 *(uint16_t *) (c->buf + c->length + 2) = htons(0);
1901 *(uint16_t *) (c->buf + c->length + 4) = htons(avp);
1902 memcpy(c->buf + c->length + 6, val, len);
1903 c->length += 6 + len;
1904 }
1905
1906 // new control connection
1907 static controlt *controlnew(uint16_t mtype)
1908 {
1909 controlt *c;
1910 if (!controlfree)
1911 c = malloc(sizeof(controlt));
1912 else
1913 {
1914 c = controlfree;
1915 controlfree = c->next;
1916 }
1917 assert(c);
1918 c->next = 0;
1919 c->buf[0] = 0xC8; // flags
1920 c->buf[1] = 0x02; // ver
1921 c->length = 12;
1922 control16(c, 0, mtype, 1);
1923 return c;
1924 }
1925
1926 // send zero block if nothing is waiting
1927 // (ZLB send).
1928 static void controlnull(tunnelidt t)
1929 {
1930 uint16_t buf[6];
1931 if (tunnel[t].controlc) // Messages queued; They will carry the ack.
1932 return;
1933
1934 buf[0] = htons(0xC802); // flags/ver
1935 buf[1] = htons(12); // length
1936 buf[2] = htons(tunnel[t].far); // tunnel
1937 buf[3] = htons(0); // session
1938 buf[4] = htons(tunnel[t].ns); // sequence
1939 buf[5] = htons(tunnel[t].nr); // sequence
1940 tunnelsend((uint8_t *)buf, 12, t);
1941 }
1942
1943 // add a control message to a tunnel, and send if within window
1944 static void controladd(controlt *c, sessionidt far, tunnelidt t)
1945 {
1946 *(uint16_t *) (c->buf + 2) = htons(c->length); // length
1947 *(uint16_t *) (c->buf + 4) = htons(tunnel[t].far); // tunnel
1948 *(uint16_t *) (c->buf + 6) = htons(far); // session
1949 *(uint16_t *) (c->buf + 8) = htons(tunnel[t].ns); // sequence
1950 tunnel[t].ns++; // advance sequence
1951 // link in message in to queue
1952 if (tunnel[t].controlc)
1953 tunnel[t].controle->next = c;
1954 else
1955 tunnel[t].controls = c;
1956
1957 tunnel[t].controle = c;
1958 tunnel[t].controlc++;
1959
1960 // send now if space in window
1961 if (tunnel[t].controlc <= tunnel[t].window)
1962 {
1963 tunnel[t].try = 0; // first send
1964 tunnelsend(c->buf, c->length, t);
1965 }
1966 }
1967
1968 //
1969 // Throttle or Unthrottle a session
1970 //
1971 // Throttle the data from/to through a session to no more than
1972 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1973 // user).
1974 //
1975 // If either value is -1, the current value is retained for that
1976 // direction.
1977 //
1978 void throttle_session(sessionidt s, int rate_in, int rate_out)
1979 {
1980 if (!session[s].opened)
1981 return; // No-one home.
1982
1983 if (!*session[s].user)
1984 return; // User not logged in
1985
1986 if (rate_in >= 0)
1987 {
1988 int bytes = rate_in * 1024 / 8; // kbits to bytes
1989 if (session[s].tbf_in)
1990 free_tbf(session[s].tbf_in);
1991
1992 if (rate_in > 0)
1993 session[s].tbf_in = new_tbf(s, bytes * 2, bytes, send_ipin);
1994 else
1995 session[s].tbf_in = 0;
1996
1997 session[s].throttle_in = rate_in;
1998 }
1999
2000 if (rate_out >= 0)
2001 {
2002 int bytes = rate_out * 1024 / 8;
2003 if (session[s].tbf_out)
2004 free_tbf(session[s].tbf_out);
2005
2006 if (rate_out > 0)
2007 session[s].tbf_out = new_tbf(s, bytes * 2, bytes, send_ipout);
2008 else
2009 session[s].tbf_out = 0;
2010
2011 session[s].throttle_out = rate_out;
2012 }
2013 }
2014
2015 // add/remove filters from session (-1 = no change)
2016 void filter_session(sessionidt s, int filter_in, int filter_out)
2017 {
2018 if (!session[s].opened)
2019 return; // No-one home.
2020
2021 if (!*session[s].user)
2022 return; // User not logged in
2023
2024 // paranoia
2025 if (filter_in > MAXFILTER) filter_in = -1;
2026 if (filter_out > MAXFILTER) filter_out = -1;
2027 if (session[s].filter_in > MAXFILTER) session[s].filter_in = 0;
2028 if (session[s].filter_out > MAXFILTER) session[s].filter_out = 0;
2029
2030 if (filter_in >= 0)
2031 {
2032 if (session[s].filter_in)
2033 ip_filters[session[s].filter_in - 1].used--;
2034
2035 if (filter_in > 0)
2036 ip_filters[filter_in - 1].used++;
2037
2038 session[s].filter_in = filter_in;
2039 }
2040
2041 if (filter_out >= 0)
2042 {
2043 if (session[s].filter_out)
2044 ip_filters[session[s].filter_out - 1].used--;
2045
2046 if (filter_out > 0)
2047 ip_filters[filter_out - 1].used++;
2048
2049 session[s].filter_out = filter_out;
2050 }
2051 }
2052
2053 // start tidy shutdown of session
2054 void sessionshutdown(sessionidt s, char const *reason, int cdn_result, int cdn_error, int term_cause)
2055 {
2056 int walled_garden = session[s].walled_garden;
2057 bundleidt b = session[s].bundle;
2058 //delete routes only for last session in bundle (in case of MPPP)
2059 int del_routes = !b || (bundle[b].num_of_links == 1);
2060
2061 CSTAT(sessionshutdown);
2062
2063 if (!session[s].opened)
2064 {
2065 LOG(3, s, session[s].tunnel, "Called sessionshutdown on an unopened session.\n");
2066 return; // not a live session
2067 }
2068
2069 if (!session[s].die)
2070 {
2071 struct param_kill_session data = { &tunnel[session[s].tunnel], &session[s] };
2072 LOG(2, s, session[s].tunnel, "Shutting down session %u: %s\n", s, reason);
2073 run_plugins(PLUGIN_KILL_SESSION, &data);
2074 }
2075
2076 if (session[s].ip && !walled_garden && !session[s].die)
2077 {
2078 // RADIUS Stop message
2079 uint16_t r = radiusnew(s);
2080 if (r)
2081 {
2082 // stop, if not already trying
2083 if (radius[r].state != RADIUSSTOP)
2084 {
2085 radius[r].term_cause = term_cause;
2086 radius[r].term_msg = reason;
2087 radiussend(r, RADIUSSTOP);
2088 }
2089 }
2090 else
2091 LOG(1, s, session[s].tunnel, "No free RADIUS sessions for Stop message\n");
2092
2093 // Save counters to dump to accounting file
2094 if (*config->accounting_dir && shut_acct_n < sizeof(shut_acct) / sizeof(*shut_acct))
2095 memcpy(&shut_acct[shut_acct_n++], &session[s], sizeof(session[s]));
2096 }
2097
2098 if (!session[s].die)
2099 session[s].die = TIME + 150; // Clean up in 15 seconds
2100
2101 if (session[s].ip)
2102 { // IP allocated, clear and unroute
2103 int r;
2104 int routed = 0;
2105 for (r = 0; r < MAXROUTE && session[s].route[r].ip; r++)
2106 {
2107 if ((session[s].ip >> (32-session[s].route[r].prefixlen)) ==
2108 (session[s].route[r].ip >> (32-session[s].route[r].prefixlen)))
2109 routed++;
2110
2111 if (del_routes) routeset(s, session[s].route[r].ip, session[s].route[r].prefixlen, 0, 0);
2112 session[s].route[r].ip = 0;
2113 }
2114
2115 if (session[s].ip_pool_index == -1) // static ip
2116 {
2117 if (!routed && del_routes) routeset(s, session[s].ip, 0, 0, 0);
2118 session[s].ip = 0;
2119 }
2120 else
2121 free_ip_address(s);
2122
2123 // unroute IPv6, if setup
2124 if (session[s].ppp.ipv6cp == Opened && session[s].ipv6prefixlen && del_routes)
2125 route6set(s, session[s].ipv6route, session[s].ipv6prefixlen, 0);
2126
2127 if (b)
2128 {
2129 // This session was part of a bundle
2130 bundle[b].num_of_links--;
2131 LOG(3, s, session[s].tunnel, "MPPP: Dropping member link: %d from bundle %d\n",s,b);
2132 if(bundle[b].num_of_links == 0)
2133 {
2134 bundleclear(b);
2135 LOG(3, s, session[s].tunnel, "MPPP: Kill bundle: %d (No remaing member links)\n",b);
2136 }
2137 else
2138 {
2139 // Adjust the members array to accomodate the new change
2140 uint8_t mem_num = 0;
2141 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2142 if(bundle[b].members[bundle[b].num_of_links] != s)
2143 {
2144 uint8_t ml;
2145 for(ml = 0; ml<bundle[b].num_of_links; ml++)
2146 if(bundle[b].members[ml] == s)
2147 {
2148 mem_num = ml;
2149 break;
2150 }
2151 bundle[b].members[mem_num] = bundle[b].members[bundle[b].num_of_links];
2152 LOG(3, s, session[s].tunnel, "MPPP: Adjusted member links array\n");
2153
2154 // If the killed session is the first of the bundle,
2155 // the new first session must be stored in the cache_ipmap
2156 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2157 if (mem_num == 0)
2158 {
2159 sessionidt new_s = bundle[b].members[0];
2160
2161 routed = 0;
2162 // Add the route for this session.
2163 for (r = 0; r < MAXROUTE && session[new_s].route[r].ip; r++)
2164 {
2165 int i, prefixlen;
2166 in_addr_t ip;
2167
2168 prefixlen = session[new_s].route[r].prefixlen;
2169 ip = session[new_s].route[r].ip;
2170
2171 if (!prefixlen) prefixlen = 32;
2172 ip &= 0xffffffff << (32 - prefixlen); // Force the ip to be the first one in the route.
2173
2174 for (i = ip; i < ip+(1<<(32-prefixlen)) ; ++i)
2175 cache_ipmap(i, new_s);
2176 }
2177 cache_ipmap(session[new_s].ip, new_s);
2178
2179 // IPV6 route
2180 if (session[new_s].ipv6prefixlen)
2181 cache_ipv6map(session[new_s].ipv6route, session[new_s].ipv6prefixlen, new_s);
2182 }
2183 }
2184 }
2185
2186 cluster_send_bundle(b);
2187 }
2188 }
2189
2190 if (session[s].throttle_in || session[s].throttle_out) // Unthrottle if throttled.
2191 throttle_session(s, 0, 0);
2192
2193 if (cdn_result)
2194 {
2195 if (session[s].tunnel == TUNNEL_ID_PPPOE)
2196 {
2197 pppoe_shutdown_session(s);
2198 }
2199 else
2200 {
2201 // Send CDN
2202 controlt *c = controlnew(14); // sending CDN
2203 if (cdn_error)
2204 {
2205 uint16_t buf[2];
2206 buf[0] = htons(cdn_result);
2207 buf[1] = htons(cdn_error);
2208 controlb(c, 1, (uint8_t *)buf, 4, 1);
2209 }
2210 else
2211 control16(c, 1, cdn_result, 1);
2212
2213 control16(c, 14, s, 1); // assigned session (our end)
2214 controladd(c, session[s].far, session[s].tunnel); // send the message
2215 }
2216 }
2217
2218 // update filter refcounts
2219 if (session[s].filter_in) ip_filters[session[s].filter_in - 1].used--;
2220 if (session[s].filter_out) ip_filters[session[s].filter_out - 1].used--;
2221
2222 // clear PPP state
2223 memset(&session[s].ppp, 0, sizeof(session[s].ppp));
2224 sess_local[s].lcp.restart = 0;
2225 sess_local[s].ipcp.restart = 0;
2226 sess_local[s].ipv6cp.restart = 0;
2227 sess_local[s].ccp.restart = 0;
2228
2229 cluster_send_session(s);
2230 }
2231
2232 void sendipcp(sessionidt s, tunnelidt t)
2233 {
2234 uint8_t buf[MAXETHER];
2235 uint8_t *q;
2236
2237 CSTAT(sendipcp);
2238 LOG(3, s, t, "IPCP: send ConfigReq\n");
2239
2240 if (!session[s].unique_id)
2241 {
2242 if (!++last_id) ++last_id; // skip zero
2243 session[s].unique_id = last_id;
2244 }
2245
2246 q = makeppp(buf, sizeof(buf), 0, 0, s, t, PPPIPCP, 0, 0, 0);
2247 if (!q) return;
2248
2249 *q = ConfigReq;
2250 q[1] = session[s].unique_id & 0xf; // ID, dont care, we only send one type of request
2251 *(uint16_t *) (q + 2) = htons(10); // packet length
2252 q[4] = 3; // ip address option
2253 q[5] = 6; // option length
2254 *(in_addr_t *) (q + 6) = config->peer_address ? config->peer_address :
2255 config->iftun_n_address[tunnel[t].indexudp] ? config->iftun_n_address[tunnel[t].indexudp] :
2256 my_address; // send my IP
2257
2258 tunnelsend(buf, 10 + (q - buf), t); // send it
2259 restart_timer(s, ipcp);
2260 }
2261
2262 void sendipv6cp(sessionidt s, tunnelidt t)
2263 {
2264 uint8_t buf[MAXETHER];
2265 uint8_t *q;
2266
2267 CSTAT(sendipv6cp);
2268 LOG(3, s, t, "IPV6CP: send ConfigReq\n");
2269
2270 q = makeppp(buf, sizeof(buf), 0, 0, s, t, PPPIPV6CP, 0, 0, 0);
2271 if (!q) return;
2272
2273 *q = ConfigReq;
2274 q[1] = session[s].unique_id & 0xf; // ID, don't care, we
2275 // only send one type
2276 // of request
2277 *(uint16_t *) (q + 2) = htons(14);
2278 q[4] = 1; // interface identifier option
2279 q[5] = 10; // option length
2280 *(uint32_t *) (q + 6) = 0; // We'll be prefix::1
2281 *(uint32_t *) (q + 10) = 0;
2282 q[13] = 1;
2283
2284 tunnelsend(buf, 14 + (q - buf), t); // send it
2285 restart_timer(s, ipv6cp);
2286 }
2287
2288 static void sessionclear(sessionidt s)
2289 {
2290 memset(&session[s], 0, sizeof(session[s]));
2291 memset(&sess_local[s], 0, sizeof(sess_local[s]));
2292 memset(&cli_session_actions[s], 0, sizeof(cli_session_actions[s]));
2293
2294 session[s].tunnel = T_FREE; // Mark it as free.
2295 session[s].next = sessionfree;
2296 sessionfree = s;
2297 }
2298
2299 // kill a session now
2300 void sessionkill(sessionidt s, char *reason)
2301 {
2302 groupidt g;
2303
2304 CSTAT(sessionkill);
2305
2306 if (!session[s].opened) // not alive
2307 return;
2308
2309 if (session[s].next)
2310 {
2311 LOG(0, s, session[s].tunnel, "Tried to kill a session with next pointer set (%u)\n", session[s].next);
2312 return;
2313 }
2314
2315 if (!session[s].die)
2316 sessionshutdown(s, reason, CDN_ADMIN_DISC, TERM_ADMIN_RESET); // close radius/routes, etc.
2317
2318 if (sess_local[s].radius)
2319 radiusclear(sess_local[s].radius, s); // cant send clean accounting data, session is killed
2320
2321 if (session[s].forwardtosession)
2322 {
2323 sessionidt sess = session[s].forwardtosession;
2324 if (session[sess].forwardtosession == s)
2325 {
2326 // Shutdown the linked session also.
2327 sessionshutdown(sess, reason, CDN_ADMIN_DISC, TERM_ADMIN_RESET);
2328 }
2329 }
2330
2331 LOG(2, s, session[s].tunnel, "Kill session %d (%s): %s\n", s, session[s].user, reason);
2332
2333 if ((g = grp_groupbysession(s)))
2334 {
2335 grp_removesession(g, s);
2336 }
2337
2338 sessionclear(s);
2339 cluster_send_session(s);
2340 }
2341
2342 static void tunnelclear(tunnelidt t)
2343 {
2344 if (!t) return;
2345 memset(&tunnel[t], 0, sizeof(tunnel[t]));
2346 tunnel[t].state = TUNNELFREE;
2347 }
2348
2349 static void bundleclear(bundleidt b)
2350 {
2351 if (!b) return;
2352 memset(&bundle[b], 0, sizeof(bundle[b]));
2353 bundle[b].state = BUNDLEFREE;
2354 }
2355
2356 // kill a tunnel now
2357 static void tunnelkill(tunnelidt t, char *reason)
2358 {
2359 sessionidt s;
2360 controlt *c;
2361
2362 CSTAT(tunnelkill);
2363
2364 tunnel[t].state = TUNNELDIE;
2365
2366 // free control messages
2367 while ((c = tunnel[t].controls))
2368 {
2369 controlt * n = c->next;
2370 tunnel[t].controls = n;
2371 tunnel[t].controlc--;
2372 c->next = controlfree;
2373 controlfree = c;
2374 }
2375 // kill sessions
2376 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
2377 if (session[s].tunnel == t)
2378 sessionkill(s, reason);
2379
2380 // free tunnel
2381 tunnelclear(t);
2382 LOG(1, 0, t, "Kill tunnel %u: %s\n", t, reason);
2383 cli_tunnel_actions[t].action = 0;
2384 cluster_send_tunnel(t);
2385 }
2386
2387 // shut down a tunnel cleanly
2388 static void tunnelshutdown(tunnelidt t, char *reason, int result, int error, char *msg)
2389 {
2390 sessionidt s;
2391
2392 CSTAT(tunnelshutdown);
2393
2394 if (!tunnel[t].last || !tunnel[t].far || tunnel[t].state == TUNNELFREE)
2395 {
2396 // never set up, can immediately kill
2397 tunnelkill(t, reason);
2398 return;
2399 }
2400 LOG(1, 0, t, "Shutting down tunnel %u (%s)\n", t, reason);
2401
2402 // close session
2403 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
2404 if (session[s].tunnel == t)
2405 sessionshutdown(s, reason, CDN_NONE, TERM_ADMIN_RESET);
2406
2407 tunnel[t].state = TUNNELDIE;
2408 tunnel[t].die = TIME + 700; // Clean up in 70 seconds
2409 cluster_send_tunnel(t);
2410 // TBA - should we wait for sessions to stop?
2411 if (result)
2412 {
2413 controlt *c = controlnew(4); // sending StopCCN
2414 if (error)
2415 {
2416 uint16_t buf[32];
2417 int l = 4;
2418 buf[0] = htons(result);
2419 buf[1] = htons(error);
2420 if (msg)
2421 {
2422 int m = strlen(msg);
2423 if (m + 4 > sizeof(buf))
2424 m = sizeof(buf) - 4;
2425
2426 memcpy(buf+2, msg, m);
2427 l += m;
2428 }
2429
2430 controlb(c, 1, (uint8_t *)buf, l, 1);
2431 }
2432 else
2433 control16(c, 1, result, 1);
2434
2435 control16(c, 9, t, 1); // assigned tunnel (our end)
2436 controladd(c, 0, t); // send the message
2437 }
2438 }
2439
2440 // read and process packet on tunnel (UDP)
2441 void processudp(uint8_t *buf, int len, struct sockaddr_in *addr, uint16_t indexudpfd)
2442 {
2443 uint8_t *chapresponse = NULL;
2444 uint16_t l = len, t = 0, s = 0, ns = 0, nr = 0;
2445 uint8_t *p = buf + 2;
2446
2447
2448 CSTAT(processudp);
2449
2450 udp_rx += len;
2451 udp_rx_pkt++;
2452 LOG_HEX(5, "UDP Data", buf, len);
2453 STAT(tunnel_rx_packets);
2454 INC_STAT(tunnel_rx_bytes, len);
2455 if (len < 6)
2456 {
2457 LOG(1, 0, 0, "Short UDP, %d bytes\n", len);
2458 STAT(tunnel_rx_errors);
2459 return;
2460 }
2461 if ((buf[1] & 0x0F) != 2)
2462 {
2463 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf[1] & 0x0F);
2464 STAT(tunnel_rx_errors);
2465 return;
2466 }
2467 if (*buf & 0x40)
2468 { // length
2469 l = ntohs(*(uint16_t *) p);
2470 p += 2;
2471 }
2472 t = ntohs(*(uint16_t *) p);
2473 p += 2;
2474 s = ntohs(*(uint16_t *) p);
2475 p += 2;
2476 if (s >= MAXSESSION)
2477 {
2478 LOG(1, s, t, "Received UDP packet with invalid session ID\n");
2479 STAT(tunnel_rx_errors);
2480 return;
2481 }
2482 if (t >= MAXTUNNEL)
2483 {
2484 LOG(1, s, t, "Received UDP packet with invalid tunnel ID\n");
2485 STAT(tunnel_rx_errors);
2486 return;
2487 }
2488 if (t == TUNNEL_ID_PPPOE)
2489 {
2490 LOG(1, s, t, "Received UDP packet with tunnel ID reserved for pppoe\n");
2491 STAT(tunnel_rx_errors);
2492 return;
2493 }
2494 if (*buf & 0x08)
2495 { // ns/nr
2496 ns = ntohs(*(uint16_t *) p);
2497 p += 2;
2498 nr = ntohs(*(uint16_t *) p);
2499 p += 2;
2500 }
2501 if (*buf & 0x02)
2502 { // offset
2503 uint16_t o = ntohs(*(uint16_t *) p);
2504 p += o + 2;
2505 }
2506 if ((p - buf) > l)
2507 {
2508 LOG(1, s, t, "Bad length %d>%d\n", (int) (p - buf), l);
2509 STAT(tunnel_rx_errors);
2510 return;
2511 }
2512 l -= (p - buf);
2513
2514 // used to time out old tunnels
2515 if (t && tunnel[t].state == TUNNELOPEN)
2516 tunnel[t].lastrec = time_now;
2517
2518 if (*buf & 0x80)
2519 { // control
2520 uint16_t message = 0xFFFF; // message type
2521 uint8_t fatal = 0;
2522 uint8_t mandatory = 0;
2523 uint16_t asession = 0; // assigned session
2524 uint32_t amagic = 0; // magic number
2525 uint8_t aflags = 0; // flags from last LCF
2526 uint16_t version = 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2527 char called[MAXTEL] = ""; // called number
2528 char calling[MAXTEL] = ""; // calling number
2529
2530 if (!config->cluster_iam_master)
2531 {
2532 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
2533 return;
2534 }
2535
2536 // control messages must have bits 0x80|0x40|0x08
2537 // (type, length and sequence) set, and bits 0x02|0x01
2538 // (offset and priority) clear
2539 if ((*buf & 0xCB) != 0xC8)
2540 {
2541 LOG(1, s, t, "Bad control header %02X\n", *buf);
2542 STAT(tunnel_rx_errors);
2543 return;
2544 }
2545
2546 // check for duplicate tunnel open message
2547 if (!t && ns == 0)
2548 {
2549 int i;
2550
2551 //
2552 // Is this a duplicate of the first packet? (SCCRQ)
2553 //
2554 for (i = 1; i <= config->cluster_highest_tunnelid ; ++i)
2555 {
2556 if (tunnel[i].state != TUNNELOPENING ||
2557 tunnel[i].ip != ntohl(*(in_addr_t *) & addr->sin_addr) ||
2558 tunnel[i].port != ntohs(addr->sin_port) )
2559 continue;
2560 t = i;
2561 LOG(3, s, t, "Duplicate SCCRQ?\n");
2562 break;
2563 }
2564 }
2565
2566 LOG(3, s, t, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2567 l, tunnel[t].controlc, tunnel[t].ns, tunnel[t].nr, ns, nr);
2568
2569 // if no tunnel specified, assign one
2570 if (!t)
2571 {
2572 if (!(t = new_tunnel()))
2573 {
2574 LOG(1, 0, 0, "No more tunnels\n");
2575 STAT(tunnel_overflow);
2576 return;
2577 }
2578 tunnelclear(t);
2579 tunnel[t].ip = ntohl(*(in_addr_t *) & addr->sin_addr);
2580 tunnel[t].port = ntohs(addr->sin_port);
2581 tunnel[t].window = 4; // default window
2582 tunnel[t].indexudp = indexudpfd;
2583 STAT(tunnel_created);
2584 LOG(1, 0, t, " New tunnel from %s:%u ID %u\n",
2585 fmtaddr(htonl(tunnel[t].ip), 0), tunnel[t].port, t);
2586 }
2587
2588 // If the 'ns' just received is not the 'nr' we're
2589 // expecting, just send an ack and drop it.
2590 //
2591 // if 'ns' is less, then we got a retransmitted packet.
2592 // if 'ns' is greater than missed a packet. Either way
2593 // we should ignore it.
2594 if (ns != tunnel[t].nr)
2595 {
2596 // is this the sequence we were expecting?
2597 STAT(tunnel_rx_errors);
2598 LOG(1, 0, t, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2599 t, ns, tunnel[t].nr);
2600
2601 if (l) // Is this not a ZLB?
2602 controlnull(t);
2603 return;
2604 }
2605
2606 // check sequence of this message
2607 {
2608 int skip = tunnel[t].window; // track how many in-window packets are still in queue
2609 // some to clear maybe?
2610 while (tunnel[t].controlc > 0 && (((tunnel[t].ns - tunnel[t].controlc) - nr) & 0x8000))
2611 {
2612 controlt *c = tunnel[t].controls;
2613 tunnel[t].controls = c->next;
2614 tunnel[t].controlc--;
2615 c->next = controlfree;
2616 controlfree = c;
2617 skip--;
2618 tunnel[t].try = 0; // we have progress
2619 }
2620
2621 // receiver advance (do here so quoted correctly in any sends below)
2622 if (l) tunnel[t].nr = (ns + 1);
2623 if (skip < 0) skip = 0;
2624 if (skip < tunnel[t].controlc)
2625 {
2626 // some control packets can now be sent that were previous stuck out of window
2627 int tosend = tunnel[t].window - skip;
2628 controlt *c = tunnel[t].controls;
2629 while (c && skip)
2630 {
2631 c = c->next;
2632 skip--;
2633 }
2634 while (c && tosend)
2635 {
2636 tunnel[t].try = 0; // first send
2637 tunnelsend(c->buf, c->length, t);
2638 c = c->next;
2639 tosend--;
2640 }
2641 }
2642 if (!tunnel[t].controlc)
2643 tunnel[t].retry = 0; // caught up
2644 }
2645 if (l)
2646 { // if not a null message
2647 int result = 0;
2648 int error = 0;
2649 char *msg = 0;
2650
2651 // Default disconnect cause/message on receipt of CDN. Set to
2652 // more specific value from attribute 1 (result code) or 46
2653 // (disconnect cause) if present below.
2654 int disc_cause_set = 0;
2655 int disc_cause = TERM_NAS_REQUEST;
2656 char const *disc_reason = "Closed (Received CDN).";
2657
2658 // process AVPs
2659 while (l && !(fatal & 0x80)) // 0x80 = mandatory AVP
2660 {
2661 uint16_t n = (ntohs(*(uint16_t *) p) & 0x3FF);
2662 uint8_t *b = p;
2663 uint8_t flags = *p;
2664 uint16_t mtype;
2665
2666 if (n > l)
2667 {
2668 LOG(1, s, t, "Invalid length in AVP\n");
2669 STAT(tunnel_rx_errors);
2670 return;
2671 }
2672 p += n; // next
2673 l -= n;
2674 if (flags & 0x3C) // reserved bits, should be clear
2675 {
2676 LOG(1, s, t, "Unrecognised AVP flags %02X\n", *b);
2677 fatal = flags;
2678 result = 2; // general error
2679 error = 3; // reserved field non-zero
2680 msg = 0;
2681 continue; // next
2682 }
2683 b += 2;
2684 if (*(uint16_t *) (b))
2685 {
2686 LOG(2, s, t, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b)));
2687 fatal = flags;
2688 result = 2; // general error
2689 error = 6; // generic vendor-specific error
2690 msg = "unsupported vendor-specific";
2691 continue; // next
2692 }
2693 b += 2;
2694 mtype = ntohs(*(uint16_t *) (b));
2695 b += 2;
2696 n -= 6;
2697
2698 if (flags & 0x40)
2699 {
2700 uint16_t orig_len;
2701
2702 // handle hidden AVPs
2703 if (!*config->l2tp_secret)
2704 {
2705 LOG(1, s, t, "Hidden AVP requested, but no L2TP secret.\n");
2706 fatal = flags;
2707 result = 2; // general error
2708 error = 6; // generic vendor-specific error
2709 msg = "secret not specified";
2710 continue;
2711 }
2712 if (!session[s].random_vector_length)
2713 {
2714 LOG(1, s, t, "Hidden AVP requested, but no random vector.\n");
2715 fatal = flags;
2716 result = 2; // general error
2717 error = 6; // generic
2718 msg = "no random vector";
2719 continue;
2720 }
2721 if (n < 8)
2722 {
2723 LOG(2, s, t, "Short hidden AVP.\n");
2724 fatal = flags;
2725 result = 2; // general error
2726 error = 2; // length is wrong
2727 msg = 0;
2728 continue;
2729 }
2730
2731 // Unhide the AVP
2732 unhide_value(b, n, mtype, session[s].random_vector, session[s].random_vector_length);
2733
2734 orig_len = ntohs(*(uint16_t *) b);
2735 if (orig_len > n + 2)
2736 {
2737 LOG(1, s, t, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2738 orig_len, n);
2739
2740 fatal = flags;
2741 result = 2; // general error
2742 error = 2; // length is wrong
2743 msg = 0;
2744 continue;
2745 }
2746
2747 b += 2;
2748 n = orig_len;
2749 }
2750
2751 LOG(4, s, t, " AVP %u (%s) len %d%s%s\n", mtype, l2tp_avp_name(mtype), n,
2752 flags & 0x40 ? ", hidden" : "", flags & 0x80 ? ", mandatory" : "");
2753
2754 switch (mtype)
2755 {
2756 case 0: // message type
2757 message = ntohs(*(uint16_t *) b);
2758 mandatory = flags & 0x80;
2759 LOG(4, s, t, " Message type = %u (%s)\n", message, l2tp_code(message));
2760 break;
2761 case 1: // result code
2762 {
2763 uint16_t rescode = ntohs(*(uint16_t *) b);
2764 char const *resdesc = "(unknown)";
2765 char const *errdesc = NULL;
2766 int cause = 0;
2767
2768 if (message == 4)
2769 { /* StopCCN */
2770 resdesc = l2tp_stopccn_result_code(rescode);
2771 cause = TERM_LOST_SERVICE;
2772 }
2773 else if (message == 14)
2774 { /* CDN */
2775 resdesc = l2tp_cdn_result_code(rescode);
2776 if (rescode == 1)
2777 cause = TERM_LOST_CARRIER;
2778 else
2779 cause = TERM_ADMIN_RESET;
2780 }
2781
2782 LOG(4, s, t, " Result Code %u: %s\n", rescode, resdesc);
2783 if (n >= 4)
2784 {
2785 uint16_t errcode = ntohs(*(uint16_t *)(b + 2));
2786 errdesc = l2tp_error_code(errcode);
2787 LOG(4, s, t, " Error Code %u: %s\n", errcode, errdesc);
2788 }
2789 if (n > 4)
2790 LOG(4, s, t, " Error String: %.*s\n", n-4, b+4);
2791
2792 if (cause && disc_cause_set < mtype) // take cause from attrib 46 in preference
2793 {
2794 disc_cause_set = mtype;
2795 disc_reason = errdesc ? errdesc : resdesc;
2796 disc_cause = cause;
2797 }
2798
2799 break;
2800 }
2801 break;
2802 case 2: // protocol version
2803 {
2804 version = ntohs(*(uint16_t *) (b));
2805 LOG(4, s, t, " Protocol version = %u\n", version);
2806 if (version && version != 0x0100)
2807 { // allow 0.0 and 1.0
2808 LOG(1, s, t, " Bad protocol version %04X\n", version);
2809 fatal = flags;
2810 result = 5; // unspported protocol version
2811 error = 0x0100; // supported version
2812 msg = 0;
2813 continue; // next
2814 }
2815 }
2816 break;
2817 case 3: // framing capabilities
2818 break;
2819 case 4: // bearer capabilities
2820 break;
2821 case 5: // tie breaker
2822 // We never open tunnels, so we don't care about tie breakers
2823 continue;
2824 case 6: // firmware revision
2825 break;
2826 case 7: // host name
2827 memset(tunnel[t].hostname, 0, sizeof(tunnel[t].hostname));
2828 memcpy(tunnel[t].hostname, b, (n < sizeof(tunnel[t].hostname)) ? n : sizeof(tunnel[t].hostname) - 1);
2829 LOG(4, s, t, " Tunnel hostname = \"%s\"\n", tunnel[t].hostname);
2830 // TBA - to send to RADIUS
2831 break;
2832 case 8: // vendor name
2833 memset(tunnel[t].vendor, 0, sizeof(tunnel[t].vendor));
2834 memcpy(tunnel[t].vendor, b, (n < sizeof(tunnel[t].vendor)) ? n : sizeof(tunnel[t].vendor) - 1);
2835 LOG(4, s, t, " Vendor name = \"%s\"\n", tunnel[t].vendor);
2836 break;
2837 case 9: // assigned tunnel
2838 tunnel[t].far = ntohs(*(uint16_t *) (b));
2839 LOG(4, s, t, " Remote tunnel id = %u\n", tunnel[t].far);
2840 break;
2841 case 10: // rx window
2842 tunnel[t].window = ntohs(*(uint16_t *) (b));
2843 if (!tunnel[t].window)
2844 tunnel[t].window = 1; // window of 0 is silly
2845 LOG(4, s, t, " rx window = %u\n", tunnel[t].window);
2846 break;
2847 case 11: // Challenge
2848 {
2849 LOG(4, s, t, " LAC requested CHAP authentication for tunnel\n");
2850 build_chap_response(b, 2, n, &chapresponse);
2851 }
2852 break;
2853 case 13: // Response
2854 if (tunnel[t].isremotelns)
2855 {
2856 chapresponse = calloc(17, 1);
2857 memcpy(chapresponse, b, (n < 17) ? n : 16);
2858 LOG(3, s, t, "received challenge response from REMOTE LNS\n");
2859 }
2860 else
2861 // Why did they send a response? We never challenge.
2862 LOG(2, s, t, " received unexpected challenge response\n");
2863 break;
2864
2865 case 14: // assigned session
2866 asession = session[s].far = ntohs(*(uint16_t *) (b));
2867 LOG(4, s, t, " assigned session = %u\n", asession);
2868 break;
2869 case 15: // call serial number
2870 LOG(4, s, t, " call serial number = %u\n", ntohl(*(uint32_t *)b));
2871 break;
2872 case 18: // bearer type
2873 LOG(4, s, t, " bearer type = %u\n", ntohl(*(uint32_t *)b));
2874 // TBA - for RADIUS
2875 break;
2876 case 19: // framing type
2877 LOG(4, s, t, " framing type = %u\n", ntohl(*(uint32_t *)b));
2878 // TBA
2879 break;
2880 case 21: // called number
2881 memset(called, 0, sizeof(called));
2882 memcpy(called, b, (n < sizeof(called)) ? n : sizeof(called) - 1);
2883 LOG(4, s, t, " Called <%s>\n", called);
2884 break;
2885 case 22: // calling number
2886 memset(calling, 0, sizeof(calling));
2887 memcpy(calling, b, (n < sizeof(calling)) ? n : sizeof(calling) - 1);
2888 LOG(4, s, t, " Calling <%s>\n", calling);
2889 break;
2890 case 23: // subtype
2891 break;
2892 case 24: // tx connect speed
2893 if (n == 4)
2894 {
2895 session[s].tx_connect_speed = ntohl(*(uint32_t *)b);
2896 }
2897 else
2898 {
2899 // AS5300s send connect speed as a string
2900 char tmp[30];
2901 memset(tmp, 0, sizeof(tmp));
2902 memcpy(tmp, b, (n < sizeof(tmp)) ? n : sizeof(tmp) - 1);
2903 session[s].tx_connect_speed = atol(tmp);
2904 }
2905 LOG(4, s, t, " TX connect speed <%u>\n", session[s].tx_connect_speed);
2906 break;
2907 case 38: // rx connect speed
2908 if (n == 4)
2909 {
2910 session[s].rx_connect_speed = ntohl(*(uint32_t *)b);
2911 }
2912 else
2913 {
2914 // AS5300s send connect speed as a string
2915 char tmp[30];
2916 memset(tmp, 0, sizeof(tmp));
2917 memcpy(tmp, b, (n < sizeof(tmp)) ? n : sizeof(tmp) - 1);
2918 session[s].rx_connect_speed = atol(tmp);
2919 }
2920 LOG(4, s, t, " RX connect speed <%u>\n", session[s].rx_connect_speed);
2921 break;
2922 case 25: // Physical Channel ID
2923 {
2924 uint32_t tmp = ntohl(*(uint32_t *) b);
2925 LOG(4, s, t, " Physical Channel ID <%X>\n", tmp);
2926 break;
2927 }
2928 case 29: // Proxy Authentication Type
2929 {
2930 uint16_t atype = ntohs(*(uint16_t *)b);
2931 LOG(4, s, t, " Proxy Auth Type %u (%s)\n", atype, ppp_auth_type(atype));
2932 break;
2933 }
2934 case 30: // Proxy Authentication Name
2935 {
2936 char authname[64];
2937 memset(authname, 0, sizeof(authname));
2938 memcpy(authname, b, (n < sizeof(authname)) ? n : sizeof(authname) - 1);
2939 LOG(4, s, t, " Proxy Auth Name (%s)\n",
2940 authname);
2941 break;
2942 }
2943 case 31: // Proxy Authentication Challenge
2944 {
2945 LOG(4, s, t, " Proxy Auth Challenge\n");
2946 break;
2947 }
2948 case 32: // Proxy Authentication ID
2949 {
2950 uint16_t authid = ntohs(*(uint16_t *)(b));
2951 LOG(4, s, t, " Proxy Auth ID (%u)\n", authid);
2952 break;
2953 }
2954 case 33: // Proxy Authentication Response
2955 LOG(4, s, t, " Proxy Auth Response\n");
2956 break;
2957 case 27: // last sent lcp
2958 { // find magic number
2959 uint8_t *p = b, *e = p + n;
2960 while (p + 1 < e && p[1] && p + p[1] <= e)
2961 {
2962 if (*p == 5 && p[1] == 6) // Magic-Number
2963 amagic = ntohl(*(uint32_t *) (p + 2));
2964 else if (*p == 7) // Protocol-Field-Compression
2965 aflags |= SESSION_PFC;
2966 else if (*p == 8) // Address-and-Control-Field-Compression
2967 aflags |= SESSION_ACFC;
2968 p += p[1];
2969 }
2970 }
2971 break;
2972 case 28: // last recv lcp confreq
2973 break;
2974 case 26: // Initial Received LCP CONFREQ
2975 break;
2976 case 39: // seq required - we control it as an LNS anyway...
2977 break;
2978 case 36: // Random Vector
2979 LOG(4, s, t, " Random Vector received. Enabled AVP Hiding.\n");
2980 memset(session[s].random_vector, 0, sizeof(session[s].random_vector));
2981 if (n > sizeof(session[s].random_vector))
2982 n = sizeof(session[s].random_vector);
2983 memcpy(session[s].random_vector, b, n);
2984 session[s].random_vector_length = n;
2985 break;
2986 case 46: // ppp disconnect cause
2987 if (n >= 5)
2988 {
2989 uint16_t code = ntohs(*(uint16_t *) b);
2990 uint16_t proto = ntohs(*(uint16_t *) (b + 2));
2991 uint8_t dir = *(b + 4);
2992
2993 LOG(4, s, t, " PPP disconnect cause "
2994 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2995 code, proto, dir, n - 5, b + 5);
2996
2997 disc_cause_set = mtype;
2998
2999 switch (code)
3000 {
3001 case 1: // admin disconnect
3002 disc_cause = TERM_ADMIN_RESET;
3003 disc_reason = "Administrative disconnect";
3004 break;
3005 case 3: // lcp terminate
3006 if (dir != 2) break; // 1=peer (LNS), 2=local (LAC)
3007 disc_cause = TERM_USER_REQUEST;
3008 disc_reason = "Normal disconnection";
3009 break;
3010 case 4: // compulsory encryption unavailable
3011 if (dir != 1) break; // 1=refused by peer, 2=local
3012 disc_cause = TERM_USER_ERROR;
3013 disc_reason = "Compulsory encryption refused";
3014 break;
3015 case 5: // lcp: fsm timeout
3016 disc_cause = TERM_PORT_ERROR;
3017 disc_reason = "LCP: FSM timeout";
3018 break;
3019 case 6: // lcp: no recognisable lcp packets received
3020 disc_cause = TERM_PORT_ERROR;
3021 disc_reason = "LCP: no recognisable LCP packets";
3022 break;
3023 case 7: // lcp: magic-no error (possibly looped back)
3024 disc_cause = TERM_PORT_ERROR;
3025 disc_reason = "LCP: magic-no error (possible loop)";
3026 break;
3027 case 8: // lcp: echo request timeout
3028 disc_cause = TERM_PORT_ERROR;
3029 disc_reason = "LCP: echo request timeout";
3030 break;
3031 case 13: // auth: fsm timeout
3032 disc_cause = TERM_SERVICE_UNAVAILABLE;
3033 disc_reason = "Authentication: FSM timeout";
3034 break;
3035 case 15: // auth: unacceptable auth protocol
3036 disc_cause = TERM_SERVICE_UNAVAILABLE;
3037 disc_reason = "Unacceptable authentication protocol";
3038 break;
3039 case 16: // auth: authentication failed
3040 disc_cause = TERM_SERVICE_UNAVAILABLE;
3041 disc_reason = "Authentication failed";
3042 break;
3043 case 17: // ncp: fsm timeout
3044 disc_cause = TERM_SERVICE_UNAVAILABLE;
3045 disc_reason = "NCP: FSM timeout";
3046 break;
3047 case 18: // ncp: no ncps available
3048 disc_cause = TERM_SERVICE_UNAVAILABLE;
3049 disc_reason = "NCP: no NCPs available";
3050 break;
3051 case 19: // ncp: failure to converge on acceptable address
3052 disc_cause = TERM_SERVICE_UNAVAILABLE;
3053 disc_reason = (dir == 1)
3054 ? "NCP: too many Configure-Naks received from peer"
3055 : "NCP: too many Configure-Naks sent to peer";
3056 break;
3057 case 20: // ncp: user not permitted to use any address
3058 disc_cause = TERM_SERVICE_UNAVAILABLE;
3059 disc_reason = (dir == 1)
3060 ? "NCP: local link address not acceptable to peer"
3061 : "NCP: remote link address not acceptable";
3062 break;
3063 }
3064 }
3065 break;
3066 default:
3067 {
3068 static char e[] = "unknown AVP 0xXXXX";
3069 LOG(2, s, t, " Unknown AVP type %u\n", mtype);
3070 fatal = flags;
3071 result = 2; // general error
3072 error = 8; // unknown mandatory AVP
3073 sprintf((msg = e) + 14, "%04x", mtype);
3074 continue; // next
3075 }
3076 }
3077 }
3078 // process message
3079 if (fatal & 0x80)
3080 tunnelshutdown(t, "Invalid mandatory AVP", result, error, msg);
3081 else
3082 switch (message)
3083 {
3084 case 1: // SCCRQ - Start Control Connection Request
3085 tunnel[t].state = TUNNELOPENING;
3086 LOG(3, s, t, "Received SCCRQ\n");
3087 if (main_quit != QUIT_SHUTDOWN)
3088 {
3089 LOG(3, s, t, "sending SCCRP\n");
3090 controlt *c = controlnew(2); // sending SCCRP
3091 control16(c, 2, version, 1); // protocol version
3092 control32(c, 3, 3, 1); // framing
3093 controls(c, 7, hostname, 1); // host name
3094 if (chapresponse) controlb(c, 13, chapresponse, 16, 1); // Challenge response
3095 control16(c, 9, t, 1); // assigned tunnel
3096 controladd(c, 0, t); // send the resply
3097 }
3098 else
3099 {
3100 tunnelshutdown(t, "Shutting down", 6, 0, 0);
3101 }
3102 break;
3103 case 2: // SCCRP
3104 tunnel[t].state = TUNNELOPEN;
3105 tunnel[t].lastrec = time_now;
3106 LOG(3, s, t, "Received SCCRP\n");
3107 if (main_quit != QUIT_SHUTDOWN)
3108 {
3109 if (tunnel[t].isremotelns && chapresponse)
3110 {
3111 hasht hash;
3112
3113 lac_calc_rlns_auth(t, 2, hash); // id = 2 (SCCRP)
3114 // check authenticator
3115 if (memcmp(hash, chapresponse, 16) == 0)
3116 {
3117 LOG(3, s, t, "sending SCCCN to REMOTE LNS\n");
3118 controlt *c = controlnew(3); // sending SCCCN
3119 controls(c, 7, hostname, 1); // host name
3120 controls(c, 8, Vendor_name, 1); // Vendor name
3121 control16(c, 2, version, 1); // protocol version
3122 control32(c, 3, 3, 1); // framing Capabilities
3123 control16(c, 9, t, 1); // assigned tunnel
3124 controladd(c, 0, t); // send
3125 }
3126 else
3127 {
3128 tunnelshutdown(t, "Bad chap response from REMOTE LNS", 4, 0, 0);
3129 }
3130 }
3131 }
3132 else
3133 {
3134 tunnelshutdown(t, "Shutting down", 6, 0, 0);
3135 }
3136 break;
3137 case 3: // SCCN
3138 LOG(3, s, t, "Received SCCN\n");
3139 tunnel[t].state = TUNNELOPEN;
3140 tunnel[t].lastrec = time_now;
3141 controlnull(t); // ack
3142 break;
3143 case 4: // StopCCN
3144 LOG(3, s, t, "Received StopCCN\n");
3145 controlnull(t); // ack
3146 tunnelshutdown(t, "Stopped", 0, 0, 0); // Shut down cleanly
3147 break;
3148 case 6: // HELLO
3149 LOG(3, s, t, "Received HELLO\n");
3150 controlnull(t); // simply ACK
3151 break;
3152 case 7: // OCRQ
3153 // TBA
3154 LOG(3, s, t, "Received OCRQ\n");
3155 break;
3156 case 8: // OCRO
3157 // TBA
3158 LOG(3, s, t, "Received OCRO\n");
3159 break;
3160 case 9: // OCCN
3161 // TBA
3162 LOG(3, s, t, "Received OCCN\n");
3163 break;
3164 case 10: // ICRQ
3165 LOG(3, s, t, "Received ICRQ\n");
3166 if (sessionfree && main_quit != QUIT_SHUTDOWN)
3167 {
3168 controlt *c = controlnew(11); // ICRP
3169
3170 LOG(3, s, t, "Sending ICRP\n");
3171
3172 s = sessionfree;
3173 sessionfree = session[s].next;
3174 memset(&session[s], 0, sizeof(session[s]));
3175
3176 if (s > config->cluster_highest_sessionid)
3177 config->cluster_highest_sessionid = s;
3178
3179 session[s].opened = time_now;
3180 session[s].tunnel = t;
3181 session[s].far = asession;
3182 session[s].last_packet = session[s].last_data = time_now;
3183 LOG(3, s, t, "New session (%u/%u)\n", tunnel[t].far, session[s].far);
3184 control16(c, 14, s, 1); // assigned session
3185 controladd(c, asession, t); // send the reply
3186
3187 strncpy(session[s].called, called, sizeof(session[s].called) - 1);
3188 strncpy(session[s].calling, calling, sizeof(session[s].calling) - 1);
3189
3190 session[s].ppp.phase = Establish;
3191 session[s].ppp.lcp = Starting;
3192
3193 STAT(session_created);
3194 break;
3195 }
3196
3197 {
3198 controlt *c = controlnew(14); // CDN
3199 LOG(3, s, t, "Sending CDN\n");
3200 if (!sessionfree)
3201 {
3202 STAT(session_overflow);
3203 LOG(1, 0, t, "No free sessions\n");
3204 control16(c, 1, 4, 0); // temporary lack of resources
3205 }
3206 else
3207 control16(c, 1, 2, 7); // shutting down, try another
3208
3209 controladd(c, asession, t); // send the message
3210 }
3211 return;
3212 case 11: // ICRP
3213 LOG(3, s, t, "Received ICRP\n");
3214 if (session[s].forwardtosession)
3215 {
3216 controlt *c = controlnew(12); // ICCN
3217
3218 session[s].opened = time_now;
3219 session[s].tunnel = t;
3220 session[s].far = asession;
3221 session[s].last_packet = session[s].last_data = time_now;
3222
3223 control32(c, 19, 1, 1); // Framing Type
3224 control32(c, 24, 10000000, 1); // Tx Connect Speed
3225 controladd(c, asession, t); // send the message
3226 LOG(3, s, t, "Sending ICCN\n");
3227 }
3228 break;
3229 case 12: // ICCN
3230 LOG(3, s, t, "Received ICCN\n");
3231 if (amagic == 0) amagic = time_now;
3232 session[s].magic = amagic; // set magic number
3233 session[s].flags = aflags; // set flags received
3234 session[s].mru = PPPoE_MRU; // default
3235 controlnull(t); // ack
3236
3237 // start LCP
3238 sess_local[s].lcp_authtype = config->radius_authprefer;
3239 sess_local[s].ppp_mru = MRU;
3240
3241 // Set multilink options before sending initial LCP packet
3242 sess_local[s].mp_mrru = 1614;
3243 sess_local[s].mp_epdis = ntohl(config->iftun_n_address[tunnel[t].indexudp] ? config->iftun_n_address[tunnel[t].indexudp] : my_address);
3244
3245 sendlcp(s, t);
3246 change_state(s, lcp, RequestSent);
3247 break;
3248
3249 case 14: // CDN
3250 LOG(3, s, t, "Received CDN\n");
3251 controlnull(t); // ack
3252 sessionshutdown(s, disc_reason, CDN_NONE, disc_cause);
3253 break;
3254 case 0xFFFF:
3255 LOG(1, s, t, "Missing message type\n");
3256 break;
3257 default:
3258 STAT(tunnel_rx_errors);
3259 if (mandatory)
3260 tunnelshutdown(t, "Unknown message type", 2, 6, "unknown message type");
3261 else
3262 LOG(1, s, t, "Unknown message type %u\n", message);
3263 break;
3264 }
3265 if (chapresponse) free(chapresponse);
3266 cluster_send_tunnel(t);
3267 }
3268 else
3269 {
3270 LOG(4, s, t, " Got a ZLB ack\n");
3271 }
3272 }
3273 else
3274 { // data
3275 uint16_t proto;
3276
3277 LOG_HEX(5, "Receive Tunnel Data", p, l);
3278 if (l > 2 && p[0] == 0xFF && p[1] == 0x03)
3279 { // HDLC address header, discard
3280 p += 2;
3281 l -= 2;
3282 }
3283 if (l < 2)
3284 {
3285 LOG(1, s, t, "Short ppp length %d\n", l);
3286 STAT(tunnel_rx_errors);
3287 return;
3288 }
3289 if (*p & 1)
3290 {
3291 proto = *p++;
3292 l--;
3293 }
3294 else
3295 {
3296 proto = ntohs(*(uint16_t *) p);
3297 p += 2;
3298 l -= 2;
3299 }
3300
3301 if (session[s].forwardtosession)
3302 {
3303 LOG(5, s, t, "Forwarding data session to session %u\n", session[s].forwardtosession);
3304 // Forward to LAC/BAS or Remote LNS session
3305 lac_session_forward(buf, len, s, proto, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3306 return;
3307 }
3308 else if (config->auth_tunnel_change_addr_src)
3309 {
3310 if (tunnel[t].ip != ntohl(addr->sin_addr.s_addr) &&
3311 tunnel[t].port == ntohs(addr->sin_port))
3312 {
3313 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3314 LOG(5, s, t, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3315 fmtaddr(htonl(tunnel[t].ip), 0), fmtaddr(addr->sin_addr.s_addr, 0));
3316
3317 tunnel[t].ip = ntohl(addr->sin_addr.s_addr);
3318 }
3319 }
3320
3321 if (s && !session[s].opened) // Is something wrong??
3322 {
3323 if (!config->cluster_iam_master)
3324 {
3325 // Pass it off to the master to deal with..
3326 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3327 return;
3328 }
3329
3330 LOG(1, s, t, "UDP packet contains session which is not opened. Dropping packet.\n");
3331 STAT(tunnel_rx_errors);
3332 return;
3333 }
3334
3335 if (proto == PPPPAP)
3336 {
3337 session[s].last_packet = time_now;
3338 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3339 processpap(s, t, p, l);
3340 }
3341 else if (proto == PPPCHAP)
3342 {
3343 session[s].last_packet = time_now;
3344 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3345 processchap(s, t, p, l);
3346 }
3347 else if (proto == PPPLCP)
3348 {
3349 session[s].last_packet = time_now;
3350 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3351 processlcp(s, t, p, l);
3352 }
3353 else if (proto == PPPIPCP)
3354 {
3355 session[s].last_packet = time_now;
3356 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3357 processipcp(s, t, p, l);
3358 }
3359 else if (proto == PPPIPV6CP && config->ipv6_prefix.s6_addr[0])
3360 {
3361 session[s].last_packet = time_now;
3362 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3363 processipv6cp(s, t, p, l);
3364 }
3365 else if (proto == PPPCCP)
3366 {
3367 session[s].last_packet = time_now;
3368 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3369 processccp(s, t, p, l);
3370 }
3371 else if (proto == PPPIP)
3372 {
3373 if (session[s].die)
3374 {
3375 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3376 return; // closing session, PPP not processed
3377 }
3378
3379 session[s].last_packet = session[s].last_data = time_now;
3380 if (session[s].walled_garden && !config->cluster_iam_master)
3381 {
3382 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3383 return;
3384 }
3385
3386 processipin(s, t, p, l);
3387 }
3388 else if (proto == PPPMP)
3389 {
3390 if (session[s].die)
3391 {
3392 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3393 return; // closing session, PPP not processed
3394 }
3395
3396 session[s].last_packet = session[s].last_data = time_now;
3397 if (!config->cluster_iam_master)
3398 {
3399 // The fragments reconstruction is managed by the Master.
3400 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3401 return;
3402 }
3403
3404 processmpin(s, t, p, l);
3405 }
3406 else if (proto == PPPIPV6 && config->ipv6_prefix.s6_addr[0])
3407 {
3408 if (session[s].die)
3409 {
3410 LOG(4, s, t, "Session %u is closing. Don't process PPP packets\n", s);
3411 return; // closing session, PPP not processed
3412 }
3413
3414 session[s].last_packet = session[s].last_data = time_now;
3415 if (session[s].walled_garden && !config->cluster_iam_master)
3416 {
3417 master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd);
3418 return;
3419 }
3420
3421 processipv6in(s, t, p, l);
3422 }
3423 else if (session[s].ppp.lcp == Opened)
3424 {
3425 session[s].last_packet = time_now;
3426 if (!config->cluster_iam_master) { master_forward_packet(buf, len, addr->sin_addr.s_addr, addr->sin_port, indexudpfd); return; }
3427 protoreject(s, t, p, l, proto);
3428 }
3429 else
3430 {
3431 LOG(2, s, t, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3432 proto, ppp_state(session[s].ppp.lcp));
3433 }
3434 }
3435 }
3436
3437 // read and process packet on tun
3438 // (i.e. this routine writes to buf[-8]).
3439 static void processtun(uint8_t * buf, int len)
3440 {
3441 LOG_HEX(5, "Receive TUN Data", buf, len);
3442 STAT(tun_rx_packets);
3443 INC_STAT(tun_rx_bytes, len);
3444
3445 CSTAT(processtun);
3446
3447 eth_rx_pkt++;
3448 eth_rx += len;
3449 if (len < 22)
3450 {
3451 LOG(1, 0, 0, "Short tun packet %d bytes\n", len);
3452 STAT(tun_rx_errors);
3453 return;
3454 }
3455
3456 if (*(uint16_t *) (buf + 2) == htons(PKTIP)) // IPv4
3457 processipout(buf, len);
3458 else if (*(uint16_t *) (buf + 2) == htons(PKTIPV6) // IPV6
3459 && config->ipv6_prefix.s6_addr[0])
3460 processipv6out(buf, len);
3461
3462 // Else discard.
3463 }
3464
3465 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3466 // that we look at the whole of the tunnel, radius and session tables
3467 // every second
3468 static void regular_cleanups(double period)
3469 {
3470 // Next tunnel, radius and session to check for actions on.
3471 static tunnelidt t = 0;
3472 static int r = 0;
3473 static sessionidt s = 0;
3474
3475 int t_actions = 0;
3476 int r_actions = 0;
3477 int s_actions = 0;
3478
3479 int t_slice;
3480 int r_slice;
3481 int s_slice;
3482
3483 int i;
3484 int a;
3485
3486 // divide up tables into slices based on the last run
3487 t_slice = config->cluster_highest_tunnelid * period;
3488 r_slice = (MAXRADIUS - 1) * period;
3489 s_slice = config->cluster_highest_sessionid * period;
3490
3491 if (t_slice < 1)
3492 t_slice = 1;
3493 else if (t_slice > config->cluster_highest_tunnelid)
3494 t_slice = config->cluster_highest_tunnelid;
3495
3496 if (r_slice < 1)
3497 r_slice = 1;
3498 else if (r_slice > (MAXRADIUS - 1))
3499 r_slice = MAXRADIUS - 1;
3500
3501 if (s_slice < 1)
3502 s_slice = 1;
3503 else if (s_slice > config->cluster_highest_sessionid)
3504 s_slice = config->cluster_highest_sessionid;
3505
3506 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period);
3507
3508 for (i = 0; i < t_slice; i++)
3509 {
3510 t++;
3511 if (t > config->cluster_highest_tunnelid)
3512 t = 1;
3513
3514 if (t == TUNNEL_ID_PPPOE)
3515 continue;
3516
3517 // check for expired tunnels
3518 if (tunnel[t].die && tunnel[t].die <= TIME)
3519 {
3520 STAT(tunnel_timeout);
3521 tunnelkill(t, "Expired");
3522 t_actions++;
3523 continue;
3524 }
3525 // check for message resend
3526 if (tunnel[t].retry && tunnel[t].controlc)
3527 {
3528 // resend pending messages as timeout on reply
3529 if (tunnel[t].retry <= TIME)
3530 {
3531 controlt *c = tunnel[t].controls;
3532 uint16_t w = tunnel[t].window;
3533 tunnel[t].try++; // another try
3534 if (tunnel[t].try > 5)
3535 tunnelkill(t, "Timeout on control message"); // game over
3536 else
3537 while (c && w--)
3538 {
3539 tunnelsend(c->buf, c->length, t);
3540 c = c->next;
3541 }
3542
3543 t_actions++;
3544 }
3545 }
3546 // Send hello
3547 if (tunnel[t].state == TUNNELOPEN && !tunnel[t].controlc && (time_now - tunnel[t].lastrec) > 60)
3548 {
3549 if (!config->disable_sending_hello)
3550 {
3551 controlt *c = controlnew(6); // sending HELLO
3552 controladd(c, 0, t); // send the message
3553 LOG(3, 0, t, "Sending HELLO message\n");
3554 t_actions++;
3555 }
3556 }
3557
3558 // Check for tunnel changes requested from the CLI
3559 if ((a = cli_tunnel_actions[t].action))
3560 {
3561 cli_tunnel_actions[t].action = 0;
3562 if (a & CLI_TUN_KILL)
3563 {
3564 LOG(2, 0, t, "Dropping tunnel by CLI\n");
3565 tunnelshutdown(t, "Requested by administrator", 1, 0, 0);
3566 t_actions++;
3567 }
3568 }
3569 }
3570
3571 for (i = 0; i < r_slice; i++)
3572 {
3573 r++;
3574 if (r >= MAXRADIUS)
3575 r = 1;
3576
3577 if (!radius[r].state)
3578 continue;
3579
3580 if (radius[r].retry <= TIME)
3581 {
3582 radiusretry(r);
3583 r_actions++;
3584 }
3585 }
3586
3587 for (i = 0; i < s_slice; i++)
3588 {
3589 s++;
3590 if (s > config->cluster_highest_sessionid)
3591 s = 1;
3592
3593 if (!session[s].opened) // Session isn't in use
3594 continue;
3595
3596 // check for expired sessions
3597 if (session[s].die)
3598 {
3599 if (session[s].die <= TIME)
3600 {
3601 sessionkill(s, "Expired");
3602 s_actions++;
3603 }
3604 continue;
3605 }
3606
3607 // PPP timeouts
3608 if (sess_local[s].lcp.restart <= time_now)
3609 {
3610 int next_state = session[s].ppp.lcp;
3611 switch (session[s].ppp.lcp)
3612 {
3613 case RequestSent:
3614 case AckReceived:
3615 next_state = RequestSent;
3616
3617 case AckSent:
3618 if (sess_local[s].lcp.conf_sent < config->ppp_max_configure)
3619 {
3620 LOG(3, s, session[s].tunnel, "No ACK for LCP ConfigReq... resending\n");
3621 sendlcp(s, session[s].tunnel);
3622 change_state(s, lcp, next_state);
3623 }
3624 else
3625 {
3626 sessionshutdown(s, "No response to LCP ConfigReq.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3627 STAT(session_timeout);
3628 }
3629
3630 s_actions++;
3631 }
3632
3633 if (session[s].die)
3634 continue;
3635 }
3636
3637 if (sess_local[s].ipcp.restart <= time_now)
3638 {
3639 int next_state = session[s].ppp.ipcp;
3640 switch (session[s].ppp.ipcp)
3641 {
3642 case RequestSent:
3643 case AckReceived:
3644 next_state = RequestSent;
3645
3646 case AckSent:
3647 if (sess_local[s].ipcp.conf_sent < config->ppp_max_configure)
3648 {
3649 LOG(3, s, session[s].tunnel, "No ACK for IPCP ConfigReq... resending\n");
3650 sendipcp(s, session[s].tunnel);
3651 change_state(s, ipcp, next_state);
3652 }
3653 else
3654 {
3655 sessionshutdown(s, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3656 STAT(session_timeout);
3657 }
3658
3659 s_actions++;
3660 }
3661
3662 if (session[s].die)
3663 continue;
3664 }
3665
3666 if (sess_local[s].ipv6cp.restart <= time_now)
3667 {
3668 int next_state = session[s].ppp.ipv6cp;
3669 switch (session[s].ppp.ipv6cp)
3670 {
3671 case RequestSent:
3672 case AckReceived:
3673 next_state = RequestSent;
3674
3675 case AckSent:
3676 if (sess_local[s].ipv6cp.conf_sent < config->ppp_max_configure)
3677 {
3678 LOG(3, s, session[s].tunnel, "No ACK for IPV6CP ConfigReq... resending\n");
3679 sendipv6cp(s, session[s].tunnel);
3680 change_state(s, ipv6cp, next_state);
3681 }
3682 else
3683 {
3684 LOG(3, s, session[s].tunnel, "No ACK for IPV6CP ConfigReq\n");
3685 change_state(s, ipv6cp, Stopped);
3686 }
3687
3688 s_actions++;
3689 }
3690 }
3691
3692 if (sess_local[s].ccp.restart <= time_now)
3693 {
3694 int next_state = session[s].ppp.ccp;
3695 switch (session[s].ppp.ccp)
3696 {
3697 case RequestSent:
3698 case AckReceived:
3699 next_state = RequestSent;
3700
3701 case AckSent:
3702 if (sess_local[s].ccp.conf_sent < config->ppp_max_configure)
3703 {
3704 LOG(3, s, session[s].tunnel, "No ACK for CCP ConfigReq... resending\n");
3705 sendccp(s, session[s].tunnel);
3706 change_state(s, ccp, next_state);
3707 }
3708 else
3709 {
3710 LOG(3, s, session[s].tunnel, "No ACK for CCP ConfigReq\n");
3711 change_state(s, ccp, Stopped);
3712 }
3713
3714 s_actions++;
3715 }
3716 }
3717
3718 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3719 if (session[s].last_packet && (time_now - session[s].last_packet >= config->idle_echo_timeout))
3720 {
3721 sessionshutdown(s, "No response to LCP ECHO requests.", CDN_ADMIN_DISC, TERM_LOST_SERVICE);
3722 STAT(session_timeout);
3723 s_actions++;
3724 continue;
3725 }
3726
3727 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3728 if (session[s].ppp.phase >= Establish && (time_now - session[s].last_packet >= config->echo_timeout) &&
3729 (time_now - sess_local[s].last_echo >= config->echo_timeout))
3730 {
3731 uint8_t b[MAXETHER];
3732
3733 uint8_t *q = makeppp(b, sizeof(b), 0, 0, s, session[s].tunnel, PPPLCP, 1, 0, 0);
3734 if (!q) continue;
3735
3736 *q = EchoReq;
3737 *(uint8_t *)(q + 1) = (time_now % 255); // ID
3738 *(uint16_t *)(q + 2) = htons(8); // Length
3739 *(uint32_t *)(q + 4) = session[s].ppp.lcp == Opened ? htonl(session[s].magic) : 0; // Magic Number
3740
3741 LOG(4, s, session[s].tunnel, "No data in %d seconds, sending LCP ECHO\n",
3742 (int)(time_now - session[s].last_packet));
3743
3744 tunnelsend(b, (q - b) + 8, session[s].tunnel); // send it
3745 sess_local[s].last_echo = time_now;
3746 s_actions++;
3747 }
3748
3749 // Drop sessions who have reached session_timeout seconds
3750 if (session[s].session_timeout)
3751 {
3752 bundleidt bid = session[s].bundle;
3753 if (bid)
3754 {
3755 if (time_now - bundle[bid].last_check >= 1)
3756 {
3757 bundle[bid].online_time += (time_now - bundle[bid].last_check) * bundle[bid].num_of_links;
3758 bundle[bid].last_check = time_now;
3759 if (bundle[bid].online_time >= session[s].session_timeout)
3760 {
3761 int ses;
3762 for (ses = bundle[bid].num_of_links - 1; ses >= 0; ses--)
3763 {
3764 sessionshutdown(bundle[bid].members[ses], "Session timeout", CDN_ADMIN_DISC, TERM_SESSION_TIMEOUT);
3765 s_actions++;
3766 continue;
3767 }
3768 }
3769 }
3770 }
3771 else if (time_now - session[s].opened >= session[s].session_timeout)
3772 {
3773 sessionshutdown(s, "Session timeout", CDN_ADMIN_DISC, TERM_SESSION_TIMEOUT);
3774 s_actions++;
3775 continue;
3776 }
3777 }
3778
3779 // Drop sessions who have reached idle_timeout seconds
3780 if (session[s].last_data && session[s].idle_timeout && (time_now - session[s].last_data >= session[s].idle_timeout))
3781 {
3782 sessionshutdown(s, "Idle Timeout Reached", CDN_ADMIN_DISC, TERM_IDLE_TIMEOUT);
3783 STAT(session_timeout);
3784 s_actions++;
3785 continue;
3786 }
3787
3788 // Check for actions requested from the CLI
3789 if ((a = cli_session_actions[s].action))
3790 {
3791 int send = 0;
3792
3793 cli_session_actions[s].action = 0;
3794 if (a & CLI_SESS_KILL)
3795 {
3796 LOG(2, s, session[s].tunnel, "Dropping session by CLI\n");
3797 sessionshutdown(s, "Requested by administrator.", CDN_ADMIN_DISC, TERM_ADMIN_RESET);
3798 a = 0; // dead, no need to check for other actions
3799 s_actions++;
3800 }
3801
3802 if (a & CLI_SESS_NOSNOOP)
3803 {
3804 LOG(2, s, session[s].tunnel, "Unsnooping session by CLI\n");
3805 session[s].snoop_ip = 0;
3806 session[s].snoop_port = 0;
3807 s_actions++;
3808 send++;
3809 }
3810 else if (a & CLI_SESS_SNOOP)
3811 {
3812 LOG(2, s, session[s].tunnel, "Snooping session by CLI (to %s:%u)\n",
3813 fmtaddr(cli_session_actions[s].snoop_ip, 0),
3814 cli_session_actions[s].snoop_port);
3815
3816 session[s].snoop_ip = cli_session_actions[s].snoop_ip;
3817 session[s].snoop_port = cli_session_actions[s].snoop_port;
3818 s_actions++;
3819 send++;
3820 }
3821
3822 if (a & CLI_SESS_NOTHROTTLE)
3823 {
3824 LOG(2, s, session[s].tunnel, "Un-throttling session by CLI\n");
3825 throttle_session(s, 0, 0);
3826 s_actions++;
3827 send++;
3828 }
3829 else if (a & CLI_SESS_THROTTLE)
3830 {
3831 LOG(2, s, session[s].tunnel, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3832 cli_session_actions[s].throttle_in,
3833 cli_session_actions[s].throttle_out);
3834
3835 throttle_session(s, cli_session_actions[s].throttle_in, cli_session_actions[s].throttle_out);
3836 s_actions++;
3837 send++;
3838 }
3839
3840 if (a & CLI_SESS_NOFILTER)
3841 {
3842 LOG(2, s, session[s].tunnel, "Un-filtering session by CLI\n");
3843 filter_session(s, 0, 0);
3844 s_actions++;
3845 send++;
3846 }
3847 else if (a & CLI_SESS_FILTER)
3848 {
3849 LOG(2, s, session[s].tunnel, "Filtering session by CLI (in=%d, out=%d)\n",
3850 cli_session_actions[s].filter_in,
3851 cli_session_actions[s].filter_out);
3852
3853 filter_session(s, cli_session_actions[s].filter_in, cli_session_actions[s].filter_out);
3854 s_actions++;
3855 send++;
3856 }
3857
3858 if (send)
3859 cluster_send_session(s);
3860 }
3861
3862 // RADIUS interim accounting
3863 if (config->radius_accounting && config->radius_interim > 0
3864 && session[s].ip && !session[s].walled_garden
3865 && !sess_local[s].radius // RADIUS already in progress
3866 && time_now - sess_local[s].last_interim >= config->radius_interim
3867 && session[s].flags & SESSION_STARTED)
3868 {
3869 int rad = radiusnew(s);
3870 if (!rad)
3871 {
3872 LOG(1, s, session[s].tunnel, "No free RADIUS sessions for Interim message\n");
3873 STAT(radius_overflow);
3874 continue;
3875 }
3876
3877 LOG(3, s, session[s].tunnel, "Sending RADIUS Interim for %s (%u)\n",
3878 session[s].user, session[s].unique_id);
3879
3880 radiussend(rad, RADIUSINTERIM);
3881 sess_local[s].last_interim = time_now;
3882 s_actions++;
3883 }
3884 }
3885
3886 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3887 t_slice, r_slice, s_slice, t_actions, r_actions, s_actions);
3888 }
3889
3890 //
3891 // Are we in the middle of a tunnel update, or radius
3892 // requests??
3893 //
3894 static int still_busy(void)
3895 {
3896 int i;
3897 static clockt last_talked = 0;
3898 static clockt start_busy_wait = 0;
3899
3900 #ifdef BGP
3901 static time_t stopped_bgp = 0;
3902 if (bgp_configured)
3903 {
3904 if (!stopped_bgp)
3905 {
3906 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY);
3907
3908 for (i = 0; i < BGP_NUM_PEERS; i++)
3909 if (bgp_peers[i].state == Established)
3910 bgp_stop(&bgp_peers[i]);
3911
3912 stopped_bgp = time_now;
3913
3914 if (!config->cluster_iam_master)
3915 {
3916 // we don't want to become master
3917 cluster_send_ping(0);
3918
3919 return 1;
3920 }
3921 }
3922
3923 if (!config->cluster_iam_master && time_now < (stopped_bgp + QUIT_DELAY))
3924 return 1;
3925 }
3926 #endif /* BGP */
3927
3928 if (!config->cluster_iam_master)
3929 return 0;
3930
3931 if (main_quit == QUIT_SHUTDOWN)
3932 {
3933 static int dropped = 0;
3934 if (!dropped)
3935 {
3936 int i;
3937
3938 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3939 for (i = 1; i < MAXTUNNEL; i++)
3940 if (tunnel[i].ip || tunnel[i].state)
3941 tunnelshutdown(i, "L2TPNS Closing", 6, 0, 0);
3942
3943 dropped = 1;
3944 }
3945 }
3946
3947 if (start_busy_wait == 0)
3948 start_busy_wait = TIME;
3949
3950 for (i = config->cluster_highest_tunnelid ; i > 0 ; --i)
3951 {
3952 if (!tunnel[i].controlc)
3953 continue;
3954
3955 if (last_talked != TIME)
3956 {
3957 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i);
3958 last_talked = TIME;
3959 }
3960 return 1;
3961 }
3962
3963 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3964 if (abs(TIME - start_busy_wait) > BUSY_WAIT_TIME)
3965 {
3966 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3967 return 0;
3968 }
3969
3970 for (i = 1; i < MAXRADIUS; i++)
3971 {
3972 if (radius[i].state == RADIUSNULL)
3973 continue;
3974 if (radius[i].state == RADIUSWAIT)
3975 continue;
3976
3977 if (last_talked != TIME)
3978 {
3979 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i, radius[i].session);
3980 last_talked = TIME;
3981 }
3982 return 1;
3983 }
3984
3985 return 0;
3986 }
3987
3988 #ifdef HAVE_EPOLL
3989 # include <sys/epoll.h>
3990 #else
3991 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3992 # include "fake_epoll.h"
3993 #endif
3994
3995 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
3996 #define BASE_FDS (9 + MAX_UDPFD)
3997
3998 // additional polled fds
3999 #ifdef BGP
4000 # define EXTRA_FDS BGP_NUM_PEERS
4001 #else
4002 # define EXTRA_FDS 0
4003 #endif
4004
4005 // main loop - gets packets on tun or udp and processes them
4006 static void mainloop(void)
4007 {
4008 int i, j;
4009 uint8_t buf[65536];
4010 uint8_t *p = buf + 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4011 // and the forwarded pppoe session
4012 int size_bufp = sizeof(buf) - 32;
4013 clockt next_cluster_ping = 0; // send initial ping immediately
4014 struct epoll_event events[BASE_FDS + RADIUS_FDS + EXTRA_FDS];
4015 int maxevent = sizeof(events)/sizeof(*events);
4016
4017 if ((epollfd = epoll_create(maxevent)) < 0)
4018 {
4019 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno));
4020 exit(1);
4021 }
4022
4023 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",
4024 clifd, cluster_sockfd, tunfd, udpfd[0], controlfd, daefd, nlfd, udplacfd, pppoediscfd, pppoesessfd);
4025
4026 /* setup our fds to poll for input */
4027 {
4028 static struct event_data d[BASE_FDS];
4029 struct epoll_event e;
4030
4031 e.events = EPOLLIN;
4032 i = 0;
4033
4034 if (clifd >= 0)
4035 {
4036 d[i].type = FD_TYPE_CLI;
4037 e.data.ptr = &d[i++];
4038 epoll_ctl(epollfd, EPOLL_CTL_ADD, clifd, &e);
4039 }
4040
4041 d[i].type = FD_TYPE_CLUSTER;
4042 e.data.ptr = &d[i++];
4043 epoll_ctl(epollfd, EPOLL_CTL_ADD, cluster_sockfd, &e);
4044
4045 d[i].type = FD_TYPE_TUN;
4046 e.data.ptr = &d[i++];
4047 epoll_ctl(epollfd, EPOLL_CTL_ADD, tunfd, &e);
4048
4049 d[i].type = FD_TYPE_CONTROL;
4050 e.data.ptr = &d[i++];
4051 epoll_ctl(epollfd, EPOLL_CTL_ADD, controlfd, &e);
4052
4053 d[i].type = FD_TYPE_DAE;
4054 e.data.ptr = &d[i++];
4055 epoll_ctl(epollfd, EPOLL_CTL_ADD, daefd, &e);
4056
4057 d[i].type = FD_TYPE_NETLINK;
4058 e.data.ptr = &d[i++];
4059 epoll_ctl(epollfd, EPOLL_CTL_ADD, nlfd, &e);
4060
4061 d[i].type = FD_TYPE_PPPOEDISC;
4062 e.data.ptr = &d[i++];
4063 epoll_ctl(epollfd, EPOLL_CTL_ADD, pppoediscfd, &e);
4064
4065 d[i].type = FD_TYPE_PPPOESESS;
4066 e.data.ptr = &d[i++];
4067 epoll_ctl(epollfd, EPOLL_CTL_ADD, pppoesessfd, &e);
4068
4069 for (j = 0; j < config->nbudpfd; j++)
4070 {
4071 d[i].type = FD_TYPE_UDP;
4072 d[i].index = j;
4073 e.data.ptr = &d[i++];
4074 epoll_ctl(epollfd, EPOLL_CTL_ADD, udpfd[j], &e);
4075 }
4076 }
4077
4078 #ifdef BGP
4079 signal(SIGPIPE, SIG_IGN);
4080 bgp_setup(config->as_number);
4081 if (config->bind_address)
4082 bgp_add_route(config->bind_address, 0xffffffff);
4083
4084 for (i = 0; i < BGP_NUM_PEERS; i++)
4085 {
4086 if (config->neighbour[i].name[0])
4087 bgp_start(&bgp_peers[i], config->neighbour[i].name,
4088 config->neighbour[i].as, config->neighbour[i].keepalive,
4089 config->neighbour[i].hold, config->neighbour[i].update_source,
4090 0); /* 0 = routing disabled */
4091 }
4092 #endif /* BGP */
4093
4094 while (!main_quit || still_busy())
4095 {
4096 int more = 0;
4097 int n;
4098
4099
4100 if (main_reload)
4101 {
4102 main_reload = 0;
4103 read_config_file();
4104 config->reload_config++;
4105 }
4106
4107 if (config->reload_config)
4108 {
4109 config->reload_config = 0;
4110 update_config();
4111 }
4112
4113 #ifdef BGP
4114 bgp_set_poll();
4115 #endif /* BGP */
4116
4117 n = epoll_wait(epollfd, events, maxevent, 100); // timeout 100ms (1/10th sec)
4118 STAT(select_called);
4119
4120 TIME = now(NULL);
4121 if (n < 0)
4122 {
4123 if (errno == EINTR ||
4124 errno == ECHILD) // EINTR was clobbered by sigchild_handler()
4125 continue;
4126
4127 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno));
4128 break; // exit
4129 }
4130
4131 if (n)
4132 {
4133 struct sockaddr_in addr;
4134 struct in_addr local;
4135 socklen_t alen;
4136 int c, s;
4137 int udp_ready[MAX_UDPFD + 1] = INIT_TABUDPVAR;
4138 int pppoesess_ready = 0;
4139 int pppoesess_pkts = 0;
4140 int tun_ready = 0;
4141 int cluster_ready = 0;
4142 int udp_pkts[MAX_UDPFD + 1] = INIT_TABUDPVAR;
4143 int tun_pkts = 0;
4144 int cluster_pkts = 0;
4145 #ifdef BGP
4146 uint32_t bgp_events[BGP_NUM_PEERS];
4147 memset(bgp_events, 0, sizeof(bgp_events));
4148 #endif /* BGP */
4149
4150 for (c = n, i = 0; i < c; i++)
4151 {
4152 struct event_data *d = events[i].data.ptr;
4153
4154 switch (d->type)
4155 {
4156 case FD_TYPE_CLI: // CLI connections
4157 {
4158 int cli;
4159
4160 alen = sizeof(addr);
4161 if ((cli = accept(clifd, (struct sockaddr *)&addr, &alen)) >= 0)
4162 {
4163 cli_do(cli);
4164 close(cli);
4165 }
4166 else
4167 LOG(0, 0, 0, "accept error: %s\n", strerror(errno));
4168
4169 n--;
4170 break;
4171 }
4172
4173 // these are handled below, with multiple interleaved reads
4174 case FD_TYPE_CLUSTER: cluster_ready++; break;
4175 case FD_TYPE_TUN: tun_ready++; break;
4176 case FD_TYPE_UDP: udp_ready[d->index]++; break;
4177 case FD_TYPE_PPPOESESS: pppoesess_ready++; break;
4178
4179 case FD_TYPE_PPPOEDISC: // pppoe discovery
4180 s = read(pppoediscfd, p, size_bufp);
4181 if (s > 0) process_pppoe_disc(p, s);
4182 n--;
4183 break;
4184
4185 case FD_TYPE_CONTROL: // nsctl commands
4186 alen = sizeof(addr);
4187 s = recvfromto(controlfd, p, size_bufp, MSG_WAITALL, (struct sockaddr *) &addr, &alen, &local);
4188 if (s > 0) processcontrol(p, s, &addr, alen, &local);
4189 n--;
4190 break;
4191
4192 case FD_TYPE_DAE: // DAE requests
4193 alen = sizeof(addr);
4194 s = recvfromto(daefd, p, size_bufp, MSG_WAITALL, (struct sockaddr *) &addr, &alen, &local);
4195 if (s > 0) processdae(p, s, &addr, alen, &local);
4196 n--;
4197 break;
4198
4199 case FD_TYPE_RADIUS: // RADIUS response
4200 alen = sizeof(addr);
4201 s = recvfrom(radfds[d->index], p, size_bufp, MSG_WAITALL, (struct sockaddr *) &addr, &alen);
4202 if (s >= 0 && config->cluster_iam_master)
4203 {
4204 if (addr.sin_addr.s_addr == config->radiusserver[0] ||
4205 addr.sin_addr.s_addr == config->radiusserver[1])
4206 processrad(p, s, d->index);
4207 else
4208 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4209 fmtaddr(addr.sin_addr.s_addr, 0));
4210 }
4211
4212 n--;
4213 break;
4214
4215 #ifdef BGP
4216 case FD_TYPE_BGP:
4217 bgp_events[d->index] = events[i].events;
4218 n--;
4219 break;
4220 #endif /* BGP */
4221
4222 case FD_TYPE_NETLINK:
4223 {
4224 struct nlmsghdr *nh = (struct nlmsghdr *)p;
4225 s = netlink_recv(p, size_bufp);
4226 if (nh->nlmsg_type == NLMSG_ERROR)
4227 {
4228 struct nlmsgerr *errmsg = NLMSG_DATA(nh);
4229 if (errmsg->error)
4230 {
4231 if (errmsg->msg.nlmsg_seq < min_initok_nlseqnum)
4232 {
4233 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg[nh->nlmsg_seq], strerror(-errmsg->error));
4234 exit(1);
4235 }
4236 else
4237 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg->error));
4238 }
4239 // else it's a ack
4240 }
4241 else
4242 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);
4243 n--;
4244 break;
4245 }
4246
4247 default:
4248 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d->type);
4249 }
4250 }
4251
4252 #ifdef BGP
4253 bgp_process(bgp_events);
4254 #endif /* BGP */
4255
4256 for (c = 0; n && c < config->multi_read_count; c++)
4257 {
4258 for (j = 0; j < config->nbudpfd; j++)
4259 {
4260 // L2TP and L2TP REMOTE LNS
4261 if (udp_ready[j])
4262 {
4263 alen = sizeof(addr);
4264 if ((s = recvfrom(udpfd[j], p, size_bufp, 0, (void *) &addr, &alen)) > 0)
4265 {
4266 processudp(p, s, &addr, j);
4267 udp_pkts[j]++;
4268 }
4269 else
4270 {
4271 udp_ready[j] = 0;
4272 n--;
4273 }
4274 }
4275 }
4276
4277 // incoming IP
4278 if (tun_ready)
4279 {
4280 if ((s = read(tunfd, p, size_bufp)) > 0)
4281 {
4282 processtun(p, s);
4283 tun_pkts++;
4284 }
4285 else
4286 {
4287 tun_ready = 0;
4288 n--;
4289 }
4290 }
4291
4292 // pppoe session
4293 if (pppoesess_ready)
4294 {
4295 if ((s = read(pppoesessfd, p, size_bufp)) > 0)
4296 {
4297 process_pppoe_sess(p, s);
4298 pppoesess_pkts++;
4299 }
4300 else
4301 {
4302 pppoesess_ready = 0;
4303 n--;
4304 }
4305 }
4306
4307 // cluster
4308 if (cluster_ready)
4309 {
4310 alen = sizeof(addr);
4311 if ((s = recvfrom(cluster_sockfd, p, size_bufp, MSG_WAITALL, (void *) &addr, &alen)) > 0)
4312 {
4313 processcluster(p, s, addr.sin_addr.s_addr);
4314 cluster_pkts++;
4315 }
4316 else
4317 {
4318 cluster_ready = 0;
4319 n--;
4320 }
4321 }
4322 }
4323
4324 if (udp_pkts[0] > 1 || tun_pkts > 1 || cluster_pkts > 1)
4325 STAT(multi_read_used);
4326
4327 if (c >= config->multi_read_count)
4328 {
4329 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4330 config->multi_read_count, udp_pkts[0], tun_pkts, cluster_pkts, pppoesess_pkts);
4331 STAT(multi_read_exceeded);
4332 more++;
4333 }
4334 }
4335 #ifdef BGP
4336 else
4337 /* no event received, but timers could still have expired */
4338 bgp_process_peers_timers();
4339 #endif /* BGP */
4340
4341 if (time_changed)
4342 {
4343 double Mbps = 1024.0 * 1024.0 / 8 * time_changed;
4344
4345 // Log current traffic stats
4346 snprintf(config->bandwidth, sizeof(config->bandwidth),
4347 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4348 (udp_rx / Mbps), (eth_tx / Mbps), (eth_rx / Mbps), (udp_tx / Mbps),
4349 ((udp_tx + udp_rx + eth_tx + eth_rx) / Mbps),
4350 udp_rx_pkt / time_changed, eth_rx_pkt / time_changed);
4351
4352 udp_tx = udp_rx = 0;
4353 udp_rx_pkt = eth_rx_pkt = 0;
4354 eth_tx = eth_rx = 0;
4355 time_changed = 0;
4356
4357 if (config->dump_speed)
4358 printf("%s\n", config->bandwidth);
4359
4360 // Update the internal time counter
4361 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
4362
4363 {
4364 // Run timer hooks
4365 struct param_timer p = { time_now };
4366 run_plugins(PLUGIN_TIMER, &p);
4367 }
4368 }
4369
4370 // Runs on every machine (master and slaves).
4371 if (next_cluster_ping <= TIME)
4372 {
4373 // Check to see which of the cluster is still alive..
4374
4375 cluster_send_ping(basetime); // Only does anything if we're a slave
4376 cluster_check_master(); // ditto.
4377
4378 cluster_heartbeat(); // Only does anything if we're a master.
4379 cluster_check_slaves(); // ditto.
4380
4381 master_update_counts(); // If we're a slave, send our byte counters to our master.
4382
4383 if (config->cluster_iam_master && !config->cluster_iam_uptodate)
4384 next_cluster_ping = TIME + 1; // out-of-date slaves, do fast updates
4385 else
4386 next_cluster_ping = TIME + config->cluster_hb_interval;
4387 }
4388
4389 if (!config->cluster_iam_master)
4390 continue;
4391
4392 // Run token bucket filtering queue..
4393 // Only run it every 1/10th of a second.
4394 {
4395 static clockt last_run = 0;
4396 if (last_run != TIME)
4397 {
4398 last_run = TIME;
4399 tbf_run_timer();
4400 }
4401 }
4402
4403 // Handle timeouts, retries etc.
4404 {
4405 static double last_clean = 0;
4406 double this_clean;
4407 double diff;
4408
4409 TIME = now(&this_clean);
4410 diff = this_clean - last_clean;
4411
4412 // Run during idle time (after we've handled
4413 // all incoming packets) or every 1/10th sec
4414 if (!more || diff > 0.1)
4415 {
4416 regular_cleanups(diff);
4417 last_clean = this_clean;
4418 }
4419 }
4420
4421 if (*config->accounting_dir)
4422 {
4423 static clockt next_acct = 0;
4424 static clockt next_shut_acct = 0;
4425
4426 if (next_acct <= TIME)
4427 {
4428 // Dump accounting data
4429 next_acct = TIME + ACCT_TIME;
4430 next_shut_acct = TIME + ACCT_SHUT_TIME;
4431 dump_acct_info(1);
4432 }
4433 else if (next_shut_acct <= TIME)
4434 {
4435 // Dump accounting data for shutdown sessions
4436 next_shut_acct = TIME + ACCT_SHUT_TIME;
4437 if (shut_acct_n)
4438 dump_acct_info(0);
4439 }
4440 }
4441 }
4442
4443 // Are we the master and shutting down??
4444 if (config->cluster_iam_master)
4445 cluster_heartbeat(); // Flush any queued changes..
4446
4447 // Ok. Notify everyone we're shutting down. If we're
4448 // the master, this will force an election.
4449 cluster_send_ping(0);
4450
4451 //
4452 // Important!!! We MUST not process any packets past this point!
4453 LOG(1, 0, 0, "Shutdown complete\n");
4454 }
4455
4456 static void stripdomain(char *host)
4457 {
4458 char *p;
4459
4460 if ((p = strchr(host, '.')))
4461 {
4462 char *domain = 0;
4463 char _domain[1024];
4464
4465 // strip off domain
4466 FILE *resolv = fopen("/etc/resolv.conf", "r");
4467 if (resolv)
4468 {
4469 char buf[1024];
4470 char *b;
4471
4472 while (fgets(buf, sizeof(buf), resolv))
4473 {
4474 if (strncmp(buf, "domain", 6) && strncmp(buf, "search", 6))
4475 continue;
4476
4477 if (!isspace(buf[6]))
4478 continue;
4479
4480 b = buf + 7;
4481 while (isspace(*b)) b++;
4482
4483 if (*b)
4484 {
4485 char *d = b;
4486 while (*b && !isspace(*b)) b++;
4487 *b = 0;
4488 if (buf[0] == 'd') // domain is canonical
4489 {
4490 domain = d;
4491 break;
4492 }
4493
4494 // first search line
4495 if (!domain)
4496 {
4497 // hold, may be subsequent domain line
4498 strncpy(_domain, d, sizeof(_domain))[sizeof(_domain)-1] = 0;
4499 domain = _domain;
4500 }
4501 }
4502 }
4503
4504 fclose(resolv);
4505 }
4506
4507 if (domain)
4508 {
4509 int hl = strlen(host);
4510 int dl = strlen(domain);
4511 if (dl < hl && host[hl - dl - 1] == '.' && !strcmp(host + hl - dl, domain))
4512 host[hl -dl - 1] = 0;
4513 }
4514 else
4515 {
4516 *p = 0; // everything after first dot
4517 }
4518 }
4519 }
4520
4521 // Init data structures
4522 static void initdata(int optdebug, char *optconfig)
4523 {
4524 int i;
4525
4526 if (!(config = shared_malloc(sizeof(configt))))
4527 {
4528 fprintf(stderr, "Error doing malloc for configuration: %s\n", strerror(errno));
4529 exit(1);
4530 }
4531
4532 memset(config, 0, sizeof(configt));
4533 time(&config->start_time);
4534 strncpy(config->config_file, optconfig, strlen(optconfig));
4535 config->debug = optdebug;
4536 config->num_tbfs = MAXTBFS;
4537 config->rl_rate = 28; // 28kbps
4538 config->cluster_mcast_ttl = 1;
4539 config->cluster_master_min_adv = 1;
4540 config->ppp_restart_time = 3;
4541 config->ppp_max_configure = 10;
4542 config->ppp_max_failure = 5;
4543 config->kill_timedout_sessions = 1;
4544 strcpy(config->random_device, RANDOMDEVICE);
4545 // Set default value echo_timeout and idle_echo_timeout
4546 config->echo_timeout = ECHO_TIMEOUT;
4547 config->idle_echo_timeout = IDLE_ECHO_TIMEOUT;
4548
4549 log_stream = stderr;
4550
4551 #ifdef RINGBUFFER
4552 if (!(ringbuffer = shared_malloc(sizeof(struct Tringbuffer))))
4553 {
4554 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno));
4555 exit(1);
4556 }
4557 memset(ringbuffer, 0, sizeof(struct Tringbuffer));
4558 #endif
4559
4560 if (!(_statistics = shared_malloc(sizeof(struct Tstats))))
4561 {
4562 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno));
4563 exit(1);
4564 }
4565 if (!(tunnel = shared_malloc(sizeof(tunnelt) * MAXTUNNEL)))
4566 {
4567 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno));
4568 exit(1);
4569 }
4570 if (!(bundle = shared_malloc(sizeof(bundlet) * MAXBUNDLE)))
4571 {
4572 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno));
4573 exit(1);
4574 }
4575 if (!(frag = shared_malloc(sizeof(fragmentationt) * MAXBUNDLE)))
4576 {
4577 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno));
4578 exit(1);
4579 }
4580 if (!(session = shared_malloc(sizeof(sessiont) * MAXSESSION)))
4581 {
4582 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno));
4583 exit(1);
4584 }
4585
4586 if (!(sess_local = shared_malloc(sizeof(sessionlocalt) * MAXSESSION)))
4587 {
4588 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno));
4589 exit(1);
4590 }
4591
4592 if (!(radius = shared_malloc(sizeof(radiust) * MAXRADIUS)))
4593 {
4594 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno));
4595 exit(1);
4596 }
4597
4598 if (!(ip_address_pool = shared_malloc(sizeof(ippoolt) * MAXIPPOOL)))
4599 {
4600 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno));
4601 exit(1);
4602 }
4603
4604 if (!(ip_filters = shared_malloc(sizeof(ip_filtert) * MAXFILTER)))
4605 {
4606 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno));
4607 exit(1);
4608 }
4609 memset(ip_filters, 0, sizeof(ip_filtert) * MAXFILTER);
4610
4611 if (!(cli_session_actions = shared_malloc(sizeof(struct cli_session_actions) * MAXSESSION)))
4612 {
4613 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno));
4614 exit(1);
4615 }
4616 memset(cli_session_actions, 0, sizeof(struct cli_session_actions) * MAXSESSION);
4617
4618 if (!(cli_tunnel_actions = shared_malloc(sizeof(struct cli_tunnel_actions) * MAXSESSION)))
4619 {
4620 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno));
4621 exit(1);
4622 }
4623 memset(cli_tunnel_actions, 0, sizeof(struct cli_tunnel_actions) * MAXSESSION);
4624
4625 memset(tunnel, 0, sizeof(tunnelt) * MAXTUNNEL);
4626 memset(bundle, 0, sizeof(bundlet) * MAXBUNDLE);
4627 memset(session, 0, sizeof(sessiont) * MAXSESSION);
4628 memset(radius, 0, sizeof(radiust) * MAXRADIUS);
4629 memset(ip_address_pool, 0, sizeof(ippoolt) * MAXIPPOOL);
4630
4631 // Put all the sessions on the free list marked as undefined.
4632 for (i = 1; i < MAXSESSION; i++)
4633 {
4634 session[i].next = i + 1;
4635 session[i].tunnel = T_UNDEF; // mark it as not filled in.
4636 }
4637 session[MAXSESSION - 1].next = 0;
4638 sessionfree = 1;
4639
4640 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4641 for (i = 1; i < MAXTUNNEL; i++)
4642 tunnel[i].state = TUNNELUNDEF; // mark it as not filled in.
4643
4644 for (i = 1; i < MAXBUNDLE; i++) {
4645 bundle[i].state = BUNDLEUNDEF;
4646 }
4647
4648 if (!*hostname)
4649 {
4650 // Grab my hostname unless it's been specified
4651 gethostname(hostname, sizeof(hostname));
4652 stripdomain(hostname);
4653 }
4654
4655 _statistics->start_time = _statistics->last_reset = time(NULL);
4656
4657 #ifdef BGP
4658 if (!(bgp_peers = shared_malloc(sizeof(struct bgp_peer) * BGP_NUM_PEERS)))
4659 {
4660 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno));
4661 exit(1);
4662 }
4663 #endif /* BGP */
4664
4665 lac_initremotelnsdata();
4666
4667 grp_initdata();
4668 }
4669
4670 static int assign_ip_address(sessionidt s)
4671 {
4672 uint32_t i;
4673 int best = -1;
4674 time_t best_time = time_now;
4675 char *u = session[s].user;
4676 char reuse = 0;
4677
4678
4679 CSTAT(assign_ip_address);
4680
4681 for (i = 1; i < ip_pool_size; i++)
4682 {
4683 if (!ip_address_pool[i].address || ip_address_pool[i].assigned)
4684 continue;
4685
4686 if (!session[s].walled_garden && ip_address_pool[i].user[0] && !strcmp(u, ip_address_pool[i].user))
4687 {
4688 best = i;
4689 reuse = 1;
4690 break;
4691 }
4692
4693 if (ip_address_pool[i].last < best_time)
4694 {
4695 best = i;
4696 if (!(best_time = ip_address_pool[i].last))
4697 break; // never used, grab this one
4698 }
4699 }
4700
4701 if (best < 0)
4702 {
4703 LOG(0, s, session[s].tunnel, "assign_ip_address(): out of addresses\n");
4704 return 0;
4705 }
4706
4707 session[s].ip = ip_address_pool[best].address;
4708 session[s].ip_pool_index = best;
4709 ip_address_pool[best].assigned = 1;
4710 ip_address_pool[best].last = time_now;
4711 ip_address_pool[best].session = s;
4712 if (session[s].walled_garden)
4713 /* Don't track addresses of users in walled garden (note: this
4714 means that their address isn't "sticky" even if they get
4715 un-gardened). */
4716 ip_address_pool[best].user[0] = 0;
4717 else
4718 strncpy(ip_address_pool[best].user, u, sizeof(ip_address_pool[best].user) - 1);
4719
4720 STAT(ip_allocated);
4721 LOG(4, s, session[s].tunnel, "assign_ip_address(): %s ip address %d from pool\n",
4722 reuse ? "Reusing" : "Allocating", best);
4723
4724 return 1;
4725 }
4726
4727 static void free_ip_address(sessionidt s)
4728 {
4729 int i = session[s].ip_pool_index;
4730
4731
4732 CSTAT(free_ip_address);
4733
4734 if (!session[s].ip)
4735 return; // what the?
4736
4737 if (i < 0) // Is this actually part of the ip pool?
4738 i = 0;
4739
4740 STAT(ip_freed);
4741 cache_ipmap(session[s].ip, -i); // Change the mapping to point back to the ip pool index.
4742 session[s].ip = 0;
4743 ip_address_pool[i].assigned = 0;
4744 ip_address_pool[i].session = 0;
4745 ip_address_pool[i].last = time_now;
4746 }
4747
4748 //
4749 // Fsck the address pool against the session table.
4750 // Normally only called when we become a master.
4751 //
4752 // This isn't perfect: We aren't keep tracking of which
4753 // users used to have an IP address.
4754 //
4755 void rebuild_address_pool(void)
4756 {
4757 int i;
4758
4759 //
4760 // Zero the IP pool allocation, and build
4761 // a map from IP address to pool index.
4762 for (i = 1; i < MAXIPPOOL; ++i)
4763 {
4764 ip_address_pool[i].assigned = 0;
4765 ip_address_pool[i].session = 0;
4766 if (!ip_address_pool[i].address)
4767 continue;
4768
4769 cache_ipmap(ip_address_pool[i].address, -i); // Map pool IP to pool index.
4770 }
4771
4772 for (i = 0; i < MAXSESSION; ++i)
4773 {
4774 int ipid;
4775 if (!(session[i].opened && session[i].ip))
4776 continue;
4777
4778 ipid = - lookup_ipmap(htonl(session[i].ip));
4779
4780 if (session[i].ip_pool_index < 0)
4781 {
4782 // Not allocated out of the pool.
4783 if (ipid < 1) // Not found in the pool either? good.
4784 continue;
4785
4786 LOG(0, i, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4787 i, fmtaddr(session[i].ip, 0), ipid);
4788
4789 // Fall through and process it as part of the pool.
4790 }
4791
4792
4793 if (ipid > MAXIPPOOL || ipid < 0)
4794 {
4795 LOG(0, i, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i, ipid);
4796 ipid = -1;
4797 session[i].ip_pool_index = ipid;
4798 continue;
4799 }
4800
4801 ip_address_pool[ipid].assigned = 1;
4802 ip_address_pool[ipid].session = i;
4803 ip_address_pool[ipid].last = time_now;
4804 strncpy(ip_address_pool[ipid].user, session[i].user, sizeof(ip_address_pool[ipid].user) - 1);
4805 session[i].ip_pool_index = ipid;
4806 cache_ipmap(session[i].ip, i); // Fix the ip map.
4807 }
4808 }
4809
4810 //
4811 // Fix the address pool to match a changed session.
4812 // (usually when the master sends us an update).
4813 static void fix_address_pool(int sid)
4814 {
4815 int ipid;
4816
4817 ipid = session[sid].ip_pool_index;
4818
4819 if (ipid > ip_pool_size)
4820 return; // Ignore it. rebuild_address_pool will fix it up.
4821
4822 if (ip_address_pool[ipid].address != session[sid].ip)
4823 return; // Just ignore it. rebuild_address_pool will take care of it.
4824
4825 ip_address_pool[ipid].assigned = 1;
4826 ip_address_pool[ipid].session = sid;
4827 ip_address_pool[ipid].last = time_now;
4828 strncpy(ip_address_pool[ipid].user, session[sid].user, sizeof(ip_address_pool[ipid].user) - 1);
4829 }
4830
4831 //
4832 // Add a block of addresses to the IP pool to hand out.
4833 //
4834 static void add_to_ip_pool(in_addr_t addr, int prefixlen)
4835 {
4836 int i;
4837 if (prefixlen == 0)
4838 prefixlen = 32; // Host route only.
4839
4840 addr &= 0xffffffff << (32 - prefixlen);
4841
4842 if (ip_pool_size >= MAXIPPOOL) // Pool is full!
4843 return ;
4844
4845 for (i = addr ; i < addr+(1<<(32-prefixlen)); ++i)
4846 {
4847 if ((i & 0xff) == 0 || (i&0xff) == 255)
4848 continue; // Skip 0 and broadcast addresses.
4849
4850 ip_address_pool[ip_pool_size].address = i;
4851 ip_address_pool[ip_pool_size].assigned = 0;
4852 ++ip_pool_size;
4853 if (ip_pool_size >= MAXIPPOOL)
4854 {
4855 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr), 0));
4856 return;
4857 }
4858 }
4859 }
4860
4861 // Initialize the IP address pool
4862 static void initippool()
4863 {
4864 FILE *f;
4865 char *p;
4866 char buf[4096];
4867 memset(ip_address_pool, 0, sizeof(ip_address_pool));
4868
4869 if (!(f = fopen(IPPOOLFILE, "r")))
4870 {
4871 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE ": %s\n", strerror(errno));
4872 exit(1);
4873 }
4874
4875 while (ip_pool_size < MAXIPPOOL && fgets(buf, 4096, f))
4876 {
4877 char *pool = buf;
4878 buf[4095] = 0; // Force it to be zero terminated/
4879
4880 if (*buf == '#' || *buf == '\n')
4881 continue; // Skip comments / blank lines
4882 if ((p = (char *)strrchr(buf, '\n'))) *p = 0;
4883 if ((p = (char *)strchr(buf, ':')))
4884 {
4885 in_addr_t src;
4886 *p = '\0';
4887 src = inet_addr(buf);
4888 if (src == INADDR_NONE)
4889 {
4890 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf);
4891 exit(1);
4892 }
4893 // This entry is for a specific IP only
4894 if (src != config->bind_address)
4895 continue;
4896 *p = ':';
4897 pool = p+1;
4898 }
4899 if ((p = (char *)strchr(pool, '/')))
4900 {
4901 // It's a range
4902 int numbits = 0;
4903 in_addr_t start = 0;
4904
4905 LOG(2, 0, 0, "Adding IP address range %s\n", buf);
4906 *p++ = 0;
4907 if (!*p || !(numbits = atoi(p)))
4908 {
4909 LOG(0, 0, 0, "Invalid pool range %s\n", buf);
4910 continue;
4911 }
4912 start = ntohl(inet_addr(pool));
4913
4914 // Add a static route for this pool
4915 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4916 fmtaddr(htonl(start), 0), numbits);
4917
4918 routeset(0, start, numbits, 0, 1);
4919
4920 add_to_ip_pool(start, numbits);
4921 }
4922 else
4923 {
4924 // It's a single ip address
4925 add_to_ip_pool(ntohl(inet_addr(pool)), 0);
4926 }
4927 }
4928 fclose(f);
4929 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size - 1);
4930 }
4931
4932 void snoop_send_packet(uint8_t *packet, uint16_t size, in_addr_t destination, uint16_t port)
4933 {
4934 struct sockaddr_in snoop_addr = {0};
4935 if (!destination || !port || snoopfd <= 0 || size <= 0 || !packet)
4936 return;
4937
4938 snoop_addr.sin_family = AF_INET;
4939 snoop_addr.sin_addr.s_addr = destination;
4940 snoop_addr.sin_port = ntohs(port);
4941
4942 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size,
4943 fmtaddr(snoop_addr.sin_addr.s_addr, 0),
4944 htons(snoop_addr.sin_port));
4945
4946 if (sendto(snoopfd, packet, size, MSG_DONTWAIT | MSG_NOSIGNAL, (void *) &snoop_addr, sizeof(snoop_addr)) < 0)
4947 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno));
4948
4949 STAT(packets_snooped);
4950 }
4951
4952 static int dump_session(FILE **f, sessiont *s)
4953 {
4954 if (!s->opened || (!s->ip && !s->forwardtosession) || !(s->cin_delta || s->cout_delta) || !*s->user || s->walled_garden)
4955 return 1;
4956
4957 if (!*f)
4958 {
4959 char filename[1024];
4960 char timestr[64];
4961 time_t now = time(NULL);
4962
4963 strftime(timestr, sizeof(timestr), "%Y%m%d%H%M%S", localtime(&now));
4964 snprintf(filename, sizeof(filename), "%s/%s", config->accounting_dir, timestr);
4965
4966 if (!(*f = fopen(filename, "w")))
4967 {
4968 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename, strerror(errno));
4969 return 0;
4970 }
4971
4972 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename);
4973 fprintf(*f, "# dslwatch.pl dump file V1.01\n"
4974 "# host: %s\n"
4975 "# endpoint: %s\n"
4976 "# time: %ld\n"
4977 "# uptime: %ld\n"
4978 "# format: username ip qos uptxoctets downrxoctets\n",
4979 hostname,
4980 fmtaddr(config->iftun_n_address[tunnel[s->tunnel].indexudp] ? config->iftun_n_address[tunnel[s->tunnel].indexudp] : my_address, 0),
4981 now,
4982 now - basetime);
4983 }
4984
4985 LOG(4, 0, 0, "Dumping accounting information for %s\n", s->user);
4986 fprintf(*f, "%s %s %d %u %u\n",
4987 s->user, // username
4988 fmtaddr(htonl(s->ip), 0), // ip
4989 (s->throttle_in || s->throttle_out) ? 2 : 1, // qos
4990 (uint32_t) s->cin_delta, // uptxoctets
4991 (uint32_t) s->cout_delta); // downrxoctets
4992
4993 s->cin_delta = s->cout_delta = 0;
4994
4995 return 1;
4996 }
4997
4998 static void dump_acct_info(int all)
4999 {
5000 int i;
5001 FILE *f = NULL;
5002
5003
5004 CSTAT(dump_acct_info);
5005
5006 if (shut_acct_n)
5007 {
5008 for (i = 0; i < shut_acct_n; i++)
5009 dump_session(&f, &shut_acct[i]);
5010
5011 shut_acct_n = 0;
5012 }
5013
5014 if (all)
5015 for (i = 1; i <= config->cluster_highest_sessionid; i++)
5016 dump_session(&f, &session[i]);
5017
5018 if (f)
5019 fclose(f);
5020 }
5021
5022 // Main program
5023 int main(int argc, char *argv[])
5024 {
5025 int i;
5026 int optdebug = 0;
5027 char *optconfig = CONFIGFILE;
5028
5029 time(&basetime); // start clock
5030
5031 // scan args
5032 while ((i = getopt(argc, argv, "dvc:h:")) >= 0)
5033 {
5034 switch (i)
5035 {
5036 case 'd':
5037 if (fork()) exit(0);
5038 setsid();
5039 freopen("/dev/null", "r", stdin);
5040 freopen("/dev/null", "w", stdout);
5041 freopen("/dev/null", "w", stderr);
5042 break;
5043 case 'v':
5044 optdebug++;
5045 break;
5046 case 'c':
5047 optconfig = optarg;
5048 break;
5049 case 'h':
5050 snprintf(hostname, sizeof(hostname), "%s", optarg);
5051 break;
5052 default:
5053 printf("Args are:\n"
5054 "\t-d\t\tDetach from terminal\n"
5055 "\t-c <file>\tConfig file\n"
5056 "\t-h <hostname>\tForce hostname\n"
5057 "\t-v\t\tDebug\n");
5058
5059 return (0);
5060 break;
5061 }
5062 }
5063
5064 // Start the timer routine off
5065 time(&time_now);
5066 strftime(time_now_string, sizeof(time_now_string), "%Y-%m-%d %H:%M:%S", localtime(&time_now));
5067
5068 initplugins();
5069 initdata(optdebug, optconfig);
5070
5071 init_cli();
5072 read_config_file();
5073 /* set hostname /after/ having read the config file */
5074 if (*config->hostname)
5075 strcpy(hostname, config->hostname);
5076 cli_init_complete(hostname);
5077 update_config();
5078 init_tbf(config->num_tbfs);
5079
5080 LOG(0, 0, 0, "L2TPNS version " VERSION "\n");
5081 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5082 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5083 {
5084 struct rlimit rlim;
5085 rlim.rlim_cur = RLIM_INFINITY;
5086 rlim.rlim_max = RLIM_INFINITY;
5087 // Remove the maximum core size
5088 if (setrlimit(RLIMIT_CORE, &rlim) < 0)
5089 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno));
5090
5091 // Make core dumps go to /tmp
5092 chdir("/tmp");
5093 }
5094
5095 if (config->scheduler_fifo)
5096 {
5097 int ret;
5098 struct sched_param params = {0};
5099 params.sched_priority = 1;
5100
5101 if (get_nprocs() < 2)
5102 {
5103 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5104 config->scheduler_fifo = 0;
5105 }
5106 else
5107 {
5108 if ((ret = sched_setscheduler(0, SCHED_FIFO, &params)) == 0)
5109 {
5110 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5111 }
5112 else
5113 {
5114 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno));
5115 config->scheduler_fifo = 0;
5116 }
5117 }
5118 }
5119
5120 initnetlink();
5121
5122 /* Set up the cluster communications port. */
5123 if (cluster_init() < 0)
5124 exit(1);
5125
5126 inittun();
5127 LOG(1, 0, 0, "Set up on interface %s\n", config->tundevicename);
5128
5129 if (*config->pppoe_if_to_bind)
5130 {
5131 init_pppoe();
5132 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config->pppoe_if_to_bind);
5133 }
5134
5135 if (!config->nbmultiaddress)
5136 {
5137 config->bind_n_address[0] = config->bind_address;
5138 config->nbmultiaddress++;
5139 }
5140 config->nbudpfd = config->nbmultiaddress;
5141 for (i = 0; i < config->nbudpfd; i++)
5142 initudp(&udpfd[i], config->bind_n_address[i]);
5143 initlacudp();
5144 config->indexlacudpfd = config->nbudpfd;
5145 udpfd[config->indexlacudpfd] = udplacfd;
5146 config->nbudpfd++;
5147
5148 initcontrol();
5149 initdae();
5150
5151 // Intercept
5152 snoopfd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
5153
5154 initrad();
5155 initippool();
5156
5157 // seed prng
5158 {
5159 unsigned seed = time_now ^ getpid();
5160 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed);
5161 srand(seed);
5162 }
5163
5164 signal(SIGHUP, sighup_handler);
5165 signal(SIGCHLD, sigchild_handler);
5166 signal(SIGTERM, shutdown_handler);
5167 signal(SIGINT, shutdown_handler);
5168 signal(SIGQUIT, shutdown_handler);
5169
5170 // Prevent us from getting paged out
5171 if (config->lock_pages)
5172 {
5173 if (!mlockall(MCL_CURRENT))
5174 LOG(1, 0, 0, "Locking pages into memory\n");
5175 else
5176 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno));
5177 }
5178
5179 //LOG(3, 0, 0, "Debug sizeof struct: sessiont %lu, tunnelt %lu, bundlet %lu, groupsesst %lu\n",
5180 // sizeof(sessiont), sizeof(tunnelt), sizeof(bundlet), sizeof(groupsesst));
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 cluster_send_groupe(g);
5683 }
5684 }
5685
5686 sess_local[s].lcp_authtype = 0; // RADIUS authentication complete
5687 lcp_open(s, t); // transition to Network phase and send initial IPCP
5688
5689 // Run the plugin's against this new session.
5690 {
5691 struct param_new_session data = { &tunnel[t], &session[s] };
5692 run_plugins(PLUGIN_NEW_SESSION, &data);
5693 }
5694
5695 // Allocate TBFs if throttled
5696 if (session[s].throttle_in || session[s].throttle_out)
5697 throttle_session(s, session[s].throttle_in, session[s].throttle_out);
5698
5699 session[s].last_packet = session[s].last_data = time_now;
5700
5701 LOG(2, s, t, "Login by %s at %s from %s (%s)\n", session[s].user,
5702 fmtaddr(htonl(session[s].ip), 0),
5703 fmtaddr(htonl(tunnel[t].ip), 1), tunnel[t].hostname);
5704
5705 cluster_send_session(s); // Mark it as dirty, and needing to the flooded to the cluster.
5706
5707 return 1; // RADIUS OK and IP allocated, done...
5708 }
5709
5710 //
5711 // This session just got dropped on us by the master or something.
5712 // Make sure our tables up up to date...
5713 //
5714 int load_session(sessionidt s, sessiont *new)
5715 {
5716 int i;
5717 int newip = 0;
5718
5719 // Sanity checks.
5720 if (new->ip_pool_index >= MAXIPPOOL ||
5721 new->tunnel >= MAXTUNNEL)
5722 {
5723 LOG(0, s, 0, "Strange session update received!\n");
5724 // FIXME! What to do here?
5725 return 0;
5726 }
5727
5728 //
5729 // Ok. All sanity checks passed. Now we're committed to
5730 // loading the new session.
5731 //
5732
5733 session[s].tunnel = new->tunnel; // For logging in cache_ipmap
5734
5735 // See if routes/ip cache need updating
5736 if (new->ip != session[s].ip)
5737 newip++;
5738
5739 for (i = 0; !newip && i < MAXROUTE && (session[s].route[i].ip || new->route[i].ip); i++)
5740 if (new->route[i].ip != session[s].route[i].ip ||
5741 new->route[i].prefixlen != session[s].route[i].prefixlen)
5742 newip++;
5743
5744 // needs update
5745 if (newip)
5746 {
5747 int routed = 0;
5748
5749 // remove old routes...
5750 for (i = 0; i < MAXROUTE && session[s].route[i].ip; i++)
5751 {
5752 if ((session[s].ip >> (32-session[s].route[i].prefixlen)) ==
5753 (session[s].route[i].ip >> (32-session[s].route[i].prefixlen)))
5754 routed++;
5755
5756 routeset(s, session[s].route[i].ip, session[s].route[i].prefixlen, 0, 0);
5757 }
5758
5759 // ...ip
5760 if (session[s].ip)
5761 {
5762 if (session[s].ip_pool_index == -1) // static IP
5763 {
5764 if (!routed) routeset(s, session[s].ip, 0, 0, 0);
5765 }
5766 else // It's part of the IP pool, remove it manually.
5767 uncache_ipmap(session[s].ip);
5768 }
5769
5770 routed = 0;
5771
5772 // add new routes...
5773 for (i = 0; i < MAXROUTE && new->route[i].ip; i++)
5774 {
5775 if ((new->ip >> (32-new->route[i].prefixlen)) ==
5776 (new->route[i].ip >> (32-new->route[i].prefixlen)))
5777 routed++;
5778
5779 routeset(s, new->route[i].ip, new->route[i].prefixlen, 0, 1);
5780 }
5781
5782 // ...ip
5783 if (new->ip)
5784 {
5785 // If there's a new one, add it.
5786 if (new->ip_pool_index == -1)
5787 {
5788 if (!routed) routeset(s, new->ip, 0, 0, 1);
5789 }
5790 else
5791 cache_ipmap(new->ip, s);
5792 }
5793 }
5794
5795 // check v6 routing
5796 if (new->ipv6prefixlen && new->ppp.ipv6cp == Opened && session[s].ppp.ipv6cp != Opened)
5797 route6set(s, new->ipv6route, new->ipv6prefixlen, 1);
5798
5799 // check filters
5800 if (new->filter_in && (new->filter_in > MAXFILTER || !ip_filters[new->filter_in - 1].name[0]))
5801 {
5802 LOG(2, s, session[s].tunnel, "Dropping invalid input filter %u\n", (int) new->filter_in);
5803 new->filter_in = 0;
5804 }
5805
5806 if (new->filter_out && (new->filter_out > MAXFILTER || !ip_filters[new->filter_out - 1].name[0]))
5807 {
5808 LOG(2, s, session[s].tunnel, "Dropping invalid output filter %u\n", (int) new->filter_out);
5809 new->filter_out = 0;
5810 }
5811
5812 if (new->filter_in != session[s].filter_in)
5813 {
5814 if (session[s].filter_in) ip_filters[session[s].filter_in - 1].used--;
5815 if (new->filter_in) ip_filters[new->filter_in - 1].used++;
5816 }
5817
5818 if (new->filter_out != session[s].filter_out)
5819 {
5820 if (session[s].filter_out) ip_filters[session[s].filter_out - 1].used--;
5821 if (new->filter_out) ip_filters[new->filter_out - 1].used++;
5822 }
5823
5824 if (new->tunnel && s > config->cluster_highest_sessionid) // Maintain this in the slave. It's used
5825 // for walking the sessions to forward byte counts to the master.
5826 config->cluster_highest_sessionid = s;
5827
5828 memcpy(&session[s], new, sizeof(session[s])); // Copy over..
5829
5830 // Do fixups into address pool.
5831 if (new->ip_pool_index != -1)
5832 fix_address_pool(s);
5833
5834 return 1;
5835 }
5836
5837 static void initplugins()
5838 {
5839 int i;
5840
5841 loaded_plugins = ll_init();
5842 // Initialize the plugins to nothing
5843 for (i = 0; i < MAX_PLUGIN_TYPES; i++)
5844 plugins[i] = ll_init();
5845 }
5846
5847 static void *open_plugin(char *plugin_name, int load)
5848 {
5849 char path[256] = "";
5850
5851 snprintf(path, 256, PLUGINDIR "/%s.so", plugin_name);
5852 LOG(2, 0, 0, "%soading plugin from %s\n", load ? "L" : "Un-l", path);
5853 return dlopen(path, RTLD_NOW);
5854 }
5855
5856 // plugin callback to get a config value
5857 static void *getconfig(char *key, enum config_typet type)
5858 {
5859 int i;
5860
5861 for (i = 0; config_values[i].key; i++)
5862 {
5863 if (!strcmp(config_values[i].key, key))
5864 {
5865 if (config_values[i].type == type)
5866 return ((void *) config) + config_values[i].offset;
5867
5868 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5869 key, type, config_values[i].type);
5870
5871 return 0;
5872 }
5873 }
5874
5875 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key);
5876 return 0;
5877 }
5878
5879 static int add_plugin(char *plugin_name)
5880 {
5881 static struct pluginfuncs funcs = {
5882 _log,
5883 _log_hex,
5884 fmtaddr,
5885 sessionbyuser,
5886 sessiontbysessionidt,
5887 sessionidtbysessiont,
5888 radiusnew,
5889 radiussend,
5890 getconfig,
5891 sessionshutdown,
5892 sessionkill,
5893 throttle_session,
5894 cluster_send_session,
5895 };
5896
5897 void *p = open_plugin(plugin_name, 1);
5898 int (*initfunc)(struct pluginfuncs *);
5899 int i;
5900
5901 if (!p)
5902 {
5903 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5904 return -1;
5905 }
5906
5907 if (ll_contains(loaded_plugins, p))
5908 {
5909 dlclose(p);
5910 return 0; // already loaded
5911 }
5912
5913 {
5914 int *v = dlsym(p, "plugin_api_version");
5915 if (!v || *v != PLUGIN_API_VERSION)
5916 {
5917 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5918 dlclose(p);
5919 return -1;
5920 }
5921 }
5922
5923 if ((initfunc = dlsym(p, "plugin_init")))
5924 {
5925 if (!initfunc(&funcs))
5926 {
5927 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5928 dlclose(p);
5929 return -1;
5930 }
5931 }
5932
5933 ll_push(loaded_plugins, p);
5934
5935 for (i = 0; i < max_plugin_functions; i++)
5936 {
5937 void *x;
5938 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
5939 {
5940 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions[i]);
5941 ll_push(plugins[i], x);
5942 }
5943 }
5944
5945 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name);
5946 return 1;
5947 }
5948
5949 static void run_plugin_done(void *plugin)
5950 {
5951 int (*donefunc)(void) = dlsym(plugin, "plugin_done");
5952
5953 if (donefunc)
5954 donefunc();
5955 }
5956
5957 static int remove_plugin(char *plugin_name)
5958 {
5959 void *p = open_plugin(plugin_name, 0);
5960 int loaded = 0;
5961
5962 if (!p)
5963 return -1;
5964
5965 if (ll_contains(loaded_plugins, p))
5966 {
5967 int i;
5968 for (i = 0; i < max_plugin_functions; i++)
5969 {
5970 void *x;
5971 if (plugin_functions[i] && (x = dlsym(p, plugin_functions[i])))
5972 ll_delete(plugins[i], x);
5973 }
5974
5975 ll_delete(loaded_plugins, p);
5976 run_plugin_done(p);
5977 loaded = 1;
5978 }
5979
5980 dlclose(p);
5981 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name);
5982 return loaded;
5983 }
5984
5985 int run_plugins(int plugin_type, void *data)
5986 {
5987 int (*func)(void *data);
5988
5989 if (!plugins[plugin_type] || plugin_type > max_plugin_functions)
5990 return PLUGIN_RET_ERROR;
5991
5992 ll_reset(plugins[plugin_type]);
5993 while ((func = ll_next(plugins[plugin_type])))
5994 {
5995 int r = func(data);
5996
5997 if (r != PLUGIN_RET_OK)
5998 return r; // stop here
5999 }
6000
6001 return PLUGIN_RET_OK;
6002 }
6003
6004 static void plugins_done()
6005 {
6006 void *p;
6007
6008 ll_reset(loaded_plugins);
6009 while ((p = ll_next(loaded_plugins)))
6010 run_plugin_done(p);
6011 }
6012
6013 static void processcontrol(uint8_t *buf, int len, struct sockaddr_in *addr, int alen, struct in_addr *local)
6014 {
6015 struct nsctl request;
6016 struct nsctl response;
6017 int type = unpack_control(&request, buf, len);
6018 int r;
6019 void *p;
6020
6021 if (log_stream && config->debug >= 4)
6022 {
6023 if (type < 0)
6024 {
6025 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6026 fmtaddr(addr->sin_addr.s_addr, 0), type);
6027 }
6028 else
6029 {
6030 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
6031 dump_control(&request, log_stream);
6032 }
6033 }
6034
6035 switch (type)
6036 {
6037 case NSCTL_REQ_LOAD:
6038 if (request.argc != 1)
6039 {
6040 response.type = NSCTL_RES_ERR;
6041 response.argc = 1;
6042 response.argv[0] = "name of plugin required";
6043 }
6044 else if ((r = add_plugin(request.argv[0])) < 1)
6045 {
6046 response.type = NSCTL_RES_ERR;
6047 response.argc = 1;
6048 response.argv[0] = !r
6049 ? "plugin already loaded"
6050 : "error loading plugin";
6051 }
6052 else
6053 {
6054 response.type = NSCTL_RES_OK;
6055 response.argc = 0;
6056 }
6057
6058 break;
6059
6060 case NSCTL_REQ_UNLOAD:
6061 if (request.argc != 1)
6062 {
6063 response.type = NSCTL_RES_ERR;
6064 response.argc = 1;
6065 response.argv[0] = "name of plugin required";
6066 }
6067 else if ((r = remove_plugin(request.argv[0])) < 1)
6068 {
6069 response.type = NSCTL_RES_ERR;
6070 response.argc = 1;
6071 response.argv[0] = !r
6072 ? "plugin not loaded"
6073 : "plugin not found";
6074 }
6075 else
6076 {
6077 response.type = NSCTL_RES_OK;
6078 response.argc = 0;
6079 }
6080
6081 break;
6082
6083 case NSCTL_REQ_HELP:
6084 response.type = NSCTL_RES_OK;
6085 response.argc = 0;
6086
6087 ll_reset(loaded_plugins);
6088 while ((p = ll_next(loaded_plugins)))
6089 {
6090 char **help = dlsym(p, "plugin_control_help");
6091 while (response.argc < 0xff && help && *help)
6092 response.argv[response.argc++] = *help++;
6093 }
6094
6095 break;
6096
6097 case NSCTL_REQ_CONTROL:
6098 {
6099 struct param_control param = {
6100 config->cluster_iam_master,
6101 request.argc,
6102 request.argv,
6103 0,
6104 NULL,
6105 };
6106
6107 int r = run_plugins(PLUGIN_CONTROL, &param);
6108
6109 if (r == PLUGIN_RET_ERROR)
6110 {
6111 response.type = NSCTL_RES_ERR;
6112 response.argc = 1;
6113 response.argv[0] = param.additional
6114 ? param.additional
6115 : "error returned by plugin";
6116 }
6117 else if (r == PLUGIN_RET_NOTMASTER)
6118 {
6119 static char msg[] = "must be run on master: 000.000.000.000";
6120
6121 response.type = NSCTL_RES_ERR;
6122 response.argc = 1;
6123 if (config->cluster_master_address)
6124 {
6125 strcpy(msg + 23, fmtaddr(config->cluster_master_address, 0));
6126 response.argv[0] = msg;
6127 }
6128 else
6129 {
6130 response.argv[0] = "must be run on master: none elected";
6131 }
6132 }
6133 else if (!(param.response & NSCTL_RESPONSE))
6134 {
6135 response.type = NSCTL_RES_ERR;
6136 response.argc = 1;
6137 response.argv[0] = param.response
6138 ? "unrecognised response value from plugin"
6139 : "unhandled action";
6140 }
6141 else
6142 {
6143 response.type = param.response;
6144 response.argc = 0;
6145 if (param.additional)
6146 {
6147 response.argc = 1;
6148 response.argv[0] = param.additional;
6149 }
6150 }
6151 }
6152
6153 break;
6154
6155 default:
6156 response.type = NSCTL_RES_ERR;
6157 response.argc = 1;
6158 response.argv[0] = "error unpacking control packet";
6159 }
6160
6161 buf = calloc(NSCTL_MAX_PKT_SZ, 1);
6162 if (!buf)
6163 {
6164 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6165 return;
6166 }
6167
6168 r = pack_control(buf, NSCTL_MAX_PKT_SZ, response.type, response.argc, response.argv);
6169 if (r > 0)
6170 {
6171 sendtofrom(controlfd, buf, r, 0, (const struct sockaddr *) addr, alen, local);
6172 if (log_stream && config->debug >= 4)
6173 {
6174 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr->sin_addr.s_addr, 0));
6175 dump_control(&response, log_stream);
6176 }
6177 }
6178 else
6179 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6180 fmtaddr(addr->sin_addr.s_addr, 0), r);
6181
6182 free(buf);
6183 }
6184
6185 static tunnelidt new_tunnel()
6186 {
6187 tunnelidt i;
6188 for (i = 1; i < MAXTUNNEL; i++)
6189 {
6190 if ((tunnel[i].state == TUNNELFREE) && (i != TUNNEL_ID_PPPOE))
6191 {
6192 LOG(4, 0, i, "Assigning tunnel ID %u\n", i);
6193 if (i > config->cluster_highest_tunnelid)
6194 config->cluster_highest_tunnelid = i;
6195 return i;
6196 }
6197 }
6198 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6199 return 0;
6200 }
6201
6202 //
6203 // We're becoming the master. Do any required setup..
6204 //
6205 // This is principally telling all the plugins that we're
6206 // now a master, and telling them about all the sessions
6207 // that are active too..
6208 //
6209 void become_master(void)
6210 {
6211 int s, i;
6212 static struct event_data d[RADIUS_FDS];
6213 struct epoll_event e;
6214
6215 run_plugins(PLUGIN_BECOME_MASTER, NULL);
6216
6217 // running a bunch of iptables commands is slow and can cause
6218 // the master to drop tunnels on takeover--kludge around the
6219 // problem by forking for the moment (note: race)
6220 if (!fork_and_close())
6221 {
6222 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
6223 {
6224 if (!session[s].opened) // Not an in-use session.
6225 continue;
6226
6227 run_plugins(PLUGIN_NEW_SESSION_MASTER, &session[s]);
6228 }
6229 exit(0);
6230 }
6231
6232 // add radius fds
6233 e.events = EPOLLIN;
6234 for (i = 0; i < RADIUS_FDS; i++)
6235 {
6236 d[i].type = FD_TYPE_RADIUS;
6237 d[i].index = i;
6238 e.data.ptr = &d[i];
6239
6240 epoll_ctl(epollfd, EPOLL_CTL_ADD, radfds[i], &e);
6241 }
6242 }
6243
6244 int cmd_show_hist_idle(struct cli_def *cli, char *command, char **argv, int argc)
6245 {
6246 int s, i;
6247 int count = 0;
6248 int buckets[64];
6249
6250 if (CLI_HELP_REQUESTED)
6251 return CLI_HELP_NO_ARGS;
6252
6253 time(&time_now);
6254 for (i = 0; i < 64;++i) buckets[i] = 0;
6255
6256 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
6257 {
6258 int idle;
6259 if (!session[s].opened)
6260 continue;
6261
6262 idle = time_now - session[s].last_data;
6263 idle /= 5 ; // In multiples of 5 seconds.
6264 if (idle < 0)
6265 idle = 0;
6266 if (idle > 63)
6267 idle = 63;
6268
6269 ++count;
6270 ++buckets[idle];
6271 }
6272
6273 for (i = 0; i < 63; ++i)
6274 {
6275 cli_print(cli, "%3d seconds : %7.2f%% (%6d)", i * 5, (double) buckets[i] * 100.0 / count , buckets[i]);
6276 }
6277 cli_print(cli, "lots of secs : %7.2f%% (%6d)", (double) buckets[63] * 100.0 / count , buckets[i]);
6278 cli_print(cli, "%d total sessions open.", count);
6279 return CLI_OK;
6280 }
6281
6282 int cmd_show_hist_open(struct cli_def *cli, char *command, char **argv, int argc)
6283 {
6284 int s, i;
6285 int count = 0;
6286 int buckets[64];
6287
6288 if (CLI_HELP_REQUESTED)
6289 return CLI_HELP_NO_ARGS;
6290
6291 time(&time_now);
6292 for (i = 0; i < 64;++i) buckets[i] = 0;
6293
6294 for (s = 1; s <= config->cluster_highest_sessionid ; ++s)
6295 {
6296 int open = 0, d;
6297 if (!session[s].opened)
6298 continue;
6299
6300 d = time_now - session[s].opened;
6301 if (d < 0)
6302 d = 0;
6303 while (d > 1 && open < 32)
6304 {
6305 ++open;
6306 d >>= 1; // half.
6307 }
6308 ++count;
6309 ++buckets[open];
6310 }
6311
6312 s = 1;
6313 for (i = 0; i < 30; ++i)
6314 {
6315 cli_print(cli, " < %8d seconds : %7.2f%% (%6d)", s, (double) buckets[i] * 100.0 / count , buckets[i]);
6316 s <<= 1;
6317 }
6318 cli_print(cli, "%d total sessions open.", count);
6319 return CLI_OK;
6320 }
6321
6322 /* Unhide an avp.
6323 *
6324 * This unencodes the AVP using the L2TP secret and the previously
6325 * stored random vector. It overwrites the hidden data with the
6326 * unhidden AVP subformat.
6327 */
6328 static void unhide_value(uint8_t *value, size_t len, uint16_t type, uint8_t *vector, size_t vec_len)
6329 {
6330 MD5_CTX ctx;
6331 uint8_t digest[16];
6332 uint8_t *last;
6333 size_t d = 0;
6334 uint16_t m = htons(type);
6335
6336 // Compute initial pad
6337 MD5_Init(&ctx);
6338 MD5_Update(&ctx, (unsigned char *) &m, 2);
6339 MD5_Update(&ctx, config->l2tp_secret, strlen(config->l2tp_secret));
6340 MD5_Update(&ctx, vector, vec_len);
6341 MD5_Final(digest, &ctx);
6342
6343 // pointer to last decoded 16 octets
6344 last = value;
6345
6346 while (len > 0)
6347 {
6348 // calculate a new pad based on the last decoded block
6349 if (d >= sizeof(digest))
6350 {
6351 MD5_Init(&ctx);
6352 MD5_Update(&ctx, config->l2tp_secret, strlen(config->l2tp_secret));
6353 MD5_Update(&ctx, last, sizeof(digest));
6354 MD5_Final(digest, &ctx);
6355
6356 d = 0;
6357 last = value;
6358 }
6359
6360 *value++ ^= digest[d++];
6361 len--;
6362 }
6363 }
6364
6365 int find_filter(char const *name, size_t len)
6366 {
6367 int free = -1;
6368 int i;
6369
6370 for (i = 0; i < MAXFILTER; i++)
6371 {
6372 if (!*ip_filters[i].name)
6373 {
6374 if (free < 0)
6375 free = i;
6376
6377 continue;
6378 }
6379
6380 if (strlen(ip_filters[i].name) != len)
6381 continue;
6382
6383 if (!strncmp(ip_filters[i].name, name, len))
6384 return i;
6385 }
6386
6387 return free;
6388 }
6389
6390 static int ip_filter_port(ip_filter_portt *p, uint16_t port)
6391 {
6392 switch (p->op)
6393 {
6394 case FILTER_PORT_OP_EQ: return port == p->port;
6395 case FILTER_PORT_OP_NEQ: return port != p->port;
6396 case FILTER_PORT_OP_GT: return port > p->port;
6397 case FILTER_PORT_OP_LT: return port < p->port;
6398 case FILTER_PORT_OP_RANGE: return port >= p->port && port <= p->port2;
6399 }
6400
6401 return 0;
6402 }
6403
6404 static int ip_filter_flag(uint8_t op, uint8_t sflags, uint8_t cflags, uint8_t flags)
6405 {
6406 switch (op)
6407 {
6408 case FILTER_FLAG_OP_ANY:
6409 return (flags & sflags) || (~flags & cflags);
6410
6411 case FILTER_FLAG_OP_ALL:
6412 return (flags & sflags) == sflags && (~flags & cflags) == cflags;
6413
6414 case FILTER_FLAG_OP_EST:
6415 return (flags & (TCP_FLAG_ACK|TCP_FLAG_RST)) && (~flags & TCP_FLAG_SYN);
6416 }
6417
6418 return 0;
6419 }
6420
6421 int ip_filter(uint8_t *buf, int len, uint8_t filter)
6422 {
6423 uint16_t frag_offset;
6424 uint8_t proto;
6425 in_addr_t src_ip;
6426 in_addr_t dst_ip;
6427 uint16_t src_port = 0;
6428 uint16_t dst_port = 0;
6429 uint8_t flags = 0;
6430 ip_filter_rulet *rule;
6431
6432 if (len < 20) // up to end of destination address
6433 return 0;
6434
6435 if ((*buf >> 4) != 4) // IPv4
6436 return 0;
6437
6438 frag_offset = ntohs(*(uint16_t *) (buf + 6)) & 0x1fff;
6439 proto = buf[9];
6440 src_ip = *(in_addr_t *) (buf + 12);
6441 dst_ip = *(in_addr_t *) (buf + 16);
6442
6443 if (frag_offset == 0 && (proto == IPPROTO_TCP || proto == IPPROTO_UDP))
6444 {
6445 int l = (buf[0] & 0xf) * 4; // length of IP header
6446 if (len < l + 4) // ports
6447 return 0;
6448
6449 src_port = ntohs(*(uint16_t *) (buf + l));
6450 dst_port = ntohs(*(uint16_t *) (buf + l + 2));
6451 if (proto == IPPROTO_TCP)
6452 {
6453 if (len < l + 14) // flags
6454 return 0;
6455
6456 flags = buf[l + 13] & 0x3f;
6457 }
6458 }
6459
6460 for (rule = ip_filters[filter].rules; rule->action; rule++)
6461 {
6462 if (rule->proto != IPPROTO_IP && proto != rule->proto)
6463 continue;
6464
6465 if (rule->src_wild != INADDR_BROADCAST &&
6466 (src_ip & ~rule->src_wild) != (rule->src_ip & ~rule->src_wild))
6467 continue;
6468
6469 if (rule->dst_wild != INADDR_BROADCAST &&
6470 (dst_ip & ~rule->dst_wild) != (rule->dst_ip & ~rule->dst_wild))
6471 continue;
6472
6473 if (frag_offset)
6474 {
6475 // layer 4 deny rules are skipped
6476 if (rule->action == FILTER_ACTION_DENY &&
6477 (rule->src_ports.op || rule->dst_ports.op || rule->tcp_flag_op))
6478 continue;
6479 }
6480 else
6481 {
6482 if (rule->frag)
6483 continue;
6484
6485 if (proto == IPPROTO_TCP || proto == IPPROTO_UDP)
6486 {
6487 if (rule->src_ports.op && !ip_filter_port(&rule->src_ports, src_port))
6488 continue;
6489
6490 if (rule->dst_ports.op && !ip_filter_port(&rule->dst_ports, dst_port))
6491 continue;
6492
6493 if (proto == IPPROTO_TCP && rule->tcp_flag_op &&
6494 !ip_filter_flag(rule->tcp_flag_op, rule->tcp_sflags, rule->tcp_cflags, flags))
6495 continue;
6496 }
6497 }
6498
6499 // matched
6500 rule->counter++;
6501 return rule->action == FILTER_ACTION_PERMIT;
6502 }
6503
6504 // default deny
6505 return 0;
6506 }
6507
6508 tunnelidt lac_new_tunnel()
6509 {
6510 return new_tunnel();
6511 }
6512
6513 void lac_tunnelclear(tunnelidt t)
6514 {
6515 tunnelclear(t);
6516 }
6517
6518 void lac_send_SCCRQ(tunnelidt t, uint8_t * auth, unsigned int auth_len)
6519 {
6520 uint16_t version = 0x0100; // protocol version
6521
6522 tunnel[t].state = TUNNELOPENING;
6523
6524 // Sent SCCRQ - Start Control Connection Request
6525 controlt *c = controlnew(1); // sending SCCRQ
6526 controls(c, 7, hostname, 1); // host name
6527 controls(c, 8, Vendor_name, 1); // Vendor name
6528 control16(c, 2, version, 1); // protocol version
6529 control32(c, 3, 3, 1); // framing Capabilities
6530 control16(c, 9, t, 1); // assigned tunnel
6531 controlb(c, 11, (uint8_t *) auth, auth_len, 1); // CHAP Challenge
6532 LOG(3, 0, t, "Sent SCCRQ to REMOTE LNS\n");
6533 controladd(c, 0, t); // send
6534 }
6535
6536 void lac_send_ICRQ(tunnelidt t, sessionidt s)
6537 {
6538 // Sent ICRQ Incoming-call-request
6539 controlt *c = controlnew(10); // ICRQ
6540
6541 control16(c, 14, s, 1); // assigned sesion
6542 call_serial_number++;
6543 control32(c, 15, call_serial_number, 1); // call serial number
6544 LOG(3, s, t, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel[t].far);
6545 controladd(c, 0, t); // send
6546 }
6547
6548 void lac_tunnelshutdown(tunnelidt t, char *reason, int result, int error, char *msg)
6549 {
6550 tunnelshutdown(t, reason, result, error, msg);
6551 }
6552