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