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