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