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