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