3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
7 char const *cvs_id_l2tpns
= "$Id: l2tpns.c,v 1.176 2011-01-20 12:48:40 bodea Exp $";
13 #include <linux/if_tun.h>
18 #include <net/route.h>
21 #include <netinet/in.h>
22 #include <netinet/ip6.h>
28 #include <sys/ioctl.h>
29 #include <sys/socket.h>
32 #include <sys/resource.h>
40 #include <sys/sysinfo.h>
48 #include "constants.h"
58 configt
*config
= NULL
; // all configuration
59 int tunfd
= -1; // tun interface file handle. (network device)
60 int udpfd
= -1; // UDP file handle
61 int controlfd
= -1; // Control signal handle
62 int clifd
= -1; // Socket listening for CLI connections.
63 int daefd
= -1; // Socket listening for DAE connections.
64 int snoopfd
= -1; // UDP file handle for sending out intercept data
65 int *radfds
= NULL
; // RADIUS requests file handles
66 int ifrfd
= -1; // File descriptor for routing, etc
67 int ifr6fd
= -1; // File descriptor for IPv6 routing, etc
68 int rand_fd
= -1; // Random data source
69 int cluster_sockfd
= -1; // Intra-cluster communications socket.
70 int epollfd
= -1; // event polling
71 time_t basetime
= 0; // base clock
72 char hostname
[1000] = ""; // us.
73 static int tunidx
; // ifr_ifindex of tun device
74 static int syslog_log
= 0; // are we logging to syslog
75 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
76 uint32_t last_id
= 0; // Unique ID for radius accounting
78 char guest_users
[10][32]; // Array of guest users
79 int guest_accounts_num
= 0; // Number of guest users
81 // calculated from config->l2tp_mtu
82 uint16_t MRU
= 0; // PPP MRU
83 uint16_t MSS
= 0; // TCP MSS
85 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
86 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
91 } ip_hash
[256]; // Mapping from IP address to session structures.
95 struct ipv6radix
*branch
;
96 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
99 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
100 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
103 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
104 time_t time_now
= 0; // Current time in seconds since epoch.
105 static char time_now_string
[64] = {0}; // Current time as a string.
106 static int time_changed
= 0; // time_now changed
107 char main_quit
= 0; // True if we're in the process of exiting.
108 static char main_reload
= 0; // Re-load pending
109 linked_list
*loaded_plugins
;
110 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
112 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
113 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
115 config_descriptt config_values
[] = {
116 CONFIG("debug", debug
, INT
),
117 CONFIG("log_file", log_filename
, STRING
),
118 CONFIG("pid_file", pid_file
, STRING
),
119 CONFIG("random_device", random_device
, STRING
),
120 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
121 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
122 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
123 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
124 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
125 CONFIG("primary_dns", default_dns1
, IPv4
),
126 CONFIG("secondary_dns", default_dns2
, IPv4
),
127 CONFIG("primary_radius", radiusserver
[0], IPv4
),
128 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
129 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
130 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
131 CONFIG("radius_accounting", radius_accounting
, BOOL
),
132 CONFIG("radius_interim", radius_interim
, INT
),
133 CONFIG("radius_secret", radiussecret
, STRING
),
134 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
135 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
136 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
137 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
138 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
139 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
140 CONFIG("guest_account", guest_user
, STRING
),
141 CONFIG("bind_address", bind_address
, IPv4
),
142 CONFIG("peer_address", peer_address
, IPv4
),
143 CONFIG("send_garp", send_garp
, BOOL
),
144 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
145 CONFIG("throttle_buckets", num_tbfs
, INT
),
146 CONFIG("accounting_dir", accounting_dir
, STRING
),
147 CONFIG("dump_speed", dump_speed
, BOOL
),
148 CONFIG("multi_read_count", multi_read_count
, INT
),
149 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
150 CONFIG("lock_pages", lock_pages
, BOOL
),
151 CONFIG("icmp_rate", icmp_rate
, INT
),
152 CONFIG("packet_limit", max_packets
, INT
),
153 CONFIG("cluster_address", cluster_address
, IPv4
),
154 CONFIG("cluster_interface", cluster_interface
, STRING
),
155 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
156 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
157 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
158 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
159 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
163 static char *plugin_functions
[] = {
170 "plugin_new_session",
171 "plugin_kill_session",
173 "plugin_radius_response",
174 "plugin_radius_reset",
175 "plugin_radius_account",
176 "plugin_become_master",
177 "plugin_new_session_master",
180 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
182 // Counters for shutdown sessions
183 static sessiont shut_acct
[8192];
184 static sessionidt shut_acct_n
= 0;
186 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
187 bundlet
*bundle
= NULL
; // Array of bundle structures.
188 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
189 sessiont
*session
= NULL
; // Array of session structures.
190 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
191 radiust
*radius
= NULL
; // Array of radius structures.
192 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
193 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
194 static controlt
*controlfree
= 0;
195 struct Tstats
*_statistics
= NULL
;
197 struct Tringbuffer
*ringbuffer
= NULL
;
200 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
201 static void uncache_ipmap(in_addr_t ip
);
202 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
203 static void free_ip_address(sessionidt s
);
204 static void dump_acct_info(int all
);
205 static void sighup_handler(int sig
);
206 static void shutdown_handler(int sig
);
207 static void sigchild_handler(int sig
);
208 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
209 static void update_config(void);
210 static void read_config_file(void);
211 static void initplugins(void);
212 static int add_plugin(char *plugin_name
);
213 static int remove_plugin(char *plugin_name
);
214 static void plugins_done(void);
215 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
216 static tunnelidt
new_tunnel(void);
217 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
218 static void bundleclear(bundleidt b
);
220 // on slaves, alow BGP to withdraw cleanly before exiting
223 // quit actions (master)
224 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
225 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
227 // return internal time (10ths since process startup), set f if given
228 // as a side-effect sets time_now, and time_changed
229 static clockt
now(double *f
)
233 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
234 if (t
.tv_sec
!= time_now
)
239 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
242 // work out a retry time based on try number
243 // This is a straight bounded exponential backoff.
244 // Maximum re-try time is 32 seconds. (2^5).
245 clockt
backoff(uint8_t try)
247 if (try > 5) try = 5; // max backoff
248 return now(NULL
) + 10 * (1 << try);
253 // Log a debug message. Typically called via the LOG macro
255 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
257 static char message
[65536] = {0};
263 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
264 ringbuffer
->tail
= 0;
265 if (ringbuffer
->tail
== ringbuffer
->head
)
266 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
267 ringbuffer
->head
= 0;
269 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
270 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
271 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
272 va_start(ap
, format
);
273 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
278 if (config
->debug
< level
) return;
280 va_start(ap
, format
);
281 vsnprintf(message
, sizeof(message
), format
, ap
);
284 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
286 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
291 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
294 const uint8_t *d
= data
;
296 if (config
->debug
< level
) return;
298 // No support for _log_hex to syslog
301 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
302 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
304 for (i
= 0; i
< maxsize
; )
306 fprintf(log_stream
, "%4X: ", i
);
307 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
309 fprintf(log_stream
, "%02X ", d
[j
]);
311 fputs(": ", log_stream
);
314 for (; j
< i
+ 16; j
++)
316 fputs(" ", log_stream
);
318 fputs(": ", log_stream
);
321 fputs(" ", log_stream
);
322 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
324 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
325 fputc(d
[j
], log_stream
);
327 fputc('.', log_stream
);
330 fputs(" ", log_stream
);
334 fputs("\n", log_stream
);
338 setbuf(log_stream
, NULL
);
342 // update a counter, accumulating 2^32 wraps
343 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
345 uint32_t new = *counter
+ delta
;
352 // initialise the random generator
353 static void initrandom(char *source
)
355 static char path
[sizeof(config
->random_device
)] = "*undefined*";
357 // reinitialise only if we are forced to do so or if the config has changed
358 if (source
&& !strncmp(path
, source
, sizeof(path
)))
361 // close previous source, if any
370 snprintf(path
, sizeof(path
), "%s", source
);
374 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
376 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
377 path
, strerror(errno
));
382 // fill buffer with random data
383 void random_data(uint8_t *buf
, int len
)
390 n
= read(rand_fd
, buf
, len
);
391 if (n
>= len
) return;
396 LOG(0, 0, 0, "Error reading from random source: %s\n",
399 // fall back to rand()
407 // append missing data
409 // not using the low order bits from the prng stream
410 buf
[n
++] = (rand() >> 4) & 0xff;
415 // This adds it to the routing table, advertises it
416 // via BGP if enabled, and stuffs it into the
417 // 'sessionbyip' cache.
419 // 'ip' and 'mask' must be in _host_ order.
421 static void routeset(sessionidt s
, in_addr_t ip
, in_addr_t mask
, in_addr_t gw
, int add
)
426 if (!mask
) mask
= 0xffffffff;
428 ip
&= mask
; // Force the ip to be the first one in the route.
430 memset(&r
, 0, sizeof(r
));
431 r
.rt_dev
= config
->tundevice
;
432 r
.rt_dst
.sa_family
= AF_INET
;
433 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_dst
)->sin_addr
.s_addr
) = htonl(ip
);
434 r
.rt_gateway
.sa_family
= AF_INET
;
435 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_gateway
)->sin_addr
.s_addr
) = htonl(gw
);
436 r
.rt_genmask
.sa_family
= AF_INET
;
437 *(uint32_t *) & (((struct sockaddr_in
*) &r
.rt_genmask
)->sin_addr
.s_addr
) = htonl(mask
);
438 r
.rt_flags
= (RTF_UP
| RTF_STATIC
);
440 r
.rt_flags
|= RTF_GATEWAY
;
441 else if (mask
== 0xffffffff)
442 r
.rt_flags
|= RTF_HOST
;
444 LOG(1, s
, 0, "Route %s %s/%s%s%s\n", add
? "add" : "del",
445 fmtaddr(htonl(ip
), 0), fmtaddr(htonl(mask
), 1),
446 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
448 if (ioctl(ifrfd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &r
) < 0)
449 LOG(0, 0, 0, "routeset() error in ioctl: %s\n", strerror(errno
));
453 bgp_add_route(htonl(ip
), htonl(mask
));
455 bgp_del_route(htonl(ip
), htonl(mask
));
458 // Add/Remove the IPs to the 'sessionbyip' cache.
459 // Note that we add the zero address in the case of
460 // a network route. Roll on CIDR.
462 // Note that 's == 0' implies this is the address pool.
463 // We still cache it here, because it will pre-fill
464 // the malloc'ed tree.
468 if (!add
) // Are we deleting a route?
469 s
= 0; // Caching the session as '0' is the same as uncaching.
471 for (i
= ip
; (i
&mask
) == (ip
&mask
) ; ++i
)
476 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
479 char ipv6addr
[INET6_ADDRSTRLEN
];
483 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
487 memset(&rt
, 0, sizeof(rt
));
489 memcpy(&rt
.rtmsg_dst
, &ip
, sizeof(struct in6_addr
));
490 rt
.rtmsg_dst_len
= prefixlen
;
492 rt
.rtmsg_flags
= RTF_UP
;
493 rt
.rtmsg_ifindex
= tunidx
;
495 LOG(1, 0, 0, "Route %s %s/%d\n",
497 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
500 if (ioctl(ifr6fd
, add
? SIOCADDRT
: SIOCDELRT
, (void *) &rt
) < 0)
501 LOG(0, 0, 0, "route6set() error in ioctl: %s\n",
504 // FIXME: need to add BGP routing (RFC2858)
508 if (!add
) // Are we deleting a route?
509 s
= 0; // Caching the session as '0' is the same as uncaching.
511 cache_ipv6map(ip
, prefixlen
, s
);
517 // defined in linux/ipv6.h, but tricky to include from user-space
518 // TODO: move routing to use netlink rather than ioctl
520 struct in6_addr ifr6_addr
;
521 __u32 ifr6_prefixlen
;
522 unsigned int ifr6_ifindex
;
526 // Set up TUN interface
527 static void inittun(void)
530 struct in6_ifreq ifr6
;
531 struct sockaddr_in sin
= {0};
532 memset(&ifr
, 0, sizeof(ifr
));
533 ifr
.ifr_flags
= IFF_TUN
;
535 tunfd
= open(TUNDEVICE
, O_RDWR
);
538 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
542 int flags
= fcntl(tunfd
, F_GETFL
, 0);
543 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
545 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
547 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
550 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
));
551 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
) - 1);
552 ifrfd
= socket(PF_INET
, SOCK_DGRAM
, IPPROTO_IP
);
554 sin
.sin_family
= AF_INET
;
555 sin
.sin_addr
.s_addr
= config
->bind_address
? config
->bind_address
: 0x01010101; // 1.1.1.1
556 memcpy(&ifr
.ifr_addr
, &sin
, sizeof(struct sockaddr
));
558 if (ioctl(ifrfd
, SIOCSIFADDR
, (void *) &ifr
) < 0)
560 LOG(0, 0, 0, "Error setting tun address: %s\n", strerror(errno
));
563 /* Bump up the qlen to deal with bursts from the network */
565 if (ioctl(ifrfd
, SIOCSIFTXQLEN
, (void *) &ifr
) < 0)
567 LOG(0, 0, 0, "Error setting tun queue length: %s\n", strerror(errno
));
570 /* set MTU to modem MRU */
572 if (ioctl(ifrfd
, SIOCSIFMTU
, (void *) &ifr
) < 0)
574 LOG(0, 0, 0, "Error setting tun MTU: %s\n", strerror(errno
));
577 ifr
.ifr_flags
= IFF_UP
;
578 if (ioctl(ifrfd
, SIOCSIFFLAGS
, (void *) &ifr
) < 0)
580 LOG(0, 0, 0, "Error setting tun flags: %s\n", strerror(errno
));
583 if (ioctl(ifrfd
, SIOCGIFINDEX
, (void *) &ifr
) < 0)
585 LOG(0, 0, 0, "Error getting tun ifindex: %s\n", strerror(errno
));
588 tunidx
= ifr
.ifr_ifindex
;
590 // Only setup IPv6 on the tun device if we have a configured prefix
591 if (config
->ipv6_prefix
.s6_addr
[0]) {
592 ifr6fd
= socket(PF_INET6
, SOCK_DGRAM
, 0);
594 // Link local address is FE80::1
595 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
596 ifr6
.ifr6_addr
.s6_addr
[0] = 0xFE;
597 ifr6
.ifr6_addr
.s6_addr
[1] = 0x80;
598 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
599 ifr6
.ifr6_prefixlen
= 64;
600 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
601 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
603 LOG(0, 0, 0, "Error setting tun IPv6 link local address:"
604 " %s\n", strerror(errno
));
607 // Global address is prefix::1
608 memset(&ifr6
.ifr6_addr
, 0, sizeof(ifr6
.ifr6_addr
));
609 ifr6
.ifr6_addr
= config
->ipv6_prefix
;
610 ifr6
.ifr6_addr
.s6_addr
[15] = 1;
611 ifr6
.ifr6_prefixlen
= 64;
612 ifr6
.ifr6_ifindex
= ifr
.ifr_ifindex
;
613 if (ioctl(ifr6fd
, SIOCSIFADDR
, (void *) &ifr6
) < 0)
615 LOG(0, 0, 0, "Error setting tun IPv6 global address: %s\n",
622 static void initudp(void)
625 struct sockaddr_in addr
;
628 memset(&addr
, 0, sizeof(addr
));
629 addr
.sin_family
= AF_INET
;
630 addr
.sin_port
= htons(L2TPPORT
);
631 addr
.sin_addr
.s_addr
= config
->bind_address
;
632 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
633 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
635 int flags
= fcntl(udpfd
, F_GETFL
, 0);
636 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
638 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
640 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
645 memset(&addr
, 0, sizeof(addr
));
646 addr
.sin_family
= AF_INET
;
647 addr
.sin_port
= htons(NSCTL_PORT
);
648 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
649 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
650 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
651 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
653 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
657 // Dynamic Authorization Extensions to RADIUS
658 memset(&addr
, 0, sizeof(addr
));
659 addr
.sin_family
= AF_INET
;
660 addr
.sin_port
= htons(config
->radius_dae_port
);
661 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
662 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
663 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
664 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
666 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
671 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
675 // Find session by IP, < 1 for not found
677 // Confusingly enough, this 'ip' must be
678 // in _network_ order. This being the common
679 // case when looking it up from IP packet headers.
681 // We actually use this cache for two things.
682 // #1. For used IP addresses, this maps to the
683 // session ID that it's used by.
684 // #2. For un-used IP addresses, this maps to the
685 // index into the pool table that contains that
689 static sessionidt
lookup_ipmap(in_addr_t ip
)
691 uint8_t *a
= (uint8_t *) &ip
;
692 union iphash
*h
= ip_hash
;
694 if (!(h
= h
[*a
++].idx
)) return 0;
695 if (!(h
= h
[*a
++].idx
)) return 0;
696 if (!(h
= h
[*a
++].idx
)) return 0;
701 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
703 struct ipv6radix
*curnode
;
706 char ipv6addr
[INET6_ADDRSTRLEN
];
708 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
712 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
714 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
719 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
720 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
727 sessionidt
sessionbyip(in_addr_t ip
)
729 sessionidt s
= lookup_ipmap(ip
);
732 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
738 sessionidt
sessionbyipv6(struct in6_addr ip
)
741 CSTAT(sessionbyipv6
);
743 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
744 (ip
.s6_addr
[0] == 0xFE &&
745 ip
.s6_addr
[1] == 0x80 &&
746 ip
.s6_addr16
[1] == 0 &&
747 ip
.s6_addr16
[2] == 0 &&
748 ip
.s6_addr16
[3] == 0)) {
749 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
751 s
= lookup_ipv6map(ip
);
754 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
761 // Take an IP address in HOST byte order and
762 // add it to the sessionid by IP cache.
764 // (It's actually cached in network order)
766 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
768 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
769 uint8_t *a
= (uint8_t *) &nip
;
770 union iphash
*h
= ip_hash
;
773 for (i
= 0; i
< 3; i
++)
775 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
784 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
787 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
788 // else a map to an ip pool index.
791 static void uncache_ipmap(in_addr_t ip
)
793 cache_ipmap(ip
, 0); // Assign it to the NULL session.
796 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
800 struct ipv6radix
*curnode
;
801 char ipv6addr
[INET6_ADDRSTRLEN
];
803 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
805 bytes
= prefixlen
>> 3;
808 if (curnode
->branch
== NULL
)
810 if (!(curnode
->branch
= calloc(256,
811 sizeof (struct ipv6radix
))))
814 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
821 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
822 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
826 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
827 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
833 // CLI list to dump current ipcache.
835 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
837 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
841 if (CLI_HELP_REQUESTED
)
842 return CLI_HELP_NO_ARGS
;
844 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
846 for (i
= 0; i
< 256; ++i
)
852 for (j
= 0; j
< 256; ++j
)
858 for (k
= 0; k
< 256; ++k
)
864 for (l
= 0; l
< 256; ++l
)
869 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
875 cli_print(cli
, "%d entries in cache", count
);
880 // Find session by username, 0 for not found
881 // walled garden users aren't authenticated, so the username is
882 // reasonably useless. Ignore them to avoid incorrect actions
884 // This is VERY inefficent. Don't call it often. :)
886 sessionidt
sessionbyuser(char *username
)
889 CSTAT(sessionbyuser
);
891 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
893 if (!session
[s
].opened
)
896 if (session
[s
].walled_garden
)
897 continue; // Skip walled garden users.
899 if (!strncmp(session
[s
].user
, username
, 128))
903 return 0; // Not found.
906 void send_garp(in_addr_t ip
)
912 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
915 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
918 memset(&ifr
, 0, sizeof(ifr
));
919 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
920 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
922 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
926 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
927 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
929 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
934 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
937 static sessiont
*sessiontbysessionidt(sessionidt s
)
939 if (!s
|| s
>= MAXSESSION
) return NULL
;
943 static sessionidt
sessionidtbysessiont(sessiont
*s
)
945 sessionidt val
= s
-session
;
946 if (s
< session
|| val
>= MAXSESSION
) return 0;
950 // actually send a control message for a specific tunnel
951 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
953 struct sockaddr_in addr
;
959 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
960 STAT(tunnel_tx_errors
);
966 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
967 STAT(tunnel_tx_errors
);
971 memset(&addr
, 0, sizeof(addr
));
972 addr
.sin_family
= AF_INET
;
973 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
974 addr
.sin_port
= htons(tunnel
[t
].port
);
976 // sequence expected, if sequence in message
977 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
979 // If this is a control message, deal with retries
982 tunnel
[t
].last
= time_now
; // control message sent
983 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
986 STAT(tunnel_retries
);
987 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
991 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
993 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
994 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
995 STAT(tunnel_tx_errors
);
999 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1000 STAT(tunnel_tx_packets
);
1001 INC_STAT(tunnel_tx_bytes
, l
);
1005 // Tiny helper function to write data to
1006 // the 'tun' device.
1008 int tun_write(uint8_t * data
, int size
)
1010 return write(tunfd
, data
, size
);
1013 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1014 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1016 int d
= (tcp
[12] >> 4) * 4;
1023 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1026 if (tcp
+ d
> buf
+ len
) // short?
1034 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1037 if (mss
+ 2 > data
) return; // short?
1041 if (*opts
== 0) return; // end of options
1042 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1045 opts
+= opts
[1]; // skip over option
1048 if (!mss
) return; // not found
1049 orig
= ntohs(*(uint16_t *) mss
);
1051 if (orig
<= MSS
) return; // mss OK
1053 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1054 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1055 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1056 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1059 *(int16_t *) mss
= htons(MSS
);
1061 // adjust checksum (see rfc1141)
1062 sum
= orig
+ (~MSS
& 0xffff);
1063 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1064 sum
= (sum
& 0xffff) + (sum
>> 16);
1065 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1068 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1072 // Skip the four extra bytes
1084 proto
= ntohs(*(uint16_t *) p
);
1092 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1093 return; // closing session, PPP not processed
1095 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1096 processipin(s
, t
, p
, l
);
1098 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1102 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1103 return; // closing session, PPP not processed
1106 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1107 processipv6in(s
, t
, p
, l
);
1109 else if (proto
== PPPIPCP
)
1111 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1112 processipcp(s
, t
, p
, l
);
1114 else if (proto
== PPPCCP
)
1116 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1117 processccp(s
, t
, p
, l
);
1121 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1125 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1127 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1128 sp
->cout_delta
+= len
;
1130 sp
->last_data
= time_now
;
1132 sess_local
[s
].cout
+= len
; // To send to master..
1133 sess_local
[s
].pout
++;
1136 // process outgoing (to tunnel) IP
1138 static void processipout(uint8_t *buf
, int len
)
1145 uint8_t *data
= buf
; // Keep a copy of the originals.
1148 uint8_t fragbuf
[MAXETHER
+ 20];
1150 CSTAT(processipout
);
1152 if (len
< MIN_IP_SIZE
)
1154 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1155 STAT(tun_rx_errors
);
1158 if (len
>= MAXETHER
)
1160 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1161 STAT(tun_rx_errors
);
1165 // Skip the tun header
1169 // Got an IP header now
1170 if (*(uint8_t *)(buf
) >> 4 != 4)
1172 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1176 ip
= *(uint32_t *)(buf
+ 16);
1177 if (!(s
= sessionbyip(ip
)))
1179 // Is this a packet for a session that doesn't exist?
1180 static int rate
= 0; // Number of ICMP packets we've sent this second.
1181 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1183 if (last
!= time_now
)
1189 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1191 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1192 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1193 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1198 t
= session
[s
].tunnel
;
1199 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1201 LOG(3, s
, t
, "Packet size more than session MRU\n");
1207 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1208 if (config
->max_packets
> 0)
1210 if (sess_local
[s
].last_packet_out
== TIME
)
1212 int max
= config
->max_packets
;
1214 // All packets for throttled sessions are handled by the
1215 // master, so further limit by using the throttle rate.
1216 // A bit of a kludge, since throttle rate is in kbps,
1217 // but should still be generous given our average DSL
1218 // packet size is 200 bytes: a limit of 28kbps equates
1219 // to around 180 packets per second.
1220 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1221 max
= sp
->throttle_out
;
1223 if (++sess_local
[s
].packets_out
> max
)
1225 sess_local
[s
].packets_dropped
++;
1231 if (sess_local
[s
].packets_dropped
)
1233 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1234 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1235 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1236 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1240 sess_local
[s
].last_packet_out
= TIME
;
1241 sess_local
[s
].packets_out
= 1;
1242 sess_local
[s
].packets_dropped
= 0;
1246 // run access-list if any
1247 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1250 // adjust MSS on SYN and SYN,ACK packets with options
1251 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1253 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1254 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1255 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1260 // Are we throttling this session?
1261 if (config
->cluster_iam_master
)
1262 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1264 master_throttle_packet(sp
->tbf_out
, data
, size
);
1268 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1270 // We are walled-gardening this
1271 master_garden_packet(s
, data
, size
);
1275 // Add on L2TP header
1278 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1280 bid
= session
[s
].bundle
;
1281 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1282 t
= session
[s
].tunnel
;
1284 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1285 if(len
> MINFRAGLEN
)
1287 // Partition the packet to "bundle[b].num_of_links" fragments
1288 bundlet
*b
= &bundle
[bid
];
1289 uint32_t num_of_links
= b
->num_of_links
;
1290 uint32_t fraglen
= len
/ num_of_links
;
1291 fraglen
= (fraglen
> session
[s
].mru
? session
[s
].mru
: fraglen
);
1292 uint32_t last_fraglen
= fraglen
+ len
% num_of_links
;
1293 last_fraglen
= (last_fraglen
> session
[s
].mru
? len
% num_of_links
: last_fraglen
);
1294 uint32_t remain
= len
;
1296 // send the first packet
1297 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1299 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1301 update_session_out_stat(s
, sp
, fraglen
);
1303 while (remain
> last_fraglen
)
1305 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1306 t
= session
[s
].tunnel
;
1308 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1309 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1311 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1312 update_session_out_stat(s
, sp
, fraglen
);
1315 // send the last fragment
1316 s
= b
->members
[b
->current_ses
= ++b
->current_ses
% num_of_links
];
1317 t
= session
[s
].tunnel
;
1319 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1320 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1322 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1323 update_session_out_stat(s
, sp
, remain
);
1324 if (remain
!= last_fraglen
)
1325 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1328 // Send it as one frame
1329 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1331 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1332 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1333 update_session_out_stat(s
, sp
, len
);
1338 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1340 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1341 update_session_out_stat(s
, sp
, len
);
1345 // Snooping this session, send it to intercept box
1346 if (sp
->snoop_ip
&& sp
->snoop_port
)
1347 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1352 // process outgoing (to tunnel) IPv6
1354 static void processipv6out(uint8_t * buf
, int len
)
1360 struct in6_addr ip6
;
1362 uint8_t *data
= buf
; // Keep a copy of the originals.
1365 uint8_t b
[MAXETHER
+ 20];
1367 CSTAT(processipv6out
);
1369 if (len
< MIN_IP_SIZE
)
1371 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1372 STAT(tunnel_tx_errors
);
1375 if (len
>= MAXETHER
)
1377 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1378 STAT(tunnel_tx_errors
);
1382 // Skip the tun header
1386 // Got an IP header now
1387 if (*(uint8_t *)(buf
) >> 4 != 6)
1389 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1393 ip6
= *(struct in6_addr
*)(buf
+24);
1394 s
= sessionbyipv6(ip6
);
1398 ip
= *(uint32_t *)(buf
+ 32);
1399 s
= sessionbyip(ip
);
1404 // Is this a packet for a session that doesn't exist?
1405 static int rate
= 0; // Number of ICMP packets we've sent this second.
1406 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1408 if (last
!= time_now
)
1414 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1416 // FIXME: Should send icmp6 host unreachable
1420 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1422 bundleidt bid
= session
[s
].bundle
;
1423 s
= bundle
[bid
].members
[bundle
[bid
].current_ses
= ++bundle
[bid
].current_ses
% bundle
[bid
].num_of_links
];
1424 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1426 t
= session
[s
].tunnel
;
1428 sp
->last_data
= time_now
;
1430 // FIXME: add DoS prevention/filters?
1434 // Are we throttling this session?
1435 if (config
->cluster_iam_master
)
1436 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1438 master_throttle_packet(sp
->tbf_out
, data
, size
);
1441 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1443 // We are walled-gardening this
1444 master_garden_packet(s
, data
, size
);
1448 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1450 // Add on L2TP header
1452 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1454 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1457 // Snooping this session, send it to intercept box
1458 if (sp
->snoop_ip
&& sp
->snoop_port
)
1459 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1461 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1462 sp
->cout_delta
+= len
;
1466 sess_local
[s
].cout
+= len
; // To send to master..
1467 sess_local
[s
].pout
++;
1471 // Helper routine for the TBF filters.
1472 // Used to send queued data in to the user!
1474 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1480 uint8_t b
[MAXETHER
+ 20];
1482 if (len
< 0 || len
> MAXETHER
)
1484 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1488 // Skip the tun header
1492 ip
= *(in_addr_t
*)(buf
+ 16);
1497 t
= session
[s
].tunnel
;
1500 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1502 // Add on L2TP header
1504 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1506 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1509 // Snooping this session.
1510 if (sp
->snoop_ip
&& sp
->snoop_port
)
1511 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1513 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1514 sp
->cout_delta
+= len
;
1518 sess_local
[s
].cout
+= len
; // To send to master..
1519 sess_local
[s
].pout
++;
1522 // add an AVP (16 bit)
1523 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1525 uint16_t l
= (m
? 0x8008 : 0x0008);
1526 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1527 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1528 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1529 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1533 // add an AVP (32 bit)
1534 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1536 uint16_t l
= (m
? 0x800A : 0x000A);
1537 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1538 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1539 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1540 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1544 // add an AVP (string)
1545 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1547 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1548 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1549 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1550 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1551 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1552 c
->length
+= 6 + strlen(val
);
1556 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1558 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1559 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1560 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1561 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1562 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1563 c
->length
+= 6 + len
;
1566 // new control connection
1567 static controlt
*controlnew(uint16_t mtype
)
1571 c
= malloc(sizeof(controlt
));
1575 controlfree
= c
->next
;
1579 *(uint16_t *) (c
->buf
+ 0) = htons(0xC802); // flags/ver
1581 control16(c
, 0, mtype
, 1);
1585 // send zero block if nothing is waiting
1587 static void controlnull(tunnelidt t
)
1590 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1593 *(uint16_t *) (buf
+ 0) = htons(0xC802); // flags/ver
1594 *(uint16_t *) (buf
+ 2) = htons(12); // length
1595 *(uint16_t *) (buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1596 *(uint16_t *) (buf
+ 6) = htons(0); // session
1597 *(uint16_t *) (buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1598 *(uint16_t *) (buf
+ 10) = htons(tunnel
[t
].nr
); // sequence
1599 tunnelsend(buf
, 12, t
);
1602 // add a control message to a tunnel, and send if within window
1603 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1605 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1606 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1607 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1608 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1609 tunnel
[t
].ns
++; // advance sequence
1610 // link in message in to queue
1611 if (tunnel
[t
].controlc
)
1612 tunnel
[t
].controle
->next
= c
;
1614 tunnel
[t
].controls
= c
;
1616 tunnel
[t
].controle
= c
;
1617 tunnel
[t
].controlc
++;
1619 // send now if space in window
1620 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1622 tunnel
[t
].try = 0; // first send
1623 tunnelsend(c
->buf
, c
->length
, t
);
1628 // Throttle or Unthrottle a session
1630 // Throttle the data from/to through a session to no more than
1631 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1634 // If either value is -1, the current value is retained for that
1637 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1639 if (!session
[s
].opened
)
1640 return; // No-one home.
1642 if (!*session
[s
].user
)
1643 return; // User not logged in
1647 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1648 if (session
[s
].tbf_in
)
1649 free_tbf(session
[s
].tbf_in
);
1652 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1654 session
[s
].tbf_in
= 0;
1656 session
[s
].throttle_in
= rate_in
;
1661 int bytes
= rate_out
* 1024 / 8;
1662 if (session
[s
].tbf_out
)
1663 free_tbf(session
[s
].tbf_out
);
1666 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1668 session
[s
].tbf_out
= 0;
1670 session
[s
].throttle_out
= rate_out
;
1674 // add/remove filters from session (-1 = no change)
1675 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1677 if (!session
[s
].opened
)
1678 return; // No-one home.
1680 if (!*session
[s
].user
)
1681 return; // User not logged in
1684 if (filter_in
> MAXFILTER
) filter_in
= -1;
1685 if (filter_out
> MAXFILTER
) filter_out
= -1;
1686 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1687 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1691 if (session
[s
].filter_in
)
1692 ip_filters
[session
[s
].filter_in
- 1].used
--;
1695 ip_filters
[filter_in
- 1].used
++;
1697 session
[s
].filter_in
= filter_in
;
1700 if (filter_out
>= 0)
1702 if (session
[s
].filter_out
)
1703 ip_filters
[session
[s
].filter_out
- 1].used
--;
1706 ip_filters
[filter_out
- 1].used
++;
1708 session
[s
].filter_out
= filter_out
;
1712 // start tidy shutdown of session
1713 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1715 int walled_garden
= session
[s
].walled_garden
;
1716 bundleidt b
= session
[s
].bundle
;
1717 //delete routes only for last session in bundle (in case of MPPP)
1718 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1720 CSTAT(sessionshutdown
);
1722 if (!session
[s
].opened
)
1724 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1725 return; // not a live session
1728 if (!session
[s
].die
)
1730 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1731 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1732 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1733 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1736 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1738 // RADIUS Stop message
1739 uint16_t r
= radiusnew(s
);
1742 // stop, if not already trying
1743 if (radius
[r
].state
!= RADIUSSTOP
)
1745 radius
[r
].term_cause
= term_cause
;
1746 radius
[r
].term_msg
= reason
;
1747 radiussend(r
, RADIUSSTOP
);
1751 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1753 // Save counters to dump to accounting file
1754 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1755 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1759 { // IP allocated, clear and unroute
1762 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1764 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
1765 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
1768 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 0);
1769 session
[s
].route
[r
].ip
= 0;
1772 if (session
[s
].ip_pool_index
== -1) // static ip
1774 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
1780 // unroute IPv6, if setup
1781 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
1782 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
1786 // This session was part of a bundle
1787 bundle
[b
].num_of_links
--;
1788 LOG(3, s
, 0, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
1789 if(bundle
[b
].num_of_links
== 0)
1792 LOG(3, s
, 0, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
1796 // Adjust the members array to accomodate the new change
1797 uint8_t mem_num
= 0;
1798 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
1799 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
1802 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
1803 if(bundle
[b
].members
[ml
] == s
)
1808 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
1809 LOG(3, s
, 0, "MPPP: Adjusted member links array\n");
1812 cluster_send_bundle(b
);
1816 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
1817 throttle_session(s
, 0, 0);
1821 controlt
*c
= controlnew(14); // sending CDN
1825 *(uint16_t *) buf
= htons(cdn_result
);
1826 *(uint16_t *) (buf
+2) = htons(cdn_error
);
1827 controlb(c
, 1, buf
, 4, 1);
1830 control16(c
, 1, cdn_result
, 1);
1832 control16(c
, 14, s
, 1); // assigned session (our end)
1833 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
1836 // update filter refcounts
1837 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
1838 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
1841 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
1842 sess_local
[s
].lcp
.restart
= 0;
1843 sess_local
[s
].ipcp
.restart
= 0;
1844 sess_local
[s
].ipv6cp
.restart
= 0;
1845 sess_local
[s
].ccp
.restart
= 0;
1847 cluster_send_session(s
);
1850 void sendipcp(sessionidt s
, tunnelidt t
)
1852 uint8_t buf
[MAXETHER
];
1856 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
1858 if (!session
[s
].unique_id
)
1860 if (!++last_id
) ++last_id
; // skip zero
1861 session
[s
].unique_id
= last_id
;
1864 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
1868 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
1869 *(uint16_t *) (q
+ 2) = htons(10); // packet length
1870 q
[4] = 3; // ip address option
1871 q
[5] = 6; // option length
1872 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
1873 config
->bind_address
? config
->bind_address
:
1874 my_address
; // send my IP
1876 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
1877 restart_timer(s
, ipcp
);
1880 void sendipv6cp(sessionidt s
, tunnelidt t
)
1882 uint8_t buf
[MAXETHER
];
1886 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
1888 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
1892 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
1893 // only send one type
1895 *(uint16_t *) (q
+ 2) = htons(14);
1896 q
[4] = 1; // interface identifier option
1897 q
[5] = 10; // option length
1898 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
1899 *(uint32_t *) (q
+ 10) = 0;
1902 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
1903 restart_timer(s
, ipv6cp
);
1906 static void sessionclear(sessionidt s
)
1908 memset(&session
[s
], 0, sizeof(session
[s
]));
1909 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
1910 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
1912 session
[s
].tunnel
= T_FREE
; // Mark it as free.
1913 session
[s
].next
= sessionfree
;
1917 // kill a session now
1918 void sessionkill(sessionidt s
, char *reason
)
1922 if (!session
[s
].opened
) // not alive
1925 if (session
[s
].next
)
1927 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
1931 if (!session
[s
].die
)
1932 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
1934 if (sess_local
[s
].radius
)
1935 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
1937 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
1939 cluster_send_session(s
);
1942 static void tunnelclear(tunnelidt t
)
1945 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
1946 tunnel
[t
].state
= TUNNELFREE
;
1949 static void bundleclear(bundleidt b
)
1952 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
1953 bundle
[b
].state
= BUNDLEFREE
;
1956 // kill a tunnel now
1957 static void tunnelkill(tunnelidt t
, char *reason
)
1964 tunnel
[t
].state
= TUNNELDIE
;
1966 // free control messages
1967 while ((c
= tunnel
[t
].controls
))
1969 controlt
* n
= c
->next
;
1970 tunnel
[t
].controls
= n
;
1971 tunnel
[t
].controlc
--;
1972 c
->next
= controlfree
;
1976 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1977 if (session
[s
].tunnel
== t
)
1978 sessionkill(s
, reason
);
1982 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
1983 cli_tunnel_actions
[t
].action
= 0;
1984 cluster_send_tunnel(t
);
1987 // shut down a tunnel cleanly
1988 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
1992 CSTAT(tunnelshutdown
);
1994 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
1996 // never set up, can immediately kill
1997 tunnelkill(t
, reason
);
2000 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2003 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2004 if (session
[s
].tunnel
== t
)
2005 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2007 tunnel
[t
].state
= TUNNELDIE
;
2008 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2009 cluster_send_tunnel(t
);
2010 // TBA - should we wait for sessions to stop?
2013 controlt
*c
= controlnew(4); // sending StopCCN
2018 *(uint16_t *) buf
= htons(result
);
2019 *(uint16_t *) (buf
+2) = htons(error
);
2022 int m
= strlen(msg
);
2023 if (m
+ 4 > sizeof(buf
))
2024 m
= sizeof(buf
) - 4;
2026 memcpy(buf
+4, msg
, m
);
2030 controlb(c
, 1, buf
, l
, 1);
2033 control16(c
, 1, result
, 1);
2035 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2036 controladd(c
, 0, t
); // send the message
2040 // read and process packet on tunnel (UDP)
2041 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2043 uint8_t *chapresponse
= NULL
;
2044 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2045 uint8_t *p
= buf
+ 2;
2052 LOG_HEX(5, "UDP Data", buf
, len
);
2053 STAT(tunnel_rx_packets
);
2054 INC_STAT(tunnel_rx_bytes
, len
);
2057 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2058 STAT(tunnel_rx_errors
);
2061 if ((buf
[1] & 0x0F) != 2)
2063 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2064 STAT(tunnel_rx_errors
);
2069 l
= ntohs(*(uint16_t *) p
);
2072 t
= ntohs(*(uint16_t *) p
);
2074 s
= ntohs(*(uint16_t *) p
);
2076 if (s
>= MAXSESSION
)
2078 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2079 STAT(tunnel_rx_errors
);
2084 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2085 STAT(tunnel_rx_errors
);
2090 ns
= ntohs(*(uint16_t *) p
);
2092 nr
= ntohs(*(uint16_t *) p
);
2097 uint16_t o
= ntohs(*(uint16_t *) p
);
2102 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2103 STAT(tunnel_rx_errors
);
2108 // used to time out old tunnels
2109 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2110 tunnel
[t
].lastrec
= time_now
;
2114 uint16_t message
= 0xFFFF; // message type
2116 uint8_t mandatory
= 0;
2117 uint16_t asession
= 0; // assigned session
2118 uint32_t amagic
= 0; // magic number
2119 uint8_t aflags
= 0; // flags from last LCF
2120 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2121 char called
[MAXTEL
] = ""; // called number
2122 char calling
[MAXTEL
] = ""; // calling number
2124 if (!config
->cluster_iam_master
)
2126 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2130 // control messages must have bits 0x80|0x40|0x08
2131 // (type, length and sequence) set, and bits 0x02|0x01
2132 // (offset and priority) clear
2133 if ((*buf
& 0xCB) != 0xC8)
2135 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2136 STAT(tunnel_rx_errors
);
2140 // check for duplicate tunnel open message
2146 // Is this a duplicate of the first packet? (SCCRQ)
2148 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2150 if (tunnel
[i
].state
!= TUNNELOPENING
||
2151 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2152 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2155 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2160 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2161 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2163 // if no tunnel specified, assign one
2166 if (!(t
= new_tunnel()))
2168 LOG(1, 0, 0, "No more tunnels\n");
2169 STAT(tunnel_overflow
);
2173 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2174 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2175 tunnel
[t
].window
= 4; // default window
2176 STAT(tunnel_created
);
2177 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2178 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2181 // If the 'ns' just received is not the 'nr' we're
2182 // expecting, just send an ack and drop it.
2184 // if 'ns' is less, then we got a retransmitted packet.
2185 // if 'ns' is greater than missed a packet. Either way
2186 // we should ignore it.
2187 if (ns
!= tunnel
[t
].nr
)
2189 // is this the sequence we were expecting?
2190 STAT(tunnel_rx_errors
);
2191 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2192 t
, ns
, tunnel
[t
].nr
);
2194 if (l
) // Is this not a ZLB?
2199 // check sequence of this message
2201 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2202 // some to clear maybe?
2203 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2205 controlt
*c
= tunnel
[t
].controls
;
2206 tunnel
[t
].controls
= c
->next
;
2207 tunnel
[t
].controlc
--;
2208 c
->next
= controlfree
;
2211 tunnel
[t
].try = 0; // we have progress
2214 // receiver advance (do here so quoted correctly in any sends below)
2215 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2216 if (skip
< 0) skip
= 0;
2217 if (skip
< tunnel
[t
].controlc
)
2219 // some control packets can now be sent that were previous stuck out of window
2220 int tosend
= tunnel
[t
].window
- skip
;
2221 controlt
*c
= tunnel
[t
].controls
;
2229 tunnel
[t
].try = 0; // first send
2230 tunnelsend(c
->buf
, c
->length
, t
);
2235 if (!tunnel
[t
].controlc
)
2236 tunnel
[t
].retry
= 0; // caught up
2239 { // if not a null message
2244 // Default disconnect cause/message on receipt of CDN. Set to
2245 // more specific value from attribute 1 (result code) or 46
2246 // (disconnect cause) if present below.
2247 int disc_cause_set
= 0;
2248 int disc_cause
= TERM_NAS_REQUEST
;
2249 char const *disc_reason
= "Closed (Received CDN).";
2252 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2254 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2261 LOG(1, s
, t
, "Invalid length in AVP\n");
2262 STAT(tunnel_rx_errors
);
2267 if (flags
& 0x3C) // reserved bits, should be clear
2269 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2271 result
= 2; // general error
2272 error
= 3; // reserved field non-zero
2277 if (*(uint16_t *) (b
))
2279 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2281 result
= 2; // general error
2282 error
= 6; // generic vendor-specific error
2283 msg
= "unsupported vendor-specific";
2287 mtype
= ntohs(*(uint16_t *) (b
));
2295 // handle hidden AVPs
2296 if (!*config
->l2tp_secret
)
2298 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2300 result
= 2; // general error
2301 error
= 6; // generic vendor-specific error
2302 msg
= "secret not specified";
2305 if (!session
[s
].random_vector_length
)
2307 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2309 result
= 2; // general error
2310 error
= 6; // generic
2311 msg
= "no random vector";
2316 LOG(2, s
, t
, "Short hidden AVP.\n");
2318 result
= 2; // general error
2319 error
= 2; // length is wrong
2325 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2327 orig_len
= ntohs(*(uint16_t *) b
);
2328 if (orig_len
> n
+ 2)
2330 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2334 result
= 2; // general error
2335 error
= 2; // length is wrong
2344 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2345 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2349 case 0: // message type
2350 message
= ntohs(*(uint16_t *) b
);
2351 mandatory
= flags
& 0x80;
2352 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2354 case 1: // result code
2356 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2357 char const *resdesc
= "(unknown)";
2358 char const *errdesc
= NULL
;
2363 resdesc
= l2tp_stopccn_result_code(rescode
);
2364 cause
= TERM_LOST_SERVICE
;
2366 else if (message
== 14)
2368 resdesc
= l2tp_cdn_result_code(rescode
);
2370 cause
= TERM_LOST_CARRIER
;
2372 cause
= TERM_ADMIN_RESET
;
2375 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2378 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2379 errdesc
= l2tp_error_code(errcode
);
2380 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2383 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2385 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2387 disc_cause_set
= mtype
;
2388 disc_reason
= errdesc
? errdesc
: resdesc
;
2395 case 2: // protocol version
2397 version
= ntohs(*(uint16_t *) (b
));
2398 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2399 if (version
&& version
!= 0x0100)
2400 { // allow 0.0 and 1.0
2401 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2403 result
= 5; // unspported protocol version
2404 error
= 0x0100; // supported version
2410 case 3: // framing capabilities
2412 case 4: // bearer capabilities
2414 case 5: // tie breaker
2415 // We never open tunnels, so we don't care about tie breakers
2417 case 6: // firmware revision
2419 case 7: // host name
2420 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2421 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2422 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2423 // TBA - to send to RADIUS
2425 case 8: // vendor name
2426 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2427 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2428 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2430 case 9: // assigned tunnel
2431 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2432 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2434 case 10: // rx window
2435 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2436 if (!tunnel
[t
].window
)
2437 tunnel
[t
].window
= 1; // window of 0 is silly
2438 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2440 case 11: // Challenge
2442 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2443 build_chap_response(b
, 2, n
, &chapresponse
);
2446 case 13: // Response
2447 // Why did they send a response? We never challenge.
2448 LOG(2, s
, t
, " received unexpected challenge response\n");
2451 case 14: // assigned session
2452 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2453 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2455 case 15: // call serial number
2456 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2458 case 18: // bearer type
2459 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2462 case 19: // framing type
2463 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2466 case 21: // called number
2467 memset(called
, 0, sizeof(called
));
2468 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2469 LOG(4, s
, t
, " Called <%s>\n", called
);
2471 case 22: // calling number
2472 memset(calling
, 0, sizeof(calling
));
2473 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2474 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2478 case 24: // tx connect speed
2481 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2485 // AS5300s send connect speed as a string
2487 memset(tmp
, 0, sizeof(tmp
));
2488 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2489 session
[s
].tx_connect_speed
= atol(tmp
);
2491 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2493 case 38: // rx connect speed
2496 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2500 // AS5300s send connect speed as a string
2502 memset(tmp
, 0, sizeof(tmp
));
2503 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2504 session
[s
].rx_connect_speed
= atol(tmp
);
2506 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2508 case 25: // Physical Channel ID
2510 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2511 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2514 case 29: // Proxy Authentication Type
2516 uint16_t atype
= ntohs(*(uint16_t *)b
);
2517 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2520 case 30: // Proxy Authentication Name
2523 memset(authname
, 0, sizeof(authname
));
2524 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2525 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2529 case 31: // Proxy Authentication Challenge
2531 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2534 case 32: // Proxy Authentication ID
2536 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2537 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2540 case 33: // Proxy Authentication Response
2541 LOG(4, s
, t
, " Proxy Auth Response\n");
2543 case 27: // last sent lcp
2544 { // find magic number
2545 uint8_t *p
= b
, *e
= p
+ n
;
2546 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2548 if (*p
== 5 && p
[1] == 6) // Magic-Number
2549 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2550 else if (*p
== 7) // Protocol-Field-Compression
2551 aflags
|= SESSION_PFC
;
2552 else if (*p
== 8) // Address-and-Control-Field-Compression
2553 aflags
|= SESSION_ACFC
;
2558 case 28: // last recv lcp confreq
2560 case 26: // Initial Received LCP CONFREQ
2562 case 39: // seq required - we control it as an LNS anyway...
2564 case 36: // Random Vector
2565 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2566 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2567 if (n
> sizeof(session
[s
].random_vector
))
2568 n
= sizeof(session
[s
].random_vector
);
2569 memcpy(session
[s
].random_vector
, b
, n
);
2570 session
[s
].random_vector_length
= n
;
2572 case 46: // ppp disconnect cause
2575 uint16_t code
= ntohs(*(uint16_t *) b
);
2576 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2577 uint8_t dir
= *(b
+ 4);
2579 LOG(4, s
, t
, " PPP disconnect cause "
2580 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2581 code
, proto
, dir
, n
- 5, b
+ 5);
2583 disc_cause_set
= mtype
;
2587 case 1: // admin disconnect
2588 disc_cause
= TERM_ADMIN_RESET
;
2589 disc_reason
= "Administrative disconnect";
2591 case 3: // lcp terminate
2592 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2593 disc_cause
= TERM_USER_REQUEST
;
2594 disc_reason
= "Normal disconnection";
2596 case 4: // compulsory encryption unavailable
2597 if (dir
!= 1) break; // 1=refused by peer, 2=local
2598 disc_cause
= TERM_USER_ERROR
;
2599 disc_reason
= "Compulsory encryption refused";
2601 case 5: // lcp: fsm timeout
2602 disc_cause
= TERM_PORT_ERROR
;
2603 disc_reason
= "LCP: FSM timeout";
2605 case 6: // lcp: no recognisable lcp packets received
2606 disc_cause
= TERM_PORT_ERROR
;
2607 disc_reason
= "LCP: no recognisable LCP packets";
2609 case 7: // lcp: magic-no error (possibly looped back)
2610 disc_cause
= TERM_PORT_ERROR
;
2611 disc_reason
= "LCP: magic-no error (possible loop)";
2613 case 8: // lcp: echo request timeout
2614 disc_cause
= TERM_PORT_ERROR
;
2615 disc_reason
= "LCP: echo request timeout";
2617 case 13: // auth: fsm timeout
2618 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2619 disc_reason
= "Authentication: FSM timeout";
2621 case 15: // auth: unacceptable auth protocol
2622 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2623 disc_reason
= "Unacceptable authentication protocol";
2625 case 16: // auth: authentication failed
2626 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2627 disc_reason
= "Authentication failed";
2629 case 17: // ncp: fsm timeout
2630 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2631 disc_reason
= "NCP: FSM timeout";
2633 case 18: // ncp: no ncps available
2634 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2635 disc_reason
= "NCP: no NCPs available";
2637 case 19: // ncp: failure to converge on acceptable address
2638 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2639 disc_reason
= (dir
== 1)
2640 ? "NCP: too many Configure-Naks received from peer"
2641 : "NCP: too many Configure-Naks sent to peer";
2643 case 20: // ncp: user not permitted to use any address
2644 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2645 disc_reason
= (dir
== 1)
2646 ? "NCP: local link address not acceptable to peer"
2647 : "NCP: remote link address not acceptable";
2654 static char e
[] = "unknown AVP 0xXXXX";
2655 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2657 result
= 2; // general error
2658 error
= 8; // unknown mandatory AVP
2659 sprintf((msg
= e
) + 14, "%04x", mtype
);
2666 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2670 case 1: // SCCRQ - Start Control Connection Request
2671 tunnel
[t
].state
= TUNNELOPENING
;
2672 if (main_quit
!= QUIT_SHUTDOWN
)
2674 controlt
*c
= controlnew(2); // sending SCCRP
2675 control16(c
, 2, version
, 1); // protocol version
2676 control32(c
, 3, 3, 1); // framing
2677 controls(c
, 7, hostname
, 1); // host name
2678 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2679 control16(c
, 9, t
, 1); // assigned tunnel
2680 controladd(c
, 0, t
); // send the resply
2684 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2688 tunnel
[t
].state
= TUNNELOPEN
;
2689 tunnel
[t
].lastrec
= time_now
;
2692 tunnel
[t
].state
= TUNNELOPEN
;
2693 tunnel
[t
].lastrec
= time_now
;
2694 controlnull(t
); // ack
2697 controlnull(t
); // ack
2698 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2701 controlnull(t
); // simply ACK
2713 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2715 controlt
*c
= controlnew(11); // ICRP
2718 sessionfree
= session
[s
].next
;
2719 memset(&session
[s
], 0, sizeof(session
[s
]));
2721 if (s
> config
->cluster_highest_sessionid
)
2722 config
->cluster_highest_sessionid
= s
;
2724 session
[s
].opened
= time_now
;
2725 session
[s
].tunnel
= t
;
2726 session
[s
].far
= asession
;
2727 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2728 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2729 control16(c
, 14, s
, 1); // assigned session
2730 controladd(c
, asession
, t
); // send the reply
2732 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2733 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2735 session
[s
].ppp
.phase
= Establish
;
2736 session
[s
].ppp
.lcp
= Starting
;
2738 STAT(session_created
);
2743 controlt
*c
= controlnew(14); // CDN
2746 STAT(session_overflow
);
2747 LOG(1, 0, t
, "No free sessions\n");
2748 control16(c
, 1, 4, 0); // temporary lack of resources
2751 control16(c
, 1, 2, 7); // shutting down, try another
2753 controladd(c
, asession
, t
); // send the message
2760 if (amagic
== 0) amagic
= time_now
;
2761 session
[s
].magic
= amagic
; // set magic number
2762 session
[s
].flags
= aflags
; // set flags received
2763 session
[s
].mru
= PPPoE_MRU
; // default
2764 controlnull(t
); // ack
2767 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
2768 sess_local
[s
].ppp_mru
= MRU
;
2770 // Set multilink options before sending initial LCP packet
2771 sess_local
[s
].mp_mrru
= 1614;
2772 sess_local
[s
].mp_epdis
= config
->bind_address
? config
->bind_address
: my_address
;
2775 change_state(s
, lcp
, RequestSent
);
2779 controlnull(t
); // ack
2780 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
2783 LOG(1, s
, t
, "Missing message type\n");
2786 STAT(tunnel_rx_errors
);
2788 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
2790 LOG(1, s
, t
, "Unknown message type %u\n", message
);
2793 if (chapresponse
) free(chapresponse
);
2794 cluster_send_tunnel(t
);
2798 LOG(4, s
, t
, " Got a ZLB ack\n");
2805 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
2806 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
2807 { // HDLC address header, discard
2813 LOG(1, s
, t
, "Short ppp length %d\n", l
);
2814 STAT(tunnel_rx_errors
);
2824 proto
= ntohs(*(uint16_t *) p
);
2829 if (s
&& !session
[s
].opened
) // Is something wrong??
2831 if (!config
->cluster_iam_master
)
2833 // Pass it off to the master to deal with..
2834 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2839 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
2840 STAT(tunnel_rx_errors
);
2844 if (proto
== PPPPAP
)
2846 session
[s
].last_packet
= time_now
;
2847 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2848 processpap(s
, t
, p
, l
);
2850 else if (proto
== PPPCHAP
)
2852 session
[s
].last_packet
= time_now
;
2853 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2854 processchap(s
, t
, p
, l
);
2856 else if (proto
== PPPLCP
)
2858 session
[s
].last_packet
= time_now
;
2859 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2860 processlcp(s
, t
, p
, l
);
2862 else if (proto
== PPPIPCP
)
2864 session
[s
].last_packet
= time_now
;
2865 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2866 processipcp(s
, t
, p
, l
);
2868 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
2870 session
[s
].last_packet
= time_now
;
2871 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2872 processipv6cp(s
, t
, p
, l
);
2874 else if (proto
== PPPCCP
)
2876 session
[s
].last_packet
= time_now
;
2877 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2878 processccp(s
, t
, p
, l
);
2880 else if (proto
== PPPIP
)
2884 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2885 return; // closing session, PPP not processed
2888 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2889 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2891 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2895 processipin(s
, t
, p
, l
);
2897 else if (proto
== PPPMP
)
2901 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2902 return; // closing session, PPP not processed
2905 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2906 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2908 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2912 processmpin(s
, t
, p
, l
);
2914 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
2918 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
2919 return; // closing session, PPP not processed
2922 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2923 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
2925 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2929 processipv6in(s
, t
, p
, l
);
2931 else if (session
[s
].ppp
.lcp
== Opened
)
2933 session
[s
].last_packet
= time_now
;
2934 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
2935 protoreject(s
, t
, p
, l
, proto
);
2939 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
2940 proto
, ppp_state(session
[s
].ppp
.lcp
));
2945 // read and process packet on tun
2946 static void processtun(uint8_t * buf
, int len
)
2948 LOG_HEX(5, "Receive TUN Data", buf
, len
);
2949 STAT(tun_rx_packets
);
2950 INC_STAT(tun_rx_bytes
, len
);
2958 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
2959 STAT(tun_rx_errors
);
2963 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
2964 processipout(buf
, len
);
2965 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
2966 && config
->ipv6_prefix
.s6_addr
[0])
2967 processipv6out(buf
, len
);
2972 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
2973 // that we look at the whole of the tunnel, radius and session tables
2975 static void regular_cleanups(double period
)
2977 // Next tunnel, radius and session to check for actions on.
2978 static tunnelidt t
= 0;
2980 static sessionidt s
= 0;
2993 // divide up tables into slices based on the last run
2994 t_slice
= config
->cluster_highest_tunnelid
* period
;
2995 r_slice
= (MAXRADIUS
- 1) * period
;
2996 s_slice
= config
->cluster_highest_sessionid
* period
;
3000 else if (t_slice
> config
->cluster_highest_tunnelid
)
3001 t_slice
= config
->cluster_highest_tunnelid
;
3005 else if (r_slice
> (MAXRADIUS
- 1))
3006 r_slice
= MAXRADIUS
- 1;
3010 else if (s_slice
> config
->cluster_highest_sessionid
)
3011 s_slice
= config
->cluster_highest_sessionid
;
3013 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3015 for (i
= 0; i
< t_slice
; i
++)
3018 if (t
> config
->cluster_highest_tunnelid
)
3021 // check for expired tunnels
3022 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3024 STAT(tunnel_timeout
);
3025 tunnelkill(t
, "Expired");
3029 // check for message resend
3030 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3032 // resend pending messages as timeout on reply
3033 if (tunnel
[t
].retry
<= TIME
)
3035 controlt
*c
= tunnel
[t
].controls
;
3036 uint16_t w
= tunnel
[t
].window
;
3037 tunnel
[t
].try++; // another try
3038 if (tunnel
[t
].try > 5)
3039 tunnelkill(t
, "Timeout on control message"); // game over
3043 tunnelsend(c
->buf
, c
->length
, t
);
3051 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3053 controlt
*c
= controlnew(6); // sending HELLO
3054 controladd(c
, 0, t
); // send the message
3055 LOG(3, 0, t
, "Sending HELLO message\n");
3059 // Check for tunnel changes requested from the CLI
3060 if ((a
= cli_tunnel_actions
[t
].action
))
3062 cli_tunnel_actions
[t
].action
= 0;
3063 if (a
& CLI_TUN_KILL
)
3065 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3066 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3072 for (i
= 0; i
< r_slice
; i
++)
3078 if (!radius
[r
].state
)
3081 if (radius
[r
].retry
<= TIME
)
3088 for (i
= 0; i
< s_slice
; i
++)
3091 if (s
> config
->cluster_highest_sessionid
)
3094 if (!session
[s
].opened
) // Session isn't in use
3097 // check for expired sessions
3100 if (session
[s
].die
<= TIME
)
3102 sessionkill(s
, "Expired");
3109 if (sess_local
[s
].lcp
.restart
<= time_now
)
3111 int next_state
= session
[s
].ppp
.lcp
;
3112 switch (session
[s
].ppp
.lcp
)
3116 next_state
= RequestSent
;
3119 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3121 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3122 sendlcp(s
, session
[s
].tunnel
);
3123 change_state(s
, lcp
, next_state
);
3127 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3128 STAT(session_timeout
);
3138 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3140 int next_state
= session
[s
].ppp
.ipcp
;
3141 switch (session
[s
].ppp
.ipcp
)
3145 next_state
= RequestSent
;
3148 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3150 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3151 sendipcp(s
, session
[s
].tunnel
);
3152 change_state(s
, ipcp
, next_state
);
3156 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3157 STAT(session_timeout
);
3167 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3169 int next_state
= session
[s
].ppp
.ipv6cp
;
3170 switch (session
[s
].ppp
.ipv6cp
)
3174 next_state
= RequestSent
;
3177 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3179 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3180 sendipv6cp(s
, session
[s
].tunnel
);
3181 change_state(s
, ipv6cp
, next_state
);
3185 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3186 change_state(s
, ipv6cp
, Stopped
);
3193 if (sess_local
[s
].ccp
.restart
<= time_now
)
3195 int next_state
= session
[s
].ppp
.ccp
;
3196 switch (session
[s
].ppp
.ccp
)
3200 next_state
= RequestSent
;
3203 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3205 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3206 sendccp(s
, session
[s
].tunnel
);
3207 change_state(s
, ccp
, next_state
);
3211 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3212 change_state(s
, ccp
, Stopped
);
3219 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3220 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3222 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3223 STAT(session_timeout
);
3228 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3229 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3230 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3232 uint8_t b
[MAXETHER
];
3234 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3238 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3239 *(uint16_t *)(q
+ 2) = htons(8); // Length
3240 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3242 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3243 (int)(time_now
- session
[s
].last_packet
));
3244 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3245 sess_local
[s
].last_echo
= time_now
;
3249 // Drop sessions who have reached session_timeout seconds
3250 if (session
[s
].session_timeout
)
3252 bundleidt bid
= session
[s
].bundle
;
3255 if (time_now
- bundle
[bid
].last_check
>= 1)
3257 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3258 bundle
[bid
].last_check
= time_now
;
3259 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3262 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3264 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3271 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3273 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3279 // Drop sessions who have reached idle_timeout seconds
3280 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3282 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3283 STAT(session_timeout
);
3288 // Check for actions requested from the CLI
3289 if ((a
= cli_session_actions
[s
].action
))
3293 cli_session_actions
[s
].action
= 0;
3294 if (a
& CLI_SESS_KILL
)
3296 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3297 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3298 a
= 0; // dead, no need to check for other actions
3302 if (a
& CLI_SESS_NOSNOOP
)
3304 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3305 session
[s
].snoop_ip
= 0;
3306 session
[s
].snoop_port
= 0;
3310 else if (a
& CLI_SESS_SNOOP
)
3312 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3313 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3314 cli_session_actions
[s
].snoop_port
);
3316 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3317 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3322 if (a
& CLI_SESS_NOTHROTTLE
)
3324 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3325 throttle_session(s
, 0, 0);
3329 else if (a
& CLI_SESS_THROTTLE
)
3331 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3332 cli_session_actions
[s
].throttle_in
,
3333 cli_session_actions
[s
].throttle_out
);
3335 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3340 if (a
& CLI_SESS_NOFILTER
)
3342 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3343 filter_session(s
, 0, 0);
3347 else if (a
& CLI_SESS_FILTER
)
3349 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3350 cli_session_actions
[s
].filter_in
,
3351 cli_session_actions
[s
].filter_out
);
3353 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3359 cluster_send_session(s
);
3362 // RADIUS interim accounting
3363 if (config
->radius_accounting
&& config
->radius_interim
> 0
3364 && session
[s
].ip
&& !session
[s
].walled_garden
3365 && !sess_local
[s
].radius
// RADIUS already in progress
3366 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3367 && session
[s
].flags
& SESSION_STARTED
)
3369 int rad
= radiusnew(s
);
3372 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3373 STAT(radius_overflow
);
3377 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3378 session
[s
].user
, session
[s
].unique_id
);
3380 radiussend(rad
, RADIUSINTERIM
);
3381 sess_local
[s
].last_interim
= time_now
;
3386 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3387 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3391 // Are we in the middle of a tunnel update, or radius
3394 static int still_busy(void)
3397 static clockt last_talked
= 0;
3398 static clockt start_busy_wait
= 0;
3400 if (!config
->cluster_iam_master
)
3403 static time_t stopped_bgp
= 0;
3408 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3410 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3411 if (bgp_peers
[i
].state
== Established
)
3412 bgp_stop(&bgp_peers
[i
]);
3414 stopped_bgp
= time_now
;
3416 // we don't want to become master
3417 cluster_send_ping(0);
3422 if (time_now
< (stopped_bgp
+ QUIT_DELAY
))
3430 if (main_quit
== QUIT_SHUTDOWN
)
3432 static int dropped
= 0;
3437 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3438 for (i
= 1; i
< MAXTUNNEL
; i
++)
3439 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3440 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3446 if (start_busy_wait
== 0)
3447 start_busy_wait
= TIME
;
3449 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3451 if (!tunnel
[i
].controlc
)
3454 if (last_talked
!= TIME
)
3456 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3462 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3463 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3465 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3469 for (i
= 1; i
< MAXRADIUS
; i
++)
3471 if (radius
[i
].state
== RADIUSNULL
)
3473 if (radius
[i
].state
== RADIUSWAIT
)
3476 if (last_talked
!= TIME
)
3478 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3488 # include <sys/epoll.h>
3490 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3491 # include "fake_epoll.h"
3494 // the base set of fds polled: cli, cluster, tun, udp, control, dae
3497 // additional polled fds
3499 # define EXTRA_FDS BGP_NUM_PEERS
3501 # define EXTRA_FDS 0
3504 // main loop - gets packets on tun or udp and processes them
3505 static void mainloop(void)
3509 clockt next_cluster_ping
= 0; // send initial ping immediately
3510 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3511 int maxevent
= sizeof(events
)/sizeof(*events
);
3513 if ((epollfd
= epoll_create(maxevent
)) < 0)
3515 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3519 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d\n",
3520 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
);
3522 /* setup our fds to poll for input */
3524 static struct event_data d
[BASE_FDS
];
3525 struct epoll_event e
;
3532 d
[i
].type
= FD_TYPE_CLI
;
3533 e
.data
.ptr
= &d
[i
++];
3534 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3537 d
[i
].type
= FD_TYPE_CLUSTER
;
3538 e
.data
.ptr
= &d
[i
++];
3539 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3541 d
[i
].type
= FD_TYPE_TUN
;
3542 e
.data
.ptr
= &d
[i
++];
3543 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3545 d
[i
].type
= FD_TYPE_UDP
;
3546 e
.data
.ptr
= &d
[i
++];
3547 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3549 d
[i
].type
= FD_TYPE_CONTROL
;
3550 e
.data
.ptr
= &d
[i
++];
3551 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3553 d
[i
].type
= FD_TYPE_DAE
;
3554 e
.data
.ptr
= &d
[i
++];
3555 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3559 signal(SIGPIPE
, SIG_IGN
);
3560 bgp_setup(config
->as_number
);
3561 if (config
->bind_address
)
3562 bgp_add_route(config
->bind_address
, 0xffffffff);
3564 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3566 if (config
->neighbour
[i
].name
[0])
3567 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3568 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3569 config
->neighbour
[i
].hold
, 0); /* 0 = routing disabled */
3573 while (!main_quit
|| still_busy())
3583 config
->reload_config
++;
3586 if (config
->reload_config
)
3588 config
->reload_config
= 0;
3596 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3597 STAT(select_called
);
3602 if (errno
== EINTR
||
3603 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3606 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3612 struct sockaddr_in addr
;
3613 struct in_addr local
;
3618 int cluster_ready
= 0;
3621 int cluster_pkts
= 0;
3623 uint32_t bgp_events
[BGP_NUM_PEERS
];
3624 memset(bgp_events
, 0, sizeof(bgp_events
));
3627 for (c
= n
, i
= 0; i
< c
; i
++)
3629 struct event_data
*d
= events
[i
].data
.ptr
;
3633 case FD_TYPE_CLI
: // CLI connections
3637 alen
= sizeof(addr
);
3638 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3644 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3650 // these are handled below, with multiple interleaved reads
3651 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3652 case FD_TYPE_TUN
: tun_ready
++; break;
3653 case FD_TYPE_UDP
: udp_ready
++; break;
3655 case FD_TYPE_CONTROL
: // nsctl commands
3656 alen
= sizeof(addr
);
3657 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3658 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3662 case FD_TYPE_DAE
: // DAE requests
3663 alen
= sizeof(addr
);
3664 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3665 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3669 case FD_TYPE_RADIUS
: // RADIUS response
3670 alen
= sizeof(addr
);
3671 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3672 if (s
>= 0 && config
->cluster_iam_master
)
3674 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3675 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3676 processrad(buf
, s
, d
->index
);
3678 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3679 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3687 bgp_events
[d
->index
] = events
[i
].events
;
3693 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3698 bgp_process(bgp_events
);
3701 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
3706 alen
= sizeof(addr
);
3707 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
3709 processudp(buf
, s
, &addr
);
3722 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
3737 alen
= sizeof(addr
);
3738 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
3740 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
3751 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
3752 STAT(multi_read_used
);
3754 if (c
>= config
->multi_read_count
)
3756 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
3757 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
3759 STAT(multi_read_exceeded
);
3766 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
3768 // Log current traffic stats
3769 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
3770 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
3771 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
3772 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
3773 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
3775 udp_tx
= udp_rx
= 0;
3776 udp_rx_pkt
= eth_rx_pkt
= 0;
3777 eth_tx
= eth_rx
= 0;
3780 if (config
->dump_speed
)
3781 printf("%s\n", config
->bandwidth
);
3783 // Update the internal time counter
3784 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
3788 struct param_timer p
= { time_now
};
3789 run_plugins(PLUGIN_TIMER
, &p
);
3793 // Runs on every machine (master and slaves).
3794 if (next_cluster_ping
<= TIME
)
3796 // Check to see which of the cluster is still alive..
3798 cluster_send_ping(basetime
); // Only does anything if we're a slave
3799 cluster_check_master(); // ditto.
3801 cluster_heartbeat(); // Only does anything if we're a master.
3802 cluster_check_slaves(); // ditto.
3804 master_update_counts(); // If we're a slave, send our byte counters to our master.
3806 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
3807 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
3809 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
3812 if (!config
->cluster_iam_master
)
3815 // Run token bucket filtering queue..
3816 // Only run it every 1/10th of a second.
3818 static clockt last_run
= 0;
3819 if (last_run
!= TIME
)
3826 // Handle timeouts, retries etc.
3828 static double last_clean
= 0;
3832 TIME
= now(&this_clean
);
3833 diff
= this_clean
- last_clean
;
3835 // Run during idle time (after we've handled
3836 // all incoming packets) or every 1/10th sec
3837 if (!more
|| diff
> 0.1)
3839 regular_cleanups(diff
);
3840 last_clean
= this_clean
;
3844 if (*config
->accounting_dir
)
3846 static clockt next_acct
= 0;
3847 static clockt next_shut_acct
= 0;
3849 if (next_acct
<= TIME
)
3851 // Dump accounting data
3852 next_acct
= TIME
+ ACCT_TIME
;
3853 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3856 else if (next_shut_acct
<= TIME
)
3858 // Dump accounting data for shutdown sessions
3859 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
3866 // Are we the master and shutting down??
3867 if (config
->cluster_iam_master
)
3868 cluster_heartbeat(); // Flush any queued changes..
3870 // Ok. Notify everyone we're shutting down. If we're
3871 // the master, this will force an election.
3872 cluster_send_ping(0);
3875 // Important!!! We MUST not process any packets past this point!
3876 LOG(1, 0, 0, "Shutdown complete\n");
3879 static void stripdomain(char *host
)
3883 if ((p
= strchr(host
, '.')))
3889 FILE *resolv
= fopen("/etc/resolv.conf", "r");
3895 while (fgets(buf
, sizeof(buf
), resolv
))
3897 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
3900 if (!isspace(buf
[6]))
3904 while (isspace(*b
)) b
++;
3909 while (*b
&& !isspace(*b
)) b
++;
3911 if (buf
[0] == 'd') // domain is canonical
3917 // first search line
3920 // hold, may be subsequent domain line
3921 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
3932 int hl
= strlen(host
);
3933 int dl
= strlen(domain
);
3934 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
3935 host
[hl
-dl
- 1] = 0;
3939 *p
= 0; // everything after first dot
3944 // Init data structures
3945 static void initdata(int optdebug
, char *optconfig
)
3949 if (!(config
= shared_malloc(sizeof(configt
))))
3951 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
3955 memset(config
, 0, sizeof(configt
));
3956 time(&config
->start_time
);
3957 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
3958 config
->debug
= optdebug
;
3959 config
->num_tbfs
= MAXTBFS
;
3960 config
->rl_rate
= 28; // 28kbps
3961 config
->cluster_mcast_ttl
= 1;
3962 config
->cluster_master_min_adv
= 1;
3963 config
->ppp_restart_time
= 3;
3964 config
->ppp_max_configure
= 10;
3965 config
->ppp_max_failure
= 5;
3966 config
->kill_timedout_sessions
= 1;
3967 strcpy(config
->random_device
, RANDOMDEVICE
);
3969 log_stream
= stderr
;
3972 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
3974 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
3977 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
3980 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
3982 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
3985 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
3987 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
3990 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
3992 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
3995 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
3997 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4000 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4002 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4006 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4008 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4012 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4014 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4018 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4020 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4024 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4026 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4029 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4031 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4033 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4036 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4038 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4040 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4043 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4045 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4046 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4047 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4048 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4049 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4051 // Put all the sessions on the free list marked as undefined.
4052 for (i
= 1; i
< MAXSESSION
; i
++)
4054 session
[i
].next
= i
+ 1;
4055 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4057 session
[MAXSESSION
- 1].next
= 0;
4060 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4061 for (i
= 1; i
< MAXTUNNEL
; i
++)
4062 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4064 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4065 bundle
[i
].state
= BUNDLEUNDEF
;
4070 // Grab my hostname unless it's been specified
4071 gethostname(hostname
, sizeof(hostname
));
4072 stripdomain(hostname
);
4075 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4078 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4080 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4086 static int assign_ip_address(sessionidt s
)
4090 time_t best_time
= time_now
;
4091 char *u
= session
[s
].user
;
4095 CSTAT(assign_ip_address
);
4097 for (i
= 1; i
< ip_pool_size
; i
++)
4099 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4102 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4109 if (ip_address_pool
[i
].last
< best_time
)
4112 if (!(best_time
= ip_address_pool
[i
].last
))
4113 break; // never used, grab this one
4119 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4123 session
[s
].ip
= ip_address_pool
[best
].address
;
4124 session
[s
].ip_pool_index
= best
;
4125 ip_address_pool
[best
].assigned
= 1;
4126 ip_address_pool
[best
].last
= time_now
;
4127 ip_address_pool
[best
].session
= s
;
4128 if (session
[s
].walled_garden
)
4129 /* Don't track addresses of users in walled garden (note: this
4130 means that their address isn't "sticky" even if they get
4132 ip_address_pool
[best
].user
[0] = 0;
4134 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4137 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4138 reuse
? "Reusing" : "Allocating", best
);
4143 static void free_ip_address(sessionidt s
)
4145 int i
= session
[s
].ip_pool_index
;
4148 CSTAT(free_ip_address
);
4151 return; // what the?
4153 if (i
< 0) // Is this actually part of the ip pool?
4157 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4159 ip_address_pool
[i
].assigned
= 0;
4160 ip_address_pool
[i
].session
= 0;
4161 ip_address_pool
[i
].last
= time_now
;
4165 // Fsck the address pool against the session table.
4166 // Normally only called when we become a master.
4168 // This isn't perfect: We aren't keep tracking of which
4169 // users used to have an IP address.
4171 void rebuild_address_pool(void)
4176 // Zero the IP pool allocation, and build
4177 // a map from IP address to pool index.
4178 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4180 ip_address_pool
[i
].assigned
= 0;
4181 ip_address_pool
[i
].session
= 0;
4182 if (!ip_address_pool
[i
].address
)
4185 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4188 for (i
= 0; i
< MAXSESSION
; ++i
)
4191 if (!(session
[i
].opened
&& session
[i
].ip
))
4194 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4196 if (session
[i
].ip_pool_index
< 0)
4198 // Not allocated out of the pool.
4199 if (ipid
< 1) // Not found in the pool either? good.
4202 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4203 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4205 // Fall through and process it as part of the pool.
4209 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4211 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4213 session
[i
].ip_pool_index
= ipid
;
4217 ip_address_pool
[ipid
].assigned
= 1;
4218 ip_address_pool
[ipid
].session
= i
;
4219 ip_address_pool
[ipid
].last
= time_now
;
4220 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4221 session
[i
].ip_pool_index
= ipid
;
4222 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4227 // Fix the address pool to match a changed session.
4228 // (usually when the master sends us an update).
4229 static void fix_address_pool(int sid
)
4233 ipid
= session
[sid
].ip_pool_index
;
4235 if (ipid
> ip_pool_size
)
4236 return; // Ignore it. rebuild_address_pool will fix it up.
4238 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4239 return; // Just ignore it. rebuild_address_pool will take care of it.
4241 ip_address_pool
[ipid
].assigned
= 1;
4242 ip_address_pool
[ipid
].session
= sid
;
4243 ip_address_pool
[ipid
].last
= time_now
;
4244 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4248 // Add a block of addresses to the IP pool to hand out.
4250 static void add_to_ip_pool(in_addr_t addr
, in_addr_t mask
)
4254 mask
= 0xffffffff; // Host route only.
4258 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4261 for (i
= addr
;(i
& mask
) == addr
; ++i
)
4263 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4264 continue; // Skip 0 and broadcast addresses.
4266 ip_address_pool
[ip_pool_size
].address
= i
;
4267 ip_address_pool
[ip_pool_size
].assigned
= 0;
4269 if (ip_pool_size
>= MAXIPPOOL
)
4271 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4277 // Initialize the IP address pool
4278 static void initippool()
4283 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4285 if (!(f
= fopen(IPPOOLFILE
, "r")))
4287 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4291 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4294 buf
[4095] = 0; // Force it to be zero terminated/
4296 if (*buf
== '#' || *buf
== '\n')
4297 continue; // Skip comments / blank lines
4298 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4299 if ((p
= (char *)strchr(buf
, ':')))
4303 src
= inet_addr(buf
);
4304 if (src
== INADDR_NONE
)
4306 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4309 // This entry is for a specific IP only
4310 if (src
!= config
->bind_address
)
4315 if ((p
= (char *)strchr(pool
, '/')))
4319 in_addr_t start
= 0, mask
= 0;
4321 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4323 if (!*p
|| !(numbits
= atoi(p
)))
4325 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4328 start
= ntohl(inet_addr(pool
));
4329 mask
= (in_addr_t
) (pow(2, numbits
) - 1) << (32 - numbits
);
4331 // Add a static route for this pool
4332 LOG(5, 0, 0, "Adding route for address pool %s/%u\n",
4333 fmtaddr(htonl(start
), 0), 32 + mask
);
4335 routeset(0, start
, mask
, 0, 1);
4337 add_to_ip_pool(start
, mask
);
4341 // It's a single ip address
4342 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4346 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4349 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4351 struct sockaddr_in snoop_addr
= {0};
4352 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4355 snoop_addr
.sin_family
= AF_INET
;
4356 snoop_addr
.sin_addr
.s_addr
= destination
;
4357 snoop_addr
.sin_port
= ntohs(port
);
4359 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4360 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4361 htons(snoop_addr
.sin_port
));
4363 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4364 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4366 STAT(packets_snooped
);
4369 static int dump_session(FILE **f
, sessiont
*s
)
4371 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4376 char filename
[1024];
4378 time_t now
= time(NULL
);
4380 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4381 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4383 if (!(*f
= fopen(filename
, "w")))
4385 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4389 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4390 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4395 "# format: username ip qos uptxoctets downrxoctets\n",
4397 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4402 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4403 fprintf(*f
, "%s %s %d %u %u\n",
4404 s
->user
, // username
4405 fmtaddr(htonl(s
->ip
), 0), // ip
4406 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4407 (uint32_t) s
->cin_delta
, // uptxoctets
4408 (uint32_t) s
->cout_delta
); // downrxoctets
4410 s
->cin_delta
= s
->cout_delta
= 0;
4415 static void dump_acct_info(int all
)
4421 CSTAT(dump_acct_info
);
4425 for (i
= 0; i
< shut_acct_n
; i
++)
4426 dump_session(&f
, &shut_acct
[i
]);
4432 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4433 dump_session(&f
, &session
[i
]);
4440 int main(int argc
, char *argv
[])
4444 char *optconfig
= CONFIGFILE
;
4446 time(&basetime
); // start clock
4449 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4454 if (fork()) exit(0);
4456 freopen("/dev/null", "r", stdin
);
4457 freopen("/dev/null", "w", stdout
);
4458 freopen("/dev/null", "w", stderr
);
4467 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4470 printf("Args are:\n"
4471 "\t-d\t\tDetach from terminal\n"
4472 "\t-c <file>\tConfig file\n"
4473 "\t-h <hostname>\tForce hostname\n"
4481 // Start the timer routine off
4483 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4486 initdata(optdebug
, optconfig
);
4491 init_tbf(config
->num_tbfs
);
4493 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4494 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4495 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4498 rlim
.rlim_cur
= RLIM_INFINITY
;
4499 rlim
.rlim_max
= RLIM_INFINITY
;
4500 // Remove the maximum core size
4501 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4502 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4504 // Make core dumps go to /tmp
4508 if (config
->scheduler_fifo
)
4511 struct sched_param params
= {0};
4512 params
.sched_priority
= 1;
4514 if (get_nprocs() < 2)
4516 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4517 config
->scheduler_fifo
= 0;
4521 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4523 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4527 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4528 config
->scheduler_fifo
= 0;
4533 /* Set up the cluster communications port. */
4534 if (cluster_init() < 0)
4538 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4546 unsigned seed
= time_now
^ getpid();
4547 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4551 signal(SIGHUP
, sighup_handler
);
4552 signal(SIGCHLD
, sigchild_handler
);
4553 signal(SIGTERM
, shutdown_handler
);
4554 signal(SIGINT
, shutdown_handler
);
4555 signal(SIGQUIT
, shutdown_handler
);
4557 // Prevent us from getting paged out
4558 if (config
->lock_pages
)
4560 if (!mlockall(MCL_CURRENT
))
4561 LOG(1, 0, 0, "Locking pages into memory\n");
4563 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4568 /* remove plugins (so cleanup code gets run) */
4571 // Remove the PID file if we wrote it
4572 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4573 unlink(config
->pid_file
);
4575 /* kill CLI children */
4576 signal(SIGTERM
, SIG_IGN
);
4581 static void sighup_handler(int sig
)
4586 static void shutdown_handler(int sig
)
4588 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4591 static void sigchild_handler(int sig
)
4593 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4597 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4600 *challenge_response
= NULL
;
4602 if (!*config
->l2tp_secret
)
4604 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4608 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4610 *challenge_response
= calloc(17, 1);
4613 MD5_Update(&ctx
, &id
, 1);
4614 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4615 MD5_Update(&ctx
, challenge
, challenge_length
);
4616 MD5_Final(*challenge_response
, &ctx
);
4621 static int facility_value(char *name
)
4624 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4626 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4627 return facilitynames
[i
].c_val
;
4632 static void update_config()
4636 static int timeout
= 0;
4637 static int interval
= 0;
4644 if (log_stream
!= stderr
)
4650 if (*config
->log_filename
)
4652 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4654 char *p
= config
->log_filename
+ 7;
4657 openlog("l2tpns", LOG_PID
, facility_value(p
));
4661 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4663 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4665 fseek(log_stream
, 0, SEEK_END
);
4666 setbuf(log_stream
, NULL
);
4670 log_stream
= stderr
;
4671 setbuf(log_stream
, NULL
);
4677 log_stream
= stderr
;
4678 setbuf(log_stream
, NULL
);
4681 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4682 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4684 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4685 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4686 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4688 // reset MRU/MSS globals
4689 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4690 if (MRU
> PPPoE_MRU
)
4693 MSS
= MRU
- TCP_HDRS
;
4696 config
->numradiusservers
= 0;
4697 for (i
= 0; i
< MAXRADSERVER
; i
++)
4698 if (config
->radiusserver
[i
])
4700 config
->numradiusservers
++;
4701 // Set radius port: if not set, take the port from the
4702 // first radius server. For the first radius server,
4703 // take the #defined default value from l2tpns.h
4705 // test twice, In case someone works with
4706 // a secondary radius server without defining
4707 // a primary one, this will work even then.
4708 if (i
> 0 && !config
->radiusport
[i
])
4709 config
->radiusport
[i
] = config
->radiusport
[i
-1];
4710 if (!config
->radiusport
[i
])
4711 config
->radiusport
[i
] = RADPORT
;
4714 if (!config
->numradiusservers
)
4715 LOG(0, 0, 0, "No RADIUS servers defined!\n");
4717 // parse radius_authtypes_s
4718 config
->radius_authtypes
= config
->radius_authprefer
= 0;
4719 p
= config
->radius_authtypes_s
;
4722 char *s
= strpbrk(p
, " \t,");
4728 while (*s
== ' ' || *s
== '\t')
4735 if (!strncasecmp("chap", p
, strlen(p
)))
4737 else if (!strncasecmp("pap", p
, strlen(p
)))
4740 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
4742 config
->radius_authtypes
|= type
;
4743 if (!config
->radius_authprefer
)
4744 config
->radius_authprefer
= type
;
4749 if (!config
->radius_authtypes
)
4751 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
4752 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
4755 // normalise radius_authtypes_s
4756 if (config
->radius_authprefer
== AUTHPAP
)
4758 strcpy(config
->radius_authtypes_s
, "pap");
4759 if (config
->radius_authtypes
& AUTHCHAP
)
4760 strcat(config
->radius_authtypes_s
, ", chap");
4764 strcpy(config
->radius_authtypes_s
, "chap");
4765 if (config
->radius_authtypes
& AUTHPAP
)
4766 strcat(config
->radius_authtypes_s
, ", pap");
4769 if (!config
->radius_dae_port
)
4770 config
->radius_dae_port
= DAEPORT
;
4772 // re-initialise the random number source
4773 initrandom(config
->random_device
);
4776 for (i
= 0; i
< MAXPLUGINS
; i
++)
4778 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
4781 if (*config
->plugins
[i
])
4784 add_plugin(config
->plugins
[i
]);
4786 else if (*config
->old_plugins
[i
])
4789 remove_plugin(config
->old_plugins
[i
]);
4794 guest_accounts_num
= 0;
4795 char *p2
= config
->guest_user
;
4798 char *s
= strpbrk(p2
, " \t,");
4802 while (*s
== ' ' || *s
== '\t')
4809 strcpy(guest_users
[guest_accounts_num
], p2
);
4810 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
4811 guest_accounts_num
++;
4814 // Rebuild the guest_user array
4815 strcpy(config
->guest_user
, "");
4817 for (ui
=0; ui
<guest_accounts_num
; ui
++)
4819 strcat(config
->guest_user
, guest_users
[ui
]);
4820 if (ui
<guest_accounts_num
-1)
4822 strcat(config
->guest_user
, ",");
4827 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
4828 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
4829 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
4830 if (!*config
->cluster_interface
)
4831 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
4833 if (!config
->cluster_hb_interval
)
4834 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
4836 if (!config
->cluster_hb_timeout
)
4837 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
4839 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
4841 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
4842 // late, ensure we're sufficiently larger than that
4843 int t
= 4 * config
->cluster_hb_interval
+ 11;
4845 if (config
->cluster_hb_timeout
< t
)
4847 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
4848 config
->cluster_hb_timeout
= t
;
4851 // Push timing changes to the slaves immediately if we're the master
4852 if (config
->cluster_iam_master
)
4853 cluster_heartbeat();
4855 interval
= config
->cluster_hb_interval
;
4856 timeout
= config
->cluster_hb_timeout
;
4860 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
4863 if ((f
= fopen(config
->pid_file
, "w")))
4865 fprintf(f
, "%d\n", getpid());
4867 config
->wrote_pid
= 1;
4871 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
4876 static void read_config_file()
4880 if (!config
->config_file
) return;
4881 if (!(f
= fopen(config
->config_file
, "r")))
4883 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
4887 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
4889 LOG(3, 0, 0, "Done reading config file\n");
4893 int sessionsetup(sessionidt s
, tunnelidt t
)
4895 // A session now exists, set it up
4901 CSTAT(sessionsetup
);
4903 LOG(3, s
, t
, "Doing session setup for session\n");
4905 // Join a bundle if the MRRU option is accepted
4906 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
4908 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
4909 if (join_bundle(s
) > 0)
4910 cluster_send_bundle(session
[s
].bundle
);
4913 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
4914 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
4921 assign_ip_address(s
);
4924 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
4925 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
4928 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
4929 fmtaddr(htonl(session
[s
].ip
), 0));
4933 // Make sure this is right
4934 session
[s
].tunnel
= t
;
4936 // zap old sessions with same IP and/or username
4937 // Don't kill gardened sessions - doing so leads to a DoS
4938 // from someone who doesn't need to know the password
4941 user
= session
[s
].user
;
4942 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4944 if (i
== s
) continue;
4945 if (!session
[s
].opened
) continue;
4946 // Allow duplicate sessions for multilink ones of the same bundle.
4947 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
4949 if (ip
== session
[i
].ip
)
4951 sessionkill(i
, "Duplicate IP address");
4955 if (config
->allow_duplicate_users
) continue;
4956 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
4960 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
4962 if (!strcasecmp(user
, guest_users
[gu
]))
4968 if (found
) continue;
4970 // Drop the new session in case of duplicate sessionss, not the old one.
4971 if (!strcasecmp(user
, session
[i
].user
))
4972 sessionkill(i
, "Duplicate session for users");
4976 // no need to set a route for the same IP address of the bundle
4977 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
4981 // Add the route for this session.
4982 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
4984 if ((session
[s
].ip
& session
[s
].route
[r
].mask
) ==
4985 (session
[s
].route
[r
].ip
& session
[s
].route
[r
].mask
))
4988 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].mask
, 0, 1);
4991 // Static IPs need to be routed if not already
4992 // convered by a Framed-Route. Anything else is part
4993 // of the IP address pool and is already routed, it
4994 // just needs to be added to the IP cache.
4995 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
4996 if (session
[s
].ip_pool_index
== -1) // static ip
4998 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5001 cache_ipmap(session
[s
].ip
, s
);
5004 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5005 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5007 // Run the plugin's against this new session.
5009 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5010 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5013 // Allocate TBFs if throttled
5014 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5015 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5017 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5019 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5020 fmtaddr(htonl(session
[s
].ip
), 0),
5021 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5023 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5025 return 1; // RADIUS OK and IP allocated, done...
5029 // This session just got dropped on us by the master or something.
5030 // Make sure our tables up up to date...
5032 int load_session(sessionidt s
, sessiont
*new)
5038 if (new->ip_pool_index
>= MAXIPPOOL
||
5039 new->tunnel
>= MAXTUNNEL
)
5041 LOG(0, s
, 0, "Strange session update received!\n");
5042 // FIXME! What to do here?
5047 // Ok. All sanity checks passed. Now we're committed to
5048 // loading the new session.
5051 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5053 // See if routes/ip cache need updating
5054 if (new->ip
!= session
[s
].ip
)
5057 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5058 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5059 new->route
[i
].mask
!= session
[s
].route
[i
].mask
)
5067 // remove old routes...
5068 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5070 if ((session
[s
].ip
& session
[s
].route
[i
].mask
) ==
5071 (session
[s
].route
[i
].ip
& session
[s
].route
[i
].mask
))
5074 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].mask
, 0, 0);
5080 if (session
[s
].ip_pool_index
== -1) // static IP
5082 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5084 else // It's part of the IP pool, remove it manually.
5085 uncache_ipmap(session
[s
].ip
);
5090 // add new routes...
5091 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5093 if ((new->ip
& new->route
[i
].mask
) ==
5094 (new->route
[i
].ip
& new->route
[i
].mask
))
5097 routeset(s
, new->route
[i
].ip
, new->route
[i
].mask
, 0, 1);
5103 // If there's a new one, add it.
5104 if (new->ip_pool_index
== -1)
5106 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5109 cache_ipmap(new->ip
, s
);
5114 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5115 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5118 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5120 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5124 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5126 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5127 new->filter_out
= 0;
5130 if (new->filter_in
!= session
[s
].filter_in
)
5132 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5133 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5136 if (new->filter_out
!= session
[s
].filter_out
)
5138 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5139 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5142 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5143 // for walking the sessions to forward byte counts to the master.
5144 config
->cluster_highest_sessionid
= s
;
5146 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5148 // Do fixups into address pool.
5149 if (new->ip_pool_index
!= -1)
5150 fix_address_pool(s
);
5155 static void initplugins()
5159 loaded_plugins
= ll_init();
5160 // Initialize the plugins to nothing
5161 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5162 plugins
[i
] = ll_init();
5165 static void *open_plugin(char *plugin_name
, int load
)
5167 char path
[256] = "";
5169 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5170 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5171 return dlopen(path
, RTLD_NOW
);
5174 // plugin callback to get a config value
5175 static void *getconfig(char *key
, enum config_typet type
)
5179 for (i
= 0; config_values
[i
].key
; i
++)
5181 if (!strcmp(config_values
[i
].key
, key
))
5183 if (config_values
[i
].type
== type
)
5184 return ((void *) config
) + config_values
[i
].offset
;
5186 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5187 key
, type
, config_values
[i
].type
);
5193 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5197 static int add_plugin(char *plugin_name
)
5199 static struct pluginfuncs funcs
= {
5204 sessiontbysessionidt
,
5205 sessionidtbysessiont
,
5212 cluster_send_session
,
5215 void *p
= open_plugin(plugin_name
, 1);
5216 int (*initfunc
)(struct pluginfuncs
*);
5221 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5225 if (ll_contains(loaded_plugins
, p
))
5228 return 0; // already loaded
5232 int *v
= dlsym(p
, "plugin_api_version");
5233 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5235 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5241 if ((initfunc
= dlsym(p
, "plugin_init")))
5243 if (!initfunc(&funcs
))
5245 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5251 ll_push(loaded_plugins
, p
);
5253 for (i
= 0; i
< max_plugin_functions
; i
++)
5256 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5258 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5259 ll_push(plugins
[i
], x
);
5263 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5267 static void run_plugin_done(void *plugin
)
5269 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5275 static int remove_plugin(char *plugin_name
)
5277 void *p
= open_plugin(plugin_name
, 0);
5283 if (ll_contains(loaded_plugins
, p
))
5286 for (i
= 0; i
< max_plugin_functions
; i
++)
5289 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5290 ll_delete(plugins
[i
], x
);
5293 ll_delete(loaded_plugins
, p
);
5299 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5303 int run_plugins(int plugin_type
, void *data
)
5305 int (*func
)(void *data
);
5307 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5308 return PLUGIN_RET_ERROR
;
5310 ll_reset(plugins
[plugin_type
]);
5311 while ((func
= ll_next(plugins
[plugin_type
])))
5315 if (r
!= PLUGIN_RET_OK
)
5316 return r
; // stop here
5319 return PLUGIN_RET_OK
;
5322 static void plugins_done()
5326 ll_reset(loaded_plugins
);
5327 while ((p
= ll_next(loaded_plugins
)))
5331 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5333 struct nsctl request
;
5334 struct nsctl response
;
5335 int type
= unpack_control(&request
, buf
, len
);
5339 if (log_stream
&& config
->debug
>= 4)
5343 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5344 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5348 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5349 dump_control(&request
, log_stream
);
5355 case NSCTL_REQ_LOAD
:
5356 if (request
.argc
!= 1)
5358 response
.type
= NSCTL_RES_ERR
;
5360 response
.argv
[0] = "name of plugin required";
5362 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5364 response
.type
= NSCTL_RES_ERR
;
5366 response
.argv
[0] = !r
5367 ? "plugin already loaded"
5368 : "error loading plugin";
5372 response
.type
= NSCTL_RES_OK
;
5378 case NSCTL_REQ_UNLOAD
:
5379 if (request
.argc
!= 1)
5381 response
.type
= NSCTL_RES_ERR
;
5383 response
.argv
[0] = "name of plugin required";
5385 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5387 response
.type
= NSCTL_RES_ERR
;
5389 response
.argv
[0] = !r
5390 ? "plugin not loaded"
5391 : "plugin not found";
5395 response
.type
= NSCTL_RES_OK
;
5401 case NSCTL_REQ_HELP
:
5402 response
.type
= NSCTL_RES_OK
;
5405 ll_reset(loaded_plugins
);
5406 while ((p
= ll_next(loaded_plugins
)))
5408 char **help
= dlsym(p
, "plugin_control_help");
5409 while (response
.argc
< 0xff && help
&& *help
)
5410 response
.argv
[response
.argc
++] = *help
++;
5415 case NSCTL_REQ_CONTROL
:
5417 struct param_control param
= {
5418 config
->cluster_iam_master
,
5425 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5427 if (r
== PLUGIN_RET_ERROR
)
5429 response
.type
= NSCTL_RES_ERR
;
5431 response
.argv
[0] = param
.additional
5433 : "error returned by plugin";
5435 else if (r
== PLUGIN_RET_NOTMASTER
)
5437 static char msg
[] = "must be run on master: 000.000.000.000";
5439 response
.type
= NSCTL_RES_ERR
;
5441 if (config
->cluster_master_address
)
5443 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5444 response
.argv
[0] = msg
;
5448 response
.argv
[0] = "must be run on master: none elected";
5451 else if (!(param
.response
& NSCTL_RESPONSE
))
5453 response
.type
= NSCTL_RES_ERR
;
5455 response
.argv
[0] = param
.response
5456 ? "unrecognised response value from plugin"
5457 : "unhandled action";
5461 response
.type
= param
.response
;
5463 if (param
.additional
)
5466 response
.argv
[0] = param
.additional
;
5474 response
.type
= NSCTL_RES_ERR
;
5476 response
.argv
[0] = "error unpacking control packet";
5479 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5482 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5486 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5489 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5490 if (log_stream
&& config
->debug
>= 4)
5492 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5493 dump_control(&response
, log_stream
);
5497 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5498 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5503 static tunnelidt
new_tunnel()
5506 for (i
= 1; i
< MAXTUNNEL
; i
++)
5508 if (tunnel
[i
].state
== TUNNELFREE
)
5510 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5511 if (i
> config
->cluster_highest_tunnelid
)
5512 config
->cluster_highest_tunnelid
= i
;
5516 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5521 // We're becoming the master. Do any required setup..
5523 // This is principally telling all the plugins that we're
5524 // now a master, and telling them about all the sessions
5525 // that are active too..
5527 void become_master(void)
5530 static struct event_data d
[RADIUS_FDS
];
5531 struct epoll_event e
;
5533 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5535 // running a bunch of iptables commands is slow and can cause
5536 // the master to drop tunnels on takeover--kludge around the
5537 // problem by forking for the moment (note: race)
5538 if (!fork_and_close())
5540 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5542 if (!session
[s
].opened
) // Not an in-use session.
5545 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5552 for (i
= 0; i
< RADIUS_FDS
; i
++)
5554 d
[i
].type
= FD_TYPE_RADIUS
;
5558 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5562 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5568 if (CLI_HELP_REQUESTED
)
5569 return CLI_HELP_NO_ARGS
;
5572 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5574 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5577 if (!session
[s
].opened
)
5580 idle
= time_now
- session
[s
].last_data
;
5581 idle
/= 5 ; // In multiples of 5 seconds.
5591 for (i
= 0; i
< 63; ++i
)
5593 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5595 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5596 cli_print(cli
, "%d total sessions open.", count
);
5600 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5606 if (CLI_HELP_REQUESTED
)
5607 return CLI_HELP_NO_ARGS
;
5610 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5612 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5615 if (!session
[s
].opened
)
5618 d
= time_now
- session
[s
].opened
;
5621 while (d
> 1 && open
< 32)
5631 for (i
= 0; i
< 30; ++i
)
5633 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5636 cli_print(cli
, "%d total sessions open.", count
);
5642 * This unencodes the AVP using the L2TP secret and the previously
5643 * stored random vector. It overwrites the hidden data with the
5644 * unhidden AVP subformat.
5646 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5652 uint16_t m
= htons(type
);
5654 // Compute initial pad
5656 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5657 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5658 MD5_Update(&ctx
, vector
, vec_len
);
5659 MD5_Final(digest
, &ctx
);
5661 // pointer to last decoded 16 octets
5666 // calculate a new pad based on the last decoded block
5667 if (d
>= sizeof(digest
))
5670 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5671 MD5_Update(&ctx
, last
, sizeof(digest
));
5672 MD5_Final(digest
, &ctx
);
5678 *value
++ ^= digest
[d
++];
5683 int find_filter(char const *name
, size_t len
)
5688 for (i
= 0; i
< MAXFILTER
; i
++)
5690 if (!*ip_filters
[i
].name
)
5698 if (strlen(ip_filters
[i
].name
) != len
)
5701 if (!strncmp(ip_filters
[i
].name
, name
, len
))
5708 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
5712 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
5713 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
5714 case FILTER_PORT_OP_GT
: return port
> p
->port
;
5715 case FILTER_PORT_OP_LT
: return port
< p
->port
;
5716 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
5722 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
5726 case FILTER_FLAG_OP_ANY
:
5727 return (flags
& sflags
) || (~flags
& cflags
);
5729 case FILTER_FLAG_OP_ALL
:
5730 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
5732 case FILTER_FLAG_OP_EST
:
5733 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
5739 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
5741 uint16_t frag_offset
;
5745 uint16_t src_port
= 0;
5746 uint16_t dst_port
= 0;
5748 ip_filter_rulet
*rule
;
5750 if (len
< 20) // up to end of destination address
5753 if ((*buf
>> 4) != 4) // IPv4
5756 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
5758 src_ip
= *(in_addr_t
*) (buf
+ 12);
5759 dst_ip
= *(in_addr_t
*) (buf
+ 16);
5761 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
5763 int l
= (buf
[0] & 0xf) * 4; // length of IP header
5764 if (len
< l
+ 4) // ports
5767 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
5768 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
5769 if (proto
== IPPROTO_TCP
)
5771 if (len
< l
+ 14) // flags
5774 flags
= buf
[l
+ 13] & 0x3f;
5778 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
5780 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
5783 if (rule
->src_wild
!= INADDR_BROADCAST
&&
5784 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
5787 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
5788 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
5793 // layer 4 deny rules are skipped
5794 if (rule
->action
== FILTER_ACTION_DENY
&&
5795 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
5803 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
5805 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
5808 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
5811 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
5812 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
5819 return rule
->action
== FILTER_ACTION_PERMIT
;