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
2722 if (*(uint16_t *) (b
))
2724 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2726 result
= 2; // general error
2727 error
= 6; // generic vendor-specific error
2728 msg
= "unsupported vendor-specific";
2732 mtype
= ntohs(*(uint16_t *) (b
));
2740 // handle hidden AVPs
2741 if (!*config
->l2tp_secret
)
2743 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2745 result
= 2; // general error
2746 error
= 6; // generic vendor-specific error
2747 msg
= "secret not specified";
2750 if (!session
[s
].random_vector_length
)
2752 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2754 result
= 2; // general error
2755 error
= 6; // generic
2756 msg
= "no random vector";
2761 LOG(2, s
, t
, "Short hidden AVP.\n");
2763 result
= 2; // general error
2764 error
= 2; // length is wrong
2770 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2772 orig_len
= ntohs(*(uint16_t *) b
);
2773 if (orig_len
> n
+ 2)
2775 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2779 result
= 2; // general error
2780 error
= 2; // length is wrong
2789 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2790 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2794 case 0: // message type
2795 message
= ntohs(*(uint16_t *) b
);
2796 mandatory
= flags
& 0x80;
2797 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2799 case 1: // result code
2801 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2802 char const *resdesc
= "(unknown)";
2803 char const *errdesc
= NULL
;
2808 resdesc
= l2tp_stopccn_result_code(rescode
);
2809 cause
= TERM_LOST_SERVICE
;
2811 else if (message
== 14)
2813 resdesc
= l2tp_cdn_result_code(rescode
);
2815 cause
= TERM_LOST_CARRIER
;
2817 cause
= TERM_ADMIN_RESET
;
2820 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2823 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2824 errdesc
= l2tp_error_code(errcode
);
2825 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2828 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2830 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2832 disc_cause_set
= mtype
;
2833 disc_reason
= errdesc
? errdesc
: resdesc
;
2840 case 2: // protocol version
2842 version
= ntohs(*(uint16_t *) (b
));
2843 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2844 if (version
&& version
!= 0x0100)
2845 { // allow 0.0 and 1.0
2846 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2848 result
= 5; // unspported protocol version
2849 error
= 0x0100; // supported version
2855 case 3: // framing capabilities
2857 case 4: // bearer capabilities
2859 case 5: // tie breaker
2860 // We never open tunnels, so we don't care about tie breakers
2862 case 6: // firmware revision
2864 case 7: // host name
2865 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2866 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2867 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2868 // TBA - to send to RADIUS
2870 case 8: // vendor name
2871 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2872 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2873 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2875 case 9: // assigned tunnel
2876 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2877 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2879 case 10: // rx window
2880 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2881 if (!tunnel
[t
].window
)
2882 tunnel
[t
].window
= 1; // window of 0 is silly
2883 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2885 case 11: // Request Challenge
2887 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2889 build_chap_response(b
, 2, n
, &sendchalresponse
);
2890 else if (message
== 2)
2891 build_chap_response(b
, 3, n
, &sendchalresponse
);
2894 case 13: // receive challenge Response
2895 if (tunnel
[t
].isremotelns
)
2897 recvchalresponse
= calloc(17, 1);
2898 memcpy(recvchalresponse
, b
, (n
< 17) ? n
: 16);
2899 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2902 // Why did they send a response? We never challenge.
2903 LOG(2, s
, t
, " received unexpected challenge response\n");
2906 case 14: // assigned session
2907 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2908 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2910 case 15: // call serial number
2911 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2913 case 18: // bearer type
2914 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2917 case 19: // framing type
2918 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2921 case 21: // called number
2922 memset(called
, 0, sizeof(called
));
2923 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2924 LOG(4, s
, t
, " Called <%s>\n", called
);
2926 case 22: // calling number
2927 memset(calling
, 0, sizeof(calling
));
2928 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2929 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2933 case 24: // tx connect speed
2936 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2940 // AS5300s send connect speed as a string
2942 memset(tmp
, 0, sizeof(tmp
));
2943 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2944 session
[s
].tx_connect_speed
= atol(tmp
);
2946 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2948 case 38: // rx connect speed
2951 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2955 // AS5300s send connect speed as a string
2957 memset(tmp
, 0, sizeof(tmp
));
2958 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2959 session
[s
].rx_connect_speed
= atol(tmp
);
2961 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2963 case 25: // Physical Channel ID
2965 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2966 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2969 case 29: // Proxy Authentication Type
2971 uint16_t atype
= ntohs(*(uint16_t *)b
);
2972 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2975 case 30: // Proxy Authentication Name
2978 memset(authname
, 0, sizeof(authname
));
2979 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2980 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2984 case 31: // Proxy Authentication Challenge
2986 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2989 case 32: // Proxy Authentication ID
2991 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2992 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2995 case 33: // Proxy Authentication Response
2996 LOG(4, s
, t
, " Proxy Auth Response\n");
2998 case 27: // last sent lcp
2999 { // find magic number
3000 uint8_t *p
= b
, *e
= p
+ n
;
3001 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
3003 if (*p
== 5 && p
[1] == 6) // Magic-Number
3004 amagic
= ntohl(*(uint32_t *) (p
+ 2));
3005 else if (*p
== 7) // Protocol-Field-Compression
3006 aflags
|= SESSION_PFC
;
3007 else if (*p
== 8) // Address-and-Control-Field-Compression
3008 aflags
|= SESSION_ACFC
;
3013 case 28: // last recv lcp confreq
3015 case 26: // Initial Received LCP CONFREQ
3017 case 39: // seq required - we control it as an LNS anyway...
3019 case 36: // Random Vector
3020 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
3021 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
3022 if (n
> sizeof(session
[s
].random_vector
))
3023 n
= sizeof(session
[s
].random_vector
);
3024 memcpy(session
[s
].random_vector
, b
, n
);
3025 session
[s
].random_vector_length
= n
;
3027 case 46: // ppp disconnect cause
3030 uint16_t code
= ntohs(*(uint16_t *) b
);
3031 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
3032 uint8_t dir
= *(b
+ 4);
3034 LOG(4, s
, t
, " PPP disconnect cause "
3035 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
3036 code
, proto
, dir
, n
- 5, b
+ 5);
3038 disc_cause_set
= mtype
;
3042 case 1: // admin disconnect
3043 disc_cause
= TERM_ADMIN_RESET
;
3044 disc_reason
= "Administrative disconnect";
3046 case 3: // lcp terminate
3047 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
3048 disc_cause
= TERM_USER_REQUEST
;
3049 disc_reason
= "Normal disconnection";
3051 case 4: // compulsory encryption unavailable
3052 if (dir
!= 1) break; // 1=refused by peer, 2=local
3053 disc_cause
= TERM_USER_ERROR
;
3054 disc_reason
= "Compulsory encryption refused";
3056 case 5: // lcp: fsm timeout
3057 disc_cause
= TERM_PORT_ERROR
;
3058 disc_reason
= "LCP: FSM timeout";
3060 case 6: // lcp: no recognisable lcp packets received
3061 disc_cause
= TERM_PORT_ERROR
;
3062 disc_reason
= "LCP: no recognisable LCP packets";
3064 case 7: // lcp: magic-no error (possibly looped back)
3065 disc_cause
= TERM_PORT_ERROR
;
3066 disc_reason
= "LCP: magic-no error (possible loop)";
3068 case 8: // lcp: echo request timeout
3069 disc_cause
= TERM_PORT_ERROR
;
3070 disc_reason
= "LCP: echo request timeout";
3072 case 13: // auth: fsm timeout
3073 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3074 disc_reason
= "Authentication: FSM timeout";
3076 case 15: // auth: unacceptable auth protocol
3077 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3078 disc_reason
= "Unacceptable authentication protocol";
3080 case 16: // auth: authentication failed
3081 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3082 disc_reason
= "Authentication failed";
3084 case 17: // ncp: fsm timeout
3085 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3086 disc_reason
= "NCP: FSM timeout";
3088 case 18: // ncp: no ncps available
3089 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3090 disc_reason
= "NCP: no NCPs available";
3092 case 19: // ncp: failure to converge on acceptable address
3093 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3094 disc_reason
= (dir
== 1)
3095 ? "NCP: too many Configure-Naks received from peer"
3096 : "NCP: too many Configure-Naks sent to peer";
3098 case 20: // ncp: user not permitted to use any address
3099 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3100 disc_reason
= (dir
== 1)
3101 ? "NCP: local link address not acceptable to peer"
3102 : "NCP: remote link address not acceptable";
3109 static char e
[] = "unknown AVP 0xXXXX";
3110 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
3112 result
= 2; // general error
3113 error
= 8; // unknown mandatory AVP
3114 sprintf((msg
= e
) + 14, "%04x", mtype
);
3121 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3125 case 1: // SCCRQ - Start Control Connection Request
3126 tunnel
[t
].state
= TUNNELOPENING
;
3127 LOG(3, s
, t
, "Received SCCRQ\n");
3128 if (main_quit
!= QUIT_SHUTDOWN
)
3130 LOG(3, s
, t
, "sending SCCRP\n");
3131 controlt
*c
= controlnew(2); // sending SCCRP
3132 control16(c
, 2, version
, 1); // protocol version
3133 control32(c
, 3, 3, 1); // framing
3134 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3135 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Send Challenge response
3136 control16(c
, 9, t
, 1); // assigned tunnel
3137 controladd(c
, 0, t
); // send the resply
3141 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3145 tunnel
[t
].state
= TUNNELOPEN
;
3146 tunnel
[t
].lastrec
= time_now
;
3147 LOG(3, s
, t
, "Received SCCRP\n");
3148 if (main_quit
!= QUIT_SHUTDOWN
)
3150 if (tunnel
[t
].isremotelns
&& recvchalresponse
)
3154 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3155 // check authenticator
3156 if (memcmp(hash
, recvchalresponse
, 16) == 0)
3158 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3159 controlt
*c
= controlnew(3); // sending SCCCN
3160 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3161 controls(c
, 8, Vendor_name
, 1); // Vendor name
3162 control16(c
, 2, version
, 1); // protocol version
3163 control32(c
, 3, 3, 1); // framing Capabilities
3164 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Challenge response
3165 control16(c
, 9, t
, 1); // assigned tunnel
3166 controladd(c
, 0, t
); // send
3170 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3176 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3180 LOG(3, s
, t
, "Received SCCN\n");
3181 tunnel
[t
].state
= TUNNELOPEN
;
3182 tunnel
[t
].lastrec
= time_now
;
3183 controlnull(t
); // ack
3186 LOG(3, s
, t
, "Received StopCCN\n");
3187 controlnull(t
); // ack
3188 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3191 LOG(3, s
, t
, "Received HELLO\n");
3192 controlnull(t
); // simply ACK
3196 LOG(3, s
, t
, "Received OCRQ\n");
3200 LOG(3, s
, t
, "Received OCRO\n");
3204 LOG(3, s
, t
, "Received OCCN\n");
3207 LOG(3, s
, t
, "Received ICRQ\n");
3208 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3210 controlt
*c
= controlnew(11); // ICRP
3212 LOG(3, s
, t
, "Sending ICRP\n");
3215 sessionfree
= session
[s
].next
;
3216 memset(&session
[s
], 0, sizeof(session
[s
]));
3218 if (s
> config
->cluster_highest_sessionid
)
3219 config
->cluster_highest_sessionid
= s
;
3221 session
[s
].opened
= time_now
;
3222 session
[s
].tunnel
= t
;
3223 session
[s
].far
= asession
;
3224 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3225 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3226 control16(c
, 14, s
, 1); // assigned session
3227 controladd(c
, asession
, t
); // send the reply
3229 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3230 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3232 session
[s
].ppp
.phase
= Establish
;
3233 session
[s
].ppp
.lcp
= Starting
;
3235 STAT(session_created
);
3240 controlt
*c
= controlnew(14); // CDN
3241 LOG(3, s
, t
, "Sending CDN\n");
3244 STAT(session_overflow
);
3245 LOG(1, 0, t
, "No free sessions\n");
3246 control16(c
, 1, 4, 0); // temporary lack of resources
3249 control16(c
, 1, 2, 7); // shutting down, try another
3251 controladd(c
, asession
, t
); // send the message
3255 LOG(3, s
, t
, "Received ICRP\n");
3256 if (session
[s
].forwardtosession
)
3258 controlt
*c
= controlnew(12); // ICCN
3260 session
[s
].opened
= time_now
;
3261 session
[s
].tunnel
= t
;
3262 session
[s
].far
= asession
;
3263 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3265 control32(c
, 19, 1, 1); // Framing Type
3266 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3267 controladd(c
, asession
, t
); // send the message
3268 LOG(3, s
, t
, "Sending ICCN\n");
3272 LOG(3, s
, t
, "Received ICCN\n");
3273 if (amagic
== 0) amagic
= time_now
;
3274 session
[s
].magic
= amagic
; // set magic number
3275 session
[s
].flags
= aflags
; // set flags received
3276 session
[s
].mru
= PPPoE_MRU
; // default
3277 controlnull(t
); // ack
3280 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3281 sess_local
[s
].ppp_mru
= MRU
;
3283 // Set multilink options before sending initial LCP packet
3284 sess_local
[s
].mp_mrru
= 1614;
3285 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_address
? config
->iftun_address
: my_address
);
3288 change_state(s
, lcp
, RequestSent
);
3292 LOG(3, s
, t
, "Received CDN\n");
3293 controlnull(t
); // ack
3294 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3297 LOG(1, s
, t
, "Missing message type\n");
3300 STAT(tunnel_rx_errors
);
3302 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3304 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3307 if (sendchalresponse
) free(sendchalresponse
);
3308 if (recvchalresponse
) free(recvchalresponse
);
3309 cluster_send_tunnel(t
);
3313 LOG(4, s
, t
, " Got a ZLB ack\n");
3320 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3321 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3322 { // HDLC address header, discard
3328 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3329 STAT(tunnel_rx_errors
);
3339 proto
= ntohs(*(uint16_t *) p
);
3344 if (session
[s
].forwardtosession
)
3346 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3347 // Forward to LAC/BAS or Remote LNS session
3348 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3351 else if (config
->auth_tunnel_change_addr_src
)
3353 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3354 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3356 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3357 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3358 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3360 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3364 if (s
&& !session
[s
].opened
) // Is something wrong??
3366 if (!config
->cluster_iam_master
)
3368 // Pass it off to the master to deal with..
3369 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3373 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3374 STAT(tunnel_rx_errors
);
3378 if (proto
== PPPPAP
)
3380 session
[s
].last_packet
= time_now
;
3381 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3382 processpap(s
, t
, p
, l
);
3384 else if (proto
== PPPCHAP
)
3386 session
[s
].last_packet
= time_now
;
3387 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3388 processchap(s
, t
, p
, l
);
3390 else if (proto
== PPPLCP
)
3392 session
[s
].last_packet
= time_now
;
3393 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3394 processlcp(s
, t
, p
, l
);
3396 else if (proto
== PPPIPCP
)
3398 session
[s
].last_packet
= time_now
;
3399 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3400 processipcp(s
, t
, p
, l
);
3402 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3404 session
[s
].last_packet
= time_now
;
3405 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3406 processipv6cp(s
, t
, p
, l
);
3408 else if (proto
== PPPCCP
)
3410 session
[s
].last_packet
= time_now
;
3411 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3412 processccp(s
, t
, p
, l
);
3414 else if (proto
== PPPIP
)
3418 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3419 return; // closing session, PPP not processed
3422 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3423 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3425 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3429 processipin(s
, t
, p
, l
);
3431 else if (proto
== PPPMP
)
3435 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3436 return; // closing session, PPP not processed
3439 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3440 if (!config
->cluster_iam_master
)
3442 // The fragments reconstruction is managed by the Master.
3443 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3447 processmpin(s
, t
, p
, l
);
3449 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3453 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3454 return; // closing session, PPP not processed
3457 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3458 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3460 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3464 if (!config
->cluster_iam_master
)
3466 // Check if DhcpV6, IP dst: FF02::1:2, Src Port 0x0222 (546), Dst Port 0x0223 (547)
3467 if (*(p
+ 6) == 17 && *(p
+ 24) == 0xFF && *(p
+ 25) == 2 &&
3468 *(uint32_t *)(p
+ 26) == 0 && *(uint32_t *)(p
+ 30) == 0 &&
3469 *(uint16_t *)(p
+ 34) == 0 && *(p
+ 36) == 0 && *(p
+ 37) == 1 && *(p
+ 38) == 0 && *(p
+ 39) == 2 &&
3470 *(p
+ 40) == 2 && *(p
+ 41) == 0x22 && *(p
+ 42) == 2 && *(p
+ 43) == 0x23)
3472 // DHCPV6 must be managed by the Master.
3473 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3478 processipv6in(s
, t
, p
, l
);
3480 else if (session
[s
].ppp
.lcp
== Opened
)
3482 session
[s
].last_packet
= time_now
;
3483 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3484 protoreject(s
, t
, p
, l
, proto
);
3488 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3489 proto
, ppp_state(session
[s
].ppp
.lcp
));
3494 // read and process packet on tun
3495 // (i.e. this routine writes to buf[-8]).
3496 static void processtun(uint8_t * buf
, int len
)
3498 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3499 STAT(tun_rx_packets
);
3500 INC_STAT(tun_rx_bytes
, len
);
3508 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3509 STAT(tun_rx_errors
);
3513 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3514 processipout(buf
, len
);
3515 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3516 && config
->ipv6_prefix
.s6_addr
[0])
3517 processipv6out(buf
, len
);
3522 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3523 // that we look at the whole of the tunnel, radius and session tables
3525 static void regular_cleanups(double period
)
3527 // Next tunnel, radius and session to check for actions on.
3528 static tunnelidt t
= 0;
3530 static sessionidt s
= 0;
3543 // divide up tables into slices based on the last run
3544 t_slice
= config
->cluster_highest_tunnelid
* period
;
3545 r_slice
= (MAXRADIUS
- 1) * period
;
3546 s_slice
= config
->cluster_highest_sessionid
* period
;
3550 else if (t_slice
> config
->cluster_highest_tunnelid
)
3551 t_slice
= config
->cluster_highest_tunnelid
;
3555 else if (r_slice
> (MAXRADIUS
- 1))
3556 r_slice
= MAXRADIUS
- 1;
3560 else if (s_slice
> config
->cluster_highest_sessionid
)
3561 s_slice
= config
->cluster_highest_sessionid
;
3563 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3565 for (i
= 0; i
< t_slice
; i
++)
3568 if (t
> config
->cluster_highest_tunnelid
)
3571 if (t
== TUNNEL_ID_PPPOE
)
3574 // check for expired tunnels
3575 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3577 STAT(tunnel_timeout
);
3578 tunnelkill(t
, "Expired");
3582 // check for message resend
3583 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3585 // resend pending messages as timeout on reply
3586 if (tunnel
[t
].retry
<= TIME
)
3588 controlt
*c
= tunnel
[t
].controls
;
3589 uint16_t w
= tunnel
[t
].window
;
3590 tunnel
[t
].try++; // another try
3591 if (tunnel
[t
].try > 5)
3592 tunnelkill(t
, "Timeout on control message"); // game over
3596 tunnelsend(c
->buf
, c
->length
, t
);
3604 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3606 if (!config
->disable_sending_hello
)
3608 controlt
*c
= controlnew(6); // sending HELLO
3609 controladd(c
, 0, t
); // send the message
3610 LOG(3, 0, t
, "Sending HELLO message\n");
3615 // Check for tunnel changes requested from the CLI
3616 if ((a
= cli_tunnel_actions
[t
].action
))
3618 cli_tunnel_actions
[t
].action
= 0;
3619 if (a
& CLI_TUN_KILL
)
3621 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3622 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3628 for (i
= 0; i
< r_slice
; i
++)
3634 if (!radius
[r
].state
)
3637 if (radius
[r
].retry
<= TIME
)
3644 for (i
= 0; i
< s_slice
; i
++)
3647 if (s
> config
->cluster_highest_sessionid
)
3650 if (!session
[s
].opened
) // Session isn't in use
3653 // check for expired sessions
3656 if (session
[s
].die
<= TIME
)
3658 sessionkill(s
, "Expired");
3665 if (sess_local
[s
].lcp
.restart
<= time_now
)
3667 int next_state
= session
[s
].ppp
.lcp
;
3668 switch (session
[s
].ppp
.lcp
)
3672 next_state
= RequestSent
;
3675 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3677 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3678 sendlcp(s
, session
[s
].tunnel
);
3679 change_state(s
, lcp
, next_state
);
3683 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3684 STAT(session_timeout
);
3694 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3696 int next_state
= session
[s
].ppp
.ipcp
;
3697 switch (session
[s
].ppp
.ipcp
)
3701 next_state
= RequestSent
;
3704 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3706 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3707 sendipcp(s
, session
[s
].tunnel
);
3708 change_state(s
, ipcp
, next_state
);
3712 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3713 STAT(session_timeout
);
3723 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3725 int next_state
= session
[s
].ppp
.ipv6cp
;
3726 switch (session
[s
].ppp
.ipv6cp
)
3730 next_state
= RequestSent
;
3733 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3735 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3736 sendipv6cp(s
, session
[s
].tunnel
);
3737 change_state(s
, ipv6cp
, next_state
);
3741 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3742 change_state(s
, ipv6cp
, Stopped
);
3749 if (sess_local
[s
].ccp
.restart
<= time_now
)
3751 int next_state
= session
[s
].ppp
.ccp
;
3752 switch (session
[s
].ppp
.ccp
)
3756 next_state
= RequestSent
;
3759 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3761 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3762 sendccp(s
, session
[s
].tunnel
);
3763 change_state(s
, ccp
, next_state
);
3767 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3768 change_state(s
, ccp
, Stopped
);
3775 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3776 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3778 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3779 STAT(session_timeout
);
3784 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3785 if (session
[s
].ppp
.phase
>= Establish
&&
3786 ((!config
->ppp_keepalive
) ||
3787 (time_now
- session
[s
].last_packet
>= config
->echo_timeout
)) &&
3788 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3790 uint8_t b
[MAXETHER
];
3792 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3796 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3797 *(uint16_t *)(q
+ 2) = htons(8); // Length
3798 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3800 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3801 (int)(time_now
- session
[s
].last_packet
));
3803 tunnelsend(b
, (q
- b
) + 8, session
[s
].tunnel
); // send it
3804 sess_local
[s
].last_echo
= time_now
;
3808 // Drop sessions who have reached session_timeout seconds
3809 if (session
[s
].session_timeout
)
3811 bundleidt bid
= session
[s
].bundle
;
3814 if (time_now
- bundle
[bid
].last_check
>= 1)
3816 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3817 bundle
[bid
].last_check
= time_now
;
3818 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3821 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3823 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3830 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3832 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3838 // Drop sessions who have reached idle_timeout seconds
3839 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3841 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3842 STAT(session_timeout
);
3847 // Check for actions requested from the CLI
3848 if ((a
= cli_session_actions
[s
].action
))
3852 cli_session_actions
[s
].action
= 0;
3853 if (a
& CLI_SESS_KILL
)
3855 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3856 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3857 a
= 0; // dead, no need to check for other actions
3861 if (a
& CLI_SESS_NOSNOOP
)
3863 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3864 session
[s
].snoop_ip
= 0;
3865 session
[s
].snoop_port
= 0;
3869 else if (a
& CLI_SESS_SNOOP
)
3871 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3872 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3873 cli_session_actions
[s
].snoop_port
);
3875 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3876 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3881 if (a
& CLI_SESS_NOTHROTTLE
)
3883 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3884 throttle_session(s
, 0, 0);
3888 else if (a
& CLI_SESS_THROTTLE
)
3890 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3891 cli_session_actions
[s
].throttle_in
,
3892 cli_session_actions
[s
].throttle_out
);
3894 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3899 if (a
& CLI_SESS_NOFILTER
)
3901 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3902 filter_session(s
, 0, 0);
3906 else if (a
& CLI_SESS_FILTER
)
3908 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3909 cli_session_actions
[s
].filter_in
,
3910 cli_session_actions
[s
].filter_out
);
3912 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3918 cluster_send_session(s
);
3921 // RADIUS interim accounting
3922 if (config
->radius_accounting
&& config
->radius_interim
> 0
3923 && session
[s
].ip
&& !session
[s
].walled_garden
3924 && !sess_local
[s
].radius
// RADIUS already in progress
3925 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3926 && session
[s
].flags
& SESSION_STARTED
)
3928 int rad
= radiusnew(s
);
3931 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3932 STAT(radius_overflow
);
3936 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3937 session
[s
].user
, session
[s
].unique_id
);
3939 radiussend(rad
, RADIUSINTERIM
);
3940 sess_local
[s
].last_interim
= time_now
;
3945 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3946 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3950 // Are we in the middle of a tunnel update, or radius
3953 static int still_busy(void)
3956 static clockt last_talked
= 0;
3957 static clockt start_busy_wait
= 0;
3960 static time_t stopped_bgp
= 0;
3965 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3967 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3968 if (bgp_peers
[i
].state
== Established
)
3969 bgp_stop(&bgp_peers
[i
]);
3971 stopped_bgp
= time_now
;
3973 if (!config
->cluster_iam_master
)
3975 // we don't want to become master
3976 cluster_send_ping(0);
3982 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3987 if (!config
->cluster_iam_master
)
3990 if (main_quit
== QUIT_SHUTDOWN
)
3992 static int dropped
= 0;
3997 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3998 for (i
= 1; i
< MAXTUNNEL
; i
++)
3999 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
4000 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
4006 if (start_busy_wait
== 0)
4007 start_busy_wait
= TIME
;
4009 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
4011 if (!tunnel
[i
].controlc
)
4014 if (last_talked
!= TIME
)
4016 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
4022 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
4023 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
4025 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
4029 for (i
= 1; i
< MAXRADIUS
; i
++)
4031 if (radius
[i
].state
== RADIUSNULL
)
4033 if (radius
[i
].state
== RADIUSWAIT
)
4036 if (last_talked
!= TIME
)
4038 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
4048 # include <sys/epoll.h>
4050 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
4051 # include "fake_epoll.h"
4054 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
4055 #define BASE_FDS (9 + MAX_UDPFD)
4057 // additional polled fds
4059 # define EXTRA_FDS BGP_NUM_PEERS
4061 # define EXTRA_FDS 0
4064 // main loop - gets packets on tun or udp and processes them
4065 static void mainloop(void)
4069 uint8_t *p
= buf
+ 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4070 // and the forwarded pppoe session
4071 int size_bufp
= sizeof(buf
) - 32;
4072 clockt next_cluster_ping
= 0; // send initial ping immediately
4073 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
4074 int maxevent
= sizeof(events
)/sizeof(*events
);
4076 if ((epollfd
= epoll_create(maxevent
)) < 0)
4078 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
4082 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",
4083 clifd
, cluster_sockfd
, tunfd
, udpfd
[0], controlfd
, daefd
, nlfd
, udplacfd
, pppoediscfd
, pppoesessfd
);
4085 /* setup our fds to poll for input */
4087 static struct event_data d
[BASE_FDS
];
4088 struct epoll_event e
;
4095 d
[i
].type
= FD_TYPE_CLI
;
4096 e
.data
.ptr
= &d
[i
++];
4097 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
4100 d
[i
].type
= FD_TYPE_CLUSTER
;
4101 e
.data
.ptr
= &d
[i
++];
4102 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
4104 d
[i
].type
= FD_TYPE_TUN
;
4105 e
.data
.ptr
= &d
[i
++];
4106 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
4108 d
[i
].type
= FD_TYPE_CONTROL
;
4109 e
.data
.ptr
= &d
[i
++];
4110 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
4112 d
[i
].type
= FD_TYPE_DAE
;
4113 e
.data
.ptr
= &d
[i
++];
4114 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
4116 d
[i
].type
= FD_TYPE_NETLINK
;
4117 e
.data
.ptr
= &d
[i
++];
4118 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
4120 d
[i
].type
= FD_TYPE_PPPOEDISC
;
4121 e
.data
.ptr
= &d
[i
++];
4122 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoediscfd
, &e
);
4124 d
[i
].type
= FD_TYPE_PPPOESESS
;
4125 e
.data
.ptr
= &d
[i
++];
4126 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoesessfd
, &e
);
4128 for (j
= 0; j
< config
->nbudpfd
; j
++)
4130 d
[i
].type
= FD_TYPE_UDP
;
4132 e
.data
.ptr
= &d
[i
++];
4133 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
[j
], &e
);
4138 signal(SIGPIPE
, SIG_IGN
);
4139 bgp_setup(config
->as_number
);
4140 if (config
->bind_address
)
4141 bgp_add_route(config
->bind_address
, 0xffffffff);
4143 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4145 if (config
->neighbour
[i
].name
[0])
4146 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4147 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4148 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4149 0); /* 0 = routing disabled */
4153 while (!main_quit
|| still_busy())
4163 config
->reload_config
++;
4166 if (config
->reload_config
)
4168 config
->reload_config
= 0;
4176 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4177 STAT(select_called
);
4182 if (errno
== EINTR
||
4183 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4186 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4192 struct sockaddr_in addr
;
4193 struct in_addr local
;
4196 int udp_ready
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4197 int pppoesess_ready
= 0;
4198 int pppoesess_pkts
= 0;
4200 int cluster_ready
= 0;
4201 int udp_pkts
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4203 int cluster_pkts
= 0;
4205 uint32_t bgp_events
[BGP_NUM_PEERS
];
4206 memset(bgp_events
, 0, sizeof(bgp_events
));
4209 for (c
= n
, i
= 0; i
< c
; i
++)
4211 struct event_data
*d
= events
[i
].data
.ptr
;
4215 case FD_TYPE_CLI
: // CLI connections
4219 alen
= sizeof(addr
);
4220 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4226 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4232 // these are handled below, with multiple interleaved reads
4233 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4234 case FD_TYPE_TUN
: tun_ready
++; break;
4235 case FD_TYPE_UDP
: udp_ready
[d
->index
]++; break;
4236 case FD_TYPE_PPPOESESS
: pppoesess_ready
++; break;
4238 case FD_TYPE_PPPOEDISC
: // pppoe discovery
4239 s
= read(pppoediscfd
, p
, size_bufp
);
4240 if (s
> 0) process_pppoe_disc(p
, s
);
4244 case FD_TYPE_CONTROL
: // nsctl commands
4245 alen
= sizeof(addr
);
4246 s
= recvfromto(controlfd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4247 if (s
> 0) processcontrol(p
, s
, &addr
, alen
, &local
);
4251 case FD_TYPE_DAE
: // DAE requests
4252 alen
= sizeof(addr
);
4253 s
= recvfromto(daefd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4254 if (s
> 0) processdae(p
, s
, &addr
, alen
, &local
);
4258 case FD_TYPE_RADIUS
: // RADIUS response
4259 alen
= sizeof(addr
);
4260 s
= recvfrom(radfds
[d
->index
], p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4261 if (s
>= 0 && config
->cluster_iam_master
)
4263 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4264 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4265 processrad(p
, s
, d
->index
);
4267 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4268 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4276 bgp_events
[d
->index
] = events
[i
].events
;
4281 case FD_TYPE_NETLINK
:
4283 struct nlmsghdr
*nh
= (struct nlmsghdr
*)p
;
4284 s
= netlink_recv(p
, size_bufp
);
4285 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4287 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4290 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4292 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4296 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4301 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
);
4307 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4312 bgp_process(bgp_events
);
4315 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4317 for (j
= 0; j
< config
->nbudpfd
; j
++)
4319 // L2TP and L2TP REMOTE LNS
4322 alen
= sizeof(addr
);
4323 if ((s
= recvfrom(udpfd
[j
], p
, size_bufp
, 0, (void *) &addr
, &alen
)) > 0)
4325 processudp(p
, s
, &addr
, j
);
4339 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4352 if (pppoesess_ready
)
4354 if ((s
= read(pppoesessfd
, p
, size_bufp
)) > 0)
4356 process_pppoe_sess(p
, s
);
4361 pppoesess_ready
= 0;
4369 alen
= sizeof(addr
);
4370 if ((s
= recvfrom(cluster_sockfd
, p
, size_bufp
, MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4372 processcluster(p
, s
, addr
.sin_addr
.s_addr
);
4383 if (udp_pkts
[0] > 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4384 STAT(multi_read_used
);
4386 if (c
>= config
->multi_read_count
)
4388 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4389 config
->multi_read_count
, udp_pkts
[0], tun_pkts
, cluster_pkts
, pppoesess_pkts
);
4390 STAT(multi_read_exceeded
);
4396 /* no event received, but timers could still have expired */
4397 bgp_process_peers_timers();
4402 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4404 // Log current traffic stats
4405 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4406 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4407 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4408 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4409 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4411 udp_tx
= udp_rx
= 0;
4412 udp_rx_pkt
= eth_rx_pkt
= 0;
4413 eth_tx
= eth_rx
= 0;
4416 if (config
->dump_speed
)
4417 printf("%s\n", config
->bandwidth
);
4419 // Update the internal time counter
4420 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4424 struct param_timer p
= { time_now
};
4425 run_plugins(PLUGIN_TIMER
, &p
);
4429 // Runs on every machine (master and slaves).
4430 if (next_cluster_ping
<= TIME
)
4432 // Check to see which of the cluster is still alive..
4434 cluster_send_ping(basetime
); // Only does anything if we're a slave
4435 cluster_check_master(); // ditto.
4437 cluster_heartbeat(); // Only does anything if we're a master.
4438 cluster_check_slaves(); // ditto.
4440 master_update_counts(); // If we're a slave, send our byte counters to our master.
4442 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4443 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4445 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4448 if (!config
->cluster_iam_master
)
4451 // Run token bucket filtering queue..
4452 // Only run it every 1/10th of a second.
4454 static clockt last_run
= 0;
4455 if (last_run
!= TIME
)
4462 // Handle timeouts, retries etc.
4464 static double last_clean
= 0;
4468 TIME
= now(&this_clean
);
4469 diff
= this_clean
- last_clean
;
4471 // Run during idle time (after we've handled
4472 // all incoming packets) or every 1/10th sec
4473 if (!more
|| diff
> 0.1)
4475 regular_cleanups(diff
);
4476 last_clean
= this_clean
;
4480 if (*config
->accounting_dir
)
4482 static clockt next_acct
= 0;
4483 static clockt next_shut_acct
= 0;
4485 if (next_acct
<= TIME
)
4487 // Dump accounting data
4488 next_acct
= TIME
+ ACCT_TIME
;
4489 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4492 else if (next_shut_acct
<= TIME
)
4494 // Dump accounting data for shutdown sessions
4495 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4502 // Are we the master and shutting down??
4503 if (config
->cluster_iam_master
)
4504 cluster_heartbeat(); // Flush any queued changes..
4506 // Ok. Notify everyone we're shutting down. If we're
4507 // the master, this will force an election.
4508 cluster_send_ping(0);
4511 // Important!!! We MUST not process any packets past this point!
4512 LOG(1, 0, 0, "Shutdown complete\n");
4515 static void stripdomain(char *host
)
4519 if ((p
= strchr(host
, '.')))
4525 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4531 while (fgets(buf
, sizeof(buf
), resolv
))
4533 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4536 if (!isspace(buf
[6]))
4540 while (isspace(*b
)) b
++;
4545 while (*b
&& !isspace(*b
)) b
++;
4547 if (buf
[0] == 'd') // domain is canonical
4553 // first search line
4556 // hold, may be subsequent domain line
4557 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4568 int hl
= strlen(host
);
4569 int dl
= strlen(domain
);
4570 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4571 host
[hl
-dl
- 1] = 0;
4575 *p
= 0; // everything after first dot
4580 // Init data structures
4581 static void initdata(int optdebug
, char *optconfig
)
4585 if (!(config
= shared_malloc(sizeof(configt
))))
4587 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4591 memset(config
, 0, sizeof(configt
));
4592 time(&config
->start_time
);
4593 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4594 config
->debug
= optdebug
;
4595 config
->num_tbfs
= MAXTBFS
;
4596 config
->rl_rate
= 28; // 28kbps
4597 config
->cluster_mcast_ttl
= 1;
4598 config
->cluster_master_min_adv
= 1;
4599 config
->ppp_restart_time
= 3;
4600 config
->ppp_max_configure
= 10;
4601 config
->ppp_max_failure
= 5;
4602 config
->kill_timedout_sessions
= 1;
4603 strcpy(config
->random_device
, RANDOMDEVICE
);
4604 // Set default value echo_timeout and idle_echo_timeout
4605 config
->echo_timeout
= ECHO_TIMEOUT
;
4606 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4607 config
->ppp_keepalive
= 1;
4608 // Set default RDNSS lifetime
4609 config
->dns6_lifetime
= 1200;
4611 log_stream
= stderr
;
4614 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4616 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4619 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4622 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4624 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4627 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4629 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4632 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4634 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4637 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4639 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4642 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4644 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4648 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4650 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4654 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4656 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4660 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4662 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4666 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4668 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4671 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4673 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4675 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4678 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4680 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4682 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4685 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4687 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4688 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4689 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4690 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4691 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4693 // Put all the sessions on the free list marked as undefined.
4694 for (i
= 1; i
< MAXSESSION
; i
++)
4696 session
[i
].next
= i
+ 1;
4697 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4699 session
[MAXSESSION
- 1].next
= 0;
4702 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4703 for (i
= 1; i
< MAXTUNNEL
; i
++)
4704 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4706 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4707 bundle
[i
].state
= BUNDLEUNDEF
;
4712 // Grab my hostname unless it's been specified
4713 gethostname(hostname
, sizeof(hostname
));
4714 stripdomain(hostname
);
4717 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4720 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4722 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4727 lac_initremotelnsdata();
4730 static int assign_ip_address(sessionidt s
)
4734 time_t best_time
= time_now
;
4735 char *u
= session
[s
].user
;
4739 CSTAT(assign_ip_address
);
4741 for (i
= 1; i
< ip_pool_size
; i
++)
4743 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4746 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4753 if (ip_address_pool
[i
].last
< best_time
)
4756 if (!(best_time
= ip_address_pool
[i
].last
))
4757 break; // never used, grab this one
4763 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4767 session
[s
].ip
= ip_address_pool
[best
].address
;
4768 session
[s
].ip_pool_index
= best
;
4769 ip_address_pool
[best
].assigned
= 1;
4770 ip_address_pool
[best
].last
= time_now
;
4771 ip_address_pool
[best
].session
= s
;
4772 if (session
[s
].walled_garden
)
4773 /* Don't track addresses of users in walled garden (note: this
4774 means that their address isn't "sticky" even if they get
4776 ip_address_pool
[best
].user
[0] = 0;
4778 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4781 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4782 reuse
? "Reusing" : "Allocating", best
);
4787 static void free_ip_address(sessionidt s
)
4789 int i
= session
[s
].ip_pool_index
;
4792 CSTAT(free_ip_address
);
4795 return; // what the?
4797 if (i
< 0) // Is this actually part of the ip pool?
4801 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4803 ip_address_pool
[i
].assigned
= 0;
4804 ip_address_pool
[i
].session
= 0;
4805 ip_address_pool
[i
].last
= time_now
;
4809 // Fsck the address pool against the session table.
4810 // Normally only called when we become a master.
4812 // This isn't perfect: We aren't keep tracking of which
4813 // users used to have an IP address.
4815 void rebuild_address_pool(void)
4820 // Zero the IP pool allocation, and build
4821 // a map from IP address to pool index.
4822 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4824 ip_address_pool
[i
].assigned
= 0;
4825 ip_address_pool
[i
].session
= 0;
4826 if (!ip_address_pool
[i
].address
)
4829 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4832 for (i
= 0; i
< MAXSESSION
; ++i
)
4835 if (!(session
[i
].opened
&& session
[i
].ip
))
4838 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4840 if (session
[i
].ip_pool_index
< 0)
4842 // Not allocated out of the pool.
4843 if (ipid
< 1) // Not found in the pool either? good.
4846 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4847 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4849 // Fall through and process it as part of the pool.
4853 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4855 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4857 session
[i
].ip_pool_index
= ipid
;
4861 ip_address_pool
[ipid
].assigned
= 1;
4862 ip_address_pool
[ipid
].session
= i
;
4863 ip_address_pool
[ipid
].last
= time_now
;
4864 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4865 session
[i
].ip_pool_index
= ipid
;
4866 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4871 // Fix the address pool to match a changed session.
4872 // (usually when the master sends us an update).
4873 static void fix_address_pool(int sid
)
4877 ipid
= session
[sid
].ip_pool_index
;
4879 if (ipid
> ip_pool_size
)
4880 return; // Ignore it. rebuild_address_pool will fix it up.
4882 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4883 return; // Just ignore it. rebuild_address_pool will take care of it.
4885 ip_address_pool
[ipid
].assigned
= 1;
4886 ip_address_pool
[ipid
].session
= sid
;
4887 ip_address_pool
[ipid
].last
= time_now
;
4888 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4892 // Add a block of addresses to the IP pool to hand out.
4894 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4898 prefixlen
= 32; // Host route only.
4900 addr
&= 0xffffffff << (32 - prefixlen
);
4902 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4905 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4907 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4908 continue; // Skip 0 and broadcast addresses.
4910 ip_address_pool
[ip_pool_size
].address
= i
;
4911 ip_address_pool
[ip_pool_size
].assigned
= 0;
4913 if (ip_pool_size
>= MAXIPPOOL
)
4915 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4921 // Initialize the IP address pool
4922 static void initippool()
4927 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4929 if (!(f
= fopen(IPPOOLFILE
, "r")))
4931 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4935 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4938 buf
[4095] = 0; // Force it to be zero terminated/
4940 if (*buf
== '#' || *buf
== '\n')
4941 continue; // Skip comments / blank lines
4942 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4943 if ((p
= (char *)strchr(buf
, ':')))
4947 src
= inet_addr(buf
);
4948 if (src
== INADDR_NONE
)
4950 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4953 // This entry is for a specific IP only
4954 if (src
!= config
->bind_address
)
4959 if ((p
= (char *)strchr(pool
, '/')))
4963 in_addr_t start
= 0;
4965 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4967 if (!*p
|| !(numbits
= atoi(p
)))
4969 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4972 start
= ntohl(inet_addr(pool
));
4974 // Add a static route for this pool
4975 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4976 fmtaddr(htonl(start
), 0), numbits
);
4978 routeset(0, start
, numbits
, 0, 1);
4980 add_to_ip_pool(start
, numbits
);
4984 // It's a single ip address
4985 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4989 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4992 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4994 struct sockaddr_in snoop_addr
= {0};
4995 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4998 snoop_addr
.sin_family
= AF_INET
;
4999 snoop_addr
.sin_addr
.s_addr
= destination
;
5000 snoop_addr
.sin_port
= ntohs(port
);
5002 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
5003 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
5004 htons(snoop_addr
.sin_port
));
5006 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
5007 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
5009 STAT(packets_snooped
);
5012 static int dump_session(FILE **f
, sessiont
*s
)
5014 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
5019 char filename
[1024];
5021 time_t now
= time(NULL
);
5023 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
5024 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
5026 if (!(*f
= fopen(filename
, "w")))
5028 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
5032 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
5033 if(config
->account_all_origin
)
5035 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5040 "# format: username ip qos uptxoctets downrxoctets origin(L=LAC, R=Remote LNS, P=PPPOE)\n",
5042 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5048 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5053 "# format: username ip qos uptxoctets downrxoctets\n",
5055 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5061 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
5062 if(config
->account_all_origin
)
5064 fprintf(*f
, "%s %s %d %u %u %s\n",
5065 s
->user
, // username
5066 fmtaddr(htonl(s
->ip
), 0), // ip
5067 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5068 (uint32_t) s
->cin_delta
, // uptxoctets
5069 (uint32_t) s
->cout_delta
, // downrxoctets
5070 (s
->tunnel
== TUNNEL_ID_PPPOE
)?"P":(tunnel
[s
->tunnel
].isremotelns
?"R":"L")); // Origin
5072 else if (!tunnel
[s
->tunnel
].isremotelns
&& (s
->tunnel
!= TUNNEL_ID_PPPOE
))
5074 fprintf(*f
, "%s %s %d %u %u\n",
5075 s
->user
, // username
5076 fmtaddr(htonl(s
->ip
), 0), // ip
5077 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5078 (uint32_t) s
->cin_delta
, // uptxoctets
5079 (uint32_t) s
->cout_delta
); // downrxoctets
5082 s
->cin_delta
= s
->cout_delta
= 0;
5087 static void dump_acct_info(int all
)
5093 CSTAT(dump_acct_info
);
5097 for (i
= 0; i
< shut_acct_n
; i
++)
5098 dump_session(&f
, &shut_acct
[i
]);
5104 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5105 dump_session(&f
, &session
[i
]);
5112 int main(int argc
, char *argv
[])
5116 char *optconfig
= CONFIGFILE
;
5118 time(&basetime
); // start clock
5121 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
5126 if (fork()) exit(0);
5128 if(!freopen("/dev/null", "r", stdin
)) LOG(0, 0, 0, "Error freopen stdin: %s\n", strerror(errno
));
5129 if(!freopen("/dev/null", "w", stdout
)) LOG(0, 0, 0, "Error freopen stdout: %s\n", strerror(errno
));
5130 if(!freopen("/dev/null", "w", stderr
)) LOG(0, 0, 0, "Error freopen stderr: %s\n", strerror(errno
));
5139 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
5142 printf("Args are:\n"
5143 "\t-d\t\tDetach from terminal\n"
5144 "\t-c <file>\tConfig file\n"
5145 "\t-h <hostname>\tForce hostname\n"
5153 // Start the timer routine off
5155 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5158 initdata(optdebug
, optconfig
);
5162 /* set hostname /after/ having read the config file */
5163 if (*config
->hostname
)
5164 strcpy(hostname
, config
->hostname
);
5165 cli_init_complete(hostname
);
5167 init_tbf(config
->num_tbfs
);
5169 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5170 LOG(0, 0, 0, "Copyright (c) 2012, 2013, 2014 ISP FDN & SAMESWIRELESS\n");
5171 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5172 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5175 rlim
.rlim_cur
= RLIM_INFINITY
;
5176 rlim
.rlim_max
= RLIM_INFINITY
;
5177 // Remove the maximum core size
5178 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5179 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5181 // Make core dumps go to /tmp
5182 if(chdir("/tmp")) LOG(0, 0, 0, "Error chdir /tmp: %s\n", strerror(errno
));
5185 if (config
->scheduler_fifo
)
5188 struct sched_param params
= {0};
5189 params
.sched_priority
= 1;
5191 if (get_nprocs() < 2)
5193 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5194 config
->scheduler_fifo
= 0;
5198 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5200 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5204 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5205 config
->scheduler_fifo
= 0;
5212 /* Set up the cluster communications port. */
5213 if (cluster_init() < 0)
5217 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5219 if (*config
->pppoe_if_to_bind
)
5222 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config
->pppoe_if_to_bind
);
5225 if (!config
->nbmultiaddress
)
5227 config
->bind_n_address
[0] = config
->bind_address
;
5228 config
->nbmultiaddress
++;
5230 config
->nbudpfd
= config
->nbmultiaddress
;
5231 for (i
= 0; i
< config
->nbudpfd
; i
++)
5232 initudp(&udpfd
[i
], config
->bind_n_address
[i
]);
5234 config
->indexlacudpfd
= config
->nbudpfd
;
5235 udpfd
[config
->indexlacudpfd
] = udplacfd
;
5242 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
5250 unsigned seed
= time_now
^ getpid();
5251 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5255 signal(SIGHUP
, sighup_handler
);
5256 signal(SIGCHLD
, sigchild_handler
);
5257 signal(SIGTERM
, shutdown_handler
);
5258 signal(SIGINT
, shutdown_handler
);
5259 signal(SIGQUIT
, shutdown_handler
);
5261 // Prevent us from getting paged out
5262 if (config
->lock_pages
)
5264 if (!mlockall(MCL_CURRENT
))
5265 LOG(1, 0, 0, "Locking pages into memory\n");
5267 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5272 /* remove plugins (so cleanup code gets run) */
5275 // Remove the PID file if we wrote it
5276 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5277 unlink(config
->pid_file
);
5279 /* kill CLI children */
5280 signal(SIGTERM
, SIG_IGN
);
5285 static void sighup_handler(int sig
)
5290 static void shutdown_handler(int sig
)
5292 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5295 static void sigchild_handler(int sig
)
5297 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5301 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5304 *challenge_response
= NULL
;
5306 if (!*config
->l2tp_secret
)
5308 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5312 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5314 *challenge_response
= calloc(17, 1);
5317 MD5_Update(&ctx
, &id
, 1);
5318 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5319 MD5_Update(&ctx
, challenge
, challenge_length
);
5320 MD5_Final(*challenge_response
, &ctx
);
5325 static int facility_value(char *name
)
5328 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5330 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5331 return facilitynames
[i
].c_val
;
5336 static void update_config()
5340 static int timeout
= 0;
5341 static int interval
= 0;
5348 if (log_stream
!= stderr
)
5354 if (*config
->log_filename
)
5356 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5358 char *p
= config
->log_filename
+ 7;
5361 openlog("l2tpns", LOG_PID
, facility_value(p
));
5365 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5367 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5369 fseek(log_stream
, 0, SEEK_END
);
5370 setbuf(log_stream
, NULL
);
5374 log_stream
= stderr
;
5375 setbuf(log_stream
, NULL
);
5381 log_stream
= stderr
;
5382 setbuf(log_stream
, NULL
);
5385 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5386 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5388 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5389 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5390 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5392 // reset MRU/MSS globals
5393 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5394 if (MRU
> PPPoE_MRU
)
5397 MSS
= MRU
- TCP_HDRS
;
5400 config
->numradiusservers
= 0;
5401 for (i
= 0; i
< MAXRADSERVER
; i
++)
5402 if (config
->radiusserver
[i
])
5404 config
->numradiusservers
++;
5405 // Set radius port: if not set, take the port from the
5406 // first radius server. For the first radius server,
5407 // take the #defined default value from l2tpns.h
5409 // test twice, In case someone works with
5410 // a secondary radius server without defining
5411 // a primary one, this will work even then.
5412 if (i
> 0 && !config
->radiusport
[i
])
5413 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5414 if (!config
->radiusport
[i
])
5415 config
->radiusport
[i
] = RADPORT
;
5418 if (!config
->numradiusservers
)
5419 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5421 // parse radius_authtypes_s
5422 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5423 p
= config
->radius_authtypes_s
;
5426 char *s
= strpbrk(p
, " \t,");
5432 while (*s
== ' ' || *s
== '\t')
5439 if (!strncasecmp("chap", p
, strlen(p
)))
5441 else if (!strncasecmp("pap", p
, strlen(p
)))
5444 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5446 config
->radius_authtypes
|= type
;
5447 if (!config
->radius_authprefer
)
5448 config
->radius_authprefer
= type
;
5453 if (!config
->radius_authtypes
)
5455 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5456 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5459 // normalise radius_authtypes_s
5460 if (config
->radius_authprefer
== AUTHPAP
)
5462 strcpy(config
->radius_authtypes_s
, "pap");
5463 if (config
->radius_authtypes
& AUTHCHAP
)
5464 strcat(config
->radius_authtypes_s
, ", chap");
5468 strcpy(config
->radius_authtypes_s
, "chap");
5469 if (config
->radius_authtypes
& AUTHPAP
)
5470 strcat(config
->radius_authtypes_s
, ", pap");
5473 if (!config
->radius_dae_port
)
5474 config
->radius_dae_port
= DAEPORT
;
5476 if(!config
->bind_portremotelns
)
5477 config
->bind_portremotelns
= L2TPLACPORT
;
5478 if(!config
->bind_address_remotelns
)
5479 config
->bind_address_remotelns
= INADDR_ANY
;
5481 if (*config
->bind_multi_address
)
5483 char *sip
= config
->bind_multi_address
;
5485 char *e
= config
->bind_multi_address
+ strlen(config
->bind_multi_address
);
5486 config
->nbmultiaddress
= 0;
5488 while (*sip
&& (sip
< e
))
5493 while (n
< e
&& (*n
== ',' || *n
== ' ')) n
++;
5495 while (n
< e
&& (isdigit(*n
) || *n
== '.'))
5503 u
= u
* 10 + *n
- '0';
5511 config
->bind_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5512 config
->iftun_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5513 config
->nbmultiaddress
++;
5514 LOG(1, 0, 0, "Bind address %s\n", fmtaddr(htonl(ip
), 0));
5516 if (config
->nbmultiaddress
>= MAX_BINDADDR
) break;
5522 if (config
->nbmultiaddress
>= 1)
5524 config
->bind_address
= config
->bind_n_address
[0];
5525 config
->iftun_address
= config
->bind_address
;
5529 if(!config
->iftun_address
)
5531 config
->iftun_address
= config
->bind_address
;
5532 config
->iftun_n_address
[0] = config
->iftun_address
;
5535 if (*config
->multi_hostname
)
5537 char *shost
= config
->multi_hostname
;
5539 char *e
= config
->multi_hostname
+ strlen(config
->multi_hostname
);
5540 config
->nbmultihostname
= 0;
5542 while (*shost
&& (shost
< e
))
5544 while ((n
< e
) && (*n
== ' ' || *n
== ',' || *n
== '\t')) n
++;
5547 while (n
< e
&& (*n
!= ',') && (*n
!= '\t'))
5549 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = *n
;
5555 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = 0;
5556 LOG(1, 0, 0, "Bind Hostname %s\n", config
->multi_n_hostname
[config
->nbmultihostname
]);
5557 config
->nbmultihostname
++;
5558 if (config
->nbmultihostname
>= MAX_NBHOSTNAME
) break;
5564 if (config
->nbmultihostname
>= 1)
5566 strcpy(hostname
, config
->multi_n_hostname
[0]);
5567 strcpy(config
->hostname
, hostname
);
5571 if (!*config
->pppoe_ac_name
)
5572 strncpy(config
->pppoe_ac_name
, DEFAULT_PPPOE_AC_NAME
, sizeof(config
->pppoe_ac_name
) - 1);
5574 // re-initialise the random number source
5575 initrandom(config
->random_device
);
5578 for (i
= 0; i
< MAXPLUGINS
; i
++)
5580 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5583 if (*config
->plugins
[i
])
5586 add_plugin(config
->plugins
[i
]);
5588 else if (*config
->old_plugins
[i
])
5591 remove_plugin(config
->old_plugins
[i
]);
5596 guest_accounts_num
= 0;
5597 char *p2
= config
->guest_user
;
5600 char *s
= strpbrk(p2
, " \t,");
5604 while (*s
== ' ' || *s
== '\t')
5611 strcpy(guest_users
[guest_accounts_num
], p2
);
5612 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5613 guest_accounts_num
++;
5616 // Rebuild the guest_user array
5617 strcpy(config
->guest_user
, "");
5619 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5621 strcat(config
->guest_user
, guest_users
[ui
]);
5622 if (ui
<guest_accounts_num
-1)
5624 strcat(config
->guest_user
, ",");
5629 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5630 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5631 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5632 if (!config
->cluster_port
) config
->cluster_port
= CLUSTERPORT
;
5633 if (!*config
->cluster_interface
)
5634 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5636 if (!config
->cluster_hb_interval
)
5637 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5639 if (!config
->cluster_hb_timeout
)
5640 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5642 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5644 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5645 // late, ensure we're sufficiently larger than that
5646 int t
= 4 * config
->cluster_hb_interval
+ 11;
5648 if (config
->cluster_hb_timeout
< t
)
5650 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5651 config
->cluster_hb_timeout
= t
;
5654 // Push timing changes to the slaves immediately if we're the master
5655 if (config
->cluster_iam_master
)
5656 cluster_heartbeat();
5658 interval
= config
->cluster_hb_interval
;
5659 timeout
= config
->cluster_hb_timeout
;
5663 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5666 if ((f
= fopen(config
->pid_file
, "w")))
5668 fprintf(f
, "%d\n", getpid());
5670 config
->wrote_pid
= 1;
5674 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5679 static void read_config_file()
5683 if (!config
->config_file
) return;
5684 if (!(f
= fopen(config
->config_file
, "r")))
5686 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5690 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5692 LOG(3, 0, 0, "Done reading config file\n");
5696 int sessionsetup(sessionidt s
, tunnelidt t
)
5698 // A session now exists, set it up
5704 CSTAT(sessionsetup
);
5706 LOG(3, s
, t
, "Doing session setup for session\n");
5708 // Join a bundle if the MRRU option is accepted
5709 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5711 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5712 if (join_bundle(s
) > 0)
5713 cluster_send_bundle(session
[s
].bundle
);
5716 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5717 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5724 assign_ip_address(s
);
5727 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5728 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5731 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5732 fmtaddr(htonl(session
[s
].ip
), 0));
5735 // Make sure this is right
5736 session
[s
].tunnel
= t
;
5738 // zap old sessions with same IP and/or username
5739 // Don't kill gardened sessions - doing so leads to a DoS
5740 // from someone who doesn't need to know the password
5743 user
= session
[s
].user
;
5744 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5746 if (i
== s
) continue;
5747 if (!session
[s
].opened
) break;
5748 // Allow duplicate sessions for multilink ones of the same bundle.
5749 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5751 if (ip
== session
[i
].ip
)
5753 sessionshutdown(i
, "Duplicate IP address", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5757 if (config
->allow_duplicate_users
) continue;
5758 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5762 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5764 if (!strcasecmp(user
, guest_users
[gu
]))
5770 if (found
) continue;
5772 // Drop the new session in case of duplicate sessionss, not the old one.
5773 if (!strcasecmp(user
, session
[i
].user
))
5774 sessionshutdown(i
, "Duplicate session for users", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5778 // no need to set a route for the same IP address of the bundle
5779 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5783 // Add the route for this session.
5784 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5786 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5787 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5790 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5793 // Static IPs need to be routed if not already
5794 // convered by a Framed-Route. Anything else is part
5795 // of the IP address pool and is already routed, it
5796 // just needs to be added to the IP cache.
5797 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5798 if (session
[s
].ip_pool_index
== -1) // static ip
5800 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5803 cache_ipmap(session
[s
].ip
, s
);
5806 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5807 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5809 // Run the plugin's against this new session.
5811 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5812 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5815 // Allocate TBFs if throttled
5816 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5817 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5819 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5821 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5822 fmtaddr(htonl(session
[s
].ip
), 0),
5823 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5825 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5827 return 1; // RADIUS OK and IP allocated, done...
5831 // This session just got dropped on us by the master or something.
5832 // Make sure our tables up up to date...
5834 int load_session(sessionidt s
, sessiont
*new)
5840 if (new->ip_pool_index
>= MAXIPPOOL
||
5841 new->tunnel
>= MAXTUNNEL
)
5843 LOG(0, s
, 0, "Strange session update received!\n");
5844 // FIXME! What to do here?
5849 // Ok. All sanity checks passed. Now we're committed to
5850 // loading the new session.
5853 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5855 // See if routes/ip cache need updating
5856 if (new->ip
!= session
[s
].ip
)
5859 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5860 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5861 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5869 // remove old routes...
5870 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5872 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5873 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5876 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5882 if (session
[s
].ip_pool_index
== -1) // static IP
5884 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5886 else // It's part of the IP pool, remove it manually.
5887 uncache_ipmap(session
[s
].ip
);
5890 // remove old IPV6 routes...
5891 for (i
= 0; i
< MAXROUTE6
&& session
[s
].route6
[i
].ipv6route
.s6_addr
[0] && session
[s
].route6
[i
].ipv6prefixlen
; i
++)
5893 route6set(s
, session
[s
].route6
[i
].ipv6route
, session
[s
].route6
[i
].ipv6prefixlen
, 0);
5896 if (session
[s
].ipv6address
.s6_addr
[0])
5898 route6set(s
, session
[s
].ipv6address
, 128, 0);
5903 // add new routes...
5904 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5906 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5907 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5910 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5916 // If there's a new one, add it.
5917 if (new->ip_pool_index
== -1)
5919 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5922 cache_ipmap(new->ip
, s
);
5927 if (new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5929 for (i
= 0; i
< MAXROUTE6
&& new->route6
[i
].ipv6prefixlen
; i
++)
5931 route6set(s
, new->route6
[i
].ipv6route
, new->route6
[i
].ipv6prefixlen
, 1);
5935 if (new->ipv6address
.s6_addr
[0] && new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5937 // Check if included in prefix
5938 if (sessionbyipv6(new->ipv6address
) != s
)
5939 route6set(s
, new->ipv6address
, 128, 1);
5943 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5945 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5949 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5951 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5952 new->filter_out
= 0;
5955 if (new->filter_in
!= session
[s
].filter_in
)
5957 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5958 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5961 if (new->filter_out
!= session
[s
].filter_out
)
5963 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5964 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5967 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5968 // for walking the sessions to forward byte counts to the master.
5969 config
->cluster_highest_sessionid
= s
;
5971 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5973 // Do fixups into address pool.
5974 if (new->ip_pool_index
!= -1)
5975 fix_address_pool(s
);
5980 static void initplugins()
5984 loaded_plugins
= ll_init();
5985 // Initialize the plugins to nothing
5986 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5987 plugins
[i
] = ll_init();
5990 static void *open_plugin(char *plugin_name
, int load
)
5992 char path
[256] = "";
5994 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5995 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5996 return dlopen(path
, RTLD_NOW
);
5999 // plugin callback to get a config value
6000 static void *getconfig(char *key
, enum config_typet type
)
6004 for (i
= 0; config_values
[i
].key
; i
++)
6006 if (!strcmp(config_values
[i
].key
, key
))
6008 if (config_values
[i
].type
== type
)
6009 return ((void *) config
) + config_values
[i
].offset
;
6011 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
6012 key
, type
, config_values
[i
].type
);
6018 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
6022 static int add_plugin(char *plugin_name
)
6024 static struct pluginfuncs funcs
= {
6029 sessiontbysessionidt
,
6030 sessionidtbysessiont
,
6037 cluster_send_session
,
6040 void *p
= open_plugin(plugin_name
, 1);
6041 int (*initfunc
)(struct pluginfuncs
*);
6046 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
6050 if (ll_contains(loaded_plugins
, p
))
6053 return 0; // already loaded
6057 int *v
= dlsym(p
, "plugin_api_version");
6058 if (!v
|| *v
!= PLUGIN_API_VERSION
)
6060 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
6066 if ((initfunc
= dlsym(p
, "plugin_init")))
6068 if (!initfunc(&funcs
))
6070 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
6076 ll_push(loaded_plugins
, p
);
6078 for (i
= 0; i
< max_plugin_functions
; i
++)
6081 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6083 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
6084 ll_push(plugins
[i
], x
);
6088 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
6092 static void run_plugin_done(void *plugin
)
6094 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
6100 static int remove_plugin(char *plugin_name
)
6102 void *p
= open_plugin(plugin_name
, 0);
6108 if (ll_contains(loaded_plugins
, p
))
6111 for (i
= 0; i
< max_plugin_functions
; i
++)
6114 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6115 ll_delete(plugins
[i
], x
);
6118 ll_delete(loaded_plugins
, p
);
6124 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
6128 int run_plugins(int plugin_type
, void *data
)
6130 int (*func
)(void *data
);
6132 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
6133 return PLUGIN_RET_ERROR
;
6135 ll_reset(plugins
[plugin_type
]);
6136 while ((func
= ll_next(plugins
[plugin_type
])))
6140 if (r
!= PLUGIN_RET_OK
)
6141 return r
; // stop here
6144 return PLUGIN_RET_OK
;
6147 static void plugins_done()
6151 ll_reset(loaded_plugins
);
6152 while ((p
= ll_next(loaded_plugins
)))
6156 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
6158 struct nsctl request
;
6159 struct nsctl response
;
6160 int type
= unpack_control(&request
, buf
, len
);
6164 if (log_stream
&& config
->debug
>= 4)
6168 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6169 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
6173 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6174 dump_control(&request
, log_stream
);
6180 case NSCTL_REQ_LOAD
:
6181 if (request
.argc
!= 1)
6183 response
.type
= NSCTL_RES_ERR
;
6185 response
.argv
[0] = "name of plugin required";
6187 else if ((r
= add_plugin(request
.argv
[0])) < 1)
6189 response
.type
= NSCTL_RES_ERR
;
6191 response
.argv
[0] = !r
6192 ? "plugin already loaded"
6193 : "error loading plugin";
6197 response
.type
= NSCTL_RES_OK
;
6203 case NSCTL_REQ_UNLOAD
:
6204 if (request
.argc
!= 1)
6206 response
.type
= NSCTL_RES_ERR
;
6208 response
.argv
[0] = "name of plugin required";
6210 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
6212 response
.type
= NSCTL_RES_ERR
;
6214 response
.argv
[0] = !r
6215 ? "plugin not loaded"
6216 : "plugin not found";
6220 response
.type
= NSCTL_RES_OK
;
6226 case NSCTL_REQ_HELP
:
6227 response
.type
= NSCTL_RES_OK
;
6230 ll_reset(loaded_plugins
);
6231 while ((p
= ll_next(loaded_plugins
)))
6233 char **help
= dlsym(p
, "plugin_control_help");
6234 while (response
.argc
< 0xff && help
&& *help
)
6235 response
.argv
[response
.argc
++] = *help
++;
6240 case NSCTL_REQ_CONTROL
:
6242 struct param_control param
= {
6243 config
->cluster_iam_master
,
6250 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
6252 if (r
== PLUGIN_RET_ERROR
)
6254 response
.type
= NSCTL_RES_ERR
;
6256 response
.argv
[0] = param
.additional
6258 : "error returned by plugin";
6260 else if (r
== PLUGIN_RET_NOTMASTER
)
6262 static char msg
[] = "must be run on master: 000.000.000.000";
6264 response
.type
= NSCTL_RES_ERR
;
6266 if (config
->cluster_master_address
)
6268 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
6269 response
.argv
[0] = msg
;
6273 response
.argv
[0] = "must be run on master: none elected";
6276 else if (!(param
.response
& NSCTL_RESPONSE
))
6278 response
.type
= NSCTL_RES_ERR
;
6280 response
.argv
[0] = param
.response
6281 ? "unrecognised response value from plugin"
6282 : "unhandled action";
6286 response
.type
= param
.response
;
6288 if (param
.additional
)
6291 response
.argv
[0] = param
.additional
;
6299 response
.type
= NSCTL_RES_ERR
;
6301 response
.argv
[0] = "error unpacking control packet";
6304 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6307 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6311 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6314 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6315 if (log_stream
&& config
->debug
>= 4)
6317 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6318 dump_control(&response
, log_stream
);
6322 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6323 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6328 static tunnelidt
new_tunnel()
6331 for (i
= 1; i
< MAXTUNNEL
; i
++)
6333 if ((tunnel
[i
].state
== TUNNELFREE
) && (i
!= TUNNEL_ID_PPPOE
))
6335 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6336 if (i
> config
->cluster_highest_tunnelid
)
6337 config
->cluster_highest_tunnelid
= i
;
6341 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6346 // We're becoming the master. Do any required setup..
6348 // This is principally telling all the plugins that we're
6349 // now a master, and telling them about all the sessions
6350 // that are active too..
6352 void become_master(void)
6355 static struct event_data d
[RADIUS_FDS
];
6356 struct epoll_event e
;
6358 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6360 // running a bunch of iptables commands is slow and can cause
6361 // the master to drop tunnels on takeover--kludge around the
6362 // problem by forking for the moment (note: race)
6363 if (!fork_and_close())
6365 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6367 if (!session
[s
].opened
) // Not an in-use session.
6370 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6377 for (i
= 0; i
< RADIUS_FDS
; i
++)
6379 d
[i
].type
= FD_TYPE_RADIUS
;
6383 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6387 int cmd_show_hist_idle(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6393 if (CLI_HELP_REQUESTED
)
6394 return CLI_HELP_NO_ARGS
;
6397 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6399 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6402 if (!session
[s
].opened
)
6405 idle
= time_now
- session
[s
].last_data
;
6406 idle
/= 5 ; // In multiples of 5 seconds.
6416 for (i
= 0; i
< 63; ++i
)
6418 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6420 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6421 cli_print(cli
, "%d total sessions open.", count
);
6425 int cmd_show_hist_open(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6431 if (CLI_HELP_REQUESTED
)
6432 return CLI_HELP_NO_ARGS
;
6435 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6437 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6440 if (!session
[s
].opened
)
6443 d
= time_now
- session
[s
].opened
;
6446 while (d
> 1 && open
< 32)
6456 for (i
= 0; i
< 30; ++i
)
6458 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6461 cli_print(cli
, "%d total sessions open.", count
);
6467 * This unencodes the AVP using the L2TP secret and the previously
6468 * stored random vector. It overwrites the hidden data with the
6469 * unhidden AVP subformat.
6471 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6477 uint16_t m
= htons(type
);
6479 // Compute initial pad
6481 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6482 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6483 MD5_Update(&ctx
, vector
, vec_len
);
6484 MD5_Final(digest
, &ctx
);
6486 // pointer to last decoded 16 octets
6491 // calculate a new pad based on the last decoded block
6492 if (d
>= sizeof(digest
))
6495 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6496 MD5_Update(&ctx
, last
, sizeof(digest
));
6497 MD5_Final(digest
, &ctx
);
6503 *value
++ ^= digest
[d
++];
6508 int find_filter(char const *name
, size_t len
)
6513 for (i
= 0; i
< MAXFILTER
; i
++)
6515 if (!*ip_filters
[i
].name
)
6523 if (strlen(ip_filters
[i
].name
) != len
)
6526 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6533 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6537 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6538 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6539 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6540 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6541 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6547 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6551 case FILTER_FLAG_OP_ANY
:
6552 return (flags
& sflags
) || (~flags
& cflags
);
6554 case FILTER_FLAG_OP_ALL
:
6555 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6557 case FILTER_FLAG_OP_EST
:
6558 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6564 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6566 uint16_t frag_offset
;
6570 uint16_t src_port
= 0;
6571 uint16_t dst_port
= 0;
6573 ip_filter_rulet
*rule
;
6575 if (len
< 20) // up to end of destination address
6578 if ((*buf
>> 4) != 4) // IPv4
6581 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6583 src_ip
= *(in_addr_t
*) (buf
+ 12);
6584 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6586 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6588 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6589 if (len
< l
+ 4) // ports
6592 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6593 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6594 if (proto
== IPPROTO_TCP
)
6596 if (len
< l
+ 14) // flags
6599 flags
= buf
[l
+ 13] & 0x3f;
6603 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6605 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6608 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6609 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6612 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6613 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6618 // layer 4 deny rules are skipped
6619 if (rule
->action
== FILTER_ACTION_DENY
&&
6620 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6628 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6630 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6633 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6636 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6637 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6644 return rule
->action
== FILTER_ACTION_PERMIT
;
6651 tunnelidt
lac_new_tunnel()
6653 return new_tunnel();
6656 void lac_tunnelclear(tunnelidt t
)
6661 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6663 uint16_t version
= 0x0100; // protocol version
6665 tunnel
[t
].state
= TUNNELOPENING
;
6667 // Sent SCCRQ - Start Control Connection Request
6668 controlt
*c
= controlnew(1); // sending SCCRQ
6669 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
6670 controls(c
, 8, Vendor_name
, 1); // Vendor name
6671 control16(c
, 2, version
, 1); // protocol version
6672 control32(c
, 3, 3, 1); // framing Capabilities
6673 control16(c
, 9, t
, 1); // assigned tunnel
6674 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6675 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6676 controladd(c
, 0, t
); // send
6679 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6681 // Sent ICRQ Incoming-call-request
6682 controlt
*c
= controlnew(10); // ICRQ
6684 control16(c
, 14, s
, 1); // assigned sesion
6685 call_serial_number
++;
6686 control32(c
, 15, call_serial_number
, 1); // call serial number
6687 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6688 controladd(c
, 0, t
); // send
6691 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6693 tunnelshutdown(t
, reason
, result
, error
, msg
);