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>
15 #include <net/route.h>
18 #include <netinet/in.h>
19 #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>
47 #include "constants.h"
59 char * Vendor_name
= "Linux L2TPNS";
60 uint32_t call_serial_number
= 0;
63 configt
*config
= NULL
; // all configuration
64 int nlfd
= -1; // netlink socket
65 int tunfd
= -1; // tun interface file handle. (network device)
66 int udpfd
[MAX_UDPFD
+ 1] = INIT_TABUDPFD
; // array UDP file handle + 1 for lac udp
67 int udplacfd
= -1; // UDP LAC file handle
68 int controlfd
= -1; // Control signal handle
69 int clifd
= -1; // Socket listening for CLI connections.
70 int daefd
= -1; // Socket listening for DAE connections.
71 int snoopfd
= -1; // UDP file handle for sending out intercept data
72 int *radfds
= NULL
; // RADIUS requests file handles
73 int rand_fd
= -1; // Random data source
74 int cluster_sockfd
= -1; // Intra-cluster communications socket.
75 int epollfd
= -1; // event polling
76 time_t basetime
= 0; // base clock
77 char hostname
[MAXHOSTNAME
] = ""; // us.
78 int tunidx
; // ifr_ifindex of tun device
79 int nlseqnum
= 0; // netlink sequence number
80 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
81 static int syslog_log
= 0; // are we logging to syslog
82 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
83 uint32_t last_id
= 0; // Unique ID for radius accounting
85 char guest_users
[10][32]; // Array of guest users
86 int guest_accounts_num
= 0; // Number of guest users
88 // calculated from config->l2tp_mtu
89 uint16_t MRU
= 0; // PPP MRU
90 uint16_t MSS
= 0; // TCP MSS
92 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
93 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
95 union iphash ip_hash
[256]; // Mapping from IP address to session structures.
99 struct ipv6radix
*branch
;
100 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
103 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
104 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
107 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
108 time_t time_now
= 0; // Current time in seconds since epoch.
109 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
110 static char time_now_string
[64] = {0}; // Current time as a string.
111 static int time_changed
= 0; // time_now changed
112 char main_quit
= 0; // True if we're in the process of exiting.
113 static char main_reload
= 0; // Re-load pending
114 linked_list
*loaded_plugins
;
115 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
117 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
118 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
120 config_descriptt config_values
[] = {
121 CONFIG("debug", debug
, INT
),
122 CONFIG("log_file", log_filename
, STRING
),
123 CONFIG("pid_file", pid_file
, STRING
),
124 CONFIG("random_device", random_device
, STRING
),
125 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
126 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
127 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
128 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
129 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
130 CONFIG("primary_dns", default_dns1
, IPv4
),
131 CONFIG("secondary_dns", default_dns2
, IPv4
),
132 CONFIG("primary_radius", radiusserver
[0], IPv4
),
133 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
134 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
135 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
136 CONFIG("radius_accounting", radius_accounting
, BOOL
),
137 CONFIG("radius_interim", radius_interim
, INT
),
138 CONFIG("radius_secret", radiussecret
, STRING
),
139 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
140 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
141 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
142 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
143 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
144 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
145 CONFIG("guest_account", guest_user
, STRING
),
146 CONFIG("bind_address", bind_address
, IPv4
),
147 CONFIG("peer_address", peer_address
, IPv4
),
148 CONFIG("send_garp", send_garp
, BOOL
),
149 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
150 CONFIG("throttle_buckets", num_tbfs
, INT
),
151 CONFIG("accounting_dir", accounting_dir
, STRING
),
152 CONFIG("account_all_origin", account_all_origin
, BOOL
),
153 CONFIG("dump_speed", dump_speed
, BOOL
),
154 CONFIG("multi_read_count", multi_read_count
, INT
),
155 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
156 CONFIG("lock_pages", lock_pages
, BOOL
),
157 CONFIG("icmp_rate", icmp_rate
, INT
),
158 CONFIG("packet_limit", max_packets
, INT
),
159 CONFIG("cluster_address", cluster_address
, IPv4
),
160 CONFIG("cluster_interface", cluster_interface
, STRING
),
161 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
162 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
163 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
164 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
165 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
166 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
167 CONFIG("hostname", hostname
, STRING
),
169 CONFIG("nexthop_address", nexthop_address
, IPv4
),
170 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
172 CONFIG("echo_timeout", echo_timeout
, INT
),
173 CONFIG("idle_echo_timeout", idle_echo_timeout
, INT
),
174 CONFIG("iftun_address", iftun_address
, IPv4
),
175 CONFIG("tundevicename", tundevicename
, STRING
),
176 CONFIG("disable_lac_func", disable_lac_func
, BOOL
),
177 CONFIG("auth_tunnel_change_addr_src", auth_tunnel_change_addr_src
, BOOL
),
178 CONFIG("bind_address_remotelns", bind_address_remotelns
, IPv4
),
179 CONFIG("bind_portremotelns", bind_portremotelns
, SHORT
),
180 CONFIG("pppoe_if_to_bind", pppoe_if_to_bind
, STRING
),
181 CONFIG("pppoe_service_name", pppoe_service_name
, STRING
),
182 CONFIG("pppoe_ac_name", pppoe_ac_name
, STRING
),
183 CONFIG("disable_sending_hello", disable_sending_hello
, BOOL
),
184 CONFIG("disable_no_spoof", disable_no_spoof
, BOOL
),
185 CONFIG("bind_multi_address", bind_multi_address
, STRING
),
186 CONFIG("grp_txrate_average_time", grp_txrate_average_time
, INT
),
187 CONFIG("pppoe_only_equal_svc_name", pppoe_only_equal_svc_name
, BOOL
),
191 static char *plugin_functions
[] = {
196 "plugin_new_session",
197 "plugin_kill_session",
199 "plugin_radius_response",
200 "plugin_radius_reset",
201 "plugin_radius_account",
202 "plugin_become_master",
203 "plugin_new_session_master",
206 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
208 // Counters for shutdown sessions
209 static sessiont shut_acct
[8192];
210 static sessionidt shut_acct_n
= 0;
212 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
213 bundlet
*bundle
= NULL
; // Array of bundle structures.
214 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
215 sessiont
*session
= NULL
; // Array of session structures.
216 groupsesst
*grpsession
= NULL
; // Array of groupsesst structures.
217 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
218 radiust
*radius
= NULL
; // Array of radius structures.
219 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
220 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
221 static controlt
*controlfree
= 0;
222 struct Tstats
*_statistics
= NULL
;
224 struct Tringbuffer
*ringbuffer
= NULL
;
227 static void uncache_ipmap(in_addr_t ip
);
228 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
229 static void free_ip_address(sessionidt s
);
230 static void dump_acct_info(int all
);
231 static void sighup_handler(int sig
);
232 static void shutdown_handler(int sig
);
233 static void sigchild_handler(int sig
);
234 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
235 static void update_config(void);
236 static void read_config_file(void);
237 static void initplugins(void);
238 static int add_plugin(char *plugin_name
);
239 static int remove_plugin(char *plugin_name
);
240 static void plugins_done(void);
241 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
242 static tunnelidt
new_tunnel(void);
243 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
244 static void bundleclear(bundleidt b
);
246 // return internal time (10ths since process startup), set f if given
247 // as a side-effect sets time_now, and time_changed
248 static clockt
now(double *f
)
252 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
253 if (t
.tv_sec
!= time_now
)
260 // Time in milliseconds
261 // TODO FOR MLPPP DEV
262 //time_now_ms = (t.tv_sec * 1000) + (t.tv_usec/1000);
264 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
267 // work out a retry time based on try number
268 // This is a straight bounded exponential backoff.
269 // Maximum re-try time is 32 seconds. (2^5).
270 clockt
backoff(uint8_t try)
272 if (try > 5) try = 5; // max backoff
273 return now(NULL
) + 10 * (1 << try);
278 // Log a debug message. Typically called via the LOG macro
280 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
282 static char message
[65536] = {0};
288 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
289 ringbuffer
->tail
= 0;
290 if (ringbuffer
->tail
== ringbuffer
->head
)
291 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
292 ringbuffer
->head
= 0;
294 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
295 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
296 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
297 va_start(ap
, format
);
298 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, MAX_LOG_LENGTH
, format
, ap
);
303 if (config
->debug
< level
) return;
305 va_start(ap
, format
);
306 vsnprintf(message
, sizeof(message
), format
, ap
);
309 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
311 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
316 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
319 const uint8_t *d
= data
;
321 if (config
->debug
< level
) return;
323 // No support for _log_hex to syslog
326 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
327 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
329 for (i
= 0; i
< maxsize
; )
331 fprintf(log_stream
, "%4X: ", i
);
332 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
334 fprintf(log_stream
, "%02X ", d
[j
]);
336 fputs(": ", log_stream
);
339 for (; j
< i
+ 16; j
++)
341 fputs(" ", log_stream
);
343 fputs(": ", log_stream
);
346 fputs(" ", log_stream
);
347 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
349 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
350 fputc(d
[j
], log_stream
);
352 fputc('.', log_stream
);
355 fputs(" ", log_stream
);
359 fputs("\n", log_stream
);
363 setbuf(log_stream
, NULL
);
367 // update a counter, accumulating 2^32 wraps
368 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
370 uint32_t new = *counter
+ delta
;
377 // initialise the random generator
378 static void initrandom(char *source
)
380 static char path
[sizeof(config
->random_device
)] = "*undefined*";
382 // reinitialise only if we are forced to do so or if the config has changed
383 if (source
&& !strncmp(path
, source
, sizeof(path
)))
386 // close previous source, if any
395 snprintf(path
, sizeof(path
), "%s", source
);
399 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
401 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
402 path
, strerror(errno
));
407 // fill buffer with random data
408 void random_data(uint8_t *buf
, int len
)
415 n
= read(rand_fd
, buf
, len
);
416 if (n
>= len
) return;
421 LOG(0, 0, 0, "Error reading from random source: %s\n",
424 // fall back to rand()
432 // append missing data
434 // not using the low order bits from the prng stream
435 buf
[n
++] = (rand() >> 4) & 0xff;
440 // This adds it to the routing table, advertises it
441 // via BGP if enabled, and stuffs it into the
442 // 'sessionbyip' cache.
444 // 'ip' must be in _host_ order.
446 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
456 if (!prefixlen
) prefixlen
= 32;
458 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
460 memset(&req
, 0, sizeof(req
));
464 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
465 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
469 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
470 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
473 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
475 req
.rt
.rtm_family
= AF_INET
;
476 req
.rt
.rtm_dst_len
= prefixlen
;
477 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
478 req
.rt
.rtm_protocol
= 42;
479 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
480 req
.rt
.rtm_type
= RTN_UNICAST
;
482 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
484 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
488 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
491 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
492 fmtaddr(htonl(ip
), 0), prefixlen
,
493 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
495 if (netlink_send(&req
.nh
) < 0)
496 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
500 bgp_add_route(htonl(ip
), prefixlen
);
502 bgp_del_route(htonl(ip
), prefixlen
);
505 // Add/Remove the IPs to the 'sessionbyip' cache.
506 // Note that we add the zero address in the case of
507 // a network route. Roll on CIDR.
509 // Note that 's == 0' implies this is the address pool.
510 // We still cache it here, because it will pre-fill
511 // the malloc'ed tree.
515 if (!add
) // Are we deleting a route?
516 s
= 0; // Caching the session as '0' is the same as uncaching.
518 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
523 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
531 char ipv6addr
[INET6_ADDRSTRLEN
];
533 if (!config
->ipv6_prefix
.s6_addr
[0])
535 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
539 memset(&req
, 0, sizeof(req
));
543 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
544 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
548 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
549 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
552 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
554 req
.rt
.rtm_family
= AF_INET6
;
555 req
.rt
.rtm_dst_len
= prefixlen
;
556 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
557 req
.rt
.rtm_protocol
= 42;
558 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
559 req
.rt
.rtm_type
= RTN_UNICAST
;
561 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
562 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
564 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
566 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
568 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
571 if (netlink_send(&req
.nh
) < 0)
572 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
576 bgp_add_route6(ip
, prefixlen
);
578 bgp_del_route6(ip
, prefixlen
);
583 if (!add
) // Are we deleting a route?
584 s
= 0; // Caching the session as '0' is the same as uncaching.
586 cache_ipv6map(ip
, prefixlen
, s
);
593 // Set up netlink socket
594 static void initnetlink(void)
596 struct sockaddr_nl nladdr
;
598 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
601 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
605 memset(&nladdr
, 0, sizeof(nladdr
));
606 nladdr
.nl_family
= AF_NETLINK
;
607 nladdr
.nl_pid
= getpid();
609 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
611 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
616 ssize_t
netlink_send(struct nlmsghdr
*nh
)
618 struct sockaddr_nl nladdr
;
622 nh
->nlmsg_pid
= getpid();
623 nh
->nlmsg_seq
= ++nlseqnum
;
625 // set kernel address
626 memset(&nladdr
, 0, sizeof(nladdr
));
627 nladdr
.nl_family
= AF_NETLINK
;
629 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
630 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
632 return sendmsg(nlfd
, &msg
, 0);
635 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
637 struct sockaddr_nl nladdr
;
641 // set kernel address
642 memset(&nladdr
, 0, sizeof(nladdr
));
643 nladdr
.nl_family
= AF_NETLINK
;
645 iov
= (struct iovec
){ buf
, len
};
646 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
648 return recvmsg(nlfd
, &msg
, 0);
651 /* adapted from iproute2 */
652 void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
654 int len
= RTA_LENGTH(alen
);
657 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
658 rta
->rta_type
= type
;
660 memcpy(RTA_DATA(rta
), data
, alen
);
661 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
664 // messages corresponding to different phases seq number
665 static char *tun_nl_phase_msg
[] = {
667 "getting tun interface index",
668 "setting tun interface parameters",
669 "setting tun IPv4 address",
670 "setting tun LL IPv6 address",
671 "setting tun global IPv6 address",
675 // Set up TUN interface
676 static void inittun(void)
680 memset(&ifr
, 0, sizeof(ifr
));
681 ifr
.ifr_flags
= IFF_TUN
;
683 tunfd
= open(TUNDEVICE
, O_RDWR
);
686 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
690 int flags
= fcntl(tunfd
, F_GETFL
, 0);
691 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
694 if (*config
->tundevicename
)
695 strncpy(ifr
.ifr_name
, config
->tundevicename
, IFNAMSIZ
);
697 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
699 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
702 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevicename
) - 1);
703 strncpy(config
->tundevicename
, ifr
.ifr_name
, sizeof(config
->tundevicename
));
705 tunidx
= if_nametoindex(config
->tundevicename
);
708 LOG(0, 0, 0, "Can't get tun interface index\n");
717 struct ifinfomsg ifinfo
;
718 struct ifaddrmsg ifaddr
;
720 char rtdata
[32]; // 32 should be enough
722 uint32_t txqlen
, mtu
;
725 memset(&req
, 0, sizeof(req
));
727 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
728 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
729 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
731 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
732 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
733 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
734 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
736 /* Bump up the qlen to deal with bursts from the network */
738 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
739 /* set MTU to modem MRU */
741 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
743 if (netlink_send(&req
.nh
) < 0)
746 memset(&req
, 0, sizeof(req
));
748 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
749 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
750 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
752 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
753 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
754 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
755 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
757 if (config
->nbmultiaddress
> 1)
760 for (i
= 0; i
< config
->nbmultiaddress
; i
++)
762 ip
= config
->iftun_n_address
[i
];
763 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
764 if (netlink_send(&req
.nh
) < 0)
770 if (config
->iftun_address
)
771 ip
= config
->iftun_address
;
773 ip
= 0x01010101; // 1.1.1.1
774 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
776 if (netlink_send(&req
.nh
) < 0)
782 // Only setup IPv6 on the tun device if we have a configured prefix
783 if (config
->ipv6_prefix
.s6_addr
[0]) {
786 memset(&req
, 0, sizeof(req
));
788 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
789 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
790 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
792 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
793 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
794 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
795 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
797 // Link local address is FE80::1
798 memset(&ip6
, 0, sizeof(ip6
));
799 ip6
.s6_addr
[0] = 0xFE;
800 ip6
.s6_addr
[1] = 0x80;
802 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
804 if (netlink_send(&req
.nh
) < 0)
807 memset(&req
, 0, sizeof(req
));
809 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
810 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
811 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
813 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
814 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
815 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
816 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
818 // Global address is prefix::1
819 ip6
= config
->ipv6_prefix
;
821 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
823 if (netlink_send(&req
.nh
) < 0)
827 memset(&req
, 0, sizeof(req
));
829 req
.nh
.nlmsg_type
= NLMSG_DONE
;
830 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
832 if (netlink_send(&req
.nh
) < 0)
835 // if we get an error for seqnum < min_initok_nlseqnum,
836 // we must exit as initialization went wrong
837 if (config
->ipv6_prefix
.s6_addr
[0])
838 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
840 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
846 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
850 // set up LAC UDP ports
851 static void initlacudp(void)
854 struct sockaddr_in addr
;
856 // Tunnel to Remote LNS
857 memset(&addr
, 0, sizeof(addr
));
858 addr
.sin_family
= AF_INET
;
859 addr
.sin_port
= htons(config
->bind_portremotelns
);
860 addr
.sin_addr
.s_addr
= config
->bind_address_remotelns
;
861 udplacfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
862 setsockopt(udplacfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
864 int flags
= fcntl(udplacfd
, F_GETFL
, 0);
865 fcntl(udplacfd
, F_SETFL
, flags
| O_NONBLOCK
);
867 if (bind(udplacfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
869 LOG(0, 0, 0, "Error in UDP REMOTE LNS bind: %s\n", strerror(errno
));
874 // set up control ports
875 static void initcontrol(void)
878 struct sockaddr_in addr
;
881 memset(&addr
, 0, sizeof(addr
));
882 addr
.sin_family
= AF_INET
;
883 addr
.sin_port
= htons(NSCTL_PORT
);
884 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
885 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
886 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
887 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
889 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
894 // set up Dynamic Authorization Extensions to RADIUS port
895 static void initdae(void)
898 struct sockaddr_in addr
;
900 // Dynamic Authorization Extensions to RADIUS
901 memset(&addr
, 0, sizeof(addr
));
902 addr
.sin_family
= AF_INET
;
903 addr
.sin_port
= htons(config
->radius_dae_port
);
904 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
905 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
906 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
907 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
909 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
915 static void initudp(int * pudpfd
, in_addr_t ip_bind
)
918 struct sockaddr_in addr
;
921 memset(&addr
, 0, sizeof(addr
));
922 addr
.sin_family
= AF_INET
;
923 addr
.sin_port
= htons(L2TPPORT
);
924 addr
.sin_addr
.s_addr
= ip_bind
;
925 (*pudpfd
) = socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
926 setsockopt((*pudpfd
), SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
928 int flags
= fcntl((*pudpfd
), F_GETFL
, 0);
929 fcntl((*pudpfd
), F_SETFL
, flags
| O_NONBLOCK
);
931 if (bind((*pudpfd
), (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
933 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
939 // Find session by IP, < 1 for not found
941 // Confusingly enough, this 'ip' must be
942 // in _network_ order. This being the common
943 // case when looking it up from IP packet headers.
945 // We actually use this cache for two things.
946 // #1. For used IP addresses, this maps to the
947 // session ID that it's used by.
948 // #2. For un-used IP addresses, this maps to the
949 // index into the pool table that contains that
953 static sessionidt
lookup_ipmap(in_addr_t ip
)
955 uint8_t *a
= (uint8_t *) &ip
;
956 union iphash
*h
= ip_hash
;
958 if (!(h
= h
[*a
++].idx
)) return 0;
959 if (!(h
= h
[*a
++].idx
)) return 0;
960 if (!(h
= h
[*a
++].idx
)) return 0;
965 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
967 struct ipv6radix
*curnode
;
970 char ipv6addr
[INET6_ADDRSTRLEN
];
972 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
976 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
978 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
983 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
984 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
991 sessionidt
sessionbyip(in_addr_t ip
)
993 sessionidt s
= lookup_ipmap(ip
);
996 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1002 sessionidt
sessionbyipv6(struct in6_addr ip
)
1005 CSTAT(sessionbyipv6
);
1007 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
1008 (ip
.s6_addr
[0] == 0xFE &&
1009 ip
.s6_addr
[1] == 0x80 &&
1010 ip
.s6_addr16
[1] == 0 &&
1011 ip
.s6_addr16
[2] == 0 &&
1012 ip
.s6_addr16
[3] == 0)) {
1013 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
1015 s
= lookup_ipv6map(ip
);
1018 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1025 // Take an IP address in HOST byte order and
1026 // add it to the sessionid by IP cache.
1028 // (It's actually cached in network order)
1030 void cache_ipmap(in_addr_t ip
, sessionidt s
)
1032 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
1033 uint8_t *a
= (uint8_t *) &nip
;
1034 union iphash
*h
= ip_hash
;
1037 for (i
= 0; i
< 3; i
++)
1039 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1048 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1051 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1052 // else a map to an ip pool index.
1055 static void uncache_ipmap(in_addr_t ip
)
1057 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1060 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1064 struct ipv6radix
*curnode
;
1065 char ipv6addr
[INET6_ADDRSTRLEN
];
1067 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
1069 bytes
= prefixlen
>> 3;
1072 if (curnode
->branch
== NULL
)
1074 if (!(curnode
->branch
= calloc(256,
1075 sizeof (struct ipv6radix
))))
1078 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1085 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1086 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1090 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1091 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1097 // CLI list to dump current ipcache.
1099 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1101 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1105 if (CLI_HELP_REQUESTED
)
1106 return CLI_HELP_NO_ARGS
;
1108 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1110 for (i
= 0; i
< 256; ++i
)
1116 for (j
= 0; j
< 256; ++j
)
1122 for (k
= 0; k
< 256; ++k
)
1128 for (l
= 0; l
< 256; ++l
)
1133 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1139 cli_print(cli
, "%d entries in cache", count
);
1144 // Find session by username, 0 for not found
1145 // walled garden users aren't authenticated, so the username is
1146 // reasonably useless. Ignore them to avoid incorrect actions
1148 // This is VERY inefficent. Don't call it often. :)
1150 sessionidt
sessionbyuser(char *username
)
1153 CSTAT(sessionbyuser
);
1155 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1157 if (!session
[s
].opened
)
1160 if (session
[s
].walled_garden
)
1161 continue; // Skip walled garden users.
1163 if (!strncmp(session
[s
].user
, username
, 128))
1167 return 0; // Not found.
1170 void send_garp(in_addr_t ip
)
1176 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1179 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1182 memset(&ifr
, 0, sizeof(ifr
));
1183 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1184 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1186 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1190 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1191 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1193 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1198 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1201 static sessiont
*sessiontbysessionidt(sessionidt s
)
1203 if (!s
|| s
>= MAXSESSION
) return NULL
;
1207 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1209 sessionidt val
= s
-session
;
1210 if (s
< session
|| val
>= MAXSESSION
) return 0;
1214 // actually send a control message for a specific tunnel
1215 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1217 struct sockaddr_in addr
;
1223 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1224 STAT(tunnel_tx_errors
);
1228 if (t
== TUNNEL_ID_PPPOE
)
1230 pppoe_sess_send(buf
, l
, t
);
1236 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1237 STAT(tunnel_tx_errors
);
1241 memset(&addr
, 0, sizeof(addr
));
1242 addr
.sin_family
= AF_INET
;
1243 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1244 addr
.sin_port
= htons(tunnel
[t
].port
);
1246 // sequence expected, if sequence in message
1247 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1249 // If this is a control message, deal with retries
1252 tunnel
[t
].last
= time_now
; // control message sent
1253 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1256 STAT(tunnel_retries
);
1257 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1261 if (sendto(udpfd
[tunnel
[t
].indexudp
], buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1263 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1264 strerror(errno
), udpfd
[tunnel
[t
].indexudp
], buf
, l
, inet_ntoa(addr
.sin_addr
));
1265 STAT(tunnel_tx_errors
);
1269 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1270 STAT(tunnel_tx_packets
);
1271 INC_STAT(tunnel_tx_bytes
, l
);
1275 // Tiny helper function to write data to
1276 // the 'tun' device.
1278 int tun_write(uint8_t * data
, int size
)
1280 return write(tunfd
, data
, size
);
1283 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1284 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1286 int d
= (tcp
[12] >> 4) * 4;
1293 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1296 if (tcp
+ d
> buf
+ len
) // short?
1304 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1307 if (mss
+ 2 > data
) return; // short?
1311 if (*opts
== 0) return; // end of options
1312 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1315 opts
+= opts
[1]; // skip over option
1318 if (!mss
) return; // not found
1319 orig
= ntohs(*(uint16_t *) mss
);
1321 if (orig
<= MSS
) return; // mss OK
1323 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1324 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1325 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1326 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1329 *(int16_t *) mss
= htons(MSS
);
1331 // adjust checksum (see rfc1141)
1332 sum
= orig
+ (~MSS
& 0xffff);
1333 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1334 sum
= (sum
& 0xffff) + (sum
>> 16);
1335 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1338 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1342 // Skip the four extra bytes
1354 proto
= ntohs(*(uint16_t *) p
);
1362 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1363 return; // closing session, PPP not processed
1365 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1366 processipin(s
, t
, p
, l
);
1368 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1372 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1373 return; // closing session, PPP not processed
1376 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1377 processipv6in(s
, t
, p
, l
);
1379 else if (proto
== PPPIPCP
)
1381 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1382 processipcp(s
, t
, p
, l
);
1384 else if (proto
== PPPCCP
)
1386 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1387 processccp(s
, t
, p
, l
);
1391 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1395 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1397 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1398 sp
->cout_delta
+= len
;
1400 sp
->last_data
= time_now
;
1402 sess_local
[s
].cout
+= len
; // To send to master..
1403 sess_local
[s
].pout
++;
1406 // process outgoing (to tunnel) IP
1408 // (i.e. this routine writes to data[-8]).
1409 void processipout(uint8_t *buf
, int len
)
1417 uint8_t *data
= buf
; // Keep a copy of the originals.
1420 uint8_t fragbuf
[MAXETHER
+ 20];
1422 CSTAT(processipout
);
1424 if (len
< MIN_IP_SIZE
)
1426 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1427 STAT(tun_rx_errors
);
1430 if (len
>= MAXETHER
)
1432 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1433 STAT(tun_rx_errors
);
1437 // Skip the tun header
1441 // Got an IP header now
1442 if (*(uint8_t *)(buf
) >> 4 != 4)
1444 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1448 ip
= *(uint32_t *)(buf
+ 16);
1449 if ((g
= grp_groupbyip(ip
)))
1451 s
= grp_getnextsession(g
, ip
);
1454 // Is this a packet for a session that doesn't exist?
1455 static int rate
= 0; // Number of ICMP packets we've sent this second.
1456 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1458 if (last
!= time_now
)
1464 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1466 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1467 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1468 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1473 else if (!(s
= sessionbyip(ip
)))
1475 // Is this a packet for a session that doesn't exist?
1476 static int rate
= 0; // Number of ICMP packets we've sent this second.
1477 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1479 if (last
!= time_now
)
1485 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1487 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1488 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1489 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1494 t
= session
[s
].tunnel
;
1495 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1497 LOG(3, s
, t
, "Packet size more than session MRU\n");
1503 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1504 if (config
->max_packets
> 0)
1506 if (sess_local
[s
].last_packet_out
== TIME
)
1508 int max
= config
->max_packets
;
1510 // All packets for throttled sessions are handled by the
1511 // master, so further limit by using the throttle rate.
1512 // A bit of a kludge, since throttle rate is in kbps,
1513 // but should still be generous given our average DSL
1514 // packet size is 200 bytes: a limit of 28kbps equates
1515 // to around 180 packets per second.
1516 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1517 max
= sp
->throttle_out
;
1519 if (++sess_local
[s
].packets_out
> max
)
1521 sess_local
[s
].packets_dropped
++;
1527 if (sess_local
[s
].packets_dropped
)
1529 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1530 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1531 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1532 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1536 sess_local
[s
].last_packet_out
= TIME
;
1537 sess_local
[s
].packets_out
= 1;
1538 sess_local
[s
].packets_dropped
= 0;
1542 // run access-list if any
1543 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1546 // adjust MSS on SYN and SYN,ACK packets with options
1547 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1549 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1550 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1551 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1556 // Are we throttling this session?
1557 if (config
->cluster_iam_master
)
1558 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1560 master_throttle_packet(sp
->tbf_out
, data
, size
);
1564 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1566 // We are walled-gardening this
1567 master_garden_packet(s
, data
, size
);
1571 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1574 if (!config
->cluster_iam_master
)
1576 // The MPPP packets must be managed by the Master.
1577 master_forward_mppp_packet(s
, data
, size
);
1581 // Add on L2TP header
1582 sessionidt members
[MAXBUNDLESES
];
1583 bundleidt bid
= session
[s
].bundle
;
1584 bundlet
*b
= &bundle
[bid
];
1585 uint32_t num_of_links
, nb_opened
;
1588 num_of_links
= b
->num_of_links
;
1590 for (i
= 0;i
< num_of_links
;i
++)
1593 if (session
[s
].ppp
.lcp
== Opened
)
1595 members
[nb_opened
] = s
;
1602 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1606 num_of_links
= nb_opened
;
1607 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1608 s
= members
[b
->current_ses
];
1609 t
= session
[s
].tunnel
;
1611 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1613 if (num_of_links
> 1)
1615 if(len
> MINFRAGLEN
)
1617 //for rotate traffic among the member links
1618 uint32_t divisor
= num_of_links
;
1620 divisor
= divisor
/2 + (divisor
& 1);
1622 // Partition the packet to "num_of_links" fragments
1623 uint32_t fraglen
= len
/ divisor
;
1624 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1625 uint32_t remain
= len
;
1627 // send the first packet
1628 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1630 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1633 update_session_out_stat(s
, sp
, fraglen
);
1636 while (remain
> last_fraglen
)
1638 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1639 s
= members
[b
->current_ses
];
1640 t
= session
[s
].tunnel
;
1642 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1643 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1645 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1646 update_session_out_stat(s
, sp
, fraglen
);
1649 // send the last fragment
1650 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1651 s
= members
[b
->current_ses
];
1652 t
= session
[s
].tunnel
;
1654 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1655 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1657 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1658 update_session_out_stat(s
, sp
, remain
);
1659 if (remain
!= last_fraglen
)
1660 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1664 // Send it as one frame
1665 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1667 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1668 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1669 update_session_out_stat(s
, sp
, len
);
1674 // Send it as one frame (NO MPPP Frame)
1675 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1676 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1677 update_session_out_stat(s
, sp
, len
);
1682 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1683 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1684 update_session_out_stat(s
, sp
, len
);
1687 // Snooping this session, send it to intercept box
1688 if (sp
->snoop_ip
&& sp
->snoop_port
)
1689 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1694 // process outgoing (to tunnel) IPv6
1696 static void processipv6out(uint8_t * buf
, int len
)
1702 struct in6_addr ip6
;
1704 uint8_t *data
= buf
; // Keep a copy of the originals.
1707 uint8_t b
[MAXETHER
+ 20];
1709 CSTAT(processipv6out
);
1711 if (len
< MIN_IP_SIZE
)
1713 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1714 STAT(tunnel_tx_errors
);
1717 if (len
>= MAXETHER
)
1719 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1720 STAT(tunnel_tx_errors
);
1724 // Skip the tun header
1728 // Got an IP header now
1729 if (*(uint8_t *)(buf
) >> 4 != 6)
1731 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1735 ip6
= *(struct in6_addr
*)(buf
+24);
1736 s
= sessionbyipv6(ip6
);
1740 ip
= *(uint32_t *)(buf
+ 32);
1741 s
= sessionbyip(ip
);
1746 // Is this a packet for a session that doesn't exist?
1747 static int rate
= 0; // Number of ICMP packets we've sent this second.
1748 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1750 if (last
!= time_now
)
1756 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1758 // FIXME: Should send icmp6 host unreachable
1762 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1764 bundleidt bid
= session
[s
].bundle
;
1765 bundlet
*b
= &bundle
[bid
];
1767 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1768 s
= b
->members
[b
->current_ses
];
1769 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1771 t
= session
[s
].tunnel
;
1773 sp
->last_data
= time_now
;
1775 // FIXME: add DoS prevention/filters?
1779 // Are we throttling this session?
1780 if (config
->cluster_iam_master
)
1781 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1783 master_throttle_packet(sp
->tbf_out
, data
, size
);
1786 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1788 // We are walled-gardening this
1789 master_garden_packet(s
, data
, size
);
1793 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1795 // Add on L2TP header
1797 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1799 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1802 // Snooping this session, send it to intercept box
1803 if (sp
->snoop_ip
&& sp
->snoop_port
)
1804 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1806 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1807 sp
->cout_delta
+= len
;
1811 sess_local
[s
].cout
+= len
; // To send to master..
1812 sess_local
[s
].pout
++;
1816 // Helper routine for the TBF filters.
1817 // Used to send queued data in to the user!
1819 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1824 uint8_t b
[MAXETHER
+ 20];
1826 if (len
< 0 || len
> MAXETHER
)
1828 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1832 // Skip the tun header
1839 t
= session
[s
].tunnel
;
1842 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1844 // Add on L2TP header
1846 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1848 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1851 // Snooping this session.
1852 if (sp
->snoop_ip
&& sp
->snoop_port
)
1853 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1855 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1856 sp
->cout_delta
+= len
;
1860 sess_local
[s
].cout
+= len
; // To send to master..
1861 sess_local
[s
].pout
++;
1864 // add an AVP (16 bit)
1865 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1867 uint16_t l
= (m
? 0x8008 : 0x0008);
1868 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1869 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1870 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1871 *(uint16_t *) (c
->buf
+ c
->length
+ 6) = htons(val
);
1875 // add an AVP (32 bit)
1876 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1878 uint16_t l
= (m
? 0x800A : 0x000A);
1879 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1880 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1881 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1882 *(uint32_t *) (c
->buf
+ c
->length
+ 6) = htonl(val
);
1886 // add an AVP (string)
1887 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1889 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1890 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1891 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1892 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1893 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1894 c
->length
+= 6 + strlen(val
);
1898 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1900 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1901 *(uint16_t *) (c
->buf
+ c
->length
+ 0) = htons(l
);
1902 *(uint16_t *) (c
->buf
+ c
->length
+ 2) = htons(0);
1903 *(uint16_t *) (c
->buf
+ c
->length
+ 4) = htons(avp
);
1904 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1905 c
->length
+= 6 + len
;
1908 // new control connection
1909 static controlt
*controlnew(uint16_t mtype
)
1913 c
= malloc(sizeof(controlt
));
1917 controlfree
= c
->next
;
1921 c
->buf
[0] = 0xC8; // flags
1922 c
->buf
[1] = 0x02; // ver
1924 control16(c
, 0, mtype
, 1);
1928 // send zero block if nothing is waiting
1930 static void controlnull(tunnelidt t
)
1933 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1936 buf
[0] = htons(0xC802); // flags/ver
1937 buf
[1] = htons(12); // length
1938 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1939 buf
[3] = htons(0); // session
1940 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1941 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1942 tunnelsend((uint8_t *)buf
, 12, t
);
1945 // add a control message to a tunnel, and send if within window
1946 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1948 *(uint16_t *) (c
->buf
+ 2) = htons(c
->length
); // length
1949 *(uint16_t *) (c
->buf
+ 4) = htons(tunnel
[t
].far
); // tunnel
1950 *(uint16_t *) (c
->buf
+ 6) = htons(far
); // session
1951 *(uint16_t *) (c
->buf
+ 8) = htons(tunnel
[t
].ns
); // sequence
1952 tunnel
[t
].ns
++; // advance sequence
1953 // link in message in to queue
1954 if (tunnel
[t
].controlc
)
1955 tunnel
[t
].controle
->next
= c
;
1957 tunnel
[t
].controls
= c
;
1959 tunnel
[t
].controle
= c
;
1960 tunnel
[t
].controlc
++;
1962 // send now if space in window
1963 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1965 tunnel
[t
].try = 0; // first send
1966 tunnelsend(c
->buf
, c
->length
, t
);
1971 // Throttle or Unthrottle a session
1973 // Throttle the data from/to through a session to no more than
1974 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1977 // If either value is -1, the current value is retained for that
1980 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1982 if (!session
[s
].opened
)
1983 return; // No-one home.
1985 if (!*session
[s
].user
)
1986 return; // User not logged in
1990 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1991 if (session
[s
].tbf_in
)
1992 free_tbf(session
[s
].tbf_in
);
1995 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1997 session
[s
].tbf_in
= 0;
1999 session
[s
].throttle_in
= rate_in
;
2004 int bytes
= rate_out
* 1024 / 8;
2005 if (session
[s
].tbf_out
)
2006 free_tbf(session
[s
].tbf_out
);
2009 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
2011 session
[s
].tbf_out
= 0;
2013 session
[s
].throttle_out
= rate_out
;
2017 // add/remove filters from session (-1 = no change)
2018 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
2020 if (!session
[s
].opened
)
2021 return; // No-one home.
2023 if (!*session
[s
].user
)
2024 return; // User not logged in
2027 if (filter_in
> MAXFILTER
) filter_in
= -1;
2028 if (filter_out
> MAXFILTER
) filter_out
= -1;
2029 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
2030 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
2034 if (session
[s
].filter_in
)
2035 ip_filters
[session
[s
].filter_in
- 1].used
--;
2038 ip_filters
[filter_in
- 1].used
++;
2040 session
[s
].filter_in
= filter_in
;
2043 if (filter_out
>= 0)
2045 if (session
[s
].filter_out
)
2046 ip_filters
[session
[s
].filter_out
- 1].used
--;
2049 ip_filters
[filter_out
- 1].used
++;
2051 session
[s
].filter_out
= filter_out
;
2055 // start tidy shutdown of session
2056 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
2058 int walled_garden
= session
[s
].walled_garden
;
2059 bundleidt b
= session
[s
].bundle
;
2060 //delete routes only for last session in bundle (in case of MPPP)
2061 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
2063 CSTAT(sessionshutdown
);
2065 if (!session
[s
].opened
)
2067 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2068 return; // not a live session
2071 if (!session
[s
].die
)
2073 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2074 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2075 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2078 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2080 // RADIUS Stop message
2081 uint16_t r
= radiusnew(s
);
2084 // stop, if not already trying
2085 if (radius
[r
].state
!= RADIUSSTOP
)
2087 radius
[r
].term_cause
= term_cause
;
2088 radius
[r
].term_msg
= reason
;
2089 radiussend(r
, RADIUSSTOP
);
2093 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2095 // Save counters to dump to accounting file
2096 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2097 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2100 if (!session
[s
].die
)
2101 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2104 { // IP allocated, clear and unroute
2107 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2109 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2110 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2113 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2114 session
[s
].route
[r
].ip
= 0;
2117 if (session
[s
].ip_pool_index
== -1) // static ip
2119 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2125 // unroute IPv6, if setup
2126 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
2127 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2131 // This session was part of a bundle
2132 bundle
[b
].num_of_links
--;
2133 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2134 if(bundle
[b
].num_of_links
== 0)
2137 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2141 // Adjust the members array to accomodate the new change
2142 uint8_t mem_num
= 0;
2143 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2144 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2147 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2148 if(bundle
[b
].members
[ml
] == s
)
2153 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2154 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2156 // If the killed session is the first of the bundle,
2157 // the new first session must be stored in the cache_ipmap
2158 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2161 sessionidt new_s
= bundle
[b
].members
[0];
2164 // Add the route for this session.
2165 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2170 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2171 ip
= session
[new_s
].route
[r
].ip
;
2173 if (!prefixlen
) prefixlen
= 32;
2174 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2176 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2177 cache_ipmap(i
, new_s
);
2179 cache_ipmap(session
[new_s
].ip
, new_s
);
2182 if (session
[new_s
].ipv6prefixlen
)
2183 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2188 cluster_send_bundle(b
);
2192 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2193 throttle_session(s
, 0, 0);
2197 if (session
[s
].tunnel
== TUNNEL_ID_PPPOE
)
2199 pppoe_shutdown_session(s
);
2204 controlt
*c
= controlnew(14); // sending CDN
2208 buf
[0] = htons(cdn_result
);
2209 buf
[1] = htons(cdn_error
);
2210 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2213 control16(c
, 1, cdn_result
, 1);
2215 control16(c
, 14, s
, 1); // assigned session (our end)
2216 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2220 // update filter refcounts
2221 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2222 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2225 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2226 sess_local
[s
].lcp
.restart
= 0;
2227 sess_local
[s
].ipcp
.restart
= 0;
2228 sess_local
[s
].ipv6cp
.restart
= 0;
2229 sess_local
[s
].ccp
.restart
= 0;
2231 cluster_send_session(s
);
2234 void sendipcp(sessionidt s
, tunnelidt t
)
2236 uint8_t buf
[MAXETHER
];
2240 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2242 if (!session
[s
].unique_id
)
2244 if (!++last_id
) ++last_id
; // skip zero
2245 session
[s
].unique_id
= last_id
;
2248 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2252 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2253 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2254 q
[4] = 3; // ip address option
2255 q
[5] = 6; // option length
2256 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2257 config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] :
2258 my_address
; // send my IP
2260 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2261 restart_timer(s
, ipcp
);
2264 void sendipv6cp(sessionidt s
, tunnelidt t
)
2266 uint8_t buf
[MAXETHER
];
2270 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2272 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2276 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2277 // only send one type
2279 *(uint16_t *) (q
+ 2) = htons(14);
2280 q
[4] = 1; // interface identifier option
2281 q
[5] = 10; // option length
2282 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2283 *(uint32_t *) (q
+ 10) = 0;
2286 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2287 restart_timer(s
, ipv6cp
);
2290 static void sessionclear(sessionidt s
)
2292 memset(&session
[s
], 0, sizeof(session
[s
]));
2293 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2294 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2296 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2297 session
[s
].next
= sessionfree
;
2301 // kill a session now
2302 void sessionkill(sessionidt s
, char *reason
)
2308 if (!session
[s
].opened
) // not alive
2311 if (session
[s
].next
)
2313 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2317 if (!session
[s
].die
)
2318 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2320 if (sess_local
[s
].radius
)
2321 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2323 if (session
[s
].forwardtosession
)
2325 sessionidt sess
= session
[s
].forwardtosession
;
2326 if (session
[sess
].forwardtosession
== s
)
2328 // Shutdown the linked session also.
2329 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2333 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2335 if ((g
= grp_groupbysession(s
)))
2337 grp_removesession(g
, s
);
2341 cluster_send_session(s
);
2344 static void tunnelclear(tunnelidt t
)
2347 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2348 tunnel
[t
].state
= TUNNELFREE
;
2351 static void bundleclear(bundleidt b
)
2354 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2355 bundle
[b
].state
= BUNDLEFREE
;
2358 // kill a tunnel now
2359 static void tunnelkill(tunnelidt t
, char *reason
)
2366 tunnel
[t
].state
= TUNNELDIE
;
2368 // free control messages
2369 while ((c
= tunnel
[t
].controls
))
2371 controlt
* n
= c
->next
;
2372 tunnel
[t
].controls
= n
;
2373 tunnel
[t
].controlc
--;
2374 c
->next
= controlfree
;
2378 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2379 if (session
[s
].tunnel
== t
)
2380 sessionkill(s
, reason
);
2384 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2385 cli_tunnel_actions
[t
].action
= 0;
2386 cluster_send_tunnel(t
);
2389 // shut down a tunnel cleanly
2390 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2394 CSTAT(tunnelshutdown
);
2396 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2398 // never set up, can immediately kill
2399 tunnelkill(t
, reason
);
2402 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2405 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2406 if (session
[s
].tunnel
== t
)
2407 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2409 tunnel
[t
].state
= TUNNELDIE
;
2410 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2411 cluster_send_tunnel(t
);
2412 // TBA - should we wait for sessions to stop?
2415 controlt
*c
= controlnew(4); // sending StopCCN
2420 buf
[0] = htons(result
);
2421 buf
[1] = htons(error
);
2424 int m
= strlen(msg
);
2425 if (m
+ 4 > sizeof(buf
))
2426 m
= sizeof(buf
) - 4;
2428 memcpy(buf
+2, msg
, m
);
2432 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2435 control16(c
, 1, result
, 1);
2437 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2438 controladd(c
, 0, t
); // send the message
2442 // read and process packet on tunnel (UDP)
2443 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, uint16_t indexudpfd
)
2445 uint8_t *sendchalresponse
= NULL
;
2446 uint8_t *recvchalresponse
= NULL
;
2447 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2448 uint8_t *p
= buf
+ 2;
2455 LOG_HEX(5, "UDP Data", buf
, len
);
2456 STAT(tunnel_rx_packets
);
2457 INC_STAT(tunnel_rx_bytes
, len
);
2460 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2461 STAT(tunnel_rx_errors
);
2464 if ((buf
[1] & 0x0F) != 2)
2466 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2467 STAT(tunnel_rx_errors
);
2472 l
= ntohs(*(uint16_t *) p
);
2475 t
= ntohs(*(uint16_t *) p
);
2477 s
= ntohs(*(uint16_t *) p
);
2479 if (s
>= MAXSESSION
)
2481 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2482 STAT(tunnel_rx_errors
);
2487 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2488 STAT(tunnel_rx_errors
);
2491 if (t
== TUNNEL_ID_PPPOE
)
2493 LOG(1, s
, t
, "Received UDP packet with tunnel ID reserved for pppoe\n");
2494 STAT(tunnel_rx_errors
);
2499 ns
= ntohs(*(uint16_t *) p
);
2501 nr
= ntohs(*(uint16_t *) p
);
2506 uint16_t o
= ntohs(*(uint16_t *) p
);
2511 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2512 STAT(tunnel_rx_errors
);
2517 // used to time out old tunnels
2518 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2519 tunnel
[t
].lastrec
= time_now
;
2523 uint16_t message
= 0xFFFF; // message type
2525 uint8_t mandatory
= 0;
2526 uint16_t asession
= 0; // assigned session
2527 uint32_t amagic
= 0; // magic number
2528 uint8_t aflags
= 0; // flags from last LCF
2529 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2530 char called
[MAXTEL
] = ""; // called number
2531 char calling
[MAXTEL
] = ""; // calling number
2533 if (!config
->cluster_iam_master
)
2535 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
2539 // control messages must have bits 0x80|0x40|0x08
2540 // (type, length and sequence) set, and bits 0x02|0x01
2541 // (offset and priority) clear
2542 if ((*buf
& 0xCB) != 0xC8)
2544 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2545 STAT(tunnel_rx_errors
);
2549 // check for duplicate tunnel open message
2555 // Is this a duplicate of the first packet? (SCCRQ)
2557 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2559 if (tunnel
[i
].state
!= TUNNELOPENING
||
2560 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2561 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2564 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2569 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2570 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2572 // if no tunnel specified, assign one
2575 if (!(t
= new_tunnel()))
2577 LOG(1, 0, 0, "No more tunnels\n");
2578 STAT(tunnel_overflow
);
2582 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2583 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2584 tunnel
[t
].window
= 4; // default window
2585 tunnel
[t
].indexudp
= indexudpfd
;
2586 STAT(tunnel_created
);
2587 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2588 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2591 // If the 'ns' just received is not the 'nr' we're
2592 // expecting, just send an ack and drop it.
2594 // if 'ns' is less, then we got a retransmitted packet.
2595 // if 'ns' is greater than missed a packet. Either way
2596 // we should ignore it.
2597 if (ns
!= tunnel
[t
].nr
)
2599 // is this the sequence we were expecting?
2600 STAT(tunnel_rx_errors
);
2601 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2602 t
, ns
, tunnel
[t
].nr
);
2604 if (l
) // Is this not a ZLB?
2609 // check sequence of this message
2611 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2612 // some to clear maybe?
2613 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2615 controlt
*c
= tunnel
[t
].controls
;
2616 tunnel
[t
].controls
= c
->next
;
2617 tunnel
[t
].controlc
--;
2618 c
->next
= controlfree
;
2621 tunnel
[t
].try = 0; // we have progress
2624 // receiver advance (do here so quoted correctly in any sends below)
2625 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2626 if (skip
< 0) skip
= 0;
2627 if (skip
< tunnel
[t
].controlc
)
2629 // some control packets can now be sent that were previous stuck out of window
2630 int tosend
= tunnel
[t
].window
- skip
;
2631 controlt
*c
= tunnel
[t
].controls
;
2639 tunnel
[t
].try = 0; // first send
2640 tunnelsend(c
->buf
, c
->length
, t
);
2645 if (!tunnel
[t
].controlc
)
2646 tunnel
[t
].retry
= 0; // caught up
2649 { // if not a null message
2654 // Default disconnect cause/message on receipt of CDN. Set to
2655 // more specific value from attribute 1 (result code) or 46
2656 // (disconnect cause) if present below.
2657 int disc_cause_set
= 0;
2658 int disc_cause
= TERM_NAS_REQUEST
;
2659 char const *disc_reason
= "Closed (Received CDN).";
2662 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2664 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2671 LOG(1, s
, t
, "Invalid length in AVP\n");
2672 STAT(tunnel_rx_errors
);
2677 if (flags
& 0x3C) // reserved bits, should be clear
2679 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2681 result
= 2; // general error
2682 error
= 3; // reserved field non-zero
2687 if (*(uint16_t *) (b
))
2689 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2691 result
= 2; // general error
2692 error
= 6; // generic vendor-specific error
2693 msg
= "unsupported vendor-specific";
2697 mtype
= ntohs(*(uint16_t *) (b
));
2705 // handle hidden AVPs
2706 if (!*config
->l2tp_secret
)
2708 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2710 result
= 2; // general error
2711 error
= 6; // generic vendor-specific error
2712 msg
= "secret not specified";
2715 if (!session
[s
].random_vector_length
)
2717 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2719 result
= 2; // general error
2720 error
= 6; // generic
2721 msg
= "no random vector";
2726 LOG(2, s
, t
, "Short hidden AVP.\n");
2728 result
= 2; // general error
2729 error
= 2; // length is wrong
2735 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2737 orig_len
= ntohs(*(uint16_t *) b
);
2738 if (orig_len
> n
+ 2)
2740 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2744 result
= 2; // general error
2745 error
= 2; // length is wrong
2754 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2755 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2759 case 0: // message type
2760 message
= ntohs(*(uint16_t *) b
);
2761 mandatory
= flags
& 0x80;
2762 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2764 case 1: // result code
2766 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2767 char const *resdesc
= "(unknown)";
2768 char const *errdesc
= NULL
;
2773 resdesc
= l2tp_stopccn_result_code(rescode
);
2774 cause
= TERM_LOST_SERVICE
;
2776 else if (message
== 14)
2778 resdesc
= l2tp_cdn_result_code(rescode
);
2780 cause
= TERM_LOST_CARRIER
;
2782 cause
= TERM_ADMIN_RESET
;
2785 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2788 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2789 errdesc
= l2tp_error_code(errcode
);
2790 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2793 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2795 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2797 disc_cause_set
= mtype
;
2798 disc_reason
= errdesc
? errdesc
: resdesc
;
2805 case 2: // protocol version
2807 version
= ntohs(*(uint16_t *) (b
));
2808 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2809 if (version
&& version
!= 0x0100)
2810 { // allow 0.0 and 1.0
2811 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2813 result
= 5; // unspported protocol version
2814 error
= 0x0100; // supported version
2820 case 3: // framing capabilities
2822 case 4: // bearer capabilities
2824 case 5: // tie breaker
2825 // We never open tunnels, so we don't care about tie breakers
2827 case 6: // firmware revision
2829 case 7: // host name
2830 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2831 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2832 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2833 // TBA - to send to RADIUS
2835 case 8: // vendor name
2836 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2837 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2838 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2840 case 9: // assigned tunnel
2841 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2842 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2844 case 10: // rx window
2845 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2846 if (!tunnel
[t
].window
)
2847 tunnel
[t
].window
= 1; // window of 0 is silly
2848 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2850 case 11: // Request Challenge
2852 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2854 build_chap_response(b
, 2, n
, &sendchalresponse
);
2855 else if (message
== 2)
2856 build_chap_response(b
, 3, n
, &sendchalresponse
);
2859 case 13: // receive challenge Response
2860 if (tunnel
[t
].isremotelns
)
2862 recvchalresponse
= calloc(17, 1);
2863 memcpy(recvchalresponse
, b
, (n
< 17) ? n
: 16);
2864 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2867 // Why did they send a response? We never challenge.
2868 LOG(2, s
, t
, " received unexpected challenge response\n");
2871 case 14: // assigned session
2872 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2873 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2875 case 15: // call serial number
2876 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2878 case 18: // bearer type
2879 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2882 case 19: // framing type
2883 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2886 case 21: // called number
2887 memset(called
, 0, sizeof(called
));
2888 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2889 LOG(4, s
, t
, " Called <%s>\n", called
);
2891 case 22: // calling number
2892 memset(calling
, 0, sizeof(calling
));
2893 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2894 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2898 case 24: // tx connect speed
2901 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2905 // AS5300s send connect speed as a string
2907 memset(tmp
, 0, sizeof(tmp
));
2908 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2909 session
[s
].tx_connect_speed
= atol(tmp
);
2911 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2913 case 38: // rx connect speed
2916 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2920 // AS5300s send connect speed as a string
2922 memset(tmp
, 0, sizeof(tmp
));
2923 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2924 session
[s
].rx_connect_speed
= atol(tmp
);
2926 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2928 case 25: // Physical Channel ID
2930 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2931 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2934 case 29: // Proxy Authentication Type
2936 uint16_t atype
= ntohs(*(uint16_t *)b
);
2937 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2940 case 30: // Proxy Authentication Name
2943 memset(authname
, 0, sizeof(authname
));
2944 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2945 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2949 case 31: // Proxy Authentication Challenge
2951 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2954 case 32: // Proxy Authentication ID
2956 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2957 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2960 case 33: // Proxy Authentication Response
2961 LOG(4, s
, t
, " Proxy Auth Response\n");
2963 case 27: // last sent lcp
2964 { // find magic number
2965 uint8_t *p
= b
, *e
= p
+ n
;
2966 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2968 if (*p
== 5 && p
[1] == 6) // Magic-Number
2969 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2970 else if (*p
== 7) // Protocol-Field-Compression
2971 aflags
|= SESSION_PFC
;
2972 else if (*p
== 8) // Address-and-Control-Field-Compression
2973 aflags
|= SESSION_ACFC
;
2978 case 28: // last recv lcp confreq
2980 case 26: // Initial Received LCP CONFREQ
2982 case 39: // seq required - we control it as an LNS anyway...
2984 case 36: // Random Vector
2985 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2986 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2987 if (n
> sizeof(session
[s
].random_vector
))
2988 n
= sizeof(session
[s
].random_vector
);
2989 memcpy(session
[s
].random_vector
, b
, n
);
2990 session
[s
].random_vector_length
= n
;
2992 case 46: // ppp disconnect cause
2995 uint16_t code
= ntohs(*(uint16_t *) b
);
2996 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2997 uint8_t dir
= *(b
+ 4);
2999 LOG(4, s
, t
, " PPP disconnect cause "
3000 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
3001 code
, proto
, dir
, n
- 5, b
+ 5);
3003 disc_cause_set
= mtype
;
3007 case 1: // admin disconnect
3008 disc_cause
= TERM_ADMIN_RESET
;
3009 disc_reason
= "Administrative disconnect";
3011 case 3: // lcp terminate
3012 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
3013 disc_cause
= TERM_USER_REQUEST
;
3014 disc_reason
= "Normal disconnection";
3016 case 4: // compulsory encryption unavailable
3017 if (dir
!= 1) break; // 1=refused by peer, 2=local
3018 disc_cause
= TERM_USER_ERROR
;
3019 disc_reason
= "Compulsory encryption refused";
3021 case 5: // lcp: fsm timeout
3022 disc_cause
= TERM_PORT_ERROR
;
3023 disc_reason
= "LCP: FSM timeout";
3025 case 6: // lcp: no recognisable lcp packets received
3026 disc_cause
= TERM_PORT_ERROR
;
3027 disc_reason
= "LCP: no recognisable LCP packets";
3029 case 7: // lcp: magic-no error (possibly looped back)
3030 disc_cause
= TERM_PORT_ERROR
;
3031 disc_reason
= "LCP: magic-no error (possible loop)";
3033 case 8: // lcp: echo request timeout
3034 disc_cause
= TERM_PORT_ERROR
;
3035 disc_reason
= "LCP: echo request timeout";
3037 case 13: // auth: fsm timeout
3038 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3039 disc_reason
= "Authentication: FSM timeout";
3041 case 15: // auth: unacceptable auth protocol
3042 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3043 disc_reason
= "Unacceptable authentication protocol";
3045 case 16: // auth: authentication failed
3046 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3047 disc_reason
= "Authentication failed";
3049 case 17: // ncp: fsm timeout
3050 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3051 disc_reason
= "NCP: FSM timeout";
3053 case 18: // ncp: no ncps available
3054 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3055 disc_reason
= "NCP: no NCPs available";
3057 case 19: // ncp: failure to converge on acceptable address
3058 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3059 disc_reason
= (dir
== 1)
3060 ? "NCP: too many Configure-Naks received from peer"
3061 : "NCP: too many Configure-Naks sent to peer";
3063 case 20: // ncp: user not permitted to use any address
3064 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3065 disc_reason
= (dir
== 1)
3066 ? "NCP: local link address not acceptable to peer"
3067 : "NCP: remote link address not acceptable";
3074 static char e
[] = "unknown AVP 0xXXXX";
3075 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
3077 result
= 2; // general error
3078 error
= 8; // unknown mandatory AVP
3079 sprintf((msg
= e
) + 14, "%04x", mtype
);
3086 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3090 case 1: // SCCRQ - Start Control Connection Request
3091 tunnel
[t
].state
= TUNNELOPENING
;
3092 LOG(3, s
, t
, "Received SCCRQ\n");
3093 if (main_quit
!= QUIT_SHUTDOWN
)
3095 LOG(3, s
, t
, "sending SCCRP\n");
3096 controlt
*c
= controlnew(2); // sending SCCRP
3097 control16(c
, 2, version
, 1); // protocol version
3098 control32(c
, 3, 3, 1); // framing
3099 controls(c
, 7, hostname
, 1); // host name
3100 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Send Challenge response
3101 control16(c
, 9, t
, 1); // assigned tunnel
3102 controladd(c
, 0, t
); // send the resply
3106 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3110 tunnel
[t
].state
= TUNNELOPEN
;
3111 tunnel
[t
].lastrec
= time_now
;
3112 LOG(3, s
, t
, "Received SCCRP\n");
3113 if (main_quit
!= QUIT_SHUTDOWN
)
3115 if (tunnel
[t
].isremotelns
&& recvchalresponse
)
3119 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3120 // check authenticator
3121 if (memcmp(hash
, recvchalresponse
, 16) == 0)
3123 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3124 controlt
*c
= controlnew(3); // sending SCCCN
3125 controls(c
, 7, hostname
, 1); // host name
3126 controls(c
, 8, Vendor_name
, 1); // Vendor name
3127 control16(c
, 2, version
, 1); // protocol version
3128 control32(c
, 3, 3, 1); // framing Capabilities
3129 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Challenge response
3130 control16(c
, 9, t
, 1); // assigned tunnel
3131 controladd(c
, 0, t
); // send
3135 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3141 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3145 LOG(3, s
, t
, "Received SCCN\n");
3146 tunnel
[t
].state
= TUNNELOPEN
;
3147 tunnel
[t
].lastrec
= time_now
;
3148 controlnull(t
); // ack
3151 LOG(3, s
, t
, "Received StopCCN\n");
3152 controlnull(t
); // ack
3153 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3156 LOG(3, s
, t
, "Received HELLO\n");
3157 controlnull(t
); // simply ACK
3161 LOG(3, s
, t
, "Received OCRQ\n");
3165 LOG(3, s
, t
, "Received OCRO\n");
3169 LOG(3, s
, t
, "Received OCCN\n");
3172 LOG(3, s
, t
, "Received ICRQ\n");
3173 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3175 controlt
*c
= controlnew(11); // ICRP
3177 LOG(3, s
, t
, "Sending ICRP\n");
3180 sessionfree
= session
[s
].next
;
3181 memset(&session
[s
], 0, sizeof(session
[s
]));
3183 if (s
> config
->cluster_highest_sessionid
)
3184 config
->cluster_highest_sessionid
= s
;
3186 session
[s
].opened
= time_now
;
3187 session
[s
].tunnel
= t
;
3188 session
[s
].far
= asession
;
3189 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3190 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3191 control16(c
, 14, s
, 1); // assigned session
3192 controladd(c
, asession
, t
); // send the reply
3194 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3195 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3197 session
[s
].ppp
.phase
= Establish
;
3198 session
[s
].ppp
.lcp
= Starting
;
3200 STAT(session_created
);
3205 controlt
*c
= controlnew(14); // CDN
3206 LOG(3, s
, t
, "Sending CDN\n");
3209 STAT(session_overflow
);
3210 LOG(1, 0, t
, "No free sessions\n");
3211 control16(c
, 1, 4, 0); // temporary lack of resources
3214 control16(c
, 1, 2, 7); // shutting down, try another
3216 controladd(c
, asession
, t
); // send the message
3220 LOG(3, s
, t
, "Received ICRP\n");
3221 if (session
[s
].forwardtosession
)
3223 controlt
*c
= controlnew(12); // ICCN
3225 session
[s
].opened
= time_now
;
3226 session
[s
].tunnel
= t
;
3227 session
[s
].far
= asession
;
3228 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3230 control32(c
, 19, 1, 1); // Framing Type
3231 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3232 controladd(c
, asession
, t
); // send the message
3233 LOG(3, s
, t
, "Sending ICCN\n");
3237 LOG(3, s
, t
, "Received ICCN\n");
3238 if (amagic
== 0) amagic
= time_now
;
3239 session
[s
].magic
= amagic
; // set magic number
3240 session
[s
].flags
= aflags
; // set flags received
3241 session
[s
].mru
= PPPoE_MRU
; // default
3242 controlnull(t
); // ack
3245 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3246 sess_local
[s
].ppp_mru
= MRU
;
3248 // Set multilink options before sending initial LCP packet
3249 sess_local
[s
].mp_mrru
= 1614;
3250 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] : my_address
);
3253 change_state(s
, lcp
, RequestSent
);
3257 LOG(3, s
, t
, "Received CDN\n");
3258 controlnull(t
); // ack
3259 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3262 LOG(1, s
, t
, "Missing message type\n");
3265 STAT(tunnel_rx_errors
);
3267 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3269 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3272 if (sendchalresponse
) free(sendchalresponse
);
3273 if (recvchalresponse
) free(recvchalresponse
);
3274 cluster_send_tunnel(t
);
3278 LOG(4, s
, t
, " Got a ZLB ack\n");
3285 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3286 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3287 { // HDLC address header, discard
3293 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3294 STAT(tunnel_rx_errors
);
3304 proto
= ntohs(*(uint16_t *) p
);
3309 if (session
[s
].forwardtosession
)
3311 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3312 // Forward to LAC/BAS or Remote LNS session
3313 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3316 else if (config
->auth_tunnel_change_addr_src
)
3318 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3319 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3321 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3322 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3323 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3325 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3329 if (s
&& !session
[s
].opened
) // Is something wrong??
3331 if (!config
->cluster_iam_master
)
3333 // Pass it off to the master to deal with..
3334 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3338 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3339 STAT(tunnel_rx_errors
);
3343 if (proto
== PPPPAP
)
3345 session
[s
].last_packet
= time_now
;
3346 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3347 processpap(s
, t
, p
, l
);
3349 else if (proto
== PPPCHAP
)
3351 session
[s
].last_packet
= time_now
;
3352 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3353 processchap(s
, t
, p
, l
);
3355 else if (proto
== PPPLCP
)
3357 session
[s
].last_packet
= time_now
;
3358 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3359 processlcp(s
, t
, p
, l
);
3361 else if (proto
== PPPIPCP
)
3363 session
[s
].last_packet
= time_now
;
3364 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3365 processipcp(s
, t
, p
, l
);
3367 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3369 session
[s
].last_packet
= time_now
;
3370 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3371 processipv6cp(s
, t
, p
, l
);
3373 else if (proto
== PPPCCP
)
3375 session
[s
].last_packet
= time_now
;
3376 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3377 processccp(s
, t
, p
, l
);
3379 else if (proto
== PPPIP
)
3383 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3384 return; // closing session, PPP not processed
3387 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3388 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3390 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3394 processipin(s
, t
, p
, l
);
3396 else if (proto
== PPPMP
)
3400 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3401 return; // closing session, PPP not processed
3404 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3405 if (!config
->cluster_iam_master
)
3407 // The fragments reconstruction is managed by the Master.
3408 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3412 processmpin(s
, t
, p
, l
);
3414 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
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 processipv6in(s
, t
, p
, l
);
3431 else if (session
[s
].ppp
.lcp
== Opened
)
3433 session
[s
].last_packet
= time_now
;
3434 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3435 protoreject(s
, t
, p
, l
, proto
);
3439 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3440 proto
, ppp_state(session
[s
].ppp
.lcp
));
3445 // read and process packet on tun
3446 // (i.e. this routine writes to buf[-8]).
3447 static void processtun(uint8_t * buf
, int len
)
3449 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3450 STAT(tun_rx_packets
);
3451 INC_STAT(tun_rx_bytes
, len
);
3459 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3460 STAT(tun_rx_errors
);
3464 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3465 processipout(buf
, len
);
3466 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3467 && config
->ipv6_prefix
.s6_addr
[0])
3468 processipv6out(buf
, len
);
3473 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3474 // that we look at the whole of the tunnel, radius and session tables
3476 static void regular_cleanups(double period
)
3478 // Next tunnel, radius and session to check for actions on.
3479 static tunnelidt t
= 0;
3481 static sessionidt s
= 0;
3494 // divide up tables into slices based on the last run
3495 t_slice
= config
->cluster_highest_tunnelid
* period
;
3496 r_slice
= (MAXRADIUS
- 1) * period
;
3497 s_slice
= config
->cluster_highest_sessionid
* period
;
3501 else if (t_slice
> config
->cluster_highest_tunnelid
)
3502 t_slice
= config
->cluster_highest_tunnelid
;
3506 else if (r_slice
> (MAXRADIUS
- 1))
3507 r_slice
= MAXRADIUS
- 1;
3511 else if (s_slice
> config
->cluster_highest_sessionid
)
3512 s_slice
= config
->cluster_highest_sessionid
;
3514 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3516 for (i
= 0; i
< t_slice
; i
++)
3519 if (t
> config
->cluster_highest_tunnelid
)
3522 if (t
== TUNNEL_ID_PPPOE
)
3525 // check for expired tunnels
3526 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3528 STAT(tunnel_timeout
);
3529 tunnelkill(t
, "Expired");
3533 // check for message resend
3534 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3536 // resend pending messages as timeout on reply
3537 if (tunnel
[t
].retry
<= TIME
)
3539 controlt
*c
= tunnel
[t
].controls
;
3540 uint16_t w
= tunnel
[t
].window
;
3541 tunnel
[t
].try++; // another try
3542 if (tunnel
[t
].try > 5)
3543 tunnelkill(t
, "Timeout on control message"); // game over
3547 tunnelsend(c
->buf
, c
->length
, t
);
3555 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3557 if (!config
->disable_sending_hello
)
3559 controlt
*c
= controlnew(6); // sending HELLO
3560 controladd(c
, 0, t
); // send the message
3561 LOG(3, 0, t
, "Sending HELLO message\n");
3566 // Check for tunnel changes requested from the CLI
3567 if ((a
= cli_tunnel_actions
[t
].action
))
3569 cli_tunnel_actions
[t
].action
= 0;
3570 if (a
& CLI_TUN_KILL
)
3572 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3573 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3579 for (i
= 0; i
< r_slice
; i
++)
3585 if (!radius
[r
].state
)
3588 if (radius
[r
].retry
<= TIME
)
3595 for (i
= 0; i
< s_slice
; i
++)
3598 if (s
> config
->cluster_highest_sessionid
)
3601 if (!session
[s
].opened
) // Session isn't in use
3604 // check for expired sessions
3607 if (session
[s
].die
<= TIME
)
3609 sessionkill(s
, "Expired");
3616 if (sess_local
[s
].lcp
.restart
<= time_now
)
3618 int next_state
= session
[s
].ppp
.lcp
;
3619 switch (session
[s
].ppp
.lcp
)
3623 next_state
= RequestSent
;
3626 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3628 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3629 sendlcp(s
, session
[s
].tunnel
);
3630 change_state(s
, lcp
, next_state
);
3634 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3635 STAT(session_timeout
);
3645 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3647 int next_state
= session
[s
].ppp
.ipcp
;
3648 switch (session
[s
].ppp
.ipcp
)
3652 next_state
= RequestSent
;
3655 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3657 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3658 sendipcp(s
, session
[s
].tunnel
);
3659 change_state(s
, ipcp
, next_state
);
3663 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3664 STAT(session_timeout
);
3674 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3676 int next_state
= session
[s
].ppp
.ipv6cp
;
3677 switch (session
[s
].ppp
.ipv6cp
)
3681 next_state
= RequestSent
;
3684 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3686 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3687 sendipv6cp(s
, session
[s
].tunnel
);
3688 change_state(s
, ipv6cp
, next_state
);
3692 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3693 change_state(s
, ipv6cp
, Stopped
);
3700 if (sess_local
[s
].ccp
.restart
<= time_now
)
3702 int next_state
= session
[s
].ppp
.ccp
;
3703 switch (session
[s
].ppp
.ccp
)
3707 next_state
= RequestSent
;
3710 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3712 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3713 sendccp(s
, session
[s
].tunnel
);
3714 change_state(s
, ccp
, next_state
);
3718 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3719 change_state(s
, ccp
, Stopped
);
3726 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3727 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3729 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3730 STAT(session_timeout
);
3735 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3736 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= config
->echo_timeout
) &&
3737 (time_now
- sess_local
[s
].last_echo
>= config
->echo_timeout
))
3739 uint8_t b
[MAXETHER
];
3741 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3745 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3746 *(uint16_t *)(q
+ 2) = htons(8); // Length
3747 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3749 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3750 (int)(time_now
- session
[s
].last_packet
));
3752 tunnelsend(b
, (q
- b
) + 8, session
[s
].tunnel
); // send it
3753 sess_local
[s
].last_echo
= time_now
;
3757 // Drop sessions who have reached session_timeout seconds
3758 if (session
[s
].session_timeout
)
3760 bundleidt bid
= session
[s
].bundle
;
3763 if (time_now
- bundle
[bid
].last_check
>= 1)
3765 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3766 bundle
[bid
].last_check
= time_now
;
3767 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3770 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3772 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3779 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3781 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3787 // Drop sessions who have reached idle_timeout seconds
3788 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3790 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3791 STAT(session_timeout
);
3796 // Check for actions requested from the CLI
3797 if ((a
= cli_session_actions
[s
].action
))
3801 cli_session_actions
[s
].action
= 0;
3802 if (a
& CLI_SESS_KILL
)
3804 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3805 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3806 a
= 0; // dead, no need to check for other actions
3810 if (a
& CLI_SESS_NOSNOOP
)
3812 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3813 session
[s
].snoop_ip
= 0;
3814 session
[s
].snoop_port
= 0;
3818 else if (a
& CLI_SESS_SNOOP
)
3820 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3821 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3822 cli_session_actions
[s
].snoop_port
);
3824 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3825 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3830 if (a
& CLI_SESS_NOTHROTTLE
)
3832 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3833 throttle_session(s
, 0, 0);
3837 else if (a
& CLI_SESS_THROTTLE
)
3839 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3840 cli_session_actions
[s
].throttle_in
,
3841 cli_session_actions
[s
].throttle_out
);
3843 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3848 if (a
& CLI_SESS_NOFILTER
)
3850 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3851 filter_session(s
, 0, 0);
3855 else if (a
& CLI_SESS_FILTER
)
3857 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3858 cli_session_actions
[s
].filter_in
,
3859 cli_session_actions
[s
].filter_out
);
3861 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3867 cluster_send_session(s
);
3870 // RADIUS interim accounting
3871 if (config
->radius_accounting
&& config
->radius_interim
> 0
3872 && session
[s
].ip
&& !session
[s
].walled_garden
3873 && !sess_local
[s
].radius
// RADIUS already in progress
3874 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3875 && session
[s
].flags
& SESSION_STARTED
)
3877 int rad
= radiusnew(s
);
3880 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3881 STAT(radius_overflow
);
3885 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3886 session
[s
].user
, session
[s
].unique_id
);
3888 radiussend(rad
, RADIUSINTERIM
);
3889 sess_local
[s
].last_interim
= time_now
;
3894 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3895 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3899 // Are we in the middle of a tunnel update, or radius
3902 static int still_busy(void)
3905 static clockt last_talked
= 0;
3906 static clockt start_busy_wait
= 0;
3909 static time_t stopped_bgp
= 0;
3914 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3916 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3917 if (bgp_peers
[i
].state
== Established
)
3918 bgp_stop(&bgp_peers
[i
]);
3920 stopped_bgp
= time_now
;
3922 if (!config
->cluster_iam_master
)
3924 // we don't want to become master
3925 cluster_send_ping(0);
3931 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3936 if (!config
->cluster_iam_master
)
3939 if (main_quit
== QUIT_SHUTDOWN
)
3941 static int dropped
= 0;
3946 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3947 for (i
= 1; i
< MAXTUNNEL
; i
++)
3948 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3949 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3955 if (start_busy_wait
== 0)
3956 start_busy_wait
= TIME
;
3958 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3960 if (!tunnel
[i
].controlc
)
3963 if (last_talked
!= TIME
)
3965 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3971 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3972 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3974 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3978 for (i
= 1; i
< MAXRADIUS
; i
++)
3980 if (radius
[i
].state
== RADIUSNULL
)
3982 if (radius
[i
].state
== RADIUSWAIT
)
3985 if (last_talked
!= TIME
)
3987 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3997 # include <sys/epoll.h>
3999 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
4000 # include "fake_epoll.h"
4003 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
4004 #define BASE_FDS (9 + MAX_UDPFD)
4006 // additional polled fds
4008 # define EXTRA_FDS BGP_NUM_PEERS
4010 # define EXTRA_FDS 0
4013 // main loop - gets packets on tun or udp and processes them
4014 static void mainloop(void)
4018 uint8_t *p
= buf
+ 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4019 // and the forwarded pppoe session
4020 int size_bufp
= sizeof(buf
) - 32;
4021 clockt next_cluster_ping
= 0; // send initial ping immediately
4022 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
4023 int maxevent
= sizeof(events
)/sizeof(*events
);
4025 if ((epollfd
= epoll_create(maxevent
)) < 0)
4027 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
4031 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",
4032 clifd
, cluster_sockfd
, tunfd
, udpfd
[0], controlfd
, daefd
, nlfd
, udplacfd
, pppoediscfd
, pppoesessfd
);
4034 /* setup our fds to poll for input */
4036 static struct event_data d
[BASE_FDS
];
4037 struct epoll_event e
;
4044 d
[i
].type
= FD_TYPE_CLI
;
4045 e
.data
.ptr
= &d
[i
++];
4046 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
4049 d
[i
].type
= FD_TYPE_CLUSTER
;
4050 e
.data
.ptr
= &d
[i
++];
4051 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
4053 d
[i
].type
= FD_TYPE_TUN
;
4054 e
.data
.ptr
= &d
[i
++];
4055 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
4057 d
[i
].type
= FD_TYPE_CONTROL
;
4058 e
.data
.ptr
= &d
[i
++];
4059 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
4061 d
[i
].type
= FD_TYPE_DAE
;
4062 e
.data
.ptr
= &d
[i
++];
4063 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
4065 d
[i
].type
= FD_TYPE_NETLINK
;
4066 e
.data
.ptr
= &d
[i
++];
4067 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
4069 d
[i
].type
= FD_TYPE_PPPOEDISC
;
4070 e
.data
.ptr
= &d
[i
++];
4071 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoediscfd
, &e
);
4073 d
[i
].type
= FD_TYPE_PPPOESESS
;
4074 e
.data
.ptr
= &d
[i
++];
4075 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoesessfd
, &e
);
4077 for (j
= 0; j
< config
->nbudpfd
; j
++)
4079 d
[i
].type
= FD_TYPE_UDP
;
4081 e
.data
.ptr
= &d
[i
++];
4082 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
[j
], &e
);
4087 signal(SIGPIPE
, SIG_IGN
);
4088 bgp_setup(config
->as_number
);
4089 if (config
->bind_address
)
4090 bgp_add_route(config
->bind_address
, 0xffffffff);
4092 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4094 if (config
->neighbour
[i
].name
[0])
4095 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4096 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4097 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4098 0); /* 0 = routing disabled */
4102 while (!main_quit
|| still_busy())
4112 config
->reload_config
++;
4115 if (config
->reload_config
)
4117 config
->reload_config
= 0;
4125 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4126 STAT(select_called
);
4131 if (errno
== EINTR
||
4132 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4135 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4141 struct sockaddr_in addr
;
4142 struct in_addr local
;
4145 int udp_ready
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4146 int pppoesess_ready
= 0;
4147 int pppoesess_pkts
= 0;
4149 int cluster_ready
= 0;
4150 int udp_pkts
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4152 int cluster_pkts
= 0;
4154 uint32_t bgp_events
[BGP_NUM_PEERS
];
4155 memset(bgp_events
, 0, sizeof(bgp_events
));
4158 for (c
= n
, i
= 0; i
< c
; i
++)
4160 struct event_data
*d
= events
[i
].data
.ptr
;
4164 case FD_TYPE_CLI
: // CLI connections
4168 alen
= sizeof(addr
);
4169 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4175 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4181 // these are handled below, with multiple interleaved reads
4182 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4183 case FD_TYPE_TUN
: tun_ready
++; break;
4184 case FD_TYPE_UDP
: udp_ready
[d
->index
]++; break;
4185 case FD_TYPE_PPPOESESS
: pppoesess_ready
++; break;
4187 case FD_TYPE_PPPOEDISC
: // pppoe discovery
4188 s
= read(pppoediscfd
, p
, size_bufp
);
4189 if (s
> 0) process_pppoe_disc(p
, s
);
4193 case FD_TYPE_CONTROL
: // nsctl commands
4194 alen
= sizeof(addr
);
4195 s
= recvfromto(controlfd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4196 if (s
> 0) processcontrol(p
, s
, &addr
, alen
, &local
);
4200 case FD_TYPE_DAE
: // DAE requests
4201 alen
= sizeof(addr
);
4202 s
= recvfromto(daefd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4203 if (s
> 0) processdae(p
, s
, &addr
, alen
, &local
);
4207 case FD_TYPE_RADIUS
: // RADIUS response
4208 alen
= sizeof(addr
);
4209 s
= recvfrom(radfds
[d
->index
], p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4210 if (s
>= 0 && config
->cluster_iam_master
)
4212 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4213 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4214 processrad(p
, s
, d
->index
);
4216 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4217 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4225 bgp_events
[d
->index
] = events
[i
].events
;
4230 case FD_TYPE_NETLINK
:
4232 struct nlmsghdr
*nh
= (struct nlmsghdr
*)p
;
4233 s
= netlink_recv(p
, size_bufp
);
4234 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4236 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4239 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4241 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4245 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4250 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
);
4256 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4261 bgp_process(bgp_events
);
4264 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4266 for (j
= 0; j
< config
->nbudpfd
; j
++)
4268 // L2TP and L2TP REMOTE LNS
4271 alen
= sizeof(addr
);
4272 if ((s
= recvfrom(udpfd
[j
], p
, size_bufp
, 0, (void *) &addr
, &alen
)) > 0)
4274 processudp(p
, s
, &addr
, j
);
4288 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4301 if (pppoesess_ready
)
4303 if ((s
= read(pppoesessfd
, p
, size_bufp
)) > 0)
4305 process_pppoe_sess(p
, s
);
4310 pppoesess_ready
= 0;
4318 alen
= sizeof(addr
);
4319 if ((s
= recvfrom(cluster_sockfd
, p
, size_bufp
, MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4321 processcluster(p
, s
, addr
.sin_addr
.s_addr
);
4332 if (udp_pkts
[0] > 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4333 STAT(multi_read_used
);
4335 if (c
>= config
->multi_read_count
)
4337 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4338 config
->multi_read_count
, udp_pkts
[0], tun_pkts
, cluster_pkts
, pppoesess_pkts
);
4339 STAT(multi_read_exceeded
);
4345 /* no event received, but timers could still have expired */
4346 bgp_process_peers_timers();
4351 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4353 // Log current traffic stats
4354 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4355 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4356 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4357 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4358 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4360 udp_tx
= udp_rx
= 0;
4361 udp_rx_pkt
= eth_rx_pkt
= 0;
4362 eth_tx
= eth_rx
= 0;
4365 if (config
->dump_speed
)
4366 printf("%s\n", config
->bandwidth
);
4368 // Update the internal time counter
4369 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4373 struct param_timer p
= { time_now
};
4374 run_plugins(PLUGIN_TIMER
, &p
);
4378 // Runs on every machine (master and slaves).
4379 if (next_cluster_ping
<= TIME
)
4381 // Check to see which of the cluster is still alive..
4383 cluster_send_ping(basetime
); // Only does anything if we're a slave
4384 cluster_check_master(); // ditto.
4386 cluster_heartbeat(); // Only does anything if we're a master.
4387 cluster_check_slaves(); // ditto.
4389 master_update_counts(); // If we're a slave, send our byte counters to our master.
4391 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4392 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4394 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4397 if (!config
->cluster_iam_master
)
4400 // Run token bucket filtering queue..
4401 // Only run it every 1/10th of a second.
4403 static clockt last_run
= 0;
4404 if (last_run
!= TIME
)
4411 // Handle timeouts, retries etc.
4413 static double last_clean
= 0;
4417 TIME
= now(&this_clean
);
4418 diff
= this_clean
- last_clean
;
4420 // Run during idle time (after we've handled
4421 // all incoming packets) or every 1/10th sec
4422 if (!more
|| diff
> 0.1)
4424 regular_cleanups(diff
);
4425 last_clean
= this_clean
;
4429 if (*config
->accounting_dir
)
4431 static clockt next_acct
= 0;
4432 static clockt next_shut_acct
= 0;
4434 if (next_acct
<= TIME
)
4436 // Dump accounting data
4437 next_acct
= TIME
+ ACCT_TIME
;
4438 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4441 else if (next_shut_acct
<= TIME
)
4443 // Dump accounting data for shutdown sessions
4444 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4451 // Are we the master and shutting down??
4452 if (config
->cluster_iam_master
)
4453 cluster_heartbeat(); // Flush any queued changes..
4455 // Ok. Notify everyone we're shutting down. If we're
4456 // the master, this will force an election.
4457 cluster_send_ping(0);
4460 // Important!!! We MUST not process any packets past this point!
4461 LOG(1, 0, 0, "Shutdown complete\n");
4464 static void stripdomain(char *host
)
4468 if ((p
= strchr(host
, '.')))
4474 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4480 while (fgets(buf
, sizeof(buf
), resolv
))
4482 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4485 if (!isspace(buf
[6]))
4489 while (isspace(*b
)) b
++;
4494 while (*b
&& !isspace(*b
)) b
++;
4496 if (buf
[0] == 'd') // domain is canonical
4502 // first search line
4505 // hold, may be subsequent domain line
4506 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4517 int hl
= strlen(host
);
4518 int dl
= strlen(domain
);
4519 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4520 host
[hl
-dl
- 1] = 0;
4524 *p
= 0; // everything after first dot
4529 // Init data structures
4530 static void initdata(int optdebug
, char *optconfig
)
4534 if (!(config
= shared_malloc(sizeof(configt
))))
4536 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4540 memset(config
, 0, sizeof(configt
));
4541 time(&config
->start_time
);
4542 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4543 config
->debug
= optdebug
;
4544 config
->num_tbfs
= MAXTBFS
;
4545 config
->rl_rate
= 28; // 28kbps
4546 config
->cluster_mcast_ttl
= 1;
4547 config
->cluster_master_min_adv
= 1;
4548 config
->ppp_restart_time
= 3;
4549 config
->ppp_max_configure
= 10;
4550 config
->ppp_max_failure
= 5;
4551 config
->kill_timedout_sessions
= 1;
4552 strcpy(config
->random_device
, RANDOMDEVICE
);
4553 // Set default value echo_timeout and idle_echo_timeout
4554 config
->echo_timeout
= ECHO_TIMEOUT
;
4555 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4557 log_stream
= stderr
;
4560 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4562 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4565 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4568 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4570 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4573 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4575 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4578 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4580 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4583 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4585 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4588 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4590 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4594 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4596 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4600 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4602 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4606 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4608 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4612 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4614 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4617 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4619 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4621 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4624 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4626 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4628 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4631 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4633 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4634 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4635 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4636 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4637 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4639 // Put all the sessions on the free list marked as undefined.
4640 for (i
= 1; i
< MAXSESSION
; i
++)
4642 session
[i
].next
= i
+ 1;
4643 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4645 session
[MAXSESSION
- 1].next
= 0;
4648 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4649 for (i
= 1; i
< MAXTUNNEL
; i
++)
4650 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4652 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4653 bundle
[i
].state
= BUNDLEUNDEF
;
4658 // Grab my hostname unless it's been specified
4659 gethostname(hostname
, sizeof(hostname
));
4660 stripdomain(hostname
);
4663 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4666 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4668 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4673 lac_initremotelnsdata();
4678 static int assign_ip_address(sessionidt s
)
4682 time_t best_time
= time_now
;
4683 char *u
= session
[s
].user
;
4687 CSTAT(assign_ip_address
);
4689 for (i
= 1; i
< ip_pool_size
; i
++)
4691 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4694 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4701 if (ip_address_pool
[i
].last
< best_time
)
4704 if (!(best_time
= ip_address_pool
[i
].last
))
4705 break; // never used, grab this one
4711 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4715 session
[s
].ip
= ip_address_pool
[best
].address
;
4716 session
[s
].ip_pool_index
= best
;
4717 ip_address_pool
[best
].assigned
= 1;
4718 ip_address_pool
[best
].last
= time_now
;
4719 ip_address_pool
[best
].session
= s
;
4720 if (session
[s
].walled_garden
)
4721 /* Don't track addresses of users in walled garden (note: this
4722 means that their address isn't "sticky" even if they get
4724 ip_address_pool
[best
].user
[0] = 0;
4726 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4729 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4730 reuse
? "Reusing" : "Allocating", best
);
4735 static void free_ip_address(sessionidt s
)
4737 int i
= session
[s
].ip_pool_index
;
4740 CSTAT(free_ip_address
);
4743 return; // what the?
4745 if (i
< 0) // Is this actually part of the ip pool?
4749 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4751 ip_address_pool
[i
].assigned
= 0;
4752 ip_address_pool
[i
].session
= 0;
4753 ip_address_pool
[i
].last
= time_now
;
4757 // Fsck the address pool against the session table.
4758 // Normally only called when we become a master.
4760 // This isn't perfect: We aren't keep tracking of which
4761 // users used to have an IP address.
4763 void rebuild_address_pool(void)
4768 // Zero the IP pool allocation, and build
4769 // a map from IP address to pool index.
4770 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4772 ip_address_pool
[i
].assigned
= 0;
4773 ip_address_pool
[i
].session
= 0;
4774 if (!ip_address_pool
[i
].address
)
4777 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4780 for (i
= 0; i
< MAXSESSION
; ++i
)
4783 if (!(session
[i
].opened
&& session
[i
].ip
))
4786 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4788 if (session
[i
].ip_pool_index
< 0)
4790 // Not allocated out of the pool.
4791 if (ipid
< 1) // Not found in the pool either? good.
4794 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4795 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4797 // Fall through and process it as part of the pool.
4801 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4803 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4805 session
[i
].ip_pool_index
= ipid
;
4809 ip_address_pool
[ipid
].assigned
= 1;
4810 ip_address_pool
[ipid
].session
= i
;
4811 ip_address_pool
[ipid
].last
= time_now
;
4812 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4813 session
[i
].ip_pool_index
= ipid
;
4814 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4819 // Fix the address pool to match a changed session.
4820 // (usually when the master sends us an update).
4821 static void fix_address_pool(int sid
)
4825 ipid
= session
[sid
].ip_pool_index
;
4827 if (ipid
> ip_pool_size
)
4828 return; // Ignore it. rebuild_address_pool will fix it up.
4830 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4831 return; // Just ignore it. rebuild_address_pool will take care of it.
4833 ip_address_pool
[ipid
].assigned
= 1;
4834 ip_address_pool
[ipid
].session
= sid
;
4835 ip_address_pool
[ipid
].last
= time_now
;
4836 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4840 // Add a block of addresses to the IP pool to hand out.
4842 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4846 prefixlen
= 32; // Host route only.
4848 addr
&= 0xffffffff << (32 - prefixlen
);
4850 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4853 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4855 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4856 continue; // Skip 0 and broadcast addresses.
4858 ip_address_pool
[ip_pool_size
].address
= i
;
4859 ip_address_pool
[ip_pool_size
].assigned
= 0;
4861 if (ip_pool_size
>= MAXIPPOOL
)
4863 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4869 // Initialize the IP address pool
4870 static void initippool()
4875 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4877 if (!(f
= fopen(IPPOOLFILE
, "r")))
4879 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4883 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4886 buf
[4095] = 0; // Force it to be zero terminated/
4888 if (*buf
== '#' || *buf
== '\n')
4889 continue; // Skip comments / blank lines
4890 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4891 if ((p
= (char *)strchr(buf
, ':')))
4895 src
= inet_addr(buf
);
4896 if (src
== INADDR_NONE
)
4898 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4901 // This entry is for a specific IP only
4902 if (src
!= config
->bind_address
)
4907 if ((p
= (char *)strchr(pool
, '/')))
4911 in_addr_t start
= 0;
4913 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4915 if (!*p
|| !(numbits
= atoi(p
)))
4917 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4920 start
= ntohl(inet_addr(pool
));
4922 // Add a static route for this pool
4923 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4924 fmtaddr(htonl(start
), 0), numbits
);
4926 routeset(0, start
, numbits
, 0, 1);
4928 add_to_ip_pool(start
, numbits
);
4932 // It's a single ip address
4933 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4937 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4940 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4942 struct sockaddr_in snoop_addr
= {0};
4943 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4946 snoop_addr
.sin_family
= AF_INET
;
4947 snoop_addr
.sin_addr
.s_addr
= destination
;
4948 snoop_addr
.sin_port
= ntohs(port
);
4950 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4951 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4952 htons(snoop_addr
.sin_port
));
4954 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4955 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4957 STAT(packets_snooped
);
4960 static int dump_session(FILE **f
, sessiont
*s
)
4962 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4967 char filename
[1024];
4969 time_t now
= time(NULL
);
4971 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4972 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4974 if (!(*f
= fopen(filename
, "w")))
4976 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4980 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4981 if(config
->account_all_origin
)
4983 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4988 "# format: username ip qos uptxoctets downrxoctets origin(L=LAC, R=Remote LNS, P=PPPOE)\n",
4990 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
4996 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5001 "# format: username ip qos uptxoctets downrxoctets\n",
5003 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5009 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
5010 if(config
->account_all_origin
)
5012 fprintf(*f
, "%s %s %d %u %u %s\n",
5013 s
->user
, // username
5014 fmtaddr(htonl(s
->ip
), 0), // ip
5015 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5016 (uint32_t) s
->cin_delta
, // uptxoctets
5017 (uint32_t) s
->cout_delta
, // downrxoctets
5018 (s
->tunnel
== TUNNEL_ID_PPPOE
)?"P":(tunnel
[s
->tunnel
].isremotelns
?"R":"L")); // Origin
5020 else if (!tunnel
[s
->tunnel
].isremotelns
&& (s
->tunnel
!= TUNNEL_ID_PPPOE
))
5022 fprintf(*f
, "%s %s %d %u %u\n",
5023 s
->user
, // username
5024 fmtaddr(htonl(s
->ip
), 0), // ip
5025 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5026 (uint32_t) s
->cin_delta
, // uptxoctets
5027 (uint32_t) s
->cout_delta
); // downrxoctets
5030 s
->cin_delta
= s
->cout_delta
= 0;
5035 static void dump_acct_info(int all
)
5041 CSTAT(dump_acct_info
);
5045 for (i
= 0; i
< shut_acct_n
; i
++)
5046 dump_session(&f
, &shut_acct
[i
]);
5052 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5053 dump_session(&f
, &session
[i
]);
5060 int main(int argc
, char *argv
[])
5064 char *optconfig
= CONFIGFILE
;
5066 time(&basetime
); // start clock
5069 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
5074 if (fork()) exit(0);
5076 freopen("/dev/null", "r", stdin
);
5077 freopen("/dev/null", "w", stdout
);
5078 freopen("/dev/null", "w", stderr
);
5087 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
5090 printf("Args are:\n"
5091 "\t-d\t\tDetach from terminal\n"
5092 "\t-c <file>\tConfig file\n"
5093 "\t-h <hostname>\tForce hostname\n"
5101 // Start the timer routine off
5103 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5106 initdata(optdebug
, optconfig
);
5110 /* set hostname /after/ having read the config file */
5111 if (*config
->hostname
)
5112 strcpy(hostname
, config
->hostname
);
5113 cli_init_complete(hostname
);
5115 init_tbf(config
->num_tbfs
);
5117 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5118 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5119 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5122 rlim
.rlim_cur
= RLIM_INFINITY
;
5123 rlim
.rlim_max
= RLIM_INFINITY
;
5124 // Remove the maximum core size
5125 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5126 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5128 // Make core dumps go to /tmp
5132 if (config
->scheduler_fifo
)
5135 struct sched_param params
= {0};
5136 params
.sched_priority
= 1;
5138 if (get_nprocs() < 2)
5140 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5141 config
->scheduler_fifo
= 0;
5145 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5147 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5151 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5152 config
->scheduler_fifo
= 0;
5159 /* Set up the cluster communications port. */
5160 if (cluster_init() < 0)
5164 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5166 if (*config
->pppoe_if_to_bind
)
5169 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config
->pppoe_if_to_bind
);
5172 if (!config
->nbmultiaddress
)
5174 config
->bind_n_address
[0] = config
->bind_address
;
5175 config
->nbmultiaddress
++;
5177 config
->nbudpfd
= config
->nbmultiaddress
;
5178 for (i
= 0; i
< config
->nbudpfd
; i
++)
5179 initudp(&udpfd
[i
], config
->bind_n_address
[i
]);
5181 config
->indexlacudpfd
= config
->nbudpfd
;
5182 udpfd
[config
->indexlacudpfd
] = udplacfd
;
5189 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
5196 unsigned seed
= time_now
^ getpid();
5197 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5201 signal(SIGHUP
, sighup_handler
);
5202 signal(SIGCHLD
, sigchild_handler
);
5203 signal(SIGTERM
, shutdown_handler
);
5204 signal(SIGINT
, shutdown_handler
);
5205 signal(SIGQUIT
, shutdown_handler
);
5207 // Prevent us from getting paged out
5208 if (config
->lock_pages
)
5210 if (!mlockall(MCL_CURRENT
))
5211 LOG(1, 0, 0, "Locking pages into memory\n");
5213 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5216 //LOG(3, 0, 0, "Debug sizeof struct: sessiont %lu, tunnelt %lu, bundlet %lu, groupsesst %lu\n",
5217 // sizeof(sessiont), sizeof(tunnelt), sizeof(bundlet), sizeof(groupsesst));
5221 /* remove plugins (so cleanup code gets run) */
5224 // Remove the PID file if we wrote it
5225 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5226 unlink(config
->pid_file
);
5228 /* kill CLI children */
5229 signal(SIGTERM
, SIG_IGN
);
5234 static void sighup_handler(int sig
)
5239 static void shutdown_handler(int sig
)
5241 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5244 static void sigchild_handler(int sig
)
5246 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5250 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5253 *challenge_response
= NULL
;
5255 if (!*config
->l2tp_secret
)
5257 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5261 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5263 *challenge_response
= calloc(17, 1);
5266 MD5_Update(&ctx
, &id
, 1);
5267 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5268 MD5_Update(&ctx
, challenge
, challenge_length
);
5269 MD5_Final(*challenge_response
, &ctx
);
5274 static int facility_value(char *name
)
5277 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5279 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5280 return facilitynames
[i
].c_val
;
5285 static void update_config()
5289 static int timeout
= 0;
5290 static int interval
= 0;
5297 if (log_stream
!= stderr
)
5303 if (*config
->log_filename
)
5305 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5307 char *p
= config
->log_filename
+ 7;
5310 openlog("l2tpns", LOG_PID
, facility_value(p
));
5314 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5316 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5318 fseek(log_stream
, 0, SEEK_END
);
5319 setbuf(log_stream
, NULL
);
5323 log_stream
= stderr
;
5324 setbuf(log_stream
, NULL
);
5330 log_stream
= stderr
;
5331 setbuf(log_stream
, NULL
);
5334 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5335 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5337 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5338 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5339 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5341 // reset MRU/MSS globals
5342 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5343 if (MRU
> PPPoE_MRU
)
5346 MSS
= MRU
- TCP_HDRS
;
5349 config
->numradiusservers
= 0;
5350 for (i
= 0; i
< MAXRADSERVER
; i
++)
5351 if (config
->radiusserver
[i
])
5353 config
->numradiusservers
++;
5354 // Set radius port: if not set, take the port from the
5355 // first radius server. For the first radius server,
5356 // take the #defined default value from l2tpns.h
5358 // test twice, In case someone works with
5359 // a secondary radius server without defining
5360 // a primary one, this will work even then.
5361 if (i
> 0 && !config
->radiusport
[i
])
5362 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5363 if (!config
->radiusport
[i
])
5364 config
->radiusport
[i
] = RADPORT
;
5367 if (!config
->numradiusservers
)
5368 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5370 // parse radius_authtypes_s
5371 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5372 p
= config
->radius_authtypes_s
;
5375 char *s
= strpbrk(p
, " \t,");
5381 while (*s
== ' ' || *s
== '\t')
5388 if (!strncasecmp("chap", p
, strlen(p
)))
5390 else if (!strncasecmp("pap", p
, strlen(p
)))
5393 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5395 config
->radius_authtypes
|= type
;
5396 if (!config
->radius_authprefer
)
5397 config
->radius_authprefer
= type
;
5402 if (!config
->radius_authtypes
)
5404 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5405 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5408 // normalise radius_authtypes_s
5409 if (config
->radius_authprefer
== AUTHPAP
)
5411 strcpy(config
->radius_authtypes_s
, "pap");
5412 if (config
->radius_authtypes
& AUTHCHAP
)
5413 strcat(config
->radius_authtypes_s
, ", chap");
5417 strcpy(config
->radius_authtypes_s
, "chap");
5418 if (config
->radius_authtypes
& AUTHPAP
)
5419 strcat(config
->radius_authtypes_s
, ", pap");
5422 if (!config
->radius_dae_port
)
5423 config
->radius_dae_port
= DAEPORT
;
5425 if(!config
->bind_portremotelns
)
5426 config
->bind_portremotelns
= L2TPLACPORT
;
5427 if(!config
->bind_address_remotelns
)
5428 config
->bind_address_remotelns
= INADDR_ANY
;
5430 if (*config
->bind_multi_address
)
5432 char *sip
= config
->bind_multi_address
;
5434 char *e
= config
->bind_multi_address
+ strlen(config
->bind_multi_address
);
5435 config
->nbmultiaddress
= 0;
5437 while (*sip
&& (sip
< e
))
5442 while (n
< e
&& (*n
== ',' || *n
== ' ')) n
++;
5444 while (n
< e
&& (isdigit(*n
) || *n
== '.'))
5452 u
= u
* 10 + *n
- '0';
5460 config
->bind_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5461 config
->iftun_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5462 config
->nbmultiaddress
++;
5463 LOG(1, 0, 0, "Bind address %s\n", fmtaddr(htonl(ip
), 0));
5469 if (config
->nbmultiaddress
>= 1)
5471 config
->bind_address
= config
->bind_n_address
[0];
5472 config
->iftun_address
= config
->bind_address
;
5476 if(!config
->iftun_address
)
5478 config
->iftun_address
= config
->bind_address
;
5479 config
->iftun_n_address
[0] = config
->iftun_address
;
5482 if (!*config
->pppoe_ac_name
)
5483 strncpy(config
->pppoe_ac_name
, DEFAULT_PPPOE_AC_NAME
, sizeof(config
->pppoe_ac_name
) - 1);
5485 // re-initialise the random number source
5486 initrandom(config
->random_device
);
5489 for (i
= 0; i
< MAXPLUGINS
; i
++)
5491 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5494 if (*config
->plugins
[i
])
5497 add_plugin(config
->plugins
[i
]);
5499 else if (*config
->old_plugins
[i
])
5502 remove_plugin(config
->old_plugins
[i
]);
5507 guest_accounts_num
= 0;
5508 char *p2
= config
->guest_user
;
5511 char *s
= strpbrk(p2
, " \t,");
5515 while (*s
== ' ' || *s
== '\t')
5522 strcpy(guest_users
[guest_accounts_num
], p2
);
5523 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5524 guest_accounts_num
++;
5527 // Rebuild the guest_user array
5528 strcpy(config
->guest_user
, "");
5530 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5532 strcat(config
->guest_user
, guest_users
[ui
]);
5533 if (ui
<guest_accounts_num
-1)
5535 strcat(config
->guest_user
, ",");
5540 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5541 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5542 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5543 if (!*config
->cluster_interface
)
5544 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5546 if (!config
->cluster_hb_interval
)
5547 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5549 if (!config
->cluster_hb_timeout
)
5550 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5552 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5554 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5555 // late, ensure we're sufficiently larger than that
5556 int t
= 4 * config
->cluster_hb_interval
+ 11;
5558 if (config
->cluster_hb_timeout
< t
)
5560 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5561 config
->cluster_hb_timeout
= t
;
5564 // Push timing changes to the slaves immediately if we're the master
5565 if (config
->cluster_iam_master
)
5566 cluster_heartbeat();
5568 interval
= config
->cluster_hb_interval
;
5569 timeout
= config
->cluster_hb_timeout
;
5573 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5576 if ((f
= fopen(config
->pid_file
, "w")))
5578 fprintf(f
, "%d\n", getpid());
5580 config
->wrote_pid
= 1;
5584 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5589 static void read_config_file()
5593 if (!config
->config_file
) return;
5594 if (!(f
= fopen(config
->config_file
, "r")))
5596 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5600 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5602 LOG(3, 0, 0, "Done reading config file\n");
5606 int sessionsetup(sessionidt s
, tunnelidt t
)
5608 // A session now exists, set it up
5614 CSTAT(sessionsetup
);
5616 LOG(3, s
, t
, "Doing session setup for session\n");
5618 // Join a bundle if the MRRU option is accepted
5619 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5621 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5622 if (join_bundle(s
) > 0)
5623 cluster_send_bundle(session
[s
].bundle
);
5626 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5627 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5634 assign_ip_address(s
);
5637 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5638 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5641 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5642 fmtaddr(htonl(session
[s
].ip
), 0));
5645 // Make sure this is right
5646 session
[s
].tunnel
= t
;
5648 // zap old sessions with same IP and/or username
5649 // Don't kill gardened sessions - doing so leads to a DoS
5650 // from someone who doesn't need to know the password
5653 user
= session
[s
].user
;
5654 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5656 if (i
== s
) continue;
5657 if (!session
[s
].opened
) break;
5658 // Allow duplicate sessions for multilink ones of the same bundle.
5659 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5661 if (ip
== session
[i
].ip
)
5663 sessionshutdown(i
, "Duplicate IP address", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5667 if (config
->allow_duplicate_users
) continue;
5668 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5672 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5674 if (!strcasecmp(user
, guest_users
[gu
]))
5680 if (found
) continue;
5682 // Drop the new session in case of duplicate sessionss, not the old one.
5683 if (!strcasecmp(user
, session
[i
].user
))
5684 sessionshutdown(i
, "Duplicate session for users", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5688 // no need to set a route for the same IP address of the bundle
5689 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5694 // Add the route for this session.
5695 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5697 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5698 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5701 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5704 // Static IPs need to be routed if not already
5705 // convered by a Framed-Route. Anything else is part
5706 // of the IP address pool and is already routed, it
5707 // just needs to be added to the IP cache.
5708 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5709 if (session
[s
].ip_pool_index
== -1) // static ip
5711 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5714 cache_ipmap(session
[s
].ip
, s
);
5716 if ((g
= grp_groupbysession(s
)))
5718 grp_setgrouproute(g
, 1);
5719 cluster_send_groupe(g
);
5723 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5724 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5726 // Run the plugin's against this new session.
5728 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5729 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5732 // Allocate TBFs if throttled
5733 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5734 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5736 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5738 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5739 fmtaddr(htonl(session
[s
].ip
), 0),
5740 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5742 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5744 return 1; // RADIUS OK and IP allocated, done...
5748 // This session just got dropped on us by the master or something.
5749 // Make sure our tables up up to date...
5751 int load_session(sessionidt s
, sessiont
*new)
5757 if (new->ip_pool_index
>= MAXIPPOOL
||
5758 new->tunnel
>= MAXTUNNEL
)
5760 LOG(0, s
, 0, "Strange session update received!\n");
5761 // FIXME! What to do here?
5766 // Ok. All sanity checks passed. Now we're committed to
5767 // loading the new session.
5770 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5772 // See if routes/ip cache need updating
5773 if (new->ip
!= session
[s
].ip
)
5776 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5777 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5778 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5786 // remove old routes...
5787 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5789 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5790 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5793 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5799 if (session
[s
].ip_pool_index
== -1) // static IP
5801 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5803 else // It's part of the IP pool, remove it manually.
5804 uncache_ipmap(session
[s
].ip
);
5809 // add new routes...
5810 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5812 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5813 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5816 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5822 // If there's a new one, add it.
5823 if (new->ip_pool_index
== -1)
5825 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5828 cache_ipmap(new->ip
, s
);
5833 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5834 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5837 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5839 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5843 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5845 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5846 new->filter_out
= 0;
5849 if (new->filter_in
!= session
[s
].filter_in
)
5851 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5852 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5855 if (new->filter_out
!= session
[s
].filter_out
)
5857 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5858 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5861 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5862 // for walking the sessions to forward byte counts to the master.
5863 config
->cluster_highest_sessionid
= s
;
5865 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5867 // Do fixups into address pool.
5868 if (new->ip_pool_index
!= -1)
5869 fix_address_pool(s
);
5874 static void initplugins()
5878 loaded_plugins
= ll_init();
5879 // Initialize the plugins to nothing
5880 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5881 plugins
[i
] = ll_init();
5884 static void *open_plugin(char *plugin_name
, int load
)
5886 char path
[256] = "";
5888 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5889 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5890 return dlopen(path
, RTLD_NOW
);
5893 // plugin callback to get a config value
5894 static void *getconfig(char *key
, enum config_typet type
)
5898 for (i
= 0; config_values
[i
].key
; i
++)
5900 if (!strcmp(config_values
[i
].key
, key
))
5902 if (config_values
[i
].type
== type
)
5903 return ((void *) config
) + config_values
[i
].offset
;
5905 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5906 key
, type
, config_values
[i
].type
);
5912 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5916 static int add_plugin(char *plugin_name
)
5918 static struct pluginfuncs funcs
= {
5923 sessiontbysessionidt
,
5924 sessionidtbysessiont
,
5931 cluster_send_session
,
5934 void *p
= open_plugin(plugin_name
, 1);
5935 int (*initfunc
)(struct pluginfuncs
*);
5940 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5944 if (ll_contains(loaded_plugins
, p
))
5947 return 0; // already loaded
5951 int *v
= dlsym(p
, "plugin_api_version");
5952 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5954 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5960 if ((initfunc
= dlsym(p
, "plugin_init")))
5962 if (!initfunc(&funcs
))
5964 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5970 ll_push(loaded_plugins
, p
);
5972 for (i
= 0; i
< max_plugin_functions
; i
++)
5975 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5977 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5978 ll_push(plugins
[i
], x
);
5982 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5986 static void run_plugin_done(void *plugin
)
5988 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5994 static int remove_plugin(char *plugin_name
)
5996 void *p
= open_plugin(plugin_name
, 0);
6002 if (ll_contains(loaded_plugins
, p
))
6005 for (i
= 0; i
< max_plugin_functions
; i
++)
6008 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6009 ll_delete(plugins
[i
], x
);
6012 ll_delete(loaded_plugins
, p
);
6018 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
6022 int run_plugins(int plugin_type
, void *data
)
6024 int (*func
)(void *data
);
6026 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
6027 return PLUGIN_RET_ERROR
;
6029 ll_reset(plugins
[plugin_type
]);
6030 while ((func
= ll_next(plugins
[plugin_type
])))
6034 if (r
!= PLUGIN_RET_OK
)
6035 return r
; // stop here
6038 return PLUGIN_RET_OK
;
6041 static void plugins_done()
6045 ll_reset(loaded_plugins
);
6046 while ((p
= ll_next(loaded_plugins
)))
6050 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
6052 struct nsctl request
;
6053 struct nsctl response
;
6054 int type
= unpack_control(&request
, buf
, len
);
6058 if (log_stream
&& config
->debug
>= 4)
6062 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6063 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
6067 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6068 dump_control(&request
, log_stream
);
6074 case NSCTL_REQ_LOAD
:
6075 if (request
.argc
!= 1)
6077 response
.type
= NSCTL_RES_ERR
;
6079 response
.argv
[0] = "name of plugin required";
6081 else if ((r
= add_plugin(request
.argv
[0])) < 1)
6083 response
.type
= NSCTL_RES_ERR
;
6085 response
.argv
[0] = !r
6086 ? "plugin already loaded"
6087 : "error loading plugin";
6091 response
.type
= NSCTL_RES_OK
;
6097 case NSCTL_REQ_UNLOAD
:
6098 if (request
.argc
!= 1)
6100 response
.type
= NSCTL_RES_ERR
;
6102 response
.argv
[0] = "name of plugin required";
6104 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
6106 response
.type
= NSCTL_RES_ERR
;
6108 response
.argv
[0] = !r
6109 ? "plugin not loaded"
6110 : "plugin not found";
6114 response
.type
= NSCTL_RES_OK
;
6120 case NSCTL_REQ_HELP
:
6121 response
.type
= NSCTL_RES_OK
;
6124 ll_reset(loaded_plugins
);
6125 while ((p
= ll_next(loaded_plugins
)))
6127 char **help
= dlsym(p
, "plugin_control_help");
6128 while (response
.argc
< 0xff && help
&& *help
)
6129 response
.argv
[response
.argc
++] = *help
++;
6134 case NSCTL_REQ_CONTROL
:
6136 struct param_control param
= {
6137 config
->cluster_iam_master
,
6144 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
6146 if (r
== PLUGIN_RET_ERROR
)
6148 response
.type
= NSCTL_RES_ERR
;
6150 response
.argv
[0] = param
.additional
6152 : "error returned by plugin";
6154 else if (r
== PLUGIN_RET_NOTMASTER
)
6156 static char msg
[] = "must be run on master: 000.000.000.000";
6158 response
.type
= NSCTL_RES_ERR
;
6160 if (config
->cluster_master_address
)
6162 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
6163 response
.argv
[0] = msg
;
6167 response
.argv
[0] = "must be run on master: none elected";
6170 else if (!(param
.response
& NSCTL_RESPONSE
))
6172 response
.type
= NSCTL_RES_ERR
;
6174 response
.argv
[0] = param
.response
6175 ? "unrecognised response value from plugin"
6176 : "unhandled action";
6180 response
.type
= param
.response
;
6182 if (param
.additional
)
6185 response
.argv
[0] = param
.additional
;
6193 response
.type
= NSCTL_RES_ERR
;
6195 response
.argv
[0] = "error unpacking control packet";
6198 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6201 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6205 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6208 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6209 if (log_stream
&& config
->debug
>= 4)
6211 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6212 dump_control(&response
, log_stream
);
6216 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6217 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6222 static tunnelidt
new_tunnel()
6225 for (i
= 1; i
< MAXTUNNEL
; i
++)
6227 if ((tunnel
[i
].state
== TUNNELFREE
) && (i
!= TUNNEL_ID_PPPOE
))
6229 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6230 if (i
> config
->cluster_highest_tunnelid
)
6231 config
->cluster_highest_tunnelid
= i
;
6235 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6240 // We're becoming the master. Do any required setup..
6242 // This is principally telling all the plugins that we're
6243 // now a master, and telling them about all the sessions
6244 // that are active too..
6246 void become_master(void)
6249 static struct event_data d
[RADIUS_FDS
];
6250 struct epoll_event e
;
6252 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6254 // running a bunch of iptables commands is slow and can cause
6255 // the master to drop tunnels on takeover--kludge around the
6256 // problem by forking for the moment (note: race)
6257 if (!fork_and_close())
6259 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6261 if (!session
[s
].opened
) // Not an in-use session.
6264 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6271 for (i
= 0; i
< RADIUS_FDS
; i
++)
6273 d
[i
].type
= FD_TYPE_RADIUS
;
6277 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6281 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6287 if (CLI_HELP_REQUESTED
)
6288 return CLI_HELP_NO_ARGS
;
6291 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6293 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6296 if (!session
[s
].opened
)
6299 idle
= time_now
- session
[s
].last_data
;
6300 idle
/= 5 ; // In multiples of 5 seconds.
6310 for (i
= 0; i
< 63; ++i
)
6312 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6314 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6315 cli_print(cli
, "%d total sessions open.", count
);
6319 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6325 if (CLI_HELP_REQUESTED
)
6326 return CLI_HELP_NO_ARGS
;
6329 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6331 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6334 if (!session
[s
].opened
)
6337 d
= time_now
- session
[s
].opened
;
6340 while (d
> 1 && open
< 32)
6350 for (i
= 0; i
< 30; ++i
)
6352 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6355 cli_print(cli
, "%d total sessions open.", count
);
6361 * This unencodes the AVP using the L2TP secret and the previously
6362 * stored random vector. It overwrites the hidden data with the
6363 * unhidden AVP subformat.
6365 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6371 uint16_t m
= htons(type
);
6373 // Compute initial pad
6375 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6376 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6377 MD5_Update(&ctx
, vector
, vec_len
);
6378 MD5_Final(digest
, &ctx
);
6380 // pointer to last decoded 16 octets
6385 // calculate a new pad based on the last decoded block
6386 if (d
>= sizeof(digest
))
6389 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6390 MD5_Update(&ctx
, last
, sizeof(digest
));
6391 MD5_Final(digest
, &ctx
);
6397 *value
++ ^= digest
[d
++];
6402 int find_filter(char const *name
, size_t len
)
6407 for (i
= 0; i
< MAXFILTER
; i
++)
6409 if (!*ip_filters
[i
].name
)
6417 if (strlen(ip_filters
[i
].name
) != len
)
6420 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6427 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6431 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6432 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6433 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6434 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6435 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6441 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6445 case FILTER_FLAG_OP_ANY
:
6446 return (flags
& sflags
) || (~flags
& cflags
);
6448 case FILTER_FLAG_OP_ALL
:
6449 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6451 case FILTER_FLAG_OP_EST
:
6452 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6458 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6460 uint16_t frag_offset
;
6464 uint16_t src_port
= 0;
6465 uint16_t dst_port
= 0;
6467 ip_filter_rulet
*rule
;
6469 if (len
< 20) // up to end of destination address
6472 if ((*buf
>> 4) != 4) // IPv4
6475 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6477 src_ip
= *(in_addr_t
*) (buf
+ 12);
6478 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6480 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6482 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6483 if (len
< l
+ 4) // ports
6486 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6487 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6488 if (proto
== IPPROTO_TCP
)
6490 if (len
< l
+ 14) // flags
6493 flags
= buf
[l
+ 13] & 0x3f;
6497 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6499 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6502 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6503 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6506 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6507 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6512 // layer 4 deny rules are skipped
6513 if (rule
->action
== FILTER_ACTION_DENY
&&
6514 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6522 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6524 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6527 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6530 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6531 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6538 return rule
->action
== FILTER_ACTION_PERMIT
;
6545 tunnelidt
lac_new_tunnel()
6547 return new_tunnel();
6550 void lac_tunnelclear(tunnelidt t
)
6555 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6557 uint16_t version
= 0x0100; // protocol version
6559 tunnel
[t
].state
= TUNNELOPENING
;
6561 // Sent SCCRQ - Start Control Connection Request
6562 controlt
*c
= controlnew(1); // sending SCCRQ
6563 controls(c
, 7, hostname
, 1); // host name
6564 controls(c
, 8, Vendor_name
, 1); // Vendor name
6565 control16(c
, 2, version
, 1); // protocol version
6566 control32(c
, 3, 3, 1); // framing Capabilities
6567 control16(c
, 9, t
, 1); // assigned tunnel
6568 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6569 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6570 controladd(c
, 0, t
); // send
6573 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6575 // Sent ICRQ Incoming-call-request
6576 controlt
*c
= controlnew(10); // ICRQ
6578 control16(c
, 14, s
, 1); // assigned sesion
6579 call_serial_number
++;
6580 control32(c
, 15, call_serial_number
, 1); // call serial number
6581 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6582 controladd(c
, 0, t
); // send
6585 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6587 tunnelshutdown(t
, reason
, result
, error
, msg
);