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