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