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