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