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