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