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