3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
11 #include <linux/if_tun.h>
16 #include <net/route.h>
19 #include <netinet/in.h>
20 #include <netinet/ip6.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
29 #include <sys/resource.h>
37 #include <sys/sysinfo.h>
39 #include <linux/netlink.h>
40 #include <linux/rtnetlink.h>
48 #include "constants.h"
61 char * Vendor_name
= "Linux L2TPNS";
62 uint32_t call_serial_number
= 0;
65 configt
*config
= NULL
; // all configuration
66 int nlfd
= -1; // netlink socket
67 int tunfd
= -1; // tun interface file handle. (network device)
68 int udpfd
[MAX_UDPFD
+ 1] = INIT_TABUDPFD
; // array UDP file handle + 1 for lac udp
69 int udplacfd
= -1; // UDP LAC file handle
70 int controlfd
= -1; // Control signal handle
71 int clifd
= -1; // Socket listening for CLI connections.
72 int daefd
= -1; // Socket listening for DAE connections.
73 int snoopfd
= -1; // UDP file handle for sending out intercept data
74 int *radfds
= NULL
; // RADIUS requests file handles
75 int rand_fd
= -1; // Random data source
76 int cluster_sockfd
= -1; // Intra-cluster communications socket.
77 int epollfd
= -1; // event polling
78 time_t basetime
= 0; // base clock
79 char hostname
[MAXHOSTNAME
] = ""; // us.
80 static int tunidx
; // ifr_ifindex of tun device
81 int nlseqnum
= 0; // netlink sequence number
82 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
83 static int syslog_log
= 0; // are we logging to syslog
84 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
85 uint32_t last_id
= 0; // Unique ID for radius accounting
87 char guest_users
[10][32]; // Array of guest users
88 int guest_accounts_num
= 0; // Number of guest users
90 // calculated from config->l2tp_mtu
91 uint16_t MRU
= 0; // PPP MRU
92 uint16_t MSS
= 0; // TCP MSS
94 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
95 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
100 } ip_hash
[256]; // Mapping from IP address to session structures.
104 struct ipv6radix
*branch
;
105 } ipv6_hash
[16]; // Mapping from IPv6 address to session structures.
108 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
109 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
112 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
113 time_t time_now
= 0; // Current time in seconds since epoch.
114 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
115 static char time_now_string
[64] = {0}; // Current time as a string.
116 static int time_changed
= 0; // time_now changed
117 char main_quit
= 0; // True if we're in the process of exiting.
118 static char main_reload
= 0; // Re-load pending
119 linked_list
*loaded_plugins
;
120 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
122 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
123 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
125 config_descriptt config_values
[] = {
126 CONFIG("debug", debug
, INT
),
127 CONFIG("log_file", log_filename
, STRING
),
128 CONFIG("pid_file", pid_file
, STRING
),
129 CONFIG("random_device", random_device
, STRING
),
130 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
131 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
132 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
133 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
134 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
135 CONFIG("ppp_keepalive", ppp_keepalive
, BOOL
),
136 CONFIG("primary_dns", default_dns1
, IPv4
),
137 CONFIG("secondary_dns", default_dns2
, IPv4
),
138 CONFIG("primary_radius", radiusserver
[0], IPv4
),
139 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
140 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
141 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
142 CONFIG("radius_accounting", radius_accounting
, BOOL
),
143 CONFIG("radius_interim", radius_interim
, INT
),
144 CONFIG("radius_secret", radiussecret
, STRING
),
145 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
146 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
147 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
148 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
149 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
150 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
151 CONFIG("guest_account", guest_user
, STRING
),
152 CONFIG("bind_address", bind_address
, IPv4
),
153 CONFIG("peer_address", peer_address
, IPv4
),
154 CONFIG("send_garp", send_garp
, BOOL
),
155 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
156 CONFIG("throttle_buckets", num_tbfs
, INT
),
157 CONFIG("accounting_dir", accounting_dir
, STRING
),
158 CONFIG("account_all_origin", account_all_origin
, BOOL
),
159 CONFIG("dump_speed", dump_speed
, BOOL
),
160 CONFIG("multi_read_count", multi_read_count
, INT
),
161 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
162 CONFIG("lock_pages", lock_pages
, BOOL
),
163 CONFIG("icmp_rate", icmp_rate
, INT
),
164 CONFIG("packet_limit", max_packets
, INT
),
165 CONFIG("cluster_address", cluster_address
, IPv4
),
166 CONFIG("cluster_port", cluster_port
, INT
),
167 CONFIG("cluster_interface", cluster_interface
, STRING
),
168 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
169 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
170 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
171 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
172 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
173 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
174 CONFIG("hostname", hostname
, STRING
),
176 CONFIG("nexthop_address", nexthop_address
, IPv4
),
177 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
179 CONFIG("echo_timeout", echo_timeout
, INT
),
180 CONFIG("idle_echo_timeout", idle_echo_timeout
, INT
),
181 CONFIG("iftun_address", iftun_address
, IPv4
),
182 CONFIG("tundevicename", tundevicename
, STRING
),
183 CONFIG("disable_lac_func", disable_lac_func
, BOOL
),
184 CONFIG("auth_tunnel_change_addr_src", auth_tunnel_change_addr_src
, BOOL
),
185 CONFIG("bind_address_remotelns", bind_address_remotelns
, IPv4
),
186 CONFIG("bind_portremotelns", bind_portremotelns
, SHORT
),
187 CONFIG("pppoe_if_to_bind", pppoe_if_to_bind
, STRING
),
188 CONFIG("pppoe_service_name", pppoe_service_name
, STRING
),
189 CONFIG("pppoe_ac_name", pppoe_ac_name
, STRING
),
190 CONFIG("disable_sending_hello", disable_sending_hello
, BOOL
),
191 CONFIG("disable_no_spoof", disable_no_spoof
, BOOL
),
192 CONFIG("bind_multi_address", bind_multi_address
, STRING
),
193 CONFIG("pppoe_only_equal_svc_name", pppoe_only_equal_svc_name
, BOOL
),
194 CONFIG("multi_hostname", multi_hostname
, STRING
),
195 CONFIG("no_throttle_local_IP", no_throttle_local_IP
, BOOL
),
196 CONFIG("dhcp6_preferred_lifetime", dhcp6_preferred_lifetime
, INT
),
197 CONFIG("dhcp6_valid_lifetime", dhcp6_valid_lifetime
, INT
),
198 CONFIG("dhcp6_server_duid", dhcp6_server_duid
, INT
),
199 CONFIG("dns6_lifetime", dns6_lifetime
, INT
),
200 CONFIG("primary_ipv6_dns", default_ipv6_dns1
, IPv6
),
201 CONFIG("secondary_ipv6_dns", default_ipv6_dns2
, IPv6
),
202 CONFIG("default_ipv6_domain_list", default_ipv6_domain_list
, STRING
),
206 static char *plugin_functions
[] = {
211 "plugin_new_session",
212 "plugin_kill_session",
214 "plugin_radius_response",
215 "plugin_radius_reset",
216 "plugin_radius_account",
217 "plugin_become_master",
218 "plugin_new_session_master",
221 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
223 // Counters for shutdown sessions
224 static sessiont shut_acct
[8192];
225 static sessionidt shut_acct_n
= 0;
227 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
228 bundlet
*bundle
= NULL
; // Array of bundle structures.
229 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
230 sessiont
*session
= NULL
; // Array of session structures.
231 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
232 radiust
*radius
= NULL
; // Array of radius structures.
233 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
234 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
235 static controlt
*controlfree
= 0;
236 struct Tstats
*_statistics
= NULL
;
238 struct Tringbuffer
*ringbuffer
= NULL
;
241 static ssize_t
netlink_send(struct nlmsghdr
*nh
);
242 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
);
243 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
244 static void uncache_ipmap(in_addr_t ip
);
245 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
246 static void free_ip_address(sessionidt s
);
247 static void dump_acct_info(int all
);
248 static void sighup_handler(int sig
);
249 static void shutdown_handler(int sig
);
250 static void sigchild_handler(int sig
);
251 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
252 static void update_config(void);
253 static void read_config_file(void);
254 static void initplugins(void);
255 static int add_plugin(char *plugin_name
);
256 static int remove_plugin(char *plugin_name
);
257 static void plugins_done(void);
258 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
259 static tunnelidt
new_tunnel(void);
260 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
261 static void bundleclear(bundleidt b
);
263 // return internal time (10ths since process startup), set f if given
264 // as a side-effect sets time_now, and time_changed
265 static clockt
now(double *f
)
269 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
270 if (t
.tv_sec
!= time_now
)
276 // Time in milliseconds
277 // TODO FOR MLPPP DEV
278 //time_now_ms = (t.tv_sec * 1000) + (t.tv_usec/1000);
280 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
283 // work out a retry time based on try number
284 // This is a straight bounded exponential backoff.
285 // Maximum re-try time is 32 seconds. (2^5).
286 clockt
backoff(uint8_t try)
288 if (try > 5) try = 5; // max backoff
289 return now(NULL
) + 10 * (1 << try);
294 // Log a debug message. Typically called via the LOG macro
296 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
298 static char message
[65536] = {0};
304 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
305 ringbuffer
->tail
= 0;
306 if (ringbuffer
->tail
== ringbuffer
->head
)
307 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
308 ringbuffer
->head
= 0;
310 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
311 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
312 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
313 va_start(ap
, format
);
314 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, MAX_LOG_LENGTH
, format
, ap
);
319 if (config
->debug
< level
) return;
321 va_start(ap
, format
);
322 vsnprintf(message
, sizeof(message
), format
, ap
);
325 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
327 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
332 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
335 const uint8_t *d
= data
;
337 if (config
->debug
< level
) return;
339 // No support for _log_hex to syslog
342 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
343 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
345 for (i
= 0; i
< maxsize
; )
347 fprintf(log_stream
, "%4X: ", i
);
348 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
350 fprintf(log_stream
, "%02X ", d
[j
]);
352 fputs(": ", log_stream
);
355 for (; j
< i
+ 16; j
++)
357 fputs(" ", log_stream
);
359 fputs(": ", log_stream
);
362 fputs(" ", log_stream
);
363 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
365 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
366 fputc(d
[j
], log_stream
);
368 fputc('.', log_stream
);
371 fputs(" ", log_stream
);
375 fputs("\n", log_stream
);
379 setbuf(log_stream
, NULL
);
383 // update a counter, accumulating 2^32 wraps
384 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
386 uint32_t new = *counter
+ delta
;
393 // initialise the random generator
394 static void initrandom(char *source
)
396 static char path
[sizeof(config
->random_device
)] = "*undefined*";
398 // reinitialise only if we are forced to do so or if the config has changed
399 if (source
&& !strncmp(path
, source
, sizeof(path
)))
402 // close previous source, if any
411 snprintf(path
, sizeof(path
), "%s", source
);
415 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
417 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
418 path
, strerror(errno
));
423 // fill buffer with random data
424 void random_data(uint8_t *buf
, int len
)
431 n
= read(rand_fd
, buf
, len
);
432 if (n
>= len
) return;
437 LOG(0, 0, 0, "Error reading from random source: %s\n",
440 // fall back to rand()
448 // append missing data
450 // not using the low order bits from the prng stream
451 buf
[n
++] = (rand() >> 4) & 0xff;
456 // This adds it to the routing table, advertises it
457 // via BGP if enabled, and stuffs it into the
458 // 'sessionbyip' cache.
460 // 'ip' must be in _host_ order.
462 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
472 if (!prefixlen
) prefixlen
= 32;
474 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
476 memset(&req
, 0, sizeof(req
));
480 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
481 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
485 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
486 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
489 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
491 req
.rt
.rtm_family
= AF_INET
;
492 req
.rt
.rtm_dst_len
= prefixlen
;
493 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
494 req
.rt
.rtm_protocol
= 42;
495 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
496 req
.rt
.rtm_type
= RTN_UNICAST
;
498 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
500 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
504 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
507 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
508 fmtaddr(htonl(ip
), 0), prefixlen
,
509 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
511 if (netlink_send(&req
.nh
) < 0)
512 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
516 bgp_add_route(htonl(ip
), prefixlen
);
518 bgp_del_route(htonl(ip
), prefixlen
);
521 // Add/Remove the IPs to the 'sessionbyip' cache.
522 // Note that we add the zero address in the case of
523 // a network route. Roll on CIDR.
525 // Note that 's == 0' implies this is the address pool.
526 // We still cache it here, because it will pre-fill
527 // the malloc'ed tree.
531 if (!add
) // Are we deleting a route?
532 s
= 0; // Caching the session as '0' is the same as uncaching.
534 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
539 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
547 char ipv6addr
[INET6_ADDRSTRLEN
];
549 if (!config
->ipv6_prefix
.s6_addr
[0])
551 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
555 memset(&req
, 0, sizeof(req
));
559 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
560 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
564 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
565 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
568 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
570 req
.rt
.rtm_family
= AF_INET6
;
571 req
.rt
.rtm_dst_len
= prefixlen
;
572 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
573 req
.rt
.rtm_protocol
= 42;
574 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
575 req
.rt
.rtm_type
= RTN_UNICAST
;
577 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
578 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
580 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
582 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
584 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
587 if (netlink_send(&req
.nh
) < 0)
588 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
592 bgp_add_route6(ip
, prefixlen
);
594 bgp_del_route6(ip
, prefixlen
);
599 if (!add
) // Are we deleting a route?
600 s
= 0; // Caching the session as '0' is the same as uncaching.
602 cache_ipv6map(ip
, prefixlen
, s
);
609 // Set up netlink socket
610 static void initnetlink(void)
612 struct sockaddr_nl nladdr
;
614 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
617 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
621 memset(&nladdr
, 0, sizeof(nladdr
));
622 nladdr
.nl_family
= AF_NETLINK
;
623 nladdr
.nl_pid
= getpid();
625 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
627 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
632 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
634 struct sockaddr_nl nladdr
;
638 nh
->nlmsg_pid
= getpid();
639 nh
->nlmsg_seq
= ++nlseqnum
;
641 // set kernel address
642 memset(&nladdr
, 0, sizeof(nladdr
));
643 nladdr
.nl_family
= AF_NETLINK
;
645 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
646 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
648 return sendmsg(nlfd
, &msg
, 0);
651 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
653 struct sockaddr_nl nladdr
;
657 // set kernel address
658 memset(&nladdr
, 0, sizeof(nladdr
));
659 nladdr
.nl_family
= AF_NETLINK
;
661 iov
= (struct iovec
){ buf
, len
};
662 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
664 return recvmsg(nlfd
, &msg
, 0);
667 /* adapted from iproute2 */
668 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
670 int len
= RTA_LENGTH(alen
);
673 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
674 rta
->rta_type
= type
;
676 memcpy(RTA_DATA(rta
), data
, alen
);
677 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
680 // messages corresponding to different phases seq number
681 static char *tun_nl_phase_msg
[] = {
683 "getting tun interface index",
684 "setting tun interface parameters",
685 "setting tun IPv4 address",
686 "setting tun LL IPv6 address",
687 "setting tun global IPv6 address",
691 // Set up TUN interface
692 static void inittun(void)
696 memset(&ifr
, 0, sizeof(ifr
));
697 ifr
.ifr_flags
= IFF_TUN
;
699 tunfd
= open(TUNDEVICE
, O_RDWR
);
702 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
706 int flags
= fcntl(tunfd
, F_GETFL
, 0);
707 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
710 if (*config
->tundevicename
)
711 strncpy(ifr
.ifr_name
, config
->tundevicename
, IFNAMSIZ
);
713 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
715 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
718 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevicename
) - 1);
719 strncpy(config
->tundevicename
, ifr
.ifr_name
, sizeof(config
->tundevicename
));
721 tunidx
= if_nametoindex(config
->tundevicename
);
724 LOG(0, 0, 0, "Can't get tun interface index\n");
733 struct ifinfomsg ifinfo
;
734 struct ifaddrmsg ifaddr
;
736 char rtdata
[32]; // 32 should be enough
738 uint32_t txqlen
, mtu
;
741 memset(&req
, 0, sizeof(req
));
743 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
744 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
745 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
747 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
748 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
749 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
750 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
752 /* Bump up the qlen to deal with bursts from the network */
754 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
755 /* set MTU to modem MRU */
757 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
759 if (netlink_send(&req
.nh
) < 0)
762 memset(&req
, 0, sizeof(req
));
764 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
765 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
766 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
768 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
769 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
770 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
771 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
773 if (config
->nbmultiaddress
> 1)
776 for (i
= 0; i
< config
->nbmultiaddress
; i
++)
778 ip
= config
->iftun_n_address
[i
];
779 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
780 if (netlink_send(&req
.nh
) < 0)
786 if (config
->iftun_address
)
787 ip
= config
->iftun_address
;
789 ip
= 0x01010101; // 1.1.1.1
790 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
792 if (netlink_send(&req
.nh
) < 0)
798 // Only setup IPv6 on the tun device if we have a configured prefix
799 if (config
->ipv6_prefix
.s6_addr
[0]) {
802 memset(&req
, 0, sizeof(req
));
804 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
805 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
806 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
808 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
809 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
810 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
811 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
813 // Link local address is FE80::1
814 memset(&ip6
, 0, sizeof(ip6
));
815 ip6
.s6_addr
[0] = 0xFE;
816 ip6
.s6_addr
[1] = 0x80;
818 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
820 if (netlink_send(&req
.nh
) < 0)
823 memset(&req
, 0, sizeof(req
));
825 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
826 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
827 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
829 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
830 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
831 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
832 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
834 // Global address is prefix::1
835 ip6
= config
->ipv6_prefix
;
837 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
839 if (netlink_send(&req
.nh
) < 0)
843 memset(&req
, 0, sizeof(req
));
845 req
.nh
.nlmsg_type
= NLMSG_DONE
;
846 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
848 if (netlink_send(&req
.nh
) < 0)
851 // if we get an error for seqnum < min_initok_nlseqnum,
852 // we must exit as initialization went wrong
853 if (config
->ipv6_prefix
.s6_addr
[0])
854 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
856 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
862 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
866 // set up LAC UDP ports
867 static void initlacudp(void)
870 struct sockaddr_in addr
;
872 // Tunnel to Remote LNS
873 memset(&addr
, 0, sizeof(addr
));
874 addr
.sin_family
= AF_INET
;
875 addr
.sin_port
= htons(config
->bind_portremotelns
);
876 addr
.sin_addr
.s_addr
= config
->bind_address_remotelns
;
877 udplacfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
878 setsockopt(udplacfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
880 int flags
= fcntl(udplacfd
, F_GETFL
, 0);
881 fcntl(udplacfd
, F_SETFL
, flags
| O_NONBLOCK
);
883 if (bind(udplacfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
885 LOG(0, 0, 0, "Error in UDP REMOTE LNS bind: %s\n", strerror(errno
));
890 // set up control ports
891 static void initcontrol(void)
894 struct sockaddr_in addr
;
897 memset(&addr
, 0, sizeof(addr
));
898 addr
.sin_family
= AF_INET
;
899 addr
.sin_port
= htons(NSCTL_PORT
);
900 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
901 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
902 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
903 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
905 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
910 // set up Dynamic Authorization Extensions to RADIUS port
911 static void initdae(void)
914 struct sockaddr_in addr
;
916 // Dynamic Authorization Extensions to RADIUS
917 memset(&addr
, 0, sizeof(addr
));
918 addr
.sin_family
= AF_INET
;
919 addr
.sin_port
= htons(config
->radius_dae_port
);
920 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
921 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
922 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
923 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
925 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
931 static void initudp(int * pudpfd
, in_addr_t ip_bind
)
934 struct sockaddr_in addr
;
937 memset(&addr
, 0, sizeof(addr
));
938 addr
.sin_family
= AF_INET
;
939 addr
.sin_port
= htons(L2TPPORT
);
940 addr
.sin_addr
.s_addr
= ip_bind
;
941 (*pudpfd
) = socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
942 setsockopt((*pudpfd
), SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
944 int flags
= fcntl((*pudpfd
), F_GETFL
, 0);
945 fcntl((*pudpfd
), F_SETFL
, flags
| O_NONBLOCK
);
947 if (bind((*pudpfd
), (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
949 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
955 // Find session by IP, < 1 for not found
957 // Confusingly enough, this 'ip' must be
958 // in _network_ order. This being the common
959 // case when looking it up from IP packet headers.
961 // We actually use this cache for two things.
962 // #1. For used IP addresses, this maps to the
963 // session ID that it's used by.
964 // #2. For un-used IP addresses, this maps to the
965 // index into the pool table that contains that
969 static sessionidt
lookup_ipmap(in_addr_t ip
)
971 uint8_t *a
= (uint8_t *) &ip
;
972 union iphash
*h
= ip_hash
;
974 if (!(h
= h
[*a
++].idx
)) return 0;
975 if (!(h
= h
[*a
++].idx
)) return 0;
976 if (!(h
= h
[*a
++].idx
)) return 0;
981 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
983 struct ipv6radix
*curnode
;
986 char ipv6addr
[INET6_ADDRSTRLEN
];
988 curnode
= &ipv6_hash
[((ip
.s6_addr
[0]) & 0xF0)>>4];
992 while (s
== 0 && i
< 32 && curnode
->branch
!= NULL
)
995 curnode
= &curnode
->branch
[ip
.s6_addr
[i
>>1] & 0x0F];
997 curnode
= &curnode
->branch
[(ip
.s6_addr
[i
>>1] & 0xF0)>>4];
1003 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
1004 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1011 sessionidt
sessionbyip(in_addr_t ip
)
1013 sessionidt s
= lookup_ipmap(ip
);
1016 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1022 sessionidt
sessionbyipv6(struct in6_addr ip
)
1025 CSTAT(sessionbyipv6
);
1027 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
1028 (ip
.s6_addr
[0] == 0xFE &&
1029 ip
.s6_addr
[1] == 0x80 &&
1030 ip
.s6_addr16
[1] == 0 &&
1031 ip
.s6_addr16
[2] == 0 &&
1032 ip
.s6_addr16
[3] == 0))
1034 in_addr_t
*pipv4
= (in_addr_t
*) &ip
.s6_addr
[8];
1035 s
= lookup_ipmap(*pipv4
);
1037 s
= lookup_ipv6map(ip
);
1040 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1046 sessionidt
sessionbyipv6new(struct in6_addr ip
)
1049 CSTAT(sessionbyipv6new
);
1051 s
= lookup_ipv6map(ip
);
1053 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1060 // Take an IP address in HOST byte order and
1061 // add it to the sessionid by IP cache.
1063 // (It's actually cached in network order)
1065 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
1067 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
1068 uint8_t *a
= (uint8_t *) &nip
;
1069 union iphash
*h
= ip_hash
;
1072 for (i
= 0; i
< 3; i
++)
1074 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1083 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1086 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1087 // else a map to an ip pool index.
1090 static void uncache_ipmap(in_addr_t ip
)
1092 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1095 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1099 struct ipv6radix
*curnode
;
1100 char ipv6addr
[INET6_ADDRSTRLEN
];
1102 curnode
= &ipv6_hash
[((ip
.s6_addr
[0]) & 0xF0)>>4];
1104 niblles
= prefixlen
>> 2;
1109 if (curnode
->branch
== NULL
)
1111 if (!(curnode
->branch
= calloc(16, sizeof (struct ipv6radix
))))
1116 curnode
= &curnode
->branch
[ip
.s6_addr
[i
>>1] & 0x0F];
1118 curnode
= &curnode
->branch
[(ip
.s6_addr
[i
>>1] & 0xF0)>>4];
1126 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1127 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1131 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1132 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1138 // CLI list to dump current ipcache.
1140 int cmd_show_ipcache(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
1142 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1146 if (CLI_HELP_REQUESTED
)
1147 return CLI_HELP_NO_ARGS
;
1149 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1151 for (i
= 0; i
< 256; ++i
)
1157 for (j
= 0; j
< 256; ++j
)
1163 for (k
= 0; k
< 256; ++k
)
1169 for (l
= 0; l
< 256; ++l
)
1174 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1180 cli_print(cli
, "%d entries in cache", count
);
1184 // Find session by username, 0 for not found
1185 // walled garden users aren't authenticated, so the username is
1186 // reasonably useless. Ignore them to avoid incorrect actions
1188 // This is VERY inefficent. Don't call it often. :)
1190 sessionidt
sessionbyuser(char *username
)
1193 CSTAT(sessionbyuser
);
1195 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1197 if (!session
[s
].opened
)
1200 if (session
[s
].walled_garden
)
1201 continue; // Skip walled garden users.
1203 if (!strncmp(session
[s
].user
, username
, 128))
1207 return 0; // Not found.
1210 void send_garp(in_addr_t ip
)
1216 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1219 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1222 memset(&ifr
, 0, sizeof(ifr
));
1223 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1224 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1226 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1230 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1231 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1233 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1238 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1241 static sessiont
*sessiontbysessionidt(sessionidt s
)
1243 if (!s
|| s
>= MAXSESSION
) return NULL
;
1247 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1249 sessionidt val
= s
-session
;
1250 if (s
< session
|| val
>= MAXSESSION
) return 0;
1254 // actually send a control message for a specific tunnel
1255 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1257 struct sockaddr_in addr
;
1263 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1264 STAT(tunnel_tx_errors
);
1268 if (t
== TUNNEL_ID_PPPOE
)
1270 pppoe_sess_send(buf
, l
, t
);
1276 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1277 STAT(tunnel_tx_errors
);
1281 memset(&addr
, 0, sizeof(addr
));
1282 addr
.sin_family
= AF_INET
;
1283 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1284 addr
.sin_port
= htons(tunnel
[t
].port
);
1286 // sequence expected, if sequence in message
1287 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1289 // If this is a control message, deal with retries
1292 tunnel
[t
].last
= time_now
; // control message sent
1293 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1296 STAT(tunnel_retries
);
1297 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1301 if (sendto(udpfd
[tunnel
[t
].indexudp
], buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1303 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1304 strerror(errno
), udpfd
[tunnel
[t
].indexudp
], buf
, l
, inet_ntoa(addr
.sin_addr
));
1305 STAT(tunnel_tx_errors
);
1309 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1310 STAT(tunnel_tx_packets
);
1311 INC_STAT(tunnel_tx_bytes
, l
);
1315 // Tiny helper function to write data to
1316 // the 'tun' device.
1318 int tun_write(uint8_t * data
, int size
)
1320 return write(tunfd
, data
, size
);
1323 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1324 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1326 int d
= (tcp
[12] >> 4) * 4;
1333 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1336 if (tcp
+ d
> buf
+ len
) // short?
1344 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1347 if (mss
+ 2 > data
) return; // short?
1351 if (*opts
== 0) return; // end of options
1352 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1355 opts
+= opts
[1]; // skip over option
1358 if (!mss
) return; // not found
1359 orig
= ntohs(*(uint16_t *) mss
);
1361 if (orig
<= MSS
) return; // mss OK
1363 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1364 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1365 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1366 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1369 *(int16_t *) mss
= htons(MSS
);
1371 // adjust checksum (see rfc1141)
1372 sum
= orig
+ (~MSS
& 0xffff);
1373 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1374 sum
= (sum
& 0xffff) + (sum
>> 16);
1375 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1378 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1382 // Skip the four extra bytes
1394 proto
= ntohs(*(uint16_t *) p
);
1402 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1403 return; // closing session, PPP not processed
1405 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1406 processipin(s
, t
, p
, l
);
1408 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1412 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1413 return; // closing session, PPP not processed
1416 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1417 processipv6in(s
, t
, p
, l
);
1419 else if (proto
== PPPIPCP
)
1421 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1422 processipcp(s
, t
, p
, l
);
1424 else if (proto
== PPPCCP
)
1426 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1427 processccp(s
, t
, p
, l
);
1431 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1435 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1437 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1438 sp
->cout_delta
+= len
;
1440 sp
->last_data
= time_now
;
1442 sess_local
[s
].cout
+= len
; // To send to master..
1443 sess_local
[s
].pout
++;
1446 // process outgoing (to tunnel) IP
1448 // (i.e. this routine writes to data[-8]).
1449 void processipout(uint8_t *buf
, int len
)
1454 in_addr_t ip
, ip_src
;
1456 uint8_t *data
= buf
; // Keep a copy of the originals.
1459 uint8_t fragbuf
[MAXETHER
+ 20];
1461 CSTAT(processipout
);
1463 if (len
< MIN_IP_SIZE
)
1465 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1466 STAT(tun_rx_errors
);
1469 if (len
>= MAXETHER
)
1471 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1472 STAT(tun_rx_errors
);
1476 // Skip the tun header
1480 // Got an IP header now
1481 if (*(uint8_t *)(buf
) >> 4 != 4)
1483 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1487 ip_src
= *(uint32_t *)(buf
+ 12);
1488 ip
= *(uint32_t *)(buf
+ 16);
1489 if (!(s
= sessionbyip(ip
)))
1491 // Is this a packet for a session that doesn't exist?
1492 static int rate
= 0; // Number of ICMP packets we've sent this second.
1493 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1495 if (last
!= time_now
)
1501 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1503 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1504 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1505 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1510 t
= session
[s
].tunnel
;
1511 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1513 LOG(3, s
, t
, "Packet size more than session MRU\n");
1519 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1520 if (config
->max_packets
> 0)
1522 if (sess_local
[s
].last_packet_out
== TIME
)
1524 int max
= config
->max_packets
;
1526 // All packets for throttled sessions are handled by the
1527 // master, so further limit by using the throttle rate.
1528 // A bit of a kludge, since throttle rate is in kbps,
1529 // but should still be generous given our average DSL
1530 // packet size is 200 bytes: a limit of 28kbps equates
1531 // to around 180 packets per second.
1532 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1533 max
= sp
->throttle_out
;
1535 if (++sess_local
[s
].packets_out
> max
)
1537 sess_local
[s
].packets_dropped
++;
1543 if (sess_local
[s
].packets_dropped
)
1545 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1546 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1547 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1548 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1552 sess_local
[s
].last_packet_out
= TIME
;
1553 sess_local
[s
].packets_out
= 1;
1554 sess_local
[s
].packets_dropped
= 0;
1558 // run access-list if any
1559 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1562 // adjust MSS on SYN and SYN,ACK packets with options
1563 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1565 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1566 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1567 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1572 if (!config
->no_throttle_local_IP
|| !sessionbyip(ip_src
))
1574 // Are we throttling this session?
1575 if (config
->cluster_iam_master
)
1576 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1578 master_throttle_packet(sp
->tbf_out
, data
, size
);
1583 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1585 // We are walled-gardening this
1586 master_garden_packet(s
, data
, size
);
1590 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1593 if (!config
->cluster_iam_master
)
1595 // The MPPP packets must be managed by the Master.
1596 master_forward_mppp_packet(s
, data
, size
);
1600 // Add on L2TP header
1601 sessionidt members
[MAXBUNDLESES
];
1602 bundleidt bid
= session
[s
].bundle
;
1603 bundlet
*b
= &bundle
[bid
];
1604 uint32_t num_of_links
, nb_opened
;
1607 num_of_links
= b
->num_of_links
;
1609 for (i
= 0;i
< num_of_links
;i
++)
1612 if (session
[s
].ppp
.lcp
== Opened
)
1614 members
[nb_opened
] = s
;
1621 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1625 num_of_links
= nb_opened
;
1626 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1627 s
= members
[b
->current_ses
];
1628 t
= session
[s
].tunnel
;
1630 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1632 if (num_of_links
> 1)
1634 if(len
> MINFRAGLEN
)
1636 //for rotate traffic among the member links
1637 uint32_t divisor
= num_of_links
;
1639 divisor
= divisor
/2 + (divisor
& 1);
1641 // Partition the packet to "num_of_links" fragments
1642 uint32_t fraglen
= len
/ divisor
;
1643 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1644 uint32_t remain
= len
;
1646 // send the first packet
1647 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1649 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1652 update_session_out_stat(s
, sp
, fraglen
);
1655 while (remain
> last_fraglen
)
1657 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1658 s
= members
[b
->current_ses
];
1659 t
= session
[s
].tunnel
;
1661 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1662 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1664 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1665 update_session_out_stat(s
, sp
, fraglen
);
1668 // send the last fragment
1669 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1670 s
= members
[b
->current_ses
];
1671 t
= session
[s
].tunnel
;
1673 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1674 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1676 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1677 update_session_out_stat(s
, sp
, remain
);
1678 if (remain
!= last_fraglen
)
1679 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1683 // Send it as one frame
1684 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1686 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1687 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1688 update_session_out_stat(s
, sp
, len
);
1693 // Send it as one frame (NO MPPP Frame)
1694 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1695 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1696 update_session_out_stat(s
, sp
, len
);
1701 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1702 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1703 update_session_out_stat(s
, sp
, len
);
1706 // Snooping this session, send it to intercept box
1707 if (sp
->snoop_ip
&& sp
->snoop_port
)
1708 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1713 // process outgoing (to tunnel) IPv6
1715 static void processipv6out(uint8_t * buf
, int len
)
1720 struct in6_addr ip6
;
1722 uint8_t *data
= buf
; // Keep a copy of the originals.
1725 uint8_t b
[MAXETHER
+ 20];
1727 CSTAT(processipv6out
);
1729 if (len
< MIN_IP_SIZE
)
1731 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1732 STAT(tunnel_tx_errors
);
1735 if (len
>= MAXETHER
)
1737 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1738 STAT(tunnel_tx_errors
);
1742 // Skip the tun header
1746 // Got an IP header now
1747 if (*(uint8_t *)(buf
) >> 4 != 6)
1749 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1753 ip6
= *(struct in6_addr
*)(buf
+24);
1754 s
= sessionbyipv6(ip6
);
1758 s
= sessionbyipv6new(ip6
);
1763 // Is this a packet for a session that doesn't exist?
1764 static int rate
= 0; // Number of ICMP packets we've sent this second.
1765 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1767 if (last
!= time_now
)
1773 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1775 // FIXME: Should send icmp6 host unreachable
1779 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1781 bundleidt bid
= session
[s
].bundle
;
1782 bundlet
*b
= &bundle
[bid
];
1784 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1785 s
= b
->members
[b
->current_ses
];
1786 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1788 t
= session
[s
].tunnel
;
1790 sp
->last_data
= time_now
;
1792 // FIXME: add DoS prevention/filters?
1796 // Are we throttling this session?
1797 if (config
->cluster_iam_master
)
1798 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1800 master_throttle_packet(sp
->tbf_out
, data
, size
);
1803 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1805 // We are walled-gardening this
1806 master_garden_packet(s
, data
, size
);
1810 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1812 // Add on L2TP header
1814 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1816 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1819 // Snooping this session, send it to intercept box
1820 if (sp
->snoop_ip
&& sp
->snoop_port
)
1821 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1823 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1824 sp
->cout_delta
+= len
;
1828 sess_local
[s
].cout
+= len
; // To send to master..
1829 sess_local
[s
].pout
++;
1833 // Helper routine for the TBF filters.
1834 // Used to send queued data in to the user!
1836 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1841 uint8_t *data
= buf
; // Keep a copy of the originals.
1843 uint8_t b
[MAXETHER
+ 20];
1845 if (len
< 0 || len
> MAXETHER
)
1847 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1851 // Skip the tun header
1858 t
= session
[s
].tunnel
;
1861 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1863 // Add on L2TP header
1864 if (*(uint16_t *) (data
+ 2) == htons(PKTIPV6
))
1865 p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0); // IPV6
1867 p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0); // IPV4
1871 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1873 // Snooping this session.
1874 if (sp
->snoop_ip
&& sp
->snoop_port
)
1875 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1877 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1878 sp
->cout_delta
+= len
;
1882 sess_local
[s
].cout
+= len
; // To send to master..
1883 sess_local
[s
].pout
++;
1886 // add an AVP (16 bit)
1887 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1889 uint16_t l
= (m
? 0x8008 : 0x0008);
1890 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1891 pint16
[0] = htons(l
);
1892 pint16
[1] = htons(0);
1893 pint16
[2] = htons(avp
);
1894 pint16
[3] = htons(val
);
1898 // add an AVP (32 bit)
1899 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1901 uint16_t l
= (m
? 0x800A : 0x000A);
1902 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1903 uint32_t *pint32
= (uint32_t *) (c
->buf
+ c
->length
+ 6);
1904 pint16
[0] = htons(l
);
1905 pint16
[1] = htons(0);
1906 pint16
[2] = htons(avp
);
1907 pint32
[0] = htonl(val
);
1911 // add an AVP (string)
1912 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1914 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1915 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1916 pint16
[0] = htons(l
);
1917 pint16
[1] = htons(0);
1918 pint16
[2] = htons(avp
);
1919 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1920 c
->length
+= 6 + strlen(val
);
1924 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1926 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1927 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1928 pint16
[0] = htons(l
);
1929 pint16
[1] = htons(0);
1930 pint16
[2] = htons(avp
);
1931 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1932 c
->length
+= 6 + len
;
1935 // new control connection
1936 static controlt
*controlnew(uint16_t mtype
)
1940 c
= malloc(sizeof(controlt
));
1944 controlfree
= c
->next
;
1948 c
->buf
[0] = 0xC8; // flags
1949 c
->buf
[1] = 0x02; // ver
1951 control16(c
, 0, mtype
, 1);
1955 // send zero block if nothing is waiting
1957 static void controlnull(tunnelidt t
)
1960 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1963 buf
[0] = htons(0xC802); // flags/ver
1964 buf
[1] = htons(12); // length
1965 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1966 buf
[3] = htons(0); // session
1967 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1968 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1969 tunnelsend((uint8_t *)buf
, 12, t
);
1972 // add a control message to a tunnel, and send if within window
1973 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1975 uint16_t *pint16
= (uint16_t *) (c
->buf
+ 2);
1976 pint16
[0] = htons(c
->length
); // length
1977 pint16
[1] = htons(tunnel
[t
].far
); // tunnel
1978 pint16
[2] = htons(far
); // session
1979 pint16
[3] = htons(tunnel
[t
].ns
); // sequence
1980 tunnel
[t
].ns
++; // advance sequence
1981 // link in message in to queue
1982 if (tunnel
[t
].controlc
)
1983 tunnel
[t
].controle
->next
= c
;
1985 tunnel
[t
].controls
= c
;
1987 tunnel
[t
].controle
= c
;
1988 tunnel
[t
].controlc
++;
1990 // send now if space in window
1991 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1993 tunnel
[t
].try = 0; // first send
1994 tunnelsend(c
->buf
, c
->length
, t
);
1999 // Throttle or Unthrottle a session
2001 // Throttle the data from/to through a session to no more than
2002 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
2005 // If either value is -1, the current value is retained for that
2008 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
2010 if (!session
[s
].opened
)
2011 return; // No-one home.
2013 if (!*session
[s
].user
)
2014 return; // User not logged in
2018 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
2019 if (session
[s
].tbf_in
)
2020 free_tbf(session
[s
].tbf_in
);
2023 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
2025 session
[s
].tbf_in
= 0;
2027 session
[s
].throttle_in
= rate_in
;
2032 int bytes
= rate_out
* 1024 / 8;
2033 if (session
[s
].tbf_out
)
2034 free_tbf(session
[s
].tbf_out
);
2037 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
2039 session
[s
].tbf_out
= 0;
2041 session
[s
].throttle_out
= rate_out
;
2045 // add/remove filters from session (-1 = no change)
2046 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
2048 if (!session
[s
].opened
)
2049 return; // No-one home.
2051 if (!*session
[s
].user
)
2052 return; // User not logged in
2055 if (filter_in
> MAXFILTER
) filter_in
= -1;
2056 if (filter_out
> MAXFILTER
) filter_out
= -1;
2057 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
2058 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
2062 if (session
[s
].filter_in
)
2063 ip_filters
[session
[s
].filter_in
- 1].used
--;
2066 ip_filters
[filter_in
- 1].used
++;
2068 session
[s
].filter_in
= filter_in
;
2071 if (filter_out
>= 0)
2073 if (session
[s
].filter_out
)
2074 ip_filters
[session
[s
].filter_out
- 1].used
--;
2077 ip_filters
[filter_out
- 1].used
++;
2079 session
[s
].filter_out
= filter_out
;
2083 // start tidy shutdown of session
2084 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
2086 int walled_garden
= session
[s
].walled_garden
;
2087 bundleidt b
= session
[s
].bundle
;
2088 //delete routes only for last session in bundle (in case of MPPP)
2089 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
2091 CSTAT(sessionshutdown
);
2093 if (!session
[s
].opened
)
2095 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2096 return; // not a live session
2099 if (!session
[s
].die
)
2101 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2102 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2103 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2106 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2108 // RADIUS Stop message
2109 uint16_t r
= radiusnew(s
);
2112 // stop, if not already trying
2113 if (radius
[r
].state
!= RADIUSSTOP
)
2115 radius
[r
].term_cause
= term_cause
;
2116 radius
[r
].term_msg
= reason
;
2117 radiussend(r
, RADIUSSTOP
);
2121 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2123 // Save counters to dump to accounting file
2124 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2125 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2128 if (!session
[s
].die
)
2129 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2132 { // IP allocated, clear and unroute
2135 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2137 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2138 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2141 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2142 session
[s
].route
[r
].ip
= 0;
2145 if (session
[s
].ip_pool_index
== -1) // static ip
2147 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2153 // unroute IPv6, if setup
2154 for (r
= 0; r
< MAXROUTE6
&& session
[s
].route6
[r
].ipv6route
.s6_addr
[0] && session
[s
].route6
[r
].ipv6prefixlen
; r
++)
2156 if (del_routes
) route6set(s
, session
[s
].route6
[r
].ipv6route
, session
[s
].route6
[r
].ipv6prefixlen
, 0);
2157 memset(&session
[s
].route6
[r
], 0, sizeof(session
[s
].route6
[r
]));
2160 if (session
[s
].ipv6address
.s6_addr
[0] && del_routes
)
2162 route6set(s
, session
[s
].ipv6address
, 128, 0);
2167 // This session was part of a bundle
2168 bundle
[b
].num_of_links
--;
2169 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2170 if(bundle
[b
].num_of_links
== 0)
2173 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2177 // Adjust the members array to accomodate the new change
2178 uint8_t mem_num
= 0;
2179 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2180 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2183 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2184 if(bundle
[b
].members
[ml
] == s
)
2189 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2190 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2192 // If the killed session is the first of the bundle,
2193 // the new first session must be stored in the cache_ipmap
2194 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2197 sessionidt new_s
= bundle
[b
].members
[0];
2200 // Add the route for this session.
2201 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2206 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2207 ip
= session
[new_s
].route
[r
].ip
;
2209 if (!prefixlen
) prefixlen
= 32;
2210 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2212 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2213 cache_ipmap(i
, new_s
);
2215 cache_ipmap(session
[new_s
].ip
, new_s
);
2218 for (r
= 0; r
< MAXROUTE6
&& session
[new_s
].route6
[r
].ipv6prefixlen
; r
++)
2220 cache_ipv6map(session
[new_s
].route6
[r
].ipv6route
, session
[new_s
].route6
[r
].ipv6prefixlen
, new_s
);
2223 if (session
[new_s
].ipv6address
.s6_addr
[0])
2225 cache_ipv6map(session
[new_s
].ipv6address
, 128, new_s
);
2231 cluster_send_bundle(b
);
2235 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2236 throttle_session(s
, 0, 0);
2240 if (session
[s
].tunnel
== TUNNEL_ID_PPPOE
)
2242 pppoe_shutdown_session(s
);
2247 controlt
*c
= controlnew(14); // sending CDN
2251 buf
[0] = htons(cdn_result
);
2252 buf
[1] = htons(cdn_error
);
2253 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2256 control16(c
, 1, cdn_result
, 1);
2258 control16(c
, 14, s
, 1); // assigned session (our end)
2259 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2263 // update filter refcounts
2264 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2265 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2268 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2269 sess_local
[s
].lcp
.restart
= 0;
2270 sess_local
[s
].ipcp
.restart
= 0;
2271 sess_local
[s
].ipv6cp
.restart
= 0;
2272 sess_local
[s
].ccp
.restart
= 0;
2274 cluster_send_session(s
);
2277 void sendipcp(sessionidt s
, tunnelidt t
)
2279 uint8_t buf
[MAXETHER
];
2283 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2285 if (!session
[s
].unique_id
)
2287 if (!++last_id
) ++last_id
; // skip zero
2288 session
[s
].unique_id
= last_id
;
2291 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2295 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2296 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2297 q
[4] = 3; // ip address option
2298 q
[5] = 6; // option length
2299 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2300 config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] :
2301 my_address
; // send my IP
2303 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2304 restart_timer(s
, ipcp
);
2307 void sendipv6cp(sessionidt s
, tunnelidt t
)
2309 uint8_t buf
[MAXETHER
];
2313 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2315 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2319 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2320 // only send one type
2322 *(uint16_t *) (q
+ 2) = htons(14);
2323 q
[4] = 1; // interface identifier option
2324 q
[5] = 10; // option length
2325 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2326 *(uint32_t *) (q
+ 10) = 0;
2329 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2330 restart_timer(s
, ipv6cp
);
2333 static void sessionclear(sessionidt s
)
2335 memset(&session
[s
], 0, sizeof(session
[s
]));
2336 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2337 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2339 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2340 session
[s
].next
= sessionfree
;
2344 // kill a session now
2345 void sessionkill(sessionidt s
, char *reason
)
2349 if (!session
[s
].opened
) // not alive
2352 if (session
[s
].next
)
2354 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2358 if (!session
[s
].die
)
2359 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2361 if (sess_local
[s
].radius
)
2362 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2364 if (session
[s
].forwardtosession
)
2366 sessionidt sess
= session
[s
].forwardtosession
;
2367 if (session
[sess
].forwardtosession
== s
)
2369 // Shutdown the linked session also.
2370 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2374 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2376 cluster_send_session(s
);
2379 static void tunnelclear(tunnelidt t
)
2382 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2383 tunnel
[t
].state
= TUNNELFREE
;
2386 static void bundleclear(bundleidt b
)
2389 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2390 bundle
[b
].state
= BUNDLEFREE
;
2393 // kill a tunnel now
2394 static void tunnelkill(tunnelidt t
, char *reason
)
2401 tunnel
[t
].state
= TUNNELDIE
;
2403 // free control messages
2404 while ((c
= tunnel
[t
].controls
))
2406 controlt
* n
= c
->next
;
2407 tunnel
[t
].controls
= n
;
2408 tunnel
[t
].controlc
--;
2409 c
->next
= controlfree
;
2413 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2414 if (session
[s
].tunnel
== t
)
2415 sessionkill(s
, reason
);
2419 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2420 cli_tunnel_actions
[t
].action
= 0;
2421 cluster_send_tunnel(t
);
2424 // shut down a tunnel cleanly
2425 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2429 CSTAT(tunnelshutdown
);
2431 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2433 // never set up, can immediately kill
2434 tunnelkill(t
, reason
);
2437 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2440 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2441 if (session
[s
].tunnel
== t
)
2442 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2444 tunnel
[t
].state
= TUNNELDIE
;
2445 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2446 cluster_send_tunnel(t
);
2447 // TBA - should we wait for sessions to stop?
2450 controlt
*c
= controlnew(4); // sending StopCCN
2455 buf
[0] = htons(result
);
2456 buf
[1] = htons(error
);
2459 int m
= strlen(msg
);
2460 if (m
+ 4 > sizeof(buf
))
2461 m
= sizeof(buf
) - 4;
2463 memcpy(buf
+2, msg
, m
);
2467 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2470 control16(c
, 1, result
, 1);
2472 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2473 controladd(c
, 0, t
); // send the message
2477 // read and process packet on tunnel (UDP)
2478 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, uint16_t indexudpfd
)
2480 uint8_t *sendchalresponse
= NULL
;
2481 uint8_t *recvchalresponse
= NULL
;
2482 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2483 uint8_t *p
= buf
+ 2;
2490 LOG_HEX(5, "UDP Data", buf
, len
);
2491 STAT(tunnel_rx_packets
);
2492 INC_STAT(tunnel_rx_bytes
, len
);
2495 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2496 STAT(tunnel_rx_errors
);
2499 if ((buf
[1] & 0x0F) != 2)
2501 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2502 STAT(tunnel_rx_errors
);
2507 l
= ntohs(*(uint16_t *) p
);
2510 t
= ntohs(*(uint16_t *) p
);
2512 s
= ntohs(*(uint16_t *) p
);
2514 if (s
>= MAXSESSION
)
2516 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2517 STAT(tunnel_rx_errors
);
2522 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2523 STAT(tunnel_rx_errors
);
2526 if (t
== TUNNEL_ID_PPPOE
)
2528 LOG(1, s
, t
, "Received UDP packet with tunnel ID reserved for pppoe\n");
2529 STAT(tunnel_rx_errors
);
2534 ns
= ntohs(*(uint16_t *) p
);
2536 nr
= ntohs(*(uint16_t *) p
);
2541 uint16_t o
= ntohs(*(uint16_t *) p
);
2546 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2547 STAT(tunnel_rx_errors
);
2552 // used to time out old tunnels
2553 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2554 tunnel
[t
].lastrec
= time_now
;
2558 uint16_t message
= 0xFFFF; // message type
2560 uint8_t mandatory
= 0;
2561 uint16_t asession
= 0; // assigned session
2562 uint32_t amagic
= 0; // magic number
2563 uint8_t aflags
= 0; // flags from last LCF
2564 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2565 char called
[MAXTEL
] = ""; // called number
2566 char calling
[MAXTEL
] = ""; // calling number
2568 if (!config
->cluster_iam_master
)
2570 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
2574 // control messages must have bits 0x80|0x40|0x08
2575 // (type, length and sequence) set, and bits 0x02|0x01
2576 // (offset and priority) clear
2577 if ((*buf
& 0xCB) != 0xC8)
2579 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2580 STAT(tunnel_rx_errors
);
2584 // check for duplicate tunnel open message
2590 // Is this a duplicate of the first packet? (SCCRQ)
2592 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2594 if (tunnel
[i
].state
!= TUNNELOPENING
||
2595 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2596 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2599 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2604 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2605 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2607 // if no tunnel specified, assign one
2610 if (!(t
= new_tunnel()))
2612 LOG(1, 0, 0, "No more tunnels\n");
2613 STAT(tunnel_overflow
);
2617 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2618 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2619 tunnel
[t
].window
= 4; // default window
2620 tunnel
[t
].indexudp
= indexudpfd
;
2621 STAT(tunnel_created
);
2622 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2623 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2626 // If the 'ns' just received is not the 'nr' we're
2627 // expecting, just send an ack and drop it.
2629 // if 'ns' is less, then we got a retransmitted packet.
2630 // if 'ns' is greater than missed a packet. Either way
2631 // we should ignore it.
2632 if (ns
!= tunnel
[t
].nr
)
2634 // is this the sequence we were expecting?
2635 STAT(tunnel_rx_errors
);
2636 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2637 t
, ns
, tunnel
[t
].nr
);
2639 if (l
) // Is this not a ZLB?
2644 // check sequence of this message
2646 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2647 // some to clear maybe?
2648 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2650 controlt
*c
= tunnel
[t
].controls
;
2651 tunnel
[t
].controls
= c
->next
;
2652 tunnel
[t
].controlc
--;
2653 c
->next
= controlfree
;
2656 tunnel
[t
].try = 0; // we have progress
2659 // receiver advance (do here so quoted correctly in any sends below)
2660 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2661 if (skip
< 0) skip
= 0;
2662 if (skip
< tunnel
[t
].controlc
)
2664 // some control packets can now be sent that were previous stuck out of window
2665 int tosend
= tunnel
[t
].window
- skip
;
2666 controlt
*c
= tunnel
[t
].controls
;
2674 tunnel
[t
].try = 0; // first send
2675 tunnelsend(c
->buf
, c
->length
, t
);
2680 if (!tunnel
[t
].controlc
)
2681 tunnel
[t
].retry
= 0; // caught up
2684 { // if not a null message
2689 // Default disconnect cause/message on receipt of CDN. Set to
2690 // more specific value from attribute 1 (result code) or 46
2691 // (disconnect cause) if present below.
2692 int disc_cause_set
= 0;
2693 int disc_cause
= TERM_NAS_REQUEST
;
2694 char const *disc_reason
= "Closed (Received CDN).";
2697 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2699 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2706 LOG(1, s
, t
, "Invalid length in AVP\n");
2707 STAT(tunnel_rx_errors
);
2712 if (flags
& 0x3C) // reserved bits, should be clear
2714 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2716 result
= 2; // general error
2717 error
= 3; // reserved field non-zero
2721 // if continue a infinity loop is created.
2722 LOG(1, s
, t
, "It's infinite loop protection %02X\n", *b
);
2729 if (*(uint16_t *) (b
))
2731 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2733 result
= 2; // general error
2734 error
= 6; // generic vendor-specific error
2735 msg
= "unsupported vendor-specific";
2738 // if continue a infinity loop is created.
2739 LOG(1, s
, t
, "It's infinite loop protection %02X\n", *b
);
2746 mtype
= ntohs(*(uint16_t *) (b
));
2754 // handle hidden AVPs
2755 if (!*config
->l2tp_secret
)
2757 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2759 result
= 2; // general error
2760 error
= 6; // generic vendor-specific error
2761 msg
= "secret not specified";
2764 if (!session
[s
].random_vector_length
)
2766 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2768 result
= 2; // general error
2769 error
= 6; // generic
2770 msg
= "no random vector";
2775 LOG(2, s
, t
, "Short hidden AVP.\n");
2777 result
= 2; // general error
2778 error
= 2; // length is wrong
2784 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2786 orig_len
= ntohs(*(uint16_t *) b
);
2787 if (orig_len
> n
+ 2)
2789 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2793 result
= 2; // general error
2794 error
= 2; // length is wrong
2803 LOG(3, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2804 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2808 case 0: // message type
2809 message
= ntohs(*(uint16_t *) b
);
2810 mandatory
= flags
& 0x80;
2811 LOG(3, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2813 case 1: // result code
2815 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2816 char const *resdesc
= "(unknown)";
2817 char const *errdesc
= NULL
;
2822 resdesc
= l2tp_stopccn_result_code(rescode
);
2823 cause
= TERM_LOST_SERVICE
;
2825 else if (message
== 14)
2827 resdesc
= l2tp_cdn_result_code(rescode
);
2829 cause
= TERM_LOST_CARRIER
;
2831 cause
= TERM_ADMIN_RESET
;
2834 LOG(3, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2837 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2838 errdesc
= l2tp_error_code(errcode
);
2839 LOG(3, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2842 LOG(3, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2844 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2846 disc_cause_set
= mtype
;
2847 disc_reason
= errdesc
? errdesc
: resdesc
;
2854 case 2: // protocol version
2856 version
= ntohs(*(uint16_t *) (b
));
2857 LOG(3, s
, t
, " Protocol version = %u\n", version
);
2858 if (version
&& version
!= 0x0100)
2859 { // allow 0.0 and 1.0
2860 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2862 result
= 5; // unspported protocol version
2863 error
= 0x0100; // supported version
2869 case 3: // framing capabilities
2871 case 4: // bearer capabilities
2873 case 5: // tie breaker
2874 // We never open tunnels, so we don't care about tie breakers
2876 case 6: // firmware revision
2878 case 7: // host name
2879 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2880 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2881 LOG(3, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2882 // TBA - to send to RADIUS
2884 case 8: // vendor name
2885 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2886 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2887 LOG(3, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2889 case 9: // assigned tunnel
2890 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2891 LOG(3, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2893 case 10: // rx window
2894 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2895 if (!tunnel
[t
].window
)
2896 tunnel
[t
].window
= 1; // window of 0 is silly
2897 LOG(3, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2899 case 11: // Request Challenge
2901 LOG(3, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2903 build_chap_response(b
, 2, n
, &sendchalresponse
);
2904 else if (message
== 2)
2905 build_chap_response(b
, 3, n
, &sendchalresponse
);
2908 case 13: // receive challenge Response
2909 if (tunnel
[t
].isremotelns
)
2911 recvchalresponse
= calloc(17, 1);
2912 memcpy(recvchalresponse
, b
, (n
< 17) ? n
: 16);
2913 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2916 // Why did they send a response? We never challenge.
2917 LOG(2, s
, t
, " received unexpected challenge response\n");
2920 case 14: // assigned session
2921 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2922 LOG(3, s
, t
, " assigned session = %u\n", asession
);
2924 case 15: // call serial number
2925 LOG(3, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2927 case 18: // bearer type
2928 LOG(3, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2931 case 19: // framing type
2932 LOG(3, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2935 case 21: // called number
2936 memset(called
, 0, sizeof(called
));
2937 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2938 LOG(3, s
, t
, " Called <%s>\n", called
);
2940 case 22: // calling number
2941 memset(calling
, 0, sizeof(calling
));
2942 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2943 LOG(3, s
, t
, " Calling <%s>\n", calling
);
2947 case 24: // tx connect speed
2950 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2954 // AS5300s send connect speed as a string
2956 memset(tmp
, 0, sizeof(tmp
));
2957 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2958 session
[s
].tx_connect_speed
= atol(tmp
);
2960 LOG(3, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2962 case 38: // rx connect speed
2965 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2969 // AS5300s send connect speed as a string
2971 memset(tmp
, 0, sizeof(tmp
));
2972 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2973 session
[s
].rx_connect_speed
= atol(tmp
);
2975 LOG(3, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2977 case 25: // Physical Channel ID
2979 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2980 LOG(3, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2983 case 29: // Proxy Authentication Type
2985 uint16_t atype
= ntohs(*(uint16_t *)b
);
2986 LOG(3, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2989 case 30: // Proxy Authentication Name
2992 memset(authname
, 0, sizeof(authname
));
2993 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2994 LOG(3, s
, t
, " Proxy Auth Name (%s)\n",
2998 case 31: // Proxy Authentication Challenge
3000 LOG(3, s
, t
, " Proxy Auth Challenge\n");
3003 case 32: // Proxy Authentication ID
3005 uint16_t authid
= ntohs(*(uint16_t *)(b
));
3006 LOG(3, s
, t
, " Proxy Auth ID (%u)\n", authid
);
3009 case 33: // Proxy Authentication Response
3010 LOG(3, s
, t
, " Proxy Auth Response\n");
3012 case 27: // last sent lcp
3013 { // find magic number
3014 uint8_t *p
= b
, *e
= p
+ n
;
3015 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
3017 if (*p
== 5 && p
[1] == 6) // Magic-Number
3018 amagic
= ntohl(*(uint32_t *) (p
+ 2));
3019 else if (*p
== 7) // Protocol-Field-Compression
3020 aflags
|= SESSION_PFC
;
3021 else if (*p
== 8) // Address-and-Control-Field-Compression
3022 aflags
|= SESSION_ACFC
;
3027 case 28: // last recv lcp confreq
3029 case 26: // Initial Received LCP CONFREQ
3031 case 39: // seq required - we control it as an LNS anyway...
3033 case 36: // Random Vector
3034 LOG(3, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
3035 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
3036 if (n
> sizeof(session
[s
].random_vector
))
3037 n
= sizeof(session
[s
].random_vector
);
3038 memcpy(session
[s
].random_vector
, b
, n
);
3039 session
[s
].random_vector_length
= n
;
3041 case 46: // ppp disconnect cause
3044 uint16_t code
= ntohs(*(uint16_t *) b
);
3045 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
3046 uint8_t dir
= *(b
+ 4);
3048 LOG(3, s
, t
, " PPP disconnect cause "
3049 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
3050 code
, proto
, dir
, n
- 5, b
+ 5);
3052 disc_cause_set
= mtype
;
3056 case 1: // admin disconnect
3057 disc_cause
= TERM_ADMIN_RESET
;
3058 disc_reason
= "Administrative disconnect";
3060 case 3: // lcp terminate
3061 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
3062 disc_cause
= TERM_USER_REQUEST
;
3063 disc_reason
= "Normal disconnection";
3065 case 4: // compulsory encryption unavailable
3066 if (dir
!= 1) break; // 1=refused by peer, 2=local
3067 disc_cause
= TERM_USER_ERROR
;
3068 disc_reason
= "Compulsory encryption refused";
3070 case 5: // lcp: fsm timeout
3071 disc_cause
= TERM_PORT_ERROR
;
3072 disc_reason
= "LCP: FSM timeout";
3074 case 6: // lcp: no recognisable lcp packets received
3075 disc_cause
= TERM_PORT_ERROR
;
3076 disc_reason
= "LCP: no recognisable LCP packets";
3078 case 7: // lcp: magic-no error (possibly looped back)
3079 disc_cause
= TERM_PORT_ERROR
;
3080 disc_reason
= "LCP: magic-no error (possible loop)";
3082 case 8: // lcp: echo request timeout
3083 disc_cause
= TERM_PORT_ERROR
;
3084 disc_reason
= "LCP: echo request timeout";
3086 case 13: // auth: fsm timeout
3087 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3088 disc_reason
= "Authentication: FSM timeout";
3090 case 15: // auth: unacceptable auth protocol
3091 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3092 disc_reason
= "Unacceptable authentication protocol";
3094 case 16: // auth: authentication failed
3095 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3096 disc_reason
= "Authentication failed";
3098 case 17: // ncp: fsm timeout
3099 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3100 disc_reason
= "NCP: FSM timeout";
3102 case 18: // ncp: no ncps available
3103 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3104 disc_reason
= "NCP: no NCPs available";
3106 case 19: // ncp: failure to converge on acceptable address
3107 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3108 disc_reason
= (dir
== 1)
3109 ? "NCP: too many Configure-Naks received from peer"
3110 : "NCP: too many Configure-Naks sent to peer";
3112 case 20: // ncp: user not permitted to use any address
3113 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3114 disc_reason
= (dir
== 1)
3115 ? "NCP: local link address not acceptable to peer"
3116 : "NCP: remote link address not acceptable";
3123 static char e
[] = "unknown AVP 0xXXXX";
3124 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
3126 result
= 2; // general error
3127 error
= 8; // unknown mandatory AVP
3128 sprintf((msg
= e
) + 14, "%04x", mtype
);
3135 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3139 case 1: // SCCRQ - Start Control Connection Request
3140 tunnel
[t
].state
= TUNNELOPENING
;
3141 LOG(3, s
, t
, "Received SCCRQ\n");
3142 if (main_quit
!= QUIT_SHUTDOWN
)
3144 LOG(3, s
, t
, "sending SCCRP\n");
3145 controlt
*c
= controlnew(2); // sending SCCRP
3146 control16(c
, 2, version
, 1); // protocol version
3147 control32(c
, 3, 3, 1); // framing
3148 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3149 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Send Challenge response
3150 control16(c
, 9, t
, 1); // assigned tunnel
3151 controladd(c
, 0, t
); // send the resply
3155 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3159 tunnel
[t
].state
= TUNNELOPEN
;
3160 tunnel
[t
].lastrec
= time_now
;
3161 LOG(3, s
, t
, "Received SCCRP\n");
3162 if (main_quit
!= QUIT_SHUTDOWN
)
3164 if (tunnel
[t
].isremotelns
&& recvchalresponse
)
3168 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3169 // check authenticator
3170 if (memcmp(hash
, recvchalresponse
, 16) == 0)
3172 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3173 controlt
*c
= controlnew(3); // sending SCCCN
3174 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3175 controls(c
, 8, Vendor_name
, 1); // Vendor name
3176 control16(c
, 2, version
, 1); // protocol version
3177 control32(c
, 3, 3, 1); // framing Capabilities
3178 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Challenge response
3179 control16(c
, 9, t
, 1); // assigned tunnel
3180 controladd(c
, 0, t
); // send
3184 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3190 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3194 LOG(3, s
, t
, "Received SCCN\n");
3195 tunnel
[t
].state
= TUNNELOPEN
;
3196 tunnel
[t
].lastrec
= time_now
;
3197 controlnull(t
); // ack
3200 LOG(3, s
, t
, "Received StopCCN\n");
3201 controlnull(t
); // ack
3202 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3205 LOG(3, s
, t
, "Received HELLO\n");
3206 controlnull(t
); // simply ACK
3210 LOG(3, s
, t
, "Received OCRQ\n");
3214 LOG(3, s
, t
, "Received OCRO\n");
3218 LOG(3, s
, t
, "Received OCCN\n");
3221 LOG(3, s
, t
, "Received ICRQ\n");
3222 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3224 controlt
*c
= controlnew(11); // ICRP
3226 LOG(3, s
, t
, "Sending ICRP\n");
3229 sessionfree
= session
[s
].next
;
3230 memset(&session
[s
], 0, sizeof(session
[s
]));
3232 if (s
> config
->cluster_highest_sessionid
)
3233 config
->cluster_highest_sessionid
= s
;
3235 session
[s
].opened
= time_now
;
3236 session
[s
].tunnel
= t
;
3237 session
[s
].far
= asession
;
3238 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3239 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3240 control16(c
, 14, s
, 1); // assigned session
3241 controladd(c
, asession
, t
); // send the reply
3243 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3244 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3246 session
[s
].ppp
.phase
= Establish
;
3247 session
[s
].ppp
.lcp
= Starting
;
3249 STAT(session_created
);
3254 controlt
*c
= controlnew(14); // CDN
3255 LOG(3, s
, t
, "Sending CDN\n");
3258 STAT(session_overflow
);
3259 LOG(1, 0, t
, "No free sessions\n");
3260 control16(c
, 1, 4, 0); // temporary lack of resources
3263 control16(c
, 1, 2, 7); // shutting down, try another
3265 controladd(c
, asession
, t
); // send the message
3269 LOG(3, s
, t
, "Received ICRP\n");
3270 if (session
[s
].forwardtosession
)
3272 controlt
*c
= controlnew(12); // ICCN
3274 session
[s
].opened
= time_now
;
3275 session
[s
].tunnel
= t
;
3276 session
[s
].far
= asession
;
3277 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3279 control32(c
, 19, 1, 1); // Framing Type
3280 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3281 controladd(c
, asession
, t
); // send the message
3282 LOG(3, s
, t
, "Sending ICCN\n");
3286 LOG(3, s
, t
, "Received ICCN\n");
3287 if (amagic
== 0) amagic
= time_now
;
3288 session
[s
].magic
= amagic
; // set magic number
3289 session
[s
].flags
= aflags
; // set flags received
3290 session
[s
].mru
= PPPoE_MRU
; // default
3291 controlnull(t
); // ack
3294 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3295 sess_local
[s
].ppp_mru
= MRU
;
3297 // Set multilink options before sending initial LCP packet
3298 sess_local
[s
].mp_mrru
= 1614;
3299 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_address
? config
->iftun_address
: my_address
);
3302 change_state(s
, lcp
, RequestSent
);
3306 LOG(3, s
, t
, "Received CDN\n");
3307 controlnull(t
); // ack
3308 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3311 LOG(1, s
, t
, "Missing message type\n");
3314 STAT(tunnel_rx_errors
);
3316 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3318 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3321 if (sendchalresponse
) free(sendchalresponse
);
3322 if (recvchalresponse
) free(recvchalresponse
);
3323 cluster_send_tunnel(t
);
3327 LOG(4, s
, t
, " Got a ZLB ack\n");
3334 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3335 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3336 { // HDLC address header, discard
3342 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3343 STAT(tunnel_rx_errors
);
3353 proto
= ntohs(*(uint16_t *) p
);
3358 if (session
[s
].forwardtosession
)
3360 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3361 // Forward to LAC/BAS or Remote LNS session
3362 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3365 else if (config
->auth_tunnel_change_addr_src
)
3367 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3368 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3370 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3371 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3372 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3374 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3378 if (s
&& !session
[s
].opened
) // Is something wrong??
3380 if (!config
->cluster_iam_master
)
3382 // Pass it off to the master to deal with..
3383 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3387 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3388 STAT(tunnel_rx_errors
);
3392 if (proto
== PPPPAP
)
3394 session
[s
].last_packet
= time_now
;
3395 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3396 processpap(s
, t
, p
, l
);
3398 else if (proto
== PPPCHAP
)
3400 session
[s
].last_packet
= time_now
;
3401 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3402 processchap(s
, t
, p
, l
);
3404 else if (proto
== PPPLCP
)
3406 session
[s
].last_packet
= time_now
;
3407 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3408 processlcp(s
, t
, p
, l
);
3410 else if (proto
== PPPIPCP
)
3412 session
[s
].last_packet
= time_now
;
3413 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3414 processipcp(s
, t
, p
, l
);
3416 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3418 session
[s
].last_packet
= time_now
;
3419 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3420 processipv6cp(s
, t
, p
, l
);
3422 else if (proto
== PPPCCP
)
3424 session
[s
].last_packet
= time_now
;
3425 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3426 processccp(s
, t
, p
, l
);
3428 else if (proto
== PPPIP
)
3432 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3433 return; // closing session, PPP not processed
3436 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3437 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3439 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3443 processipin(s
, t
, p
, l
);
3445 else if (proto
== PPPMP
)
3449 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3450 return; // closing session, PPP not processed
3453 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3454 if (!config
->cluster_iam_master
)
3456 // The fragments reconstruction is managed by the Master.
3457 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3461 processmpin(s
, t
, p
, l
);
3463 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3467 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3468 return; // closing session, PPP not processed
3471 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3472 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3474 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3478 if (!config
->cluster_iam_master
)
3480 // Check if DhcpV6, IP dst: FF02::1:2, Src Port 0x0222 (546), Dst Port 0x0223 (547)
3481 if (*(p
+ 6) == 17 && *(p
+ 24) == 0xFF && *(p
+ 25) == 2 &&
3482 *(uint32_t *)(p
+ 26) == 0 && *(uint32_t *)(p
+ 30) == 0 &&
3483 *(uint16_t *)(p
+ 34) == 0 && *(p
+ 36) == 0 && *(p
+ 37) == 1 && *(p
+ 38) == 0 && *(p
+ 39) == 2 &&
3484 *(p
+ 40) == 2 && *(p
+ 41) == 0x22 && *(p
+ 42) == 2 && *(p
+ 43) == 0x23)
3486 // DHCPV6 must be managed by the Master.
3487 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3492 processipv6in(s
, t
, p
, l
);
3494 else if (session
[s
].ppp
.lcp
== Opened
)
3496 session
[s
].last_packet
= time_now
;
3497 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3498 protoreject(s
, t
, p
, l
, proto
);
3502 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3503 proto
, ppp_state(session
[s
].ppp
.lcp
));
3508 // read and process packet on tun
3509 // (i.e. this routine writes to buf[-8]).
3510 static void processtun(uint8_t * buf
, int len
)
3512 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3513 STAT(tun_rx_packets
);
3514 INC_STAT(tun_rx_bytes
, len
);
3522 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3523 STAT(tun_rx_errors
);
3527 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3528 processipout(buf
, len
);
3529 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3530 && config
->ipv6_prefix
.s6_addr
[0])
3531 processipv6out(buf
, len
);
3536 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3537 // that we look at the whole of the tunnel, radius and session tables
3539 static void regular_cleanups(double period
)
3541 // Next tunnel, radius and session to check for actions on.
3542 static tunnelidt t
= 0;
3544 static sessionidt s
= 0;
3557 // divide up tables into slices based on the last run
3558 t_slice
= config
->cluster_highest_tunnelid
* period
;
3559 r_slice
= (MAXRADIUS
- 1) * period
;
3560 s_slice
= config
->cluster_highest_sessionid
* period
;
3564 else if (t_slice
> config
->cluster_highest_tunnelid
)
3565 t_slice
= config
->cluster_highest_tunnelid
;
3569 else if (r_slice
> (MAXRADIUS
- 1))
3570 r_slice
= MAXRADIUS
- 1;
3574 else if (s_slice
> config
->cluster_highest_sessionid
)
3575 s_slice
= config
->cluster_highest_sessionid
;
3577 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3579 for (i
= 0; i
< t_slice
; i
++)
3582 if (t
> config
->cluster_highest_tunnelid
)
3585 if (t
== TUNNEL_ID_PPPOE
)
3588 // check for expired tunnels
3589 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3591 STAT(tunnel_timeout
);
3592 tunnelkill(t
, "Expired");
3596 // check for message resend
3597 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3599 // resend pending messages as timeout on reply
3600 if (tunnel
[t
].retry
<= TIME
)
3602 controlt
*c
= tunnel
[t
].controls
;
3603 uint16_t w
= tunnel
[t
].window
;
3604 tunnel
[t
].try++; // another try
3605 if (tunnel
[t
].try > 5)
3606 tunnelkill(t
, "Timeout on control message"); // game over
3610 tunnelsend(c
->buf
, c
->length
, t
);
3618 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3620 if (!config
->disable_sending_hello
)
3622 controlt
*c
= controlnew(6); // sending HELLO
3623 controladd(c
, 0, t
); // send the message
3624 LOG(3, 0, t
, "Sending HELLO message\n");
3629 // Check for tunnel changes requested from the CLI
3630 if ((a
= cli_tunnel_actions
[t
].action
))
3632 cli_tunnel_actions
[t
].action
= 0;
3633 if (a
& CLI_TUN_KILL
)
3635 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3636 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3642 for (i
= 0; i
< r_slice
; i
++)
3648 if (!radius
[r
].state
)
3651 if (radius
[r
].retry
<= TIME
)
3658 for (i
= 0; i
< s_slice
; i
++)
3661 if (s
> config
->cluster_highest_sessionid
)
3664 if (!session
[s
].opened
) // Session isn't in use
3667 // check for expired sessions
3670 if (session
[s
].die
<= TIME
)
3672 sessionkill(s
, "Expired");
3679 if (sess_local
[s
].lcp
.restart
<= time_now
)
3681 int next_state
= session
[s
].ppp
.lcp
;
3682 switch (session
[s
].ppp
.lcp
)
3686 next_state
= RequestSent
;
3689 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3691 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3692 sendlcp(s
, session
[s
].tunnel
);
3693 change_state(s
, lcp
, next_state
);
3697 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3698 STAT(session_timeout
);
3708 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3710 int next_state
= session
[s
].ppp
.ipcp
;
3711 switch (session
[s
].ppp
.ipcp
)
3715 next_state
= RequestSent
;
3718 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3720 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3721 sendipcp(s
, session
[s
].tunnel
);
3722 change_state(s
, ipcp
, next_state
);
3726 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3727 STAT(session_timeout
);
3737 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3739 int next_state
= session
[s
].ppp
.ipv6cp
;
3740 switch (session
[s
].ppp
.ipv6cp
)
3744 next_state
= RequestSent
;
3747 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3749 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3750 sendipv6cp(s
, session
[s
].tunnel
);
3751 change_state(s
, ipv6cp
, next_state
);
3755 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3756 change_state(s
, ipv6cp
, Stopped
);
3763 if (sess_local
[s
].ccp
.restart
<= time_now
)
3765 int next_state
= session
[s
].ppp
.ccp
;
3766 switch (session
[s
].ppp
.ccp
)
3770 next_state
= RequestSent
;
3773 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3775 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3776 sendccp(s
, session
[s
].tunnel
);
3777 change_state(s
, ccp
, next_state
);
3781 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3782 change_state(s
, ccp
, Stopped
);
3789 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3790 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3792 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3793 STAT(session_timeout
);
3798 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3799 if (session
[s
].ppp
.phase
>= Establish
&&
3800 ((!config
->ppp_keepalive
) ||
3801 (time_now
- session
[s
].last_packet
>= config
->echo_timeout
)) &&
3802 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3804 uint8_t b
[MAXETHER
];
3806 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3810 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3811 *(uint16_t *)(q
+ 2) = htons(8); // Length
3812 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3814 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3815 (int)(time_now
- session
[s
].last_packet
));
3817 tunnelsend(b
, (q
- b
) + 8, session
[s
].tunnel
); // send it
3818 sess_local
[s
].last_echo
= time_now
;
3822 // Drop sessions who have reached session_timeout seconds
3823 if (session
[s
].session_timeout
)
3825 bundleidt bid
= session
[s
].bundle
;
3828 if (time_now
- bundle
[bid
].last_check
>= 1)
3830 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3831 bundle
[bid
].last_check
= time_now
;
3832 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3835 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3837 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3844 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3846 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3852 // Drop sessions who have reached idle_timeout seconds
3853 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3855 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3856 STAT(session_timeout
);
3861 // Check for actions requested from the CLI
3862 if ((a
= cli_session_actions
[s
].action
))
3866 cli_session_actions
[s
].action
= 0;
3867 if (a
& CLI_SESS_KILL
)
3869 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3870 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3871 a
= 0; // dead, no need to check for other actions
3875 if (a
& CLI_SESS_NOSNOOP
)
3877 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3878 session
[s
].snoop_ip
= 0;
3879 session
[s
].snoop_port
= 0;
3883 else if (a
& CLI_SESS_SNOOP
)
3885 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3886 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3887 cli_session_actions
[s
].snoop_port
);
3889 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3890 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3895 if (a
& CLI_SESS_NOTHROTTLE
)
3897 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3898 throttle_session(s
, 0, 0);
3902 else if (a
& CLI_SESS_THROTTLE
)
3904 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3905 cli_session_actions
[s
].throttle_in
,
3906 cli_session_actions
[s
].throttle_out
);
3908 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3913 if (a
& CLI_SESS_NOFILTER
)
3915 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3916 filter_session(s
, 0, 0);
3920 else if (a
& CLI_SESS_FILTER
)
3922 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3923 cli_session_actions
[s
].filter_in
,
3924 cli_session_actions
[s
].filter_out
);
3926 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3932 cluster_send_session(s
);
3935 // RADIUS interim accounting
3936 if (config
->radius_accounting
&& config
->radius_interim
> 0
3937 && session
[s
].ip
&& !session
[s
].walled_garden
3938 && !sess_local
[s
].radius
// RADIUS already in progress
3939 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3940 && session
[s
].flags
& SESSION_STARTED
)
3942 int rad
= radiusnew(s
);
3945 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3946 STAT(radius_overflow
);
3950 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3951 session
[s
].user
, session
[s
].unique_id
);
3953 radiussend(rad
, RADIUSINTERIM
);
3954 sess_local
[s
].last_interim
= time_now
;
3959 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3960 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3964 // Are we in the middle of a tunnel update, or radius
3967 static int still_busy(void)
3970 static clockt last_talked
= 0;
3971 static clockt start_busy_wait
= 0;
3974 static time_t stopped_bgp
= 0;
3979 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3981 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3982 if (bgp_peers
[i
].state
== Established
)
3983 bgp_stop(&bgp_peers
[i
]);
3985 stopped_bgp
= time_now
;
3987 if (!config
->cluster_iam_master
)
3989 // we don't want to become master
3990 cluster_send_ping(0);
3996 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
4001 if (!config
->cluster_iam_master
)
4004 if (main_quit
== QUIT_SHUTDOWN
)
4006 static int dropped
= 0;
4011 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
4012 for (i
= 1; i
< MAXTUNNEL
; i
++)
4013 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
4014 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
4020 if (start_busy_wait
== 0)
4021 start_busy_wait
= TIME
;
4023 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
4025 if (!tunnel
[i
].controlc
)
4028 if (last_talked
!= TIME
)
4030 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
4036 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
4037 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
4039 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
4043 for (i
= 1; i
< MAXRADIUS
; i
++)
4045 if (radius
[i
].state
== RADIUSNULL
)
4047 if (radius
[i
].state
== RADIUSWAIT
)
4050 if (last_talked
!= TIME
)
4052 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
4062 # include <sys/epoll.h>
4064 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
4065 # include "fake_epoll.h"
4068 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
4069 #define BASE_FDS (9 + MAX_UDPFD)
4071 // additional polled fds
4073 # define EXTRA_FDS BGP_NUM_PEERS
4075 # define EXTRA_FDS 0
4078 // main loop - gets packets on tun or udp and processes them
4079 static void mainloop(void)
4083 uint8_t *p
= buf
+ 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4084 // and the forwarded pppoe session
4085 int size_bufp
= sizeof(buf
) - 32;
4086 clockt next_cluster_ping
= 0; // send initial ping immediately
4087 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
4088 int maxevent
= sizeof(events
)/sizeof(*events
);
4090 if ((epollfd
= epoll_create(maxevent
)) < 0)
4092 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
4096 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d , udplacfd=%d, pppoefd=%d, pppoesessfd=%d\n",
4097 clifd
, cluster_sockfd
, tunfd
, udpfd
[0], controlfd
, daefd
, nlfd
, udplacfd
, pppoediscfd
, pppoesessfd
);
4099 /* setup our fds to poll for input */
4101 static struct event_data d
[BASE_FDS
];
4102 struct epoll_event e
;
4109 d
[i
].type
= FD_TYPE_CLI
;
4110 e
.data
.ptr
= &d
[i
++];
4111 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
4114 d
[i
].type
= FD_TYPE_CLUSTER
;
4115 e
.data
.ptr
= &d
[i
++];
4116 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
4118 d
[i
].type
= FD_TYPE_TUN
;
4119 e
.data
.ptr
= &d
[i
++];
4120 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
4122 d
[i
].type
= FD_TYPE_CONTROL
;
4123 e
.data
.ptr
= &d
[i
++];
4124 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
4126 d
[i
].type
= FD_TYPE_DAE
;
4127 e
.data
.ptr
= &d
[i
++];
4128 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
4130 d
[i
].type
= FD_TYPE_NETLINK
;
4131 e
.data
.ptr
= &d
[i
++];
4132 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
4134 d
[i
].type
= FD_TYPE_PPPOEDISC
;
4135 e
.data
.ptr
= &d
[i
++];
4136 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoediscfd
, &e
);
4138 d
[i
].type
= FD_TYPE_PPPOESESS
;
4139 e
.data
.ptr
= &d
[i
++];
4140 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoesessfd
, &e
);
4142 for (j
= 0; j
< config
->nbudpfd
; j
++)
4144 d
[i
].type
= FD_TYPE_UDP
;
4146 e
.data
.ptr
= &d
[i
++];
4147 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
[j
], &e
);
4152 signal(SIGPIPE
, SIG_IGN
);
4153 bgp_setup(config
->as_number
);
4154 if (config
->bind_address
)
4155 bgp_add_route(config
->bind_address
, 0xffffffff);
4157 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4159 if (config
->neighbour
[i
].name
[0])
4160 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4161 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4162 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4163 0); /* 0 = routing disabled */
4167 while (!main_quit
|| still_busy())
4177 config
->reload_config
++;
4180 if (config
->reload_config
)
4182 config
->reload_config
= 0;
4190 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4191 STAT(select_called
);
4196 if (errno
== EINTR
||
4197 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4200 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4206 struct sockaddr_in addr
;
4207 struct in_addr local
;
4210 int udp_ready
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4211 int pppoesess_ready
= 0;
4212 int pppoesess_pkts
= 0;
4214 int cluster_ready
= 0;
4215 int udp_pkts
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4217 int cluster_pkts
= 0;
4219 uint32_t bgp_events
[BGP_NUM_PEERS
];
4220 memset(bgp_events
, 0, sizeof(bgp_events
));
4223 for (c
= n
, i
= 0; i
< c
; i
++)
4225 struct event_data
*d
= events
[i
].data
.ptr
;
4229 case FD_TYPE_CLI
: // CLI connections
4233 alen
= sizeof(addr
);
4234 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4240 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4246 // these are handled below, with multiple interleaved reads
4247 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4248 case FD_TYPE_TUN
: tun_ready
++; break;
4249 case FD_TYPE_UDP
: udp_ready
[d
->index
]++; break;
4250 case FD_TYPE_PPPOESESS
: pppoesess_ready
++; break;
4252 case FD_TYPE_PPPOEDISC
: // pppoe discovery
4253 s
= read(pppoediscfd
, p
, size_bufp
);
4254 if (s
> 0) process_pppoe_disc(p
, s
);
4258 case FD_TYPE_CONTROL
: // nsctl commands
4259 alen
= sizeof(addr
);
4260 s
= recvfromto(controlfd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4261 if (s
> 0) processcontrol(p
, s
, &addr
, alen
, &local
);
4265 case FD_TYPE_DAE
: // DAE requests
4266 alen
= sizeof(addr
);
4267 s
= recvfromto(daefd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4268 if (s
> 0) processdae(p
, s
, &addr
, alen
, &local
);
4272 case FD_TYPE_RADIUS
: // RADIUS response
4273 alen
= sizeof(addr
);
4274 s
= recvfrom(radfds
[d
->index
], p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4275 if (s
>= 0 && config
->cluster_iam_master
)
4277 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4278 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4279 processrad(p
, s
, d
->index
);
4281 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4282 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4290 bgp_events
[d
->index
] = events
[i
].events
;
4295 case FD_TYPE_NETLINK
:
4297 struct nlmsghdr
*nh
= (struct nlmsghdr
*)p
;
4298 s
= netlink_recv(p
, size_bufp
);
4299 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4301 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4304 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4306 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4310 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4315 LOG(1, 0, 0, "Got a unknown netlink message: type %d seq %d flags %d\n", nh
->nlmsg_type
, nh
->nlmsg_seq
, nh
->nlmsg_flags
);
4321 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4326 bgp_process(bgp_events
);
4329 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4331 for (j
= 0; j
< config
->nbudpfd
; j
++)
4333 // L2TP and L2TP REMOTE LNS
4336 alen
= sizeof(addr
);
4337 if ((s
= recvfrom(udpfd
[j
], p
, size_bufp
, 0, (void *) &addr
, &alen
)) > 0)
4339 processudp(p
, s
, &addr
, j
);
4353 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4366 if (pppoesess_ready
)
4368 if ((s
= read(pppoesessfd
, p
, size_bufp
)) > 0)
4370 process_pppoe_sess(p
, s
);
4375 pppoesess_ready
= 0;
4383 alen
= sizeof(addr
);
4384 if ((s
= recvfrom(cluster_sockfd
, p
, size_bufp
, MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4386 processcluster(p
, s
, addr
.sin_addr
.s_addr
);
4397 if (udp_pkts
[0] > 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4398 STAT(multi_read_used
);
4400 if (c
>= config
->multi_read_count
)
4402 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4403 config
->multi_read_count
, udp_pkts
[0], tun_pkts
, cluster_pkts
, pppoesess_pkts
);
4404 STAT(multi_read_exceeded
);
4410 /* no event received, but timers could still have expired */
4411 bgp_process_peers_timers();
4416 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4418 // Log current traffic stats
4419 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4420 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4421 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4422 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4423 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4425 udp_tx
= udp_rx
= 0;
4426 udp_rx_pkt
= eth_rx_pkt
= 0;
4427 eth_tx
= eth_rx
= 0;
4430 if (config
->dump_speed
)
4431 printf("%s\n", config
->bandwidth
);
4433 // Update the internal time counter
4434 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4438 struct param_timer p
= { time_now
};
4439 run_plugins(PLUGIN_TIMER
, &p
);
4443 // Runs on every machine (master and slaves).
4444 if (next_cluster_ping
<= TIME
)
4446 // Check to see which of the cluster is still alive..
4448 cluster_send_ping(basetime
); // Only does anything if we're a slave
4449 cluster_check_master(); // ditto.
4451 cluster_heartbeat(); // Only does anything if we're a master.
4452 cluster_check_slaves(); // ditto.
4454 master_update_counts(); // If we're a slave, send our byte counters to our master.
4456 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4457 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4459 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4462 if (!config
->cluster_iam_master
)
4465 // Run token bucket filtering queue..
4466 // Only run it every 1/10th of a second.
4468 static clockt last_run
= 0;
4469 if (last_run
!= TIME
)
4476 // Handle timeouts, retries etc.
4478 static double last_clean
= 0;
4482 TIME
= now(&this_clean
);
4483 diff
= this_clean
- last_clean
;
4485 // Run during idle time (after we've handled
4486 // all incoming packets) or every 1/10th sec
4487 if (!more
|| diff
> 0.1)
4489 regular_cleanups(diff
);
4490 last_clean
= this_clean
;
4494 if (*config
->accounting_dir
)
4496 static clockt next_acct
= 0;
4497 static clockt next_shut_acct
= 0;
4499 if (next_acct
<= TIME
)
4501 // Dump accounting data
4502 next_acct
= TIME
+ ACCT_TIME
;
4503 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4506 else if (next_shut_acct
<= TIME
)
4508 // Dump accounting data for shutdown sessions
4509 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4516 // Are we the master and shutting down??
4517 if (config
->cluster_iam_master
)
4518 cluster_heartbeat(); // Flush any queued changes..
4520 // Ok. Notify everyone we're shutting down. If we're
4521 // the master, this will force an election.
4522 cluster_send_ping(0);
4525 // Important!!! We MUST not process any packets past this point!
4526 LOG(1, 0, 0, "Shutdown complete\n");
4529 static void stripdomain(char *host
)
4533 if ((p
= strchr(host
, '.')))
4539 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4545 while (fgets(buf
, sizeof(buf
), resolv
))
4547 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4550 if (!isspace(buf
[6]))
4554 while (isspace(*b
)) b
++;
4559 while (*b
&& !isspace(*b
)) b
++;
4561 if (buf
[0] == 'd') // domain is canonical
4567 // first search line
4570 // hold, may be subsequent domain line
4571 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4582 int hl
= strlen(host
);
4583 int dl
= strlen(domain
);
4584 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4585 host
[hl
-dl
- 1] = 0;
4589 *p
= 0; // everything after first dot
4594 // Init data structures
4595 static void initdata(int optdebug
, char *optconfig
)
4599 if (!(config
= shared_malloc(sizeof(configt
))))
4601 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4605 memset(config
, 0, sizeof(configt
));
4606 time(&config
->start_time
);
4607 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4608 config
->debug
= optdebug
;
4609 config
->num_tbfs
= MAXTBFS
;
4610 config
->rl_rate
= 28; // 28kbps
4611 config
->cluster_mcast_ttl
= 1;
4612 config
->cluster_master_min_adv
= 1;
4613 config
->ppp_restart_time
= 3;
4614 config
->ppp_max_configure
= 10;
4615 config
->ppp_max_failure
= 5;
4616 config
->kill_timedout_sessions
= 1;
4617 strcpy(config
->random_device
, RANDOMDEVICE
);
4618 // Set default value echo_timeout and idle_echo_timeout
4619 config
->echo_timeout
= ECHO_TIMEOUT
;
4620 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4621 config
->ppp_keepalive
= 1;
4622 // Set default RDNSS lifetime
4623 config
->dns6_lifetime
= 1200;
4625 log_stream
= stderr
;
4628 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4630 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4633 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4636 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4638 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4641 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4643 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4646 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4648 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4651 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4653 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4656 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4658 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4662 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4664 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4668 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4670 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4674 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4676 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4680 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4682 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4685 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4687 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4689 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4692 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4694 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4696 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4699 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4701 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4702 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4703 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4704 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4705 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4707 // Put all the sessions on the free list marked as undefined.
4708 for (i
= 1; i
< MAXSESSION
; i
++)
4710 session
[i
].next
= i
+ 1;
4711 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4713 session
[MAXSESSION
- 1].next
= 0;
4716 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4717 for (i
= 1; i
< MAXTUNNEL
; i
++)
4718 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4720 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4721 bundle
[i
].state
= BUNDLEUNDEF
;
4726 // Grab my hostname unless it's been specified
4727 gethostname(hostname
, sizeof(hostname
));
4728 stripdomain(hostname
);
4731 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4734 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4736 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4741 lac_initremotelnsdata();
4744 static int assign_ip_address(sessionidt s
)
4748 time_t best_time
= time_now
;
4749 char *u
= session
[s
].user
;
4753 CSTAT(assign_ip_address
);
4755 for (i
= 1; i
< ip_pool_size
; i
++)
4757 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4760 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4767 if (ip_address_pool
[i
].last
< best_time
)
4770 if (!(best_time
= ip_address_pool
[i
].last
))
4771 break; // never used, grab this one
4777 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4781 session
[s
].ip
= ip_address_pool
[best
].address
;
4782 session
[s
].ip_pool_index
= best
;
4783 ip_address_pool
[best
].assigned
= 1;
4784 ip_address_pool
[best
].last
= time_now
;
4785 ip_address_pool
[best
].session
= s
;
4786 if (session
[s
].walled_garden
)
4787 /* Don't track addresses of users in walled garden (note: this
4788 means that their address isn't "sticky" even if they get
4790 ip_address_pool
[best
].user
[0] = 0;
4792 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4795 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4796 reuse
? "Reusing" : "Allocating", best
);
4801 static void free_ip_address(sessionidt s
)
4803 int i
= session
[s
].ip_pool_index
;
4806 CSTAT(free_ip_address
);
4809 return; // what the?
4811 if (i
< 0) // Is this actually part of the ip pool?
4815 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4817 ip_address_pool
[i
].assigned
= 0;
4818 ip_address_pool
[i
].session
= 0;
4819 ip_address_pool
[i
].last
= time_now
;
4823 // Fsck the address pool against the session table.
4824 // Normally only called when we become a master.
4826 // This isn't perfect: We aren't keep tracking of which
4827 // users used to have an IP address.
4829 void rebuild_address_pool(void)
4834 // Zero the IP pool allocation, and build
4835 // a map from IP address to pool index.
4836 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4838 ip_address_pool
[i
].assigned
= 0;
4839 ip_address_pool
[i
].session
= 0;
4840 if (!ip_address_pool
[i
].address
)
4843 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4846 for (i
= 0; i
< MAXSESSION
; ++i
)
4849 if (!(session
[i
].opened
&& session
[i
].ip
))
4852 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4854 if (session
[i
].ip_pool_index
< 0)
4856 // Not allocated out of the pool.
4857 if (ipid
< 1) // Not found in the pool either? good.
4860 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4861 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4863 // Fall through and process it as part of the pool.
4867 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4869 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4871 session
[i
].ip_pool_index
= ipid
;
4875 ip_address_pool
[ipid
].assigned
= 1;
4876 ip_address_pool
[ipid
].session
= i
;
4877 ip_address_pool
[ipid
].last
= time_now
;
4878 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4879 session
[i
].ip_pool_index
= ipid
;
4880 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4885 // Fix the address pool to match a changed session.
4886 // (usually when the master sends us an update).
4887 static void fix_address_pool(int sid
)
4891 ipid
= session
[sid
].ip_pool_index
;
4893 if (ipid
> ip_pool_size
)
4894 return; // Ignore it. rebuild_address_pool will fix it up.
4896 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4897 return; // Just ignore it. rebuild_address_pool will take care of it.
4899 ip_address_pool
[ipid
].assigned
= 1;
4900 ip_address_pool
[ipid
].session
= sid
;
4901 ip_address_pool
[ipid
].last
= time_now
;
4902 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4906 // Add a block of addresses to the IP pool to hand out.
4908 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4912 prefixlen
= 32; // Host route only.
4914 addr
&= 0xffffffff << (32 - prefixlen
);
4916 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4919 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4921 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4922 continue; // Skip 0 and broadcast addresses.
4924 ip_address_pool
[ip_pool_size
].address
= i
;
4925 ip_address_pool
[ip_pool_size
].assigned
= 0;
4927 if (ip_pool_size
>= MAXIPPOOL
)
4929 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4935 // Initialize the IP address pool
4936 static void initippool()
4941 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4943 if (!(f
= fopen(IPPOOLFILE
, "r")))
4945 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4949 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4952 buf
[4095] = 0; // Force it to be zero terminated/
4954 if (*buf
== '#' || *buf
== '\n')
4955 continue; // Skip comments / blank lines
4956 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4957 if ((p
= (char *)strchr(buf
, ':')))
4961 src
= inet_addr(buf
);
4962 if (src
== INADDR_NONE
)
4964 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4967 // This entry is for a specific IP only
4968 if (src
!= config
->bind_address
)
4973 if ((p
= (char *)strchr(pool
, '/')))
4977 in_addr_t start
= 0;
4979 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4981 if (!*p
|| !(numbits
= atoi(p
)))
4983 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4986 start
= ntohl(inet_addr(pool
));
4988 // Add a static route for this pool
4989 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4990 fmtaddr(htonl(start
), 0), numbits
);
4992 routeset(0, start
, numbits
, 0, 1);
4994 add_to_ip_pool(start
, numbits
);
4998 // It's a single ip address
4999 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
5003 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
5006 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
5008 struct sockaddr_in snoop_addr
= {0};
5009 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
5012 snoop_addr
.sin_family
= AF_INET
;
5013 snoop_addr
.sin_addr
.s_addr
= destination
;
5014 snoop_addr
.sin_port
= ntohs(port
);
5016 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
5017 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
5018 htons(snoop_addr
.sin_port
));
5020 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
5021 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
5023 STAT(packets_snooped
);
5026 static int dump_session(FILE **f
, sessiont
*s
)
5028 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
5033 char filename
[1024];
5035 time_t now
= time(NULL
);
5037 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
5038 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
5040 if (!(*f
= fopen(filename
, "w")))
5042 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
5046 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
5047 if(config
->account_all_origin
)
5049 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5054 "# format: username ip qos uptxoctets downrxoctets origin(L=LAC, R=Remote LNS, P=PPPOE)\n",
5056 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5062 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5067 "# format: username ip qos uptxoctets downrxoctets\n",
5069 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5075 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
5076 if(config
->account_all_origin
)
5078 fprintf(*f
, "%s %s %d %u %u %s\n",
5079 s
->user
, // username
5080 fmtaddr(htonl(s
->ip
), 0), // ip
5081 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5082 (uint32_t) s
->cin_delta
, // uptxoctets
5083 (uint32_t) s
->cout_delta
, // downrxoctets
5084 (s
->tunnel
== TUNNEL_ID_PPPOE
)?"P":(tunnel
[s
->tunnel
].isremotelns
?"R":"L")); // Origin
5086 else if (!tunnel
[s
->tunnel
].isremotelns
&& (s
->tunnel
!= TUNNEL_ID_PPPOE
))
5088 fprintf(*f
, "%s %s %d %u %u\n",
5089 s
->user
, // username
5090 fmtaddr(htonl(s
->ip
), 0), // ip
5091 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5092 (uint32_t) s
->cin_delta
, // uptxoctets
5093 (uint32_t) s
->cout_delta
); // downrxoctets
5096 s
->cin_delta
= s
->cout_delta
= 0;
5101 static void dump_acct_info(int all
)
5107 CSTAT(dump_acct_info
);
5111 for (i
= 0; i
< shut_acct_n
; i
++)
5112 dump_session(&f
, &shut_acct
[i
]);
5118 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5119 dump_session(&f
, &session
[i
]);
5126 int main(int argc
, char *argv
[])
5130 char *optconfig
= CONFIGFILE
;
5132 time(&basetime
); // start clock
5135 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
5140 if (fork()) exit(0);
5142 if(!freopen("/dev/null", "r", stdin
)) LOG(0, 0, 0, "Error freopen stdin: %s\n", strerror(errno
));
5143 if(!freopen("/dev/null", "w", stdout
)) LOG(0, 0, 0, "Error freopen stdout: %s\n", strerror(errno
));
5144 if(!freopen("/dev/null", "w", stderr
)) LOG(0, 0, 0, "Error freopen stderr: %s\n", strerror(errno
));
5153 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
5156 printf("Args are:\n"
5157 "\t-d\t\tDetach from terminal\n"
5158 "\t-c <file>\tConfig file\n"
5159 "\t-h <hostname>\tForce hostname\n"
5167 // Start the timer routine off
5169 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5172 initdata(optdebug
, optconfig
);
5176 /* set hostname /after/ having read the config file */
5177 if (*config
->hostname
)
5178 strcpy(hostname
, config
->hostname
);
5179 cli_init_complete(hostname
);
5181 init_tbf(config
->num_tbfs
);
5183 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5184 LOG(0, 0, 0, "Copyright (c) 2012, 2013, 2014 ISP FDN & SAMESWIRELESS\n");
5185 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5186 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5189 rlim
.rlim_cur
= RLIM_INFINITY
;
5190 rlim
.rlim_max
= RLIM_INFINITY
;
5191 // Remove the maximum core size
5192 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5193 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5195 // Make core dumps go to /tmp
5196 if(chdir("/tmp")) LOG(0, 0, 0, "Error chdir /tmp: %s\n", strerror(errno
));
5199 if (config
->scheduler_fifo
)
5202 struct sched_param params
= {0};
5203 params
.sched_priority
= 1;
5205 if (get_nprocs() < 2)
5207 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5208 config
->scheduler_fifo
= 0;
5212 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5214 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5218 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5219 config
->scheduler_fifo
= 0;
5226 /* Set up the cluster communications port. */
5227 if (cluster_init() < 0)
5231 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5233 if (*config
->pppoe_if_to_bind
)
5236 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config
->pppoe_if_to_bind
);
5239 if (!config
->nbmultiaddress
)
5241 config
->bind_n_address
[0] = config
->bind_address
;
5242 config
->nbmultiaddress
++;
5244 config
->nbudpfd
= config
->nbmultiaddress
;
5245 for (i
= 0; i
< config
->nbudpfd
; i
++)
5246 initudp(&udpfd
[i
], config
->bind_n_address
[i
]);
5248 config
->indexlacudpfd
= config
->nbudpfd
;
5249 udpfd
[config
->indexlacudpfd
] = udplacfd
;
5256 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
5264 unsigned seed
= time_now
^ getpid();
5265 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5269 signal(SIGHUP
, sighup_handler
);
5270 signal(SIGCHLD
, sigchild_handler
);
5271 signal(SIGTERM
, shutdown_handler
);
5272 signal(SIGINT
, shutdown_handler
);
5273 signal(SIGQUIT
, shutdown_handler
);
5275 // Prevent us from getting paged out
5276 if (config
->lock_pages
)
5278 if (!mlockall(MCL_CURRENT
))
5279 LOG(1, 0, 0, "Locking pages into memory\n");
5281 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5286 /* remove plugins (so cleanup code gets run) */
5289 // Remove the PID file if we wrote it
5290 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5291 unlink(config
->pid_file
);
5293 /* kill CLI children */
5294 signal(SIGTERM
, SIG_IGN
);
5299 static void sighup_handler(int sig
)
5304 static void shutdown_handler(int sig
)
5306 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5309 static void sigchild_handler(int sig
)
5311 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5315 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5318 *challenge_response
= NULL
;
5320 if (!*config
->l2tp_secret
)
5322 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5326 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5328 *challenge_response
= calloc(17, 1);
5331 MD5_Update(&ctx
, &id
, 1);
5332 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5333 MD5_Update(&ctx
, challenge
, challenge_length
);
5334 MD5_Final(*challenge_response
, &ctx
);
5339 static int facility_value(char *name
)
5342 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5344 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5345 return facilitynames
[i
].c_val
;
5350 static void update_config()
5354 static int timeout
= 0;
5355 static int interval
= 0;
5362 if (log_stream
!= stderr
)
5368 if (*config
->log_filename
)
5370 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5372 char *p
= config
->log_filename
+ 7;
5375 openlog("l2tpns", LOG_PID
, facility_value(p
));
5379 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5381 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5383 fseek(log_stream
, 0, SEEK_END
);
5384 setbuf(log_stream
, NULL
);
5388 log_stream
= stderr
;
5389 setbuf(log_stream
, NULL
);
5395 log_stream
= stderr
;
5396 setbuf(log_stream
, NULL
);
5399 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5400 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5402 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5403 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5404 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5406 // reset MRU/MSS globals
5407 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5408 if (MRU
> PPPoE_MRU
)
5411 MSS
= MRU
- TCP_HDRS
;
5414 config
->numradiusservers
= 0;
5415 for (i
= 0; i
< MAXRADSERVER
; i
++)
5416 if (config
->radiusserver
[i
])
5418 config
->numradiusservers
++;
5419 // Set radius port: if not set, take the port from the
5420 // first radius server. For the first radius server,
5421 // take the #defined default value from l2tpns.h
5423 // test twice, In case someone works with
5424 // a secondary radius server without defining
5425 // a primary one, this will work even then.
5426 if (i
> 0 && !config
->radiusport
[i
])
5427 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5428 if (!config
->radiusport
[i
])
5429 config
->radiusport
[i
] = RADPORT
;
5432 if (!config
->numradiusservers
)
5433 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5435 // parse radius_authtypes_s
5436 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5437 p
= config
->radius_authtypes_s
;
5440 char *s
= strpbrk(p
, " \t,");
5446 while (*s
== ' ' || *s
== '\t')
5453 if (!strncasecmp("chap", p
, strlen(p
)))
5455 else if (!strncasecmp("pap", p
, strlen(p
)))
5458 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5460 config
->radius_authtypes
|= type
;
5461 if (!config
->radius_authprefer
)
5462 config
->radius_authprefer
= type
;
5467 if (!config
->radius_authtypes
)
5469 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5470 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5473 // normalise radius_authtypes_s
5474 if (config
->radius_authprefer
== AUTHPAP
)
5476 strcpy(config
->radius_authtypes_s
, "pap");
5477 if (config
->radius_authtypes
& AUTHCHAP
)
5478 strcat(config
->radius_authtypes_s
, ", chap");
5482 strcpy(config
->radius_authtypes_s
, "chap");
5483 if (config
->radius_authtypes
& AUTHPAP
)
5484 strcat(config
->radius_authtypes_s
, ", pap");
5487 if (!config
->radius_dae_port
)
5488 config
->radius_dae_port
= DAEPORT
;
5490 if(!config
->bind_portremotelns
)
5491 config
->bind_portremotelns
= L2TPLACPORT
;
5492 if(!config
->bind_address_remotelns
)
5493 config
->bind_address_remotelns
= INADDR_ANY
;
5495 if (*config
->bind_multi_address
)
5497 char *sip
= config
->bind_multi_address
;
5499 char *e
= config
->bind_multi_address
+ strlen(config
->bind_multi_address
);
5500 config
->nbmultiaddress
= 0;
5502 while (*sip
&& (sip
< e
))
5507 while (n
< e
&& (*n
== ',' || *n
== ' ')) n
++;
5509 while (n
< e
&& (isdigit(*n
) || *n
== '.'))
5517 u
= u
* 10 + *n
- '0';
5525 config
->bind_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5526 config
->iftun_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5527 config
->nbmultiaddress
++;
5528 LOG(1, 0, 0, "Bind address %s\n", fmtaddr(htonl(ip
), 0));
5530 if (config
->nbmultiaddress
>= MAX_BINDADDR
) break;
5536 if (config
->nbmultiaddress
>= 1)
5538 config
->bind_address
= config
->bind_n_address
[0];
5539 config
->iftun_address
= config
->bind_address
;
5543 if(!config
->iftun_address
)
5545 config
->iftun_address
= config
->bind_address
;
5546 config
->iftun_n_address
[0] = config
->iftun_address
;
5549 if (*config
->multi_hostname
)
5551 char *shost
= config
->multi_hostname
;
5553 char *e
= config
->multi_hostname
+ strlen(config
->multi_hostname
);
5554 config
->nbmultihostname
= 0;
5556 while (*shost
&& (shost
< e
))
5558 while ((n
< e
) && (*n
== ' ' || *n
== ',' || *n
== '\t')) n
++;
5561 while (n
< e
&& (*n
!= ',') && (*n
!= '\t'))
5563 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = *n
;
5569 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = 0;
5570 LOG(1, 0, 0, "Bind Hostname %s\n", config
->multi_n_hostname
[config
->nbmultihostname
]);
5571 config
->nbmultihostname
++;
5572 if (config
->nbmultihostname
>= MAX_NBHOSTNAME
) break;
5578 if (config
->nbmultihostname
>= 1)
5580 strcpy(hostname
, config
->multi_n_hostname
[0]);
5581 strcpy(config
->hostname
, hostname
);
5585 if (!*config
->pppoe_ac_name
)
5586 strncpy(config
->pppoe_ac_name
, DEFAULT_PPPOE_AC_NAME
, sizeof(config
->pppoe_ac_name
) - 1);
5588 // re-initialise the random number source
5589 initrandom(config
->random_device
);
5592 for (i
= 0; i
< MAXPLUGINS
; i
++)
5594 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5597 if (*config
->plugins
[i
])
5600 add_plugin(config
->plugins
[i
]);
5602 else if (*config
->old_plugins
[i
])
5605 remove_plugin(config
->old_plugins
[i
]);
5610 guest_accounts_num
= 0;
5611 char *p2
= config
->guest_user
;
5614 char *s
= strpbrk(p2
, " \t,");
5618 while (*s
== ' ' || *s
== '\t')
5625 strcpy(guest_users
[guest_accounts_num
], p2
);
5626 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5627 guest_accounts_num
++;
5630 // Rebuild the guest_user array
5631 strcpy(config
->guest_user
, "");
5633 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5635 strcat(config
->guest_user
, guest_users
[ui
]);
5636 if (ui
<guest_accounts_num
-1)
5638 strcat(config
->guest_user
, ",");
5643 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5644 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5645 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5646 if (!config
->cluster_port
) config
->cluster_port
= CLUSTERPORT
;
5647 if (!*config
->cluster_interface
)
5648 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5650 if (!config
->cluster_hb_interval
)
5651 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5653 if (!config
->cluster_hb_timeout
)
5654 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5656 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5658 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5659 // late, ensure we're sufficiently larger than that
5660 int t
= 4 * config
->cluster_hb_interval
+ 11;
5662 if (config
->cluster_hb_timeout
< t
)
5664 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5665 config
->cluster_hb_timeout
= t
;
5668 // Push timing changes to the slaves immediately if we're the master
5669 if (config
->cluster_iam_master
)
5670 cluster_heartbeat();
5672 interval
= config
->cluster_hb_interval
;
5673 timeout
= config
->cluster_hb_timeout
;
5677 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5680 if ((f
= fopen(config
->pid_file
, "w")))
5682 fprintf(f
, "%d\n", getpid());
5684 config
->wrote_pid
= 1;
5688 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5693 static void read_config_file()
5697 if (!config
->config_file
) return;
5698 if (!(f
= fopen(config
->config_file
, "r")))
5700 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5704 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5706 LOG(3, 0, 0, "Done reading config file\n");
5710 int sessionsetup(sessionidt s
, tunnelidt t
)
5712 // A session now exists, set it up
5718 CSTAT(sessionsetup
);
5720 LOG(3, s
, t
, "Doing session setup for session\n");
5722 // Join a bundle if the MRRU option is accepted
5723 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5725 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5726 if (join_bundle(s
) > 0)
5727 cluster_send_bundle(session
[s
].bundle
);
5730 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5731 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5738 assign_ip_address(s
);
5741 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5742 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5745 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5746 fmtaddr(htonl(session
[s
].ip
), 0));
5749 // Make sure this is right
5750 session
[s
].tunnel
= t
;
5752 // zap old sessions with same IP and/or username
5753 // Don't kill gardened sessions - doing so leads to a DoS
5754 // from someone who doesn't need to know the password
5757 user
= session
[s
].user
;
5758 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5760 if (i
== s
) continue;
5761 if (!session
[s
].opened
) break;
5762 // Allow duplicate sessions for multilink ones of the same bundle.
5763 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5765 if (ip
== session
[i
].ip
)
5767 sessionshutdown(i
, "Duplicate IP address", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5771 if (config
->allow_duplicate_users
) continue;
5772 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5776 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5778 if (!strcasecmp(user
, guest_users
[gu
]))
5784 if (found
) continue;
5786 // Drop the new session in case of duplicate sessionss, not the old one.
5787 if (!strcasecmp(user
, session
[i
].user
))
5788 sessionshutdown(i
, "Duplicate session for users", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5792 // no need to set a route for the same IP address of the bundle
5793 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5797 // Add the route for this session.
5798 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5800 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5801 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5804 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5807 // Static IPs need to be routed if not already
5808 // convered by a Framed-Route. Anything else is part
5809 // of the IP address pool and is already routed, it
5810 // just needs to be added to the IP cache.
5811 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5812 if (session
[s
].ip_pool_index
== -1) // static ip
5814 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5817 cache_ipmap(session
[s
].ip
, s
);
5820 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5821 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5823 // Run the plugin's against this new session.
5825 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5826 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5829 // Allocate TBFs if throttled
5830 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5831 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5833 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5835 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5836 fmtaddr(htonl(session
[s
].ip
), 0),
5837 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5839 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5841 return 1; // RADIUS OK and IP allocated, done...
5845 // This session just got dropped on us by the master or something.
5846 // Make sure our tables up up to date...
5848 int load_session(sessionidt s
, sessiont
*new)
5854 if (new->ip_pool_index
>= MAXIPPOOL
||
5855 new->tunnel
>= MAXTUNNEL
)
5857 LOG(0, s
, 0, "Strange session update received!\n");
5858 // FIXME! What to do here?
5863 // Ok. All sanity checks passed. Now we're committed to
5864 // loading the new session.
5867 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5869 // See if routes/ip cache need updating
5870 if (new->ip
!= session
[s
].ip
)
5873 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5874 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5875 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5883 // remove old routes...
5884 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5886 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5887 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5890 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5896 if (session
[s
].ip_pool_index
== -1) // static IP
5898 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5900 else // It's part of the IP pool, remove it manually.
5901 uncache_ipmap(session
[s
].ip
);
5904 // remove old IPV6 routes...
5905 for (i
= 0; i
< MAXROUTE6
&& session
[s
].route6
[i
].ipv6route
.s6_addr
[0] && session
[s
].route6
[i
].ipv6prefixlen
; i
++)
5907 route6set(s
, session
[s
].route6
[i
].ipv6route
, session
[s
].route6
[i
].ipv6prefixlen
, 0);
5910 if (session
[s
].ipv6address
.s6_addr
[0])
5912 route6set(s
, session
[s
].ipv6address
, 128, 0);
5917 // add new routes...
5918 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5920 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5921 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5924 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5930 // If there's a new one, add it.
5931 if (new->ip_pool_index
== -1)
5933 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5936 cache_ipmap(new->ip
, s
);
5941 if (new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5943 for (i
= 0; i
< MAXROUTE6
&& new->route6
[i
].ipv6prefixlen
; i
++)
5945 route6set(s
, new->route6
[i
].ipv6route
, new->route6
[i
].ipv6prefixlen
, 1);
5949 if (new->ipv6address
.s6_addr
[0] && new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5951 // Check if included in prefix
5952 if (sessionbyipv6(new->ipv6address
) != s
)
5953 route6set(s
, new->ipv6address
, 128, 1);
5957 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5959 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5963 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5965 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5966 new->filter_out
= 0;
5969 if (new->filter_in
!= session
[s
].filter_in
)
5971 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5972 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5975 if (new->filter_out
!= session
[s
].filter_out
)
5977 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5978 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5981 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5982 // for walking the sessions to forward byte counts to the master.
5983 config
->cluster_highest_sessionid
= s
;
5985 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5987 // Do fixups into address pool.
5988 if (new->ip_pool_index
!= -1)
5989 fix_address_pool(s
);
5994 static void initplugins()
5998 loaded_plugins
= ll_init();
5999 // Initialize the plugins to nothing
6000 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
6001 plugins
[i
] = ll_init();
6004 static void *open_plugin(char *plugin_name
, int load
)
6006 char path
[256] = "";
6008 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
6009 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
6010 return dlopen(path
, RTLD_NOW
);
6013 // plugin callback to get a config value
6014 static void *getconfig(char *key
, enum config_typet type
)
6018 for (i
= 0; config_values
[i
].key
; i
++)
6020 if (!strcmp(config_values
[i
].key
, key
))
6022 if (config_values
[i
].type
== type
)
6023 return ((void *) config
) + config_values
[i
].offset
;
6025 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
6026 key
, type
, config_values
[i
].type
);
6032 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
6036 static int add_plugin(char *plugin_name
)
6038 static struct pluginfuncs funcs
= {
6043 sessiontbysessionidt
,
6044 sessionidtbysessiont
,
6051 cluster_send_session
,
6054 void *p
= open_plugin(plugin_name
, 1);
6055 int (*initfunc
)(struct pluginfuncs
*);
6060 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
6064 if (ll_contains(loaded_plugins
, p
))
6067 return 0; // already loaded
6071 int *v
= dlsym(p
, "plugin_api_version");
6072 if (!v
|| *v
!= PLUGIN_API_VERSION
)
6074 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
6080 if ((initfunc
= dlsym(p
, "plugin_init")))
6082 if (!initfunc(&funcs
))
6084 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
6090 ll_push(loaded_plugins
, p
);
6092 for (i
= 0; i
< max_plugin_functions
; i
++)
6095 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6097 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
6098 ll_push(plugins
[i
], x
);
6102 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
6106 static void run_plugin_done(void *plugin
)
6108 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
6114 static int remove_plugin(char *plugin_name
)
6116 void *p
= open_plugin(plugin_name
, 0);
6122 if (ll_contains(loaded_plugins
, p
))
6125 for (i
= 0; i
< max_plugin_functions
; i
++)
6128 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6129 ll_delete(plugins
[i
], x
);
6132 ll_delete(loaded_plugins
, p
);
6138 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
6142 int run_plugins(int plugin_type
, void *data
)
6144 int (*func
)(void *data
);
6146 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
6147 return PLUGIN_RET_ERROR
;
6149 ll_reset(plugins
[plugin_type
]);
6150 while ((func
= ll_next(plugins
[plugin_type
])))
6154 if (r
!= PLUGIN_RET_OK
)
6155 return r
; // stop here
6158 return PLUGIN_RET_OK
;
6161 static void plugins_done()
6165 ll_reset(loaded_plugins
);
6166 while ((p
= ll_next(loaded_plugins
)))
6170 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
6172 struct nsctl request
;
6173 struct nsctl response
;
6174 int type
= unpack_control(&request
, buf
, len
);
6178 if (log_stream
&& config
->debug
>= 4)
6182 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6183 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
6187 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6188 dump_control(&request
, log_stream
);
6194 case NSCTL_REQ_LOAD
:
6195 if (request
.argc
!= 1)
6197 response
.type
= NSCTL_RES_ERR
;
6199 response
.argv
[0] = "name of plugin required";
6201 else if ((r
= add_plugin(request
.argv
[0])) < 1)
6203 response
.type
= NSCTL_RES_ERR
;
6205 response
.argv
[0] = !r
6206 ? "plugin already loaded"
6207 : "error loading plugin";
6211 response
.type
= NSCTL_RES_OK
;
6217 case NSCTL_REQ_UNLOAD
:
6218 if (request
.argc
!= 1)
6220 response
.type
= NSCTL_RES_ERR
;
6222 response
.argv
[0] = "name of plugin required";
6224 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
6226 response
.type
= NSCTL_RES_ERR
;
6228 response
.argv
[0] = !r
6229 ? "plugin not loaded"
6230 : "plugin not found";
6234 response
.type
= NSCTL_RES_OK
;
6240 case NSCTL_REQ_HELP
:
6241 response
.type
= NSCTL_RES_OK
;
6244 ll_reset(loaded_plugins
);
6245 while ((p
= ll_next(loaded_plugins
)))
6247 char **help
= dlsym(p
, "plugin_control_help");
6248 while (response
.argc
< 0xff && help
&& *help
)
6249 response
.argv
[response
.argc
++] = *help
++;
6254 case NSCTL_REQ_CONTROL
:
6256 struct param_control param
= {
6257 config
->cluster_iam_master
,
6264 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
6266 if (r
== PLUGIN_RET_ERROR
)
6268 response
.type
= NSCTL_RES_ERR
;
6270 response
.argv
[0] = param
.additional
6272 : "error returned by plugin";
6274 else if (r
== PLUGIN_RET_NOTMASTER
)
6276 static char msg
[] = "must be run on master: 000.000.000.000";
6278 response
.type
= NSCTL_RES_ERR
;
6280 if (config
->cluster_master_address
)
6282 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
6283 response
.argv
[0] = msg
;
6287 response
.argv
[0] = "must be run on master: none elected";
6290 else if (!(param
.response
& NSCTL_RESPONSE
))
6292 response
.type
= NSCTL_RES_ERR
;
6294 response
.argv
[0] = param
.response
6295 ? "unrecognised response value from plugin"
6296 : "unhandled action";
6300 response
.type
= param
.response
;
6302 if (param
.additional
)
6305 response
.argv
[0] = param
.additional
;
6313 response
.type
= NSCTL_RES_ERR
;
6315 response
.argv
[0] = "error unpacking control packet";
6318 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6321 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6325 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6328 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6329 if (log_stream
&& config
->debug
>= 4)
6331 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6332 dump_control(&response
, log_stream
);
6336 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6337 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6342 static tunnelidt
new_tunnel()
6345 for (i
= 1; i
< MAXTUNNEL
; i
++)
6347 if ((tunnel
[i
].state
== TUNNELFREE
) && (i
!= TUNNEL_ID_PPPOE
))
6349 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6350 if (i
> config
->cluster_highest_tunnelid
)
6351 config
->cluster_highest_tunnelid
= i
;
6355 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6360 // We're becoming the master. Do any required setup..
6362 // This is principally telling all the plugins that we're
6363 // now a master, and telling them about all the sessions
6364 // that are active too..
6366 void become_master(void)
6369 static struct event_data d
[RADIUS_FDS
];
6370 struct epoll_event e
;
6372 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6374 // running a bunch of iptables commands is slow and can cause
6375 // the master to drop tunnels on takeover--kludge around the
6376 // problem by forking for the moment (note: race)
6377 if (!fork_and_close())
6379 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6381 if (!session
[s
].opened
) // Not an in-use session.
6384 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6391 for (i
= 0; i
< RADIUS_FDS
; i
++)
6393 d
[i
].type
= FD_TYPE_RADIUS
;
6397 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6401 int cmd_show_hist_idle(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6407 if (CLI_HELP_REQUESTED
)
6408 return CLI_HELP_NO_ARGS
;
6411 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6413 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6416 if (!session
[s
].opened
)
6419 idle
= time_now
- session
[s
].last_data
;
6420 idle
/= 5 ; // In multiples of 5 seconds.
6430 for (i
= 0; i
< 63; ++i
)
6432 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6434 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6435 cli_print(cli
, "%d total sessions open.", count
);
6439 int cmd_show_hist_open(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6445 if (CLI_HELP_REQUESTED
)
6446 return CLI_HELP_NO_ARGS
;
6449 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6451 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6454 if (!session
[s
].opened
)
6457 d
= time_now
- session
[s
].opened
;
6460 while (d
> 1 && open
< 32)
6470 for (i
= 0; i
< 30; ++i
)
6472 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6475 cli_print(cli
, "%d total sessions open.", count
);
6481 * This unencodes the AVP using the L2TP secret and the previously
6482 * stored random vector. It overwrites the hidden data with the
6483 * unhidden AVP subformat.
6485 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6491 uint16_t m
= htons(type
);
6493 // Compute initial pad
6495 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6496 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6497 MD5_Update(&ctx
, vector
, vec_len
);
6498 MD5_Final(digest
, &ctx
);
6500 // pointer to last decoded 16 octets
6505 // calculate a new pad based on the last decoded block
6506 if (d
>= sizeof(digest
))
6509 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6510 MD5_Update(&ctx
, last
, sizeof(digest
));
6511 MD5_Final(digest
, &ctx
);
6517 *value
++ ^= digest
[d
++];
6522 int find_filter(char const *name
, size_t len
)
6527 for (i
= 0; i
< MAXFILTER
; i
++)
6529 if (!*ip_filters
[i
].name
)
6537 if (strlen(ip_filters
[i
].name
) != len
)
6540 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6547 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6551 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6552 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6553 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6554 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6555 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6561 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6565 case FILTER_FLAG_OP_ANY
:
6566 return (flags
& sflags
) || (~flags
& cflags
);
6568 case FILTER_FLAG_OP_ALL
:
6569 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6571 case FILTER_FLAG_OP_EST
:
6572 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6578 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6580 uint16_t frag_offset
;
6584 uint16_t src_port
= 0;
6585 uint16_t dst_port
= 0;
6587 ip_filter_rulet
*rule
;
6589 if (len
< 20) // up to end of destination address
6592 if ((*buf
>> 4) != 4) // IPv4
6595 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6597 src_ip
= *(in_addr_t
*) (buf
+ 12);
6598 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6600 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6602 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6603 if (len
< l
+ 4) // ports
6606 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6607 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6608 if (proto
== IPPROTO_TCP
)
6610 if (len
< l
+ 14) // flags
6613 flags
= buf
[l
+ 13] & 0x3f;
6617 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6619 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6622 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6623 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6626 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6627 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6632 // layer 4 deny rules are skipped
6633 if (rule
->action
== FILTER_ACTION_DENY
&&
6634 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6642 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6644 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6647 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6650 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6651 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6658 return rule
->action
== FILTER_ACTION_PERMIT
;
6665 tunnelidt
lac_new_tunnel()
6667 return new_tunnel();
6670 void lac_tunnelclear(tunnelidt t
)
6675 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6677 uint16_t version
= 0x0100; // protocol version
6679 tunnel
[t
].state
= TUNNELOPENING
;
6681 // Sent SCCRQ - Start Control Connection Request
6682 controlt
*c
= controlnew(1); // sending SCCRQ
6683 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
6684 controls(c
, 8, Vendor_name
, 1); // Vendor name
6685 control16(c
, 2, version
, 1); // protocol version
6686 control32(c
, 3, 3, 1); // framing Capabilities
6687 control16(c
, 9, t
, 1); // assigned tunnel
6688 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6689 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6690 controladd(c
, 0, t
); // send
6693 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6695 // Sent ICRQ Incoming-call-request
6696 controlt
*c
= controlnew(10); // ICRQ
6698 control16(c
, 14, s
, 1); // assigned sesion
6699 call_serial_number
++;
6700 control32(c
, 15, call_serial_number
, 1); // call serial number
6701 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6702 controladd(c
, 0, t
); // send
6705 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6707 tunnelshutdown(t
, reason
, result
, error
, msg
);