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