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