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