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