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