3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
11 #include <linux/if_tun.h>
16 #include <net/route.h>
19 #include <netinet/in.h>
20 #include <netinet/ip6.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
29 #include <sys/resource.h>
37 #include <sys/sysinfo.h>
39 #include <linux/netlink.h>
40 #include <linux/rtnetlink.h>
48 #include "constants.h"
61 char * Vendor_name
= "Linux L2TPNS";
62 uint32_t call_serial_number
= 0;
65 configt
*config
= NULL
; // all configuration
66 int nlfd
= -1; // netlink socket
67 int tunfd
= -1; // tun interface file handle. (network device)
68 int udpfd
[MAX_UDPFD
+ 1] = INIT_TABUDPFD
; // array UDP file handle + 1 for lac udp
69 int udplacfd
= -1; // UDP LAC file handle
70 int controlfd
= -1; // Control signal handle
71 int clifd
= -1; // Socket listening for CLI connections.
72 int daefd
= -1; // Socket listening for DAE connections.
73 int snoopfd
= -1; // UDP file handle for sending out intercept data
74 int *radfds
= NULL
; // RADIUS requests file handles
75 int rand_fd
= -1; // Random data source
76 int cluster_sockfd
= -1; // Intra-cluster communications socket.
77 int epollfd
= -1; // event polling
78 time_t basetime
= 0; // base clock
79 char hostname
[MAXHOSTNAME
] = ""; // us.
80 int tunidx
; // ifr_ifindex of tun device
81 int nlseqnum
= 0; // netlink sequence number
82 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
83 static int syslog_log
= 0; // are we logging to syslog
84 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
85 uint32_t last_id
= 0; // Unique ID for radius accounting
87 char guest_users
[10][32]; // Array of guest users
88 int guest_accounts_num
= 0; // Number of guest users
90 // calculated from config->l2tp_mtu
91 uint16_t MRU
= 0; // PPP MRU
92 uint16_t MSS
= 0; // TCP MSS
94 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
95 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
101 }ip_hash
[256]; // Mapping from IP address to session structures.
105 struct ipv6radix
*branch
;
106 } ipv6_hash
[16]; // Mapping from IPv6 address to session structures.
109 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
110 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
113 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
114 time_t time_now
= 0; // Current time in seconds since epoch.
115 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
116 static char time_now_string
[64] = {0}; // Current time as a string.
117 static int time_changed
= 0; // time_now changed
118 char main_quit
= 0; // True if we're in the process of exiting.
119 static char main_reload
= 0; // Re-load pending
120 linked_list
*loaded_plugins
;
121 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
123 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
124 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
126 config_descriptt config_values
[] = {
127 CONFIG("debug", debug
, INT
),
128 CONFIG("log_file", log_filename
, STRING
),
129 CONFIG("pid_file", pid_file
, STRING
),
130 CONFIG("random_device", random_device
, STRING
),
131 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
132 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
133 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
134 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
135 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
136 CONFIG("primary_dns", default_dns1
, IPv4
),
137 CONFIG("secondary_dns", default_dns2
, IPv4
),
138 CONFIG("primary_radius", radiusserver
[0], IPv4
),
139 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
140 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
141 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
142 CONFIG("radius_accounting", radius_accounting
, BOOL
),
143 CONFIG("radius_interim", radius_interim
, INT
),
144 CONFIG("radius_secret", radiussecret
, STRING
),
145 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
146 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
147 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
148 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
149 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
150 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
151 CONFIG("guest_account", guest_user
, STRING
),
152 CONFIG("bind_address", bind_address
, IPv4
),
153 CONFIG("peer_address", peer_address
, IPv4
),
154 CONFIG("send_garp", send_garp
, BOOL
),
155 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
156 CONFIG("throttle_buckets", num_tbfs
, INT
),
157 CONFIG("accounting_dir", accounting_dir
, STRING
),
158 CONFIG("account_all_origin", account_all_origin
, BOOL
),
159 CONFIG("dump_speed", dump_speed
, BOOL
),
160 CONFIG("multi_read_count", multi_read_count
, INT
),
161 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
162 CONFIG("lock_pages", lock_pages
, BOOL
),
163 CONFIG("icmp_rate", icmp_rate
, INT
),
164 CONFIG("packet_limit", max_packets
, INT
),
165 CONFIG("cluster_address", cluster_address
, IPv4
),
166 CONFIG("cluster_interface", cluster_interface
, STRING
),
167 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
168 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
169 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
170 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
171 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
172 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
173 CONFIG("hostname", hostname
, STRING
),
175 CONFIG("nexthop_address", nexthop_address
, IPv4
),
176 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
178 CONFIG("echo_timeout", echo_timeout
, INT
),
179 CONFIG("idle_echo_timeout", idle_echo_timeout
, INT
),
180 CONFIG("iftun_address", iftun_address
, IPv4
),
181 CONFIG("tundevicename", tundevicename
, STRING
),
182 CONFIG("disable_lac_func", disable_lac_func
, BOOL
),
183 CONFIG("auth_tunnel_change_addr_src", auth_tunnel_change_addr_src
, BOOL
),
184 CONFIG("bind_address_remotelns", bind_address_remotelns
, IPv4
),
185 CONFIG("bind_portremotelns", bind_portremotelns
, SHORT
),
186 CONFIG("pppoe_if_to_bind", pppoe_if_to_bind
, STRING
),
187 CONFIG("pppoe_service_name", pppoe_service_name
, STRING
),
188 CONFIG("pppoe_ac_name", pppoe_ac_name
, STRING
),
189 CONFIG("disable_sending_hello", disable_sending_hello
, BOOL
),
190 CONFIG("disable_no_spoof", disable_no_spoof
, BOOL
),
191 CONFIG("bind_multi_address", bind_multi_address
, STRING
),
192 CONFIG("grp_txrate_average_time", grp_txrate_average_time
, INT
),
193 CONFIG("pppoe_only_equal_svc_name", pppoe_only_equal_svc_name
, BOOL
),
194 CONFIG("multi_hostname", multi_hostname
, STRING
),
195 CONFIG("no_throttle_local_IP", no_throttle_local_IP
, BOOL
),
196 CONFIG("dhcp6_preferred_lifetime", dhcp6_preferred_lifetime
, INT
),
197 CONFIG("dhcp6_valid_lifetime", dhcp6_valid_lifetime
, INT
),
198 CONFIG("dhcp6_server_duid", dhcp6_server_duid
, INT
),
199 CONFIG("primary_ipv6_dns", default_ipv6_dns1
, IPv6
),
200 CONFIG("secondary_ipv6_dns", default_ipv6_dns2
, IPv6
),
201 CONFIG("default_ipv6_domain_list", default_ipv6_domain_list
, STRING
),
205 static char *plugin_functions
[] = {
210 "plugin_new_session",
211 "plugin_kill_session",
213 "plugin_radius_response",
214 "plugin_radius_reset",
215 "plugin_radius_account",
216 "plugin_become_master",
217 "plugin_new_session_master",
220 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
222 // Counters for shutdown sessions
223 static sessiont shut_acct
[8192];
224 static sessionidt shut_acct_n
= 0;
226 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
227 bundlet
*bundle
= NULL
; // Array of bundle structures.
228 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
229 sessiont
*session
= NULL
; // Array of session structures.
230 groupsesst
*grpsession
= NULL
; // Array of groupsesst structures.
231 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
232 radiust
*radius
= NULL
; // Array of radius structures.
233 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
234 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
235 static controlt
*controlfree
= 0;
236 struct Tstats
*_statistics
= NULL
;
238 struct Tringbuffer
*ringbuffer
= NULL
;
241 static void uncache_ipmap(in_addr_t ip
);
242 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
243 static void free_ip_address(sessionidt s
);
244 static void dump_acct_info(int all
);
245 static void sighup_handler(int sig
);
246 static void shutdown_handler(int sig
);
247 static void sigchild_handler(int sig
);
248 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
249 static void update_config(void);
250 static void read_config_file(void);
251 static void initplugins(void);
252 static int add_plugin(char *plugin_name
);
253 static int remove_plugin(char *plugin_name
);
254 static void plugins_done(void);
255 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
256 static tunnelidt
new_tunnel(void);
257 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
258 static void bundleclear(bundleidt b
);
260 // return internal time (10ths since process startup), set f if given
261 // as a side-effect sets time_now, and time_changed
262 static clockt
now(double *f
)
266 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
267 if (t
.tv_sec
!= time_now
)
274 // Time in milliseconds
275 // TODO FOR MLPPP DEV
276 //time_now_ms = (t.tv_sec * 1000) + (t.tv_usec/1000);
278 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
281 // work out a retry time based on try number
282 // This is a straight bounded exponential backoff.
283 // Maximum re-try time is 32 seconds. (2^5).
284 clockt
backoff(uint8_t try)
286 if (try > 5) try = 5; // max backoff
287 return now(NULL
) + 10 * (1 << try);
292 // Log a debug message. Typically called via the LOG macro
294 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
296 static char message
[65536] = {0};
302 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
303 ringbuffer
->tail
= 0;
304 if (ringbuffer
->tail
== ringbuffer
->head
)
305 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
306 ringbuffer
->head
= 0;
308 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
309 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
310 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
311 va_start(ap
, format
);
312 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, MAX_LOG_LENGTH
, format
, ap
);
317 if (config
->debug
< level
) return;
319 va_start(ap
, format
);
320 vsnprintf(message
, sizeof(message
), format
, ap
);
323 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
325 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
330 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
333 const uint8_t *d
= data
;
335 if (config
->debug
< level
) return;
337 // No support for _log_hex to syslog
340 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
341 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
343 for (i
= 0; i
< maxsize
; )
345 fprintf(log_stream
, "%4X: ", i
);
346 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
348 fprintf(log_stream
, "%02X ", d
[j
]);
350 fputs(": ", log_stream
);
353 for (; j
< i
+ 16; j
++)
355 fputs(" ", log_stream
);
357 fputs(": ", log_stream
);
360 fputs(" ", log_stream
);
361 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
363 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
364 fputc(d
[j
], log_stream
);
366 fputc('.', log_stream
);
369 fputs(" ", log_stream
);
373 fputs("\n", log_stream
);
377 setbuf(log_stream
, NULL
);
381 // update a counter, accumulating 2^32 wraps
382 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
384 uint32_t new = *counter
+ delta
;
391 // initialise the random generator
392 static void initrandom(char *source
)
394 static char path
[sizeof(config
->random_device
)] = "*undefined*";
396 // reinitialise only if we are forced to do so or if the config has changed
397 if (source
&& !strncmp(path
, source
, sizeof(path
)))
400 // close previous source, if any
409 snprintf(path
, sizeof(path
), "%s", source
);
413 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
415 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
416 path
, strerror(errno
));
421 // fill buffer with random data
422 void random_data(uint8_t *buf
, int len
)
429 n
= read(rand_fd
, buf
, len
);
430 if (n
>= len
) return;
435 LOG(0, 0, 0, "Error reading from random source: %s\n",
438 // fall back to rand()
446 // append missing data
448 // not using the low order bits from the prng stream
449 buf
[n
++] = (rand() >> 4) & 0xff;
454 // This adds it to the routing table, advertises it
455 // via BGP if enabled, and stuffs it into the
456 // 'sessionbyip' cache.
458 // 'ip' must be in _host_ order.
460 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
470 if (!prefixlen
) prefixlen
= 32;
472 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
474 memset(&req
, 0, sizeof(req
));
478 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
479 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
483 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
484 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
487 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
489 req
.rt
.rtm_family
= AF_INET
;
490 req
.rt
.rtm_dst_len
= prefixlen
;
491 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
492 req
.rt
.rtm_protocol
= 42;
493 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
494 req
.rt
.rtm_type
= RTN_UNICAST
;
496 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
498 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
502 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
505 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
506 fmtaddr(htonl(ip
), 0), prefixlen
,
507 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
509 if (netlink_send(&req
.nh
) < 0)
510 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
514 bgp_add_route(htonl(ip
), prefixlen
);
516 bgp_del_route(htonl(ip
), prefixlen
);
519 // Add/Remove the IPs to the 'sessionbyip' cache.
520 // Note that we add the zero address in the case of
521 // a network route. Roll on CIDR.
523 // Note that 's == 0' implies this is the address pool.
524 // We still cache it here, because it will pre-fill
525 // the malloc'ed tree.
529 if (!add
) // Are we deleting a route?
530 s
= 0; // Caching the session as '0' is the same as uncaching.
532 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
537 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
545 char ipv6addr
[INET6_ADDRSTRLEN
];
547 if (!config
->ipv6_prefix
.s6_addr
[0])
549 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
553 memset(&req
, 0, sizeof(req
));
557 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
558 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
562 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
563 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
566 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
568 req
.rt
.rtm_family
= AF_INET6
;
569 req
.rt
.rtm_dst_len
= prefixlen
;
570 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
571 req
.rt
.rtm_protocol
= 42;
572 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
573 req
.rt
.rtm_type
= RTN_UNICAST
;
575 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
576 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
578 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
580 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
582 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
585 if (netlink_send(&req
.nh
) < 0)
586 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
590 bgp_add_route6(ip
, prefixlen
);
592 bgp_del_route6(ip
, prefixlen
);
597 if (!add
) // Are we deleting a route?
598 s
= 0; // Caching the session as '0' is the same as uncaching.
600 cache_ipv6map(ip
, prefixlen
, s
);
607 // Set up netlink socket
608 static void initnetlink(void)
610 struct sockaddr_nl nladdr
;
612 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
615 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
619 memset(&nladdr
, 0, sizeof(nladdr
));
620 nladdr
.nl_family
= AF_NETLINK
;
621 nladdr
.nl_pid
= getpid();
623 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
625 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
630 ssize_t
netlink_send(struct nlmsghdr
*nh
)
632 struct sockaddr_nl nladdr
;
636 nh
->nlmsg_pid
= getpid();
637 nh
->nlmsg_seq
= ++nlseqnum
;
639 // set kernel address
640 memset(&nladdr
, 0, sizeof(nladdr
));
641 nladdr
.nl_family
= AF_NETLINK
;
643 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
644 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
646 return sendmsg(nlfd
, &msg
, 0);
649 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
651 struct sockaddr_nl nladdr
;
655 // set kernel address
656 memset(&nladdr
, 0, sizeof(nladdr
));
657 nladdr
.nl_family
= AF_NETLINK
;
659 iov
= (struct iovec
){ buf
, len
};
660 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
662 return recvmsg(nlfd
, &msg
, 0);
665 /* adapted from iproute2 */
666 void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
668 int len
= RTA_LENGTH(alen
);
671 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
672 rta
->rta_type
= type
;
674 memcpy(RTA_DATA(rta
), data
, alen
);
675 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
678 // messages corresponding to different phases seq number
679 static char *tun_nl_phase_msg
[] = {
681 "getting tun interface index",
682 "setting tun interface parameters",
683 "setting tun IPv4 address",
684 "setting tun LL IPv6 address",
685 "setting tun global IPv6 address",
689 // Set up TUN interface
690 static void inittun(void)
694 memset(&ifr
, 0, sizeof(ifr
));
695 ifr
.ifr_flags
= IFF_TUN
;
697 tunfd
= open(TUNDEVICE
, O_RDWR
);
700 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
704 int flags
= fcntl(tunfd
, F_GETFL
, 0);
705 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
708 if (*config
->tundevicename
)
709 strncpy(ifr
.ifr_name
, config
->tundevicename
, IFNAMSIZ
);
711 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
713 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
716 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevicename
) - 1);
717 strncpy(config
->tundevicename
, ifr
.ifr_name
, sizeof(config
->tundevicename
));
719 tunidx
= if_nametoindex(config
->tundevicename
);
722 LOG(0, 0, 0, "Can't get tun interface index\n");
731 struct ifinfomsg ifinfo
;
732 struct ifaddrmsg ifaddr
;
734 char rtdata
[32]; // 32 should be enough
736 uint32_t txqlen
, mtu
;
739 memset(&req
, 0, sizeof(req
));
741 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
742 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
743 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
745 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
746 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
747 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
748 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
750 /* Bump up the qlen to deal with bursts from the network */
752 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
753 /* set MTU to modem MRU */
755 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
757 if (netlink_send(&req
.nh
) < 0)
760 memset(&req
, 0, sizeof(req
));
762 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
763 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
764 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
766 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
767 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
768 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
769 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
771 if (config
->nbmultiaddress
> 1)
774 for (i
= 0; i
< config
->nbmultiaddress
; i
++)
776 ip
= config
->iftun_n_address
[i
];
777 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
778 if (netlink_send(&req
.nh
) < 0)
784 if (config
->iftun_address
)
785 ip
= config
->iftun_address
;
787 ip
= 0x01010101; // 1.1.1.1
788 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
790 if (netlink_send(&req
.nh
) < 0)
796 // Only setup IPv6 on the tun device if we have a configured prefix
797 if (config
->ipv6_prefix
.s6_addr
[0]) {
800 memset(&req
, 0, sizeof(req
));
802 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
803 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
804 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
806 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
807 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
808 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
809 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
811 // Link local address is FE80::1
812 memset(&ip6
, 0, sizeof(ip6
));
813 ip6
.s6_addr
[0] = 0xFE;
814 ip6
.s6_addr
[1] = 0x80;
816 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
818 if (netlink_send(&req
.nh
) < 0)
821 memset(&req
, 0, sizeof(req
));
823 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
824 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
825 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
827 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
828 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
829 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
830 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
832 // Global address is prefix::1
833 ip6
= config
->ipv6_prefix
;
835 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
837 if (netlink_send(&req
.nh
) < 0)
841 memset(&req
, 0, sizeof(req
));
843 req
.nh
.nlmsg_type
= NLMSG_DONE
;
844 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
846 if (netlink_send(&req
.nh
) < 0)
849 // if we get an error for seqnum < min_initok_nlseqnum,
850 // we must exit as initialization went wrong
851 if (config
->ipv6_prefix
.s6_addr
[0])
852 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
854 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
860 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
864 // set up LAC UDP ports
865 static void initlacudp(void)
868 struct sockaddr_in addr
;
870 // Tunnel to Remote LNS
871 memset(&addr
, 0, sizeof(addr
));
872 addr
.sin_family
= AF_INET
;
873 addr
.sin_port
= htons(config
->bind_portremotelns
);
874 addr
.sin_addr
.s_addr
= config
->bind_address_remotelns
;
875 udplacfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
876 setsockopt(udplacfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
878 int flags
= fcntl(udplacfd
, F_GETFL
, 0);
879 fcntl(udplacfd
, F_SETFL
, flags
| O_NONBLOCK
);
881 if (bind(udplacfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
883 LOG(0, 0, 0, "Error in UDP REMOTE LNS bind: %s\n", strerror(errno
));
888 // set up control ports
889 static void initcontrol(void)
892 struct sockaddr_in addr
;
895 memset(&addr
, 0, sizeof(addr
));
896 addr
.sin_family
= AF_INET
;
897 addr
.sin_port
= htons(NSCTL_PORT
);
898 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
899 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
900 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
901 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
903 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
908 // set up Dynamic Authorization Extensions to RADIUS port
909 static void initdae(void)
912 struct sockaddr_in addr
;
914 // Dynamic Authorization Extensions to RADIUS
915 memset(&addr
, 0, sizeof(addr
));
916 addr
.sin_family
= AF_INET
;
917 addr
.sin_port
= htons(config
->radius_dae_port
);
918 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
919 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
920 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
921 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
923 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
929 static void initudp(int * pudpfd
, in_addr_t ip_bind
)
932 struct sockaddr_in addr
;
935 memset(&addr
, 0, sizeof(addr
));
936 addr
.sin_family
= AF_INET
;
937 addr
.sin_port
= htons(L2TPPORT
);
938 addr
.sin_addr
.s_addr
= ip_bind
;
939 (*pudpfd
) = socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
940 setsockopt((*pudpfd
), SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
942 int flags
= fcntl((*pudpfd
), F_GETFL
, 0);
943 fcntl((*pudpfd
), F_SETFL
, flags
| O_NONBLOCK
);
945 if (bind((*pudpfd
), (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
947 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
953 // Find session by IP, < 1 for not found
955 // Confusingly enough, this 'ip' must be
956 // in _network_ order. This being the common
957 // case when looking it up from IP packet headers.
959 // We actually use this cache for two things.
960 // #1. For used IP addresses, this maps to the
961 // session ID that it's used by.
962 // #2. For un-used IP addresses, this maps to the
963 // index into the pool table that contains that
967 static sessionidt
lookup_ipmap(in_addr_t ip
)
969 uint8_t *a
= (uint8_t *) &ip
;
970 union iphash
*h
= ip_hash
;
972 if (!(h
= h
[*a
++].idx
)) return 0;
973 if (!(h
= h
[*a
++].idx
)) return 0;
974 if (!(h
= h
[*a
++].idx
)) return 0;
979 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
981 struct ipv6radix
*curnode
;
984 char ipv6addr
[INET6_ADDRSTRLEN
];
986 curnode
= &ipv6_hash
[((ip
.s6_addr
[0]) & 0xF0)>>4];
990 while (s
== 0 && i
< 32 && curnode
->branch
!= NULL
)
993 curnode
= &curnode
->branch
[ip
.s6_addr
[i
>>1] & 0x0F];
995 curnode
= &curnode
->branch
[(ip
.s6_addr
[i
>>1] & 0xF0)>>4];
1001 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
1002 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1009 sessionidt
sessionbyip(in_addr_t ip
)
1011 sessionidt s
= lookup_ipmap(ip
);
1014 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1020 sessionidt
sessionbyipv6(struct in6_addr ip
)
1023 CSTAT(sessionbyipv6
);
1025 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
1026 (ip
.s6_addr
[0] == 0xFE &&
1027 ip
.s6_addr
[1] == 0x80 &&
1028 ip
.s6_addr16
[1] == 0 &&
1029 ip
.s6_addr16
[2] == 0 &&
1030 ip
.s6_addr16
[3] == 0))
1032 in_addr_t
*pipv4
= (in_addr_t
*) &ip
.s6_addr
[8];
1033 s
= lookup_ipmap(*pipv4
);
1035 s
= lookup_ipv6map(ip
);
1038 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1044 sessionidt
sessionbyipv6new(struct in6_addr ip
)
1047 CSTAT(sessionbyipv6new
);
1049 s
= lookup_ipv6map(ip
);
1051 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1058 // Take an IP address in HOST byte order and
1059 // add it to the sessionid by IP cache.
1061 // (It's actually cached in network order)
1063 void cache_ipmap(in_addr_t ip
, sessionidt s
)
1065 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
1066 uint8_t *a
= (uint8_t *) &nip
;
1067 union iphash
*h
= ip_hash
;
1070 for (i
= 0; i
< 3; i
++)
1072 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1081 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1083 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1084 // else a map to an ip pool index.
1087 static void uncache_ipmap(in_addr_t ip
)
1089 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1092 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1096 struct ipv6radix
*curnode
;
1097 char ipv6addr
[INET6_ADDRSTRLEN
];
1099 curnode
= &ipv6_hash
[((ip
.s6_addr
[0]) & 0xF0)>>4];
1101 niblles
= prefixlen
>> 2;
1106 if (curnode
->branch
== NULL
)
1108 if (!(curnode
->branch
= calloc(16, sizeof (struct ipv6radix
))))
1113 curnode
= &curnode
->branch
[ip
.s6_addr
[i
>>1] & 0x0F];
1115 curnode
= &curnode
->branch
[(ip
.s6_addr
[i
>>1] & 0xF0)>>4];
1123 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1124 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1128 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1129 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1135 // CLI list to dump current ipcache.
1137 int cmd_show_ipcache(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
1139 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1143 if (CLI_HELP_REQUESTED
)
1144 return CLI_HELP_NO_ARGS
;
1146 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1148 for (i
= 0; i
< 256; ++i
)
1154 for (j
= 0; j
< 256; ++j
)
1160 for (k
= 0; k
< 256; ++k
)
1166 for (l
= 0; l
< 256; ++l
)
1171 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1177 cli_print(cli
, "%d entries in cache", count
);
1181 // Find session by username, 0 for not found
1182 // walled garden users aren't authenticated, so the username is
1183 // reasonably useless. Ignore them to avoid incorrect actions
1185 // This is VERY inefficent. Don't call it often. :)
1187 sessionidt
sessionbyuser(char *username
)
1190 CSTAT(sessionbyuser
);
1192 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1194 if (!session
[s
].opened
)
1197 if (session
[s
].walled_garden
)
1198 continue; // Skip walled garden users.
1200 if (!strncmp(session
[s
].user
, username
, 128))
1204 return 0; // Not found.
1207 void send_garp(in_addr_t ip
)
1213 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1216 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1219 memset(&ifr
, 0, sizeof(ifr
));
1220 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1221 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1223 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1227 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1228 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1230 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1235 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1238 static sessiont
*sessiontbysessionidt(sessionidt s
)
1240 if (!s
|| s
>= MAXSESSION
) return NULL
;
1244 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1246 sessionidt val
= s
-session
;
1247 if (s
< session
|| val
>= MAXSESSION
) return 0;
1251 // actually send a control message for a specific tunnel
1252 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1254 struct sockaddr_in addr
;
1260 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1261 STAT(tunnel_tx_errors
);
1265 if (t
== TUNNEL_ID_PPPOE
)
1267 pppoe_sess_send(buf
, l
, t
);
1273 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1274 STAT(tunnel_tx_errors
);
1278 memset(&addr
, 0, sizeof(addr
));
1279 addr
.sin_family
= AF_INET
;
1280 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1281 addr
.sin_port
= htons(tunnel
[t
].port
);
1283 // sequence expected, if sequence in message
1284 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1286 // If this is a control message, deal with retries
1289 tunnel
[t
].last
= time_now
; // control message sent
1290 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1293 STAT(tunnel_retries
);
1294 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1298 if (sendto(udpfd
[tunnel
[t
].indexudp
], buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1300 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1301 strerror(errno
), udpfd
[tunnel
[t
].indexudp
], buf
, l
, inet_ntoa(addr
.sin_addr
));
1302 STAT(tunnel_tx_errors
);
1306 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1307 STAT(tunnel_tx_packets
);
1308 INC_STAT(tunnel_tx_bytes
, l
);
1312 // Tiny helper function to write data to
1313 // the 'tun' device.
1315 int tun_write(uint8_t * data
, int size
)
1317 return write(tunfd
, data
, size
);
1320 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1321 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1323 int d
= (tcp
[12] >> 4) * 4;
1330 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1333 if (tcp
+ d
> buf
+ len
) // short?
1341 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1344 if (mss
+ 2 > data
) return; // short?
1348 if (*opts
== 0) return; // end of options
1349 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1352 opts
+= opts
[1]; // skip over option
1355 if (!mss
) return; // not found
1356 orig
= ntohs(*(uint16_t *) mss
);
1358 if (orig
<= MSS
) return; // mss OK
1360 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1361 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1362 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1363 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1366 *(int16_t *) mss
= htons(MSS
);
1368 // adjust checksum (see rfc1141)
1369 sum
= orig
+ (~MSS
& 0xffff);
1370 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1371 sum
= (sum
& 0xffff) + (sum
>> 16);
1372 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1375 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1379 // Skip the four extra bytes
1391 proto
= ntohs(*(uint16_t *) p
);
1399 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1400 return; // closing session, PPP not processed
1402 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1403 processipin(s
, t
, p
, l
);
1405 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1409 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1410 return; // closing session, PPP not processed
1413 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1414 processipv6in(s
, t
, p
, l
);
1416 else if (proto
== PPPIPCP
)
1418 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1419 processipcp(s
, t
, p
, l
);
1421 else if (proto
== PPPCCP
)
1423 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1424 processccp(s
, t
, p
, l
);
1428 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1432 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1434 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1435 sp
->cout_delta
+= len
;
1437 sp
->last_data
= time_now
;
1439 sess_local
[s
].cout
+= len
; // To send to master..
1440 sess_local
[s
].pout
++;
1443 // process outgoing (to tunnel) IP
1445 // (i.e. this routine writes to data[-8]).
1446 void processipout(uint8_t *buf
, int len
)
1452 in_addr_t ip
, ip_src
;
1454 uint8_t *data
= buf
; // Keep a copy of the originals.
1457 uint8_t fragbuf
[MAXETHER
+ 20];
1459 CSTAT(processipout
);
1461 if (len
< MIN_IP_SIZE
)
1463 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1464 STAT(tun_rx_errors
);
1467 if (len
>= MAXETHER
)
1469 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1470 STAT(tun_rx_errors
);
1474 // Skip the tun header
1478 // Got an IP header now
1479 if (*(uint8_t *)(buf
) >> 4 != 4)
1481 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1485 ip_src
= *(uint32_t *)(buf
+ 12);
1486 ip
= *(uint32_t *)(buf
+ 16);
1487 if ((g
= grp_groupbyip(ip
)))
1489 s
= grp_getnextsession(g
, &ip
, &ip_src
, 0);
1492 // Is this a packet for a session that doesn't exist?
1493 static int rate
= 0; // Number of ICMP packets we've sent this second.
1494 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1496 if (last
!= time_now
)
1502 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1504 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1505 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1506 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1511 else if (!(s
= sessionbyip(ip
)))
1513 // Is this a packet for a session that doesn't exist?
1514 static int rate
= 0; // Number of ICMP packets we've sent this second.
1515 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1517 if (last
!= time_now
)
1523 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1525 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1526 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1527 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1532 t
= session
[s
].tunnel
;
1533 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1535 LOG(3, s
, t
, "Packet size more than session MRU\n");
1541 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1542 if (config
->max_packets
> 0)
1544 if (sess_local
[s
].last_packet_out
== TIME
)
1546 int max
= config
->max_packets
;
1548 // All packets for throttled sessions are handled by the
1549 // master, so further limit by using the throttle rate.
1550 // A bit of a kludge, since throttle rate is in kbps,
1551 // but should still be generous given our average DSL
1552 // packet size is 200 bytes: a limit of 28kbps equates
1553 // to around 180 packets per second.
1554 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1555 max
= sp
->throttle_out
;
1557 if (++sess_local
[s
].packets_out
> max
)
1559 sess_local
[s
].packets_dropped
++;
1565 if (sess_local
[s
].packets_dropped
)
1567 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1568 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1569 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1570 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1574 sess_local
[s
].last_packet_out
= TIME
;
1575 sess_local
[s
].packets_out
= 1;
1576 sess_local
[s
].packets_dropped
= 0;
1580 // run access-list if any
1581 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1584 // adjust MSS on SYN and SYN,ACK packets with options
1585 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1587 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1588 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1589 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1594 if (!config
->no_throttle_local_IP
|| !sessionbyip(ip_src
))
1596 // Are we throttling this session?
1597 if (config
->cluster_iam_master
)
1598 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1600 master_throttle_packet(sp
->tbf_out
, data
, size
);
1605 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1607 // We are walled-gardening this
1608 master_garden_packet(s
, data
, size
);
1612 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1615 if (!config
->cluster_iam_master
)
1617 // The MPPP packets must be managed by the Master.
1618 master_forward_mppp_packet(s
, data
, size
);
1622 // Add on L2TP header
1623 sessionidt members
[MAXBUNDLESES
];
1624 bundleidt bid
= session
[s
].bundle
;
1625 bundlet
*b
= &bundle
[bid
];
1626 uint32_t num_of_links
, nb_opened
;
1629 num_of_links
= b
->num_of_links
;
1631 for (i
= 0;i
< num_of_links
;i
++)
1634 if (session
[s
].ppp
.lcp
== Opened
)
1636 members
[nb_opened
] = s
;
1643 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1647 num_of_links
= nb_opened
;
1648 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1649 s
= members
[b
->current_ses
];
1650 t
= session
[s
].tunnel
;
1652 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1654 if (num_of_links
> 1)
1656 if(len
> MINFRAGLEN
)
1658 //for rotate traffic among the member links
1659 uint32_t divisor
= num_of_links
;
1661 divisor
= divisor
/2 + (divisor
& 1);
1663 // Partition the packet to "num_of_links" fragments
1664 uint32_t fraglen
= len
/ divisor
;
1665 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1666 uint32_t remain
= len
;
1668 // send the first packet
1669 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1671 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1674 update_session_out_stat(s
, sp
, fraglen
);
1677 while (remain
> last_fraglen
)
1679 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1680 s
= members
[b
->current_ses
];
1681 t
= session
[s
].tunnel
;
1683 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1684 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1686 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1687 update_session_out_stat(s
, sp
, fraglen
);
1690 // send the last fragment
1691 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1692 s
= members
[b
->current_ses
];
1693 t
= session
[s
].tunnel
;
1695 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1696 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1698 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1699 update_session_out_stat(s
, sp
, remain
);
1700 if (remain
!= last_fraglen
)
1701 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1705 // Send it as one frame
1706 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1708 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1709 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1710 update_session_out_stat(s
, sp
, len
);
1715 // Send it as one frame (NO MPPP Frame)
1716 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1717 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1718 update_session_out_stat(s
, sp
, len
);
1723 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1724 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1725 update_session_out_stat(s
, sp
, len
);
1728 // Snooping this session, send it to intercept box
1729 if (sp
->snoop_ip
&& sp
->snoop_port
)
1730 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1735 // process outgoing (to tunnel) IPv6
1737 static void processipv6out(uint8_t * buf
, int len
)
1743 struct in6_addr
*p_ip6
;
1744 struct in6_addr
*p_ip6_src
;
1746 uint8_t *data
= buf
; // Keep a copy of the originals.
1749 uint8_t b
[MAXETHER
+ 20];
1751 CSTAT(processipv6out
);
1753 if (len
< MIN_IP_SIZE
)
1755 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1756 STAT(tunnel_tx_errors
);
1759 if (len
>= MAXETHER
)
1761 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1762 STAT(tunnel_tx_errors
);
1766 // Skip the tun header
1770 // Got an IP header now
1771 if (*(uint8_t *)(buf
) >> 4 != 6)
1773 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1777 p_ip6_src
= (struct in6_addr
*)(buf
+8);
1778 p_ip6
= (struct in6_addr
*)(buf
+24);
1780 if ((g
= grp_groupbyipv6(*p_ip6
)))
1782 s
= grp_getnextsession(g
, p_ip6
, p_ip6_src
, 1);
1784 else if (!(s
= sessionbyipv6(*p_ip6
)))
1786 s
= sessionbyipv6new(*p_ip6
);
1791 // Is this a packet for a session that doesn't exist?
1792 static int rate
= 0; // Number of ICMP packets we've sent this second.
1793 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1795 if (last
!= time_now
)
1801 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1803 // FIXME: Should send icmp6 host unreachable
1807 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1809 bundleidt bid
= session
[s
].bundle
;
1810 bundlet
*b
= &bundle
[bid
];
1812 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1813 s
= b
->members
[b
->current_ses
];
1814 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1816 t
= session
[s
].tunnel
;
1818 sp
->last_data
= time_now
;
1820 // FIXME: add DoS prevention/filters?
1824 // Are we throttling this session?
1825 if (config
->cluster_iam_master
)
1826 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1828 master_throttle_packet(sp
->tbf_out
, data
, size
);
1831 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1833 // We are walled-gardening this
1834 master_garden_packet(s
, data
, size
);
1838 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1840 // Add on L2TP header
1842 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1844 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1847 // Snooping this session, send it to intercept box
1848 if (sp
->snoop_ip
&& sp
->snoop_port
)
1849 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1851 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1852 sp
->cout_delta
+= len
;
1856 sess_local
[s
].cout
+= len
; // To send to master..
1857 sess_local
[s
].pout
++;
1861 // Helper routine for the TBF filters.
1862 // Used to send queued data in to the user!
1864 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1869 uint8_t *data
= buf
; // Keep a copy of the originals.
1871 uint8_t b
[MAXETHER
+ 20];
1873 if (len
< 0 || len
> MAXETHER
)
1875 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1879 // Skip the tun header
1886 t
= session
[s
].tunnel
;
1889 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1891 // Add on L2TP header
1892 if (*(uint16_t *) (data
+ 2) == htons(PKTIPV6
))
1893 p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0); // IPV6
1895 p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0); // IPV4
1899 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1901 // Snooping this session.
1902 if (sp
->snoop_ip
&& sp
->snoop_port
)
1903 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1905 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1906 sp
->cout_delta
+= len
;
1910 sess_local
[s
].cout
+= len
; // To send to master..
1911 sess_local
[s
].pout
++;
1914 // add an AVP (16 bit)
1915 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1917 uint16_t l
= (m
? 0x8008 : 0x0008);
1918 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1919 pint16
[0] = htons(l
);
1920 pint16
[1] = htons(0);
1921 pint16
[2] = htons(avp
);
1922 pint16
[3] = htons(val
);
1926 // add an AVP (32 bit)
1927 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1929 uint16_t l
= (m
? 0x800A : 0x000A);
1930 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1931 uint32_t *pint32
= (uint32_t *) (c
->buf
+ c
->length
+ 6);
1932 pint16
[0] = htons(l
);
1933 pint16
[1] = htons(0);
1934 pint16
[2] = htons(avp
);
1935 pint32
[0] = htonl(val
);
1939 // add an AVP (string)
1940 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1942 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1943 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1944 pint16
[0] = htons(l
);
1945 pint16
[1] = htons(0);
1946 pint16
[2] = htons(avp
);
1947 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1948 c
->length
+= 6 + strlen(val
);
1952 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1954 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1955 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1956 pint16
[0] = htons(l
);
1957 pint16
[1] = htons(0);
1958 pint16
[2] = htons(avp
);
1959 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1960 c
->length
+= 6 + len
;
1963 // new control connection
1964 static controlt
*controlnew(uint16_t mtype
)
1968 c
= malloc(sizeof(controlt
));
1972 controlfree
= c
->next
;
1976 c
->buf
[0] = 0xC8; // flags
1977 c
->buf
[1] = 0x02; // ver
1979 control16(c
, 0, mtype
, 1);
1983 // send zero block if nothing is waiting
1985 static void controlnull(tunnelidt t
)
1988 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1991 buf
[0] = htons(0xC802); // flags/ver
1992 buf
[1] = htons(12); // length
1993 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1994 buf
[3] = htons(0); // session
1995 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1996 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1997 tunnelsend((uint8_t *)buf
, 12, t
);
2000 // add a control message to a tunnel, and send if within window
2001 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
2003 uint16_t *pint16
= (uint16_t *) (c
->buf
+ 2);
2004 pint16
[0] = htons(c
->length
); // length
2005 pint16
[1] = htons(tunnel
[t
].far
); // tunnel
2006 pint16
[2] = htons(far
); // session
2007 pint16
[3] = htons(tunnel
[t
].ns
); // sequence
2008 tunnel
[t
].ns
++; // advance sequence
2009 // link in message in to queue
2010 if (tunnel
[t
].controlc
)
2011 tunnel
[t
].controle
->next
= c
;
2013 tunnel
[t
].controls
= c
;
2015 tunnel
[t
].controle
= c
;
2016 tunnel
[t
].controlc
++;
2018 // send now if space in window
2019 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
2021 tunnel
[t
].try = 0; // first send
2022 tunnelsend(c
->buf
, c
->length
, t
);
2027 // Throttle or Unthrottle a session
2029 // Throttle the data from/to through a session to no more than
2030 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
2033 // If either value is -1, the current value is retained for that
2036 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
2038 if (!session
[s
].opened
)
2039 return; // No-one home.
2041 if (!*session
[s
].user
)
2042 return; // User not logged in
2046 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
2047 if (session
[s
].tbf_in
)
2048 free_tbf(session
[s
].tbf_in
);
2051 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
2053 session
[s
].tbf_in
= 0;
2055 session
[s
].throttle_in
= rate_in
;
2060 int bytes
= rate_out
* 1024 / 8;
2061 if (session
[s
].tbf_out
)
2062 free_tbf(session
[s
].tbf_out
);
2065 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
2067 session
[s
].tbf_out
= 0;
2069 session
[s
].throttle_out
= rate_out
;
2073 // add/remove filters from session (-1 = no change)
2074 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
2076 if (!session
[s
].opened
)
2077 return; // No-one home.
2079 if (!*session
[s
].user
)
2080 return; // User not logged in
2083 if (filter_in
> MAXFILTER
) filter_in
= -1;
2084 if (filter_out
> MAXFILTER
) filter_out
= -1;
2085 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
2086 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
2090 if (session
[s
].filter_in
)
2091 ip_filters
[session
[s
].filter_in
- 1].used
--;
2094 ip_filters
[filter_in
- 1].used
++;
2096 session
[s
].filter_in
= filter_in
;
2099 if (filter_out
>= 0)
2101 if (session
[s
].filter_out
)
2102 ip_filters
[session
[s
].filter_out
- 1].used
--;
2105 ip_filters
[filter_out
- 1].used
++;
2107 session
[s
].filter_out
= filter_out
;
2111 // start tidy shutdown of session
2112 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
2114 int walled_garden
= session
[s
].walled_garden
;
2115 bundleidt b
= session
[s
].bundle
;
2116 //delete routes only for last session in bundle (in case of MPPP)
2117 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
2119 CSTAT(sessionshutdown
);
2121 if (!session
[s
].opened
)
2123 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2124 return; // not a live session
2127 if (!session
[s
].die
)
2129 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2130 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2131 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2134 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2136 // RADIUS Stop message
2137 uint16_t r
= radiusnew(s
);
2140 // stop, if not already trying
2141 if (radius
[r
].state
!= RADIUSSTOP
)
2143 radius
[r
].term_cause
= term_cause
;
2144 radius
[r
].term_msg
= reason
;
2145 radiussend(r
, RADIUSSTOP
);
2149 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2151 // Save counters to dump to accounting file
2152 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2153 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2156 if (!session
[s
].die
)
2157 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2160 { // IP allocated, clear and unroute
2163 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2165 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2166 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2169 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2170 session
[s
].route
[r
].ip
= 0;
2173 if (session
[s
].ip_pool_index
== -1) // static ip
2175 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2181 // unroute IPv6, if setup
2182 for (r
= 0; r
< MAXROUTE6
&& session
[s
].route6
[r
].ipv6route
.s6_addr
[0] && session
[s
].route6
[r
].ipv6prefixlen
; r
++)
2184 if (del_routes
) route6set(s
, session
[s
].route6
[r
].ipv6route
, session
[s
].route6
[r
].ipv6prefixlen
, 0);
2185 memset(&session
[s
].route6
[r
], 0, sizeof(session
[s
].route6
[r
]));
2188 if (session
[s
].ipv6address
.s6_addr
[0] && del_routes
)
2190 route6set(s
, session
[s
].ipv6address
, 128, 0);
2195 // This session was part of a bundle
2196 bundle
[b
].num_of_links
--;
2197 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2198 if(bundle
[b
].num_of_links
== 0)
2201 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2205 // Adjust the members array to accomodate the new change
2206 uint8_t mem_num
= 0;
2207 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2208 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2211 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2212 if(bundle
[b
].members
[ml
] == s
)
2217 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2218 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2220 // If the killed session is the first of the bundle,
2221 // the new first session must be stored in the cache_ipmap
2222 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2225 sessionidt new_s
= bundle
[b
].members
[0];
2228 // Add the route for this session.
2229 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2234 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2235 ip
= session
[new_s
].route
[r
].ip
;
2237 if (!prefixlen
) prefixlen
= 32;
2238 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2240 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2241 cache_ipmap(i
, new_s
);
2243 cache_ipmap(session
[new_s
].ip
, new_s
);
2246 for (r
= 0; r
< MAXROUTE6
&& session
[new_s
].route6
[r
].ipv6prefixlen
; r
++)
2248 cache_ipv6map(session
[new_s
].route6
[r
].ipv6route
, session
[new_s
].route6
[r
].ipv6prefixlen
, new_s
);
2251 if (session
[new_s
].ipv6address
.s6_addr
[0])
2253 cache_ipv6map(session
[new_s
].ipv6address
, 128, new_s
);
2259 cluster_send_bundle(b
);
2263 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2264 throttle_session(s
, 0, 0);
2268 if (session
[s
].tunnel
== TUNNEL_ID_PPPOE
)
2270 pppoe_shutdown_session(s
);
2275 controlt
*c
= controlnew(14); // sending CDN
2279 buf
[0] = htons(cdn_result
);
2280 buf
[1] = htons(cdn_error
);
2281 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2284 control16(c
, 1, cdn_result
, 1);
2286 control16(c
, 14, s
, 1); // assigned session (our end)
2287 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2291 // update filter refcounts
2292 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2293 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2296 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2297 sess_local
[s
].lcp
.restart
= 0;
2298 sess_local
[s
].ipcp
.restart
= 0;
2299 sess_local
[s
].ipv6cp
.restart
= 0;
2300 sess_local
[s
].ccp
.restart
= 0;
2302 cluster_send_session(s
);
2305 void sendipcp(sessionidt s
, tunnelidt t
)
2307 uint8_t buf
[MAXETHER
];
2311 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2313 if (!session
[s
].unique_id
)
2315 if (!++last_id
) ++last_id
; // skip zero
2316 session
[s
].unique_id
= last_id
;
2319 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2323 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2324 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2325 q
[4] = 3; // ip address option
2326 q
[5] = 6; // option length
2327 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2328 config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] :
2329 my_address
; // send my IP
2331 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2332 restart_timer(s
, ipcp
);
2335 void sendipv6cp(sessionidt s
, tunnelidt t
)
2337 uint8_t buf
[MAXETHER
];
2341 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2343 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2347 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2348 // only send one type
2350 *(uint16_t *) (q
+ 2) = htons(14);
2351 q
[4] = 1; // interface identifier option
2352 q
[5] = 10; // option length
2353 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2354 *(uint32_t *) (q
+ 10) = 0;
2357 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2358 restart_timer(s
, ipv6cp
);
2361 static void sessionclear(sessionidt s
)
2363 memset(&session
[s
], 0, sizeof(session
[s
]));
2364 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2365 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2367 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2368 session
[s
].next
= sessionfree
;
2372 // kill a session now
2373 void sessionkill(sessionidt s
, char *reason
)
2379 if (!session
[s
].opened
) // not alive
2382 if (session
[s
].next
)
2384 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2388 if (!session
[s
].die
)
2389 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2391 if (sess_local
[s
].radius
)
2392 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2394 if (session
[s
].forwardtosession
)
2396 sessionidt sess
= session
[s
].forwardtosession
;
2397 if (session
[sess
].forwardtosession
== s
)
2399 // Shutdown the linked session also.
2400 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2404 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2406 if ((g
= grp_groupbysession(s
)))
2408 grp_removesession(g
, s
);
2412 cluster_send_session(s
);
2415 static void tunnelclear(tunnelidt t
)
2418 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2419 tunnel
[t
].state
= TUNNELFREE
;
2422 static void bundleclear(bundleidt b
)
2425 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2426 bundle
[b
].state
= BUNDLEFREE
;
2429 // kill a tunnel now
2430 static void tunnelkill(tunnelidt t
, char *reason
)
2437 tunnel
[t
].state
= TUNNELDIE
;
2439 // free control messages
2440 while ((c
= tunnel
[t
].controls
))
2442 controlt
* n
= c
->next
;
2443 tunnel
[t
].controls
= n
;
2444 tunnel
[t
].controlc
--;
2445 c
->next
= controlfree
;
2449 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2450 if (session
[s
].tunnel
== t
)
2451 sessionkill(s
, reason
);
2455 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2456 cli_tunnel_actions
[t
].action
= 0;
2457 cluster_send_tunnel(t
);
2460 // shut down a tunnel cleanly
2461 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2465 CSTAT(tunnelshutdown
);
2467 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2469 // never set up, can immediately kill
2470 tunnelkill(t
, reason
);
2473 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2476 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2477 if (session
[s
].tunnel
== t
)
2478 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2480 tunnel
[t
].state
= TUNNELDIE
;
2481 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2482 cluster_send_tunnel(t
);
2483 // TBA - should we wait for sessions to stop?
2486 controlt
*c
= controlnew(4); // sending StopCCN
2491 buf
[0] = htons(result
);
2492 buf
[1] = htons(error
);
2495 int m
= strlen(msg
);
2496 if (m
+ 4 > sizeof(buf
))
2497 m
= sizeof(buf
) - 4;
2499 memcpy(buf
+2, msg
, m
);
2503 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2506 control16(c
, 1, result
, 1);
2508 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2509 controladd(c
, 0, t
); // send the message
2513 // read and process packet on tunnel (UDP)
2514 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, uint16_t indexudpfd
)
2516 uint8_t *sendchalresponse
= NULL
;
2517 uint8_t *recvchalresponse
= NULL
;
2518 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2519 uint8_t *p
= buf
+ 2;
2526 LOG_HEX(5, "UDP Data", buf
, len
);
2527 STAT(tunnel_rx_packets
);
2528 INC_STAT(tunnel_rx_bytes
, len
);
2531 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2532 STAT(tunnel_rx_errors
);
2535 if ((buf
[1] & 0x0F) != 2)
2537 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2538 STAT(tunnel_rx_errors
);
2543 l
= ntohs(*(uint16_t *) p
);
2546 t
= ntohs(*(uint16_t *) p
);
2548 s
= ntohs(*(uint16_t *) p
);
2550 if (s
>= MAXSESSION
)
2552 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2553 STAT(tunnel_rx_errors
);
2558 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2559 STAT(tunnel_rx_errors
);
2562 if (t
== TUNNEL_ID_PPPOE
)
2564 LOG(1, s
, t
, "Received UDP packet with tunnel ID reserved for pppoe\n");
2565 STAT(tunnel_rx_errors
);
2570 ns
= ntohs(*(uint16_t *) p
);
2572 nr
= ntohs(*(uint16_t *) p
);
2577 uint16_t o
= ntohs(*(uint16_t *) p
);
2582 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2583 STAT(tunnel_rx_errors
);
2588 // used to time out old tunnels
2589 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2590 tunnel
[t
].lastrec
= time_now
;
2594 uint16_t message
= 0xFFFF; // message type
2596 uint8_t mandatory
= 0;
2597 uint16_t asession
= 0; // assigned session
2598 uint32_t amagic
= 0; // magic number
2599 uint8_t aflags
= 0; // flags from last LCF
2600 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2601 char called
[MAXTEL
] = ""; // called number
2602 char calling
[MAXTEL
] = ""; // calling number
2604 if (!config
->cluster_iam_master
)
2606 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
2610 // control messages must have bits 0x80|0x40|0x08
2611 // (type, length and sequence) set, and bits 0x02|0x01
2612 // (offset and priority) clear
2613 if ((*buf
& 0xCB) != 0xC8)
2615 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2616 STAT(tunnel_rx_errors
);
2620 // check for duplicate tunnel open message
2626 // Is this a duplicate of the first packet? (SCCRQ)
2628 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2630 if (tunnel
[i
].state
!= TUNNELOPENING
||
2631 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2632 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2635 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2640 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2641 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2643 // if no tunnel specified, assign one
2646 if (!(t
= new_tunnel()))
2648 LOG(1, 0, 0, "No more tunnels\n");
2649 STAT(tunnel_overflow
);
2653 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2654 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2655 tunnel
[t
].window
= 4; // default window
2656 tunnel
[t
].indexudp
= indexudpfd
;
2657 STAT(tunnel_created
);
2658 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2659 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2662 // If the 'ns' just received is not the 'nr' we're
2663 // expecting, just send an ack and drop it.
2665 // if 'ns' is less, then we got a retransmitted packet.
2666 // if 'ns' is greater than missed a packet. Either way
2667 // we should ignore it.
2668 if (ns
!= tunnel
[t
].nr
)
2670 // is this the sequence we were expecting?
2671 STAT(tunnel_rx_errors
);
2672 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2673 t
, ns
, tunnel
[t
].nr
);
2675 if (l
) // Is this not a ZLB?
2680 // check sequence of this message
2682 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2683 // some to clear maybe?
2684 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2686 controlt
*c
= tunnel
[t
].controls
;
2687 tunnel
[t
].controls
= c
->next
;
2688 tunnel
[t
].controlc
--;
2689 c
->next
= controlfree
;
2692 tunnel
[t
].try = 0; // we have progress
2695 // receiver advance (do here so quoted correctly in any sends below)
2696 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2697 if (skip
< 0) skip
= 0;
2698 if (skip
< tunnel
[t
].controlc
)
2700 // some control packets can now be sent that were previous stuck out of window
2701 int tosend
= tunnel
[t
].window
- skip
;
2702 controlt
*c
= tunnel
[t
].controls
;
2710 tunnel
[t
].try = 0; // first send
2711 tunnelsend(c
->buf
, c
->length
, t
);
2716 if (!tunnel
[t
].controlc
)
2717 tunnel
[t
].retry
= 0; // caught up
2720 { // if not a null message
2725 // Default disconnect cause/message on receipt of CDN. Set to
2726 // more specific value from attribute 1 (result code) or 46
2727 // (disconnect cause) if present below.
2728 int disc_cause_set
= 0;
2729 int disc_cause
= TERM_NAS_REQUEST
;
2730 char const *disc_reason
= "Closed (Received CDN).";
2733 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2735 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2742 LOG(1, s
, t
, "Invalid length in AVP\n");
2743 STAT(tunnel_rx_errors
);
2748 if (flags
& 0x3C) // reserved bits, should be clear
2750 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2752 result
= 2; // general error
2753 error
= 3; // reserved field non-zero
2758 if (*(uint16_t *) (b
))
2760 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2762 result
= 2; // general error
2763 error
= 6; // generic vendor-specific error
2764 msg
= "unsupported vendor-specific";
2768 mtype
= ntohs(*(uint16_t *) (b
));
2776 // handle hidden AVPs
2777 if (!*config
->l2tp_secret
)
2779 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2781 result
= 2; // general error
2782 error
= 6; // generic vendor-specific error
2783 msg
= "secret not specified";
2786 if (!session
[s
].random_vector_length
)
2788 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2790 result
= 2; // general error
2791 error
= 6; // generic
2792 msg
= "no random vector";
2797 LOG(2, s
, t
, "Short hidden AVP.\n");
2799 result
= 2; // general error
2800 error
= 2; // length is wrong
2806 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2808 orig_len
= ntohs(*(uint16_t *) b
);
2809 if (orig_len
> n
+ 2)
2811 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2815 result
= 2; // general error
2816 error
= 2; // length is wrong
2825 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2826 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2830 case 0: // message type
2831 message
= ntohs(*(uint16_t *) b
);
2832 mandatory
= flags
& 0x80;
2833 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2835 case 1: // result code
2837 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2838 char const *resdesc
= "(unknown)";
2839 char const *errdesc
= NULL
;
2844 resdesc
= l2tp_stopccn_result_code(rescode
);
2845 cause
= TERM_LOST_SERVICE
;
2847 else if (message
== 14)
2849 resdesc
= l2tp_cdn_result_code(rescode
);
2851 cause
= TERM_LOST_CARRIER
;
2853 cause
= TERM_ADMIN_RESET
;
2856 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2859 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2860 errdesc
= l2tp_error_code(errcode
);
2861 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2864 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2866 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2868 disc_cause_set
= mtype
;
2869 disc_reason
= errdesc
? errdesc
: resdesc
;
2876 case 2: // protocol version
2878 version
= ntohs(*(uint16_t *) (b
));
2879 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2880 if (version
&& version
!= 0x0100)
2881 { // allow 0.0 and 1.0
2882 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2884 result
= 5; // unspported protocol version
2885 error
= 0x0100; // supported version
2891 case 3: // framing capabilities
2893 case 4: // bearer capabilities
2895 case 5: // tie breaker
2896 // We never open tunnels, so we don't care about tie breakers
2898 case 6: // firmware revision
2900 case 7: // host name
2901 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2902 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2903 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2904 // TBA - to send to RADIUS
2906 case 8: // vendor name
2907 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2908 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2909 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2911 case 9: // assigned tunnel
2912 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2913 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2915 case 10: // rx window
2916 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2917 if (!tunnel
[t
].window
)
2918 tunnel
[t
].window
= 1; // window of 0 is silly
2919 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2921 case 11: // Request Challenge
2923 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2925 build_chap_response(b
, 2, n
, &sendchalresponse
);
2926 else if (message
== 2)
2927 build_chap_response(b
, 3, n
, &sendchalresponse
);
2930 case 13: // receive challenge Response
2931 if (tunnel
[t
].isremotelns
)
2933 recvchalresponse
= calloc(17, 1);
2934 memcpy(recvchalresponse
, b
, (n
< 17) ? n
: 16);
2935 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2938 // Why did they send a response? We never challenge.
2939 LOG(2, s
, t
, " received unexpected challenge response\n");
2942 case 14: // assigned session
2943 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2944 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2946 case 15: // call serial number
2947 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2949 case 18: // bearer type
2950 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2953 case 19: // framing type
2954 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2957 case 21: // called number
2958 memset(called
, 0, sizeof(called
));
2959 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2960 LOG(4, s
, t
, " Called <%s>\n", called
);
2962 case 22: // calling number
2963 memset(calling
, 0, sizeof(calling
));
2964 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2965 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2969 case 24: // tx connect speed
2972 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2976 // AS5300s send connect speed as a string
2978 memset(tmp
, 0, sizeof(tmp
));
2979 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2980 session
[s
].tx_connect_speed
= atol(tmp
);
2982 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2984 case 38: // rx connect speed
2987 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2991 // AS5300s send connect speed as a string
2993 memset(tmp
, 0, sizeof(tmp
));
2994 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2995 session
[s
].rx_connect_speed
= atol(tmp
);
2997 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2999 case 25: // Physical Channel ID
3001 uint32_t tmp
= ntohl(*(uint32_t *) b
);
3002 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
3005 case 29: // Proxy Authentication Type
3007 uint16_t atype
= ntohs(*(uint16_t *)b
);
3008 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
3011 case 30: // Proxy Authentication Name
3014 memset(authname
, 0, sizeof(authname
));
3015 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
3016 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
3020 case 31: // Proxy Authentication Challenge
3022 LOG(4, s
, t
, " Proxy Auth Challenge\n");
3025 case 32: // Proxy Authentication ID
3027 uint16_t authid
= ntohs(*(uint16_t *)(b
));
3028 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
3031 case 33: // Proxy Authentication Response
3032 LOG(4, s
, t
, " Proxy Auth Response\n");
3034 case 27: // last sent lcp
3035 { // find magic number
3036 uint8_t *p
= b
, *e
= p
+ n
;
3037 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
3039 if (*p
== 5 && p
[1] == 6) // Magic-Number
3040 amagic
= ntohl(*(uint32_t *) (p
+ 2));
3041 else if (*p
== 7) // Protocol-Field-Compression
3042 aflags
|= SESSION_PFC
;
3043 else if (*p
== 8) // Address-and-Control-Field-Compression
3044 aflags
|= SESSION_ACFC
;
3049 case 28: // last recv lcp confreq
3051 case 26: // Initial Received LCP CONFREQ
3053 case 39: // seq required - we control it as an LNS anyway...
3055 case 36: // Random Vector
3056 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
3057 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
3058 if (n
> sizeof(session
[s
].random_vector
))
3059 n
= sizeof(session
[s
].random_vector
);
3060 memcpy(session
[s
].random_vector
, b
, n
);
3061 session
[s
].random_vector_length
= n
;
3063 case 46: // ppp disconnect cause
3066 uint16_t code
= ntohs(*(uint16_t *) b
);
3067 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
3068 uint8_t dir
= *(b
+ 4);
3070 LOG(4, s
, t
, " PPP disconnect cause "
3071 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
3072 code
, proto
, dir
, n
- 5, b
+ 5);
3074 disc_cause_set
= mtype
;
3078 case 1: // admin disconnect
3079 disc_cause
= TERM_ADMIN_RESET
;
3080 disc_reason
= "Administrative disconnect";
3082 case 3: // lcp terminate
3083 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
3084 disc_cause
= TERM_USER_REQUEST
;
3085 disc_reason
= "Normal disconnection";
3087 case 4: // compulsory encryption unavailable
3088 if (dir
!= 1) break; // 1=refused by peer, 2=local
3089 disc_cause
= TERM_USER_ERROR
;
3090 disc_reason
= "Compulsory encryption refused";
3092 case 5: // lcp: fsm timeout
3093 disc_cause
= TERM_PORT_ERROR
;
3094 disc_reason
= "LCP: FSM timeout";
3096 case 6: // lcp: no recognisable lcp packets received
3097 disc_cause
= TERM_PORT_ERROR
;
3098 disc_reason
= "LCP: no recognisable LCP packets";
3100 case 7: // lcp: magic-no error (possibly looped back)
3101 disc_cause
= TERM_PORT_ERROR
;
3102 disc_reason
= "LCP: magic-no error (possible loop)";
3104 case 8: // lcp: echo request timeout
3105 disc_cause
= TERM_PORT_ERROR
;
3106 disc_reason
= "LCP: echo request timeout";
3108 case 13: // auth: fsm timeout
3109 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3110 disc_reason
= "Authentication: FSM timeout";
3112 case 15: // auth: unacceptable auth protocol
3113 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3114 disc_reason
= "Unacceptable authentication protocol";
3116 case 16: // auth: authentication failed
3117 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3118 disc_reason
= "Authentication failed";
3120 case 17: // ncp: fsm timeout
3121 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3122 disc_reason
= "NCP: FSM timeout";
3124 case 18: // ncp: no ncps available
3125 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3126 disc_reason
= "NCP: no NCPs available";
3128 case 19: // ncp: failure to converge on acceptable address
3129 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3130 disc_reason
= (dir
== 1)
3131 ? "NCP: too many Configure-Naks received from peer"
3132 : "NCP: too many Configure-Naks sent to peer";
3134 case 20: // ncp: user not permitted to use any address
3135 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3136 disc_reason
= (dir
== 1)
3137 ? "NCP: local link address not acceptable to peer"
3138 : "NCP: remote link address not acceptable";
3145 static char e
[] = "unknown AVP 0xXXXX";
3146 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
3148 result
= 2; // general error
3149 error
= 8; // unknown mandatory AVP
3150 sprintf((msg
= e
) + 14, "%04x", mtype
);
3157 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3161 case 1: // SCCRQ - Start Control Connection Request
3162 tunnel
[t
].state
= TUNNELOPENING
;
3163 LOG(3, s
, t
, "Received SCCRQ\n");
3164 if (main_quit
!= QUIT_SHUTDOWN
)
3166 LOG(3, s
, t
, "sending SCCRP\n");
3167 controlt
*c
= controlnew(2); // sending SCCRP
3168 control16(c
, 2, version
, 1); // protocol version
3169 control32(c
, 3, 3, 1); // framing
3170 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3171 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Send Challenge response
3172 control16(c
, 9, t
, 1); // assigned tunnel
3173 controladd(c
, 0, t
); // send the resply
3177 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3181 tunnel
[t
].state
= TUNNELOPEN
;
3182 tunnel
[t
].lastrec
= time_now
;
3183 LOG(3, s
, t
, "Received SCCRP\n");
3184 if (main_quit
!= QUIT_SHUTDOWN
)
3186 if (tunnel
[t
].isremotelns
&& recvchalresponse
)
3190 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3191 // check authenticator
3192 if (memcmp(hash
, recvchalresponse
, 16) == 0)
3194 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3195 controlt
*c
= controlnew(3); // sending SCCCN
3196 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3197 controls(c
, 8, Vendor_name
, 1); // Vendor name
3198 control16(c
, 2, version
, 1); // protocol version
3199 control32(c
, 3, 3, 1); // framing Capabilities
3200 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Challenge response
3201 control16(c
, 9, t
, 1); // assigned tunnel
3202 controladd(c
, 0, t
); // send
3206 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3212 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3216 LOG(3, s
, t
, "Received SCCN\n");
3217 tunnel
[t
].state
= TUNNELOPEN
;
3218 tunnel
[t
].lastrec
= time_now
;
3219 controlnull(t
); // ack
3222 LOG(3, s
, t
, "Received StopCCN\n");
3223 controlnull(t
); // ack
3224 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3227 LOG(3, s
, t
, "Received HELLO\n");
3228 controlnull(t
); // simply ACK
3232 LOG(3, s
, t
, "Received OCRQ\n");
3236 LOG(3, s
, t
, "Received OCRO\n");
3240 LOG(3, s
, t
, "Received OCCN\n");
3243 LOG(3, s
, t
, "Received ICRQ\n");
3244 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3246 controlt
*c
= controlnew(11); // ICRP
3248 LOG(3, s
, t
, "Sending ICRP\n");
3251 sessionfree
= session
[s
].next
;
3252 memset(&session
[s
], 0, sizeof(session
[s
]));
3254 if (s
> config
->cluster_highest_sessionid
)
3255 config
->cluster_highest_sessionid
= s
;
3257 session
[s
].opened
= time_now
;
3258 session
[s
].tunnel
= t
;
3259 session
[s
].far
= asession
;
3260 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3261 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3262 control16(c
, 14, s
, 1); // assigned session
3263 controladd(c
, asession
, t
); // send the reply
3265 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3266 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3268 session
[s
].ppp
.phase
= Establish
;
3269 session
[s
].ppp
.lcp
= Starting
;
3271 STAT(session_created
);
3276 controlt
*c
= controlnew(14); // CDN
3277 LOG(3, s
, t
, "Sending CDN\n");
3280 STAT(session_overflow
);
3281 LOG(1, 0, t
, "No free sessions\n");
3282 control16(c
, 1, 4, 0); // temporary lack of resources
3285 control16(c
, 1, 2, 7); // shutting down, try another
3287 controladd(c
, asession
, t
); // send the message
3291 LOG(3, s
, t
, "Received ICRP\n");
3292 if (session
[s
].forwardtosession
)
3294 controlt
*c
= controlnew(12); // ICCN
3296 session
[s
].opened
= time_now
;
3297 session
[s
].tunnel
= t
;
3298 session
[s
].far
= asession
;
3299 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3301 control32(c
, 19, 1, 1); // Framing Type
3302 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3303 controladd(c
, asession
, t
); // send the message
3304 LOG(3, s
, t
, "Sending ICCN\n");
3308 LOG(3, s
, t
, "Received ICCN\n");
3309 if (amagic
== 0) amagic
= time_now
;
3310 session
[s
].magic
= amagic
; // set magic number
3311 session
[s
].flags
= aflags
; // set flags received
3312 session
[s
].mru
= PPPoE_MRU
; // default
3313 controlnull(t
); // ack
3316 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3317 sess_local
[s
].ppp_mru
= MRU
;
3319 // Set multilink options before sending initial LCP packet
3320 sess_local
[s
].mp_mrru
= 1614;
3321 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_address
? config
->iftun_address
: my_address
);
3324 change_state(s
, lcp
, RequestSent
);
3328 LOG(3, s
, t
, "Received CDN\n");
3329 controlnull(t
); // ack
3330 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3333 LOG(1, s
, t
, "Missing message type\n");
3336 STAT(tunnel_rx_errors
);
3338 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3340 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3343 if (sendchalresponse
) free(sendchalresponse
);
3344 if (recvchalresponse
) free(recvchalresponse
);
3345 cluster_send_tunnel(t
);
3349 LOG(4, s
, t
, " Got a ZLB ack\n");
3356 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3357 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3358 { // HDLC address header, discard
3364 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3365 STAT(tunnel_rx_errors
);
3375 proto
= ntohs(*(uint16_t *) p
);
3380 if (session
[s
].forwardtosession
)
3382 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3383 // Forward to LAC/BAS or Remote LNS session
3384 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3387 else if (config
->auth_tunnel_change_addr_src
)
3389 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3390 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3392 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3393 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3394 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3396 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3400 if (s
&& !session
[s
].opened
) // Is something wrong??
3402 if (!config
->cluster_iam_master
)
3404 // Pass it off to the master to deal with..
3405 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3409 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3410 STAT(tunnel_rx_errors
);
3414 if (proto
== PPPPAP
)
3416 session
[s
].last_packet
= time_now
;
3417 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3418 processpap(s
, t
, p
, l
);
3420 else if (proto
== PPPCHAP
)
3422 session
[s
].last_packet
= time_now
;
3423 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3424 processchap(s
, t
, p
, l
);
3426 else if (proto
== PPPLCP
)
3428 session
[s
].last_packet
= time_now
;
3429 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3430 processlcp(s
, t
, p
, l
);
3432 else if (proto
== PPPIPCP
)
3434 session
[s
].last_packet
= time_now
;
3435 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3436 processipcp(s
, t
, p
, l
);
3438 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3440 session
[s
].last_packet
= time_now
;
3441 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3442 processipv6cp(s
, t
, p
, l
);
3444 else if (proto
== PPPCCP
)
3446 session
[s
].last_packet
= time_now
;
3447 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3448 processccp(s
, t
, p
, l
);
3450 else if (proto
== PPPIP
)
3454 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3455 return; // closing session, PPP not processed
3458 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3459 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3461 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3465 processipin(s
, t
, p
, l
);
3467 else if (proto
== PPPMP
)
3471 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3472 return; // closing session, PPP not processed
3475 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3476 if (!config
->cluster_iam_master
)
3478 // The fragments reconstruction is managed by the Master.
3479 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3483 processmpin(s
, t
, p
, l
);
3485 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3489 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3490 return; // closing session, PPP not processed
3493 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3494 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3496 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3500 if (!config
->cluster_iam_master
)
3502 // Check if DhcpV6, IP dst: FF02::1:2, Src Port 0x0222 (546), Dst Port 0x0223 (547)
3503 if (*(p
+ 6) == 17 && *(p
+ 24) == 0xFF && *(p
+ 25) == 2 &&
3504 *(uint32_t *)(p
+ 26) == 0 && *(uint32_t *)(p
+ 30) == 0 &&
3505 *(uint16_t *)(p
+ 34) == 0 && *(p
+ 36) == 0 && *(p
+ 37) == 1 && *(p
+ 38) == 0 && *(p
+ 39) == 2 &&
3506 *(p
+ 40) == 2 && *(p
+ 41) == 0x22 && *(p
+ 42) == 2 && *(p
+ 43) == 0x23)
3508 // DHCPV6 must be managed by the Master.
3509 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3514 processipv6in(s
, t
, p
, l
);
3516 else if (session
[s
].ppp
.lcp
== Opened
)
3518 session
[s
].last_packet
= time_now
;
3519 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3520 protoreject(s
, t
, p
, l
, proto
);
3524 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3525 proto
, ppp_state(session
[s
].ppp
.lcp
));
3530 // read and process packet on tun
3531 // (i.e. this routine writes to buf[-8]).
3532 static void processtun(uint8_t * buf
, int len
)
3534 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3535 STAT(tun_rx_packets
);
3536 INC_STAT(tun_rx_bytes
, len
);
3544 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3545 STAT(tun_rx_errors
);
3549 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3550 processipout(buf
, len
);
3551 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3552 && config
->ipv6_prefix
.s6_addr
[0])
3553 processipv6out(buf
, len
);
3558 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3559 // that we look at the whole of the tunnel, radius and session tables
3561 static void regular_cleanups(double period
)
3563 // Next tunnel, radius and session to check for actions on.
3564 static tunnelidt t
= 0;
3566 static sessionidt s
= 0;
3579 // divide up tables into slices based on the last run
3580 t_slice
= config
->cluster_highest_tunnelid
* period
;
3581 r_slice
= (MAXRADIUS
- 1) * period
;
3582 s_slice
= config
->cluster_highest_sessionid
* period
;
3586 else if (t_slice
> config
->cluster_highest_tunnelid
)
3587 t_slice
= config
->cluster_highest_tunnelid
;
3591 else if (r_slice
> (MAXRADIUS
- 1))
3592 r_slice
= MAXRADIUS
- 1;
3596 else if (s_slice
> config
->cluster_highest_sessionid
)
3597 s_slice
= config
->cluster_highest_sessionid
;
3599 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3601 for (i
= 0; i
< t_slice
; i
++)
3604 if (t
> config
->cluster_highest_tunnelid
)
3607 if (t
== TUNNEL_ID_PPPOE
)
3610 // check for expired tunnels
3611 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3613 STAT(tunnel_timeout
);
3614 tunnelkill(t
, "Expired");
3618 // check for message resend
3619 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3621 // resend pending messages as timeout on reply
3622 if (tunnel
[t
].retry
<= TIME
)
3624 controlt
*c
= tunnel
[t
].controls
;
3625 uint16_t w
= tunnel
[t
].window
;
3626 tunnel
[t
].try++; // another try
3627 if (tunnel
[t
].try > 5)
3628 tunnelkill(t
, "Timeout on control message"); // game over
3632 tunnelsend(c
->buf
, c
->length
, t
);
3640 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3642 if (!config
->disable_sending_hello
)
3644 controlt
*c
= controlnew(6); // sending HELLO
3645 controladd(c
, 0, t
); // send the message
3646 LOG(3, 0, t
, "Sending HELLO message\n");
3651 // Check for tunnel changes requested from the CLI
3652 if ((a
= cli_tunnel_actions
[t
].action
))
3654 cli_tunnel_actions
[t
].action
= 0;
3655 if (a
& CLI_TUN_KILL
)
3657 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3658 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3664 for (i
= 0; i
< r_slice
; i
++)
3670 if (!radius
[r
].state
)
3673 if (radius
[r
].retry
<= TIME
)
3680 for (i
= 0; i
< s_slice
; i
++)
3683 if (s
> config
->cluster_highest_sessionid
)
3686 if (!session
[s
].opened
) // Session isn't in use
3689 // check for expired sessions
3692 if (session
[s
].die
<= TIME
)
3694 sessionkill(s
, "Expired");
3701 if (sess_local
[s
].lcp
.restart
<= time_now
)
3703 int next_state
= session
[s
].ppp
.lcp
;
3704 switch (session
[s
].ppp
.lcp
)
3708 next_state
= RequestSent
;
3711 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3713 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3714 sendlcp(s
, session
[s
].tunnel
);
3715 change_state(s
, lcp
, next_state
);
3719 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3720 STAT(session_timeout
);
3730 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3732 int next_state
= session
[s
].ppp
.ipcp
;
3733 switch (session
[s
].ppp
.ipcp
)
3737 next_state
= RequestSent
;
3740 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3742 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3743 sendipcp(s
, session
[s
].tunnel
);
3744 change_state(s
, ipcp
, next_state
);
3748 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3749 STAT(session_timeout
);
3759 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3761 int next_state
= session
[s
].ppp
.ipv6cp
;
3762 switch (session
[s
].ppp
.ipv6cp
)
3766 next_state
= RequestSent
;
3769 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3771 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3772 sendipv6cp(s
, session
[s
].tunnel
);
3773 change_state(s
, ipv6cp
, next_state
);
3777 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3778 change_state(s
, ipv6cp
, Stopped
);
3785 if (sess_local
[s
].ccp
.restart
<= time_now
)
3787 int next_state
= session
[s
].ppp
.ccp
;
3788 switch (session
[s
].ppp
.ccp
)
3792 next_state
= RequestSent
;
3795 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3797 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3798 sendccp(s
, session
[s
].tunnel
);
3799 change_state(s
, ccp
, next_state
);
3803 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3804 change_state(s
, ccp
, Stopped
);
3811 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3812 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3814 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3815 STAT(session_timeout
);
3820 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3821 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= config
->echo_timeout
) &&
3822 (time_now
- sess_local
[s
].last_echo
>= config
->echo_timeout
))
3824 uint8_t b
[MAXETHER
];
3826 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3830 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3831 *(uint16_t *)(q
+ 2) = htons(8); // Length
3832 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3834 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3835 (int)(time_now
- session
[s
].last_packet
));
3837 tunnelsend(b
, (q
- b
) + 8, session
[s
].tunnel
); // send it
3838 sess_local
[s
].last_echo
= time_now
;
3842 // Drop sessions who have reached session_timeout seconds
3843 if (session
[s
].session_timeout
)
3845 bundleidt bid
= session
[s
].bundle
;
3848 if (time_now
- bundle
[bid
].last_check
>= 1)
3850 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3851 bundle
[bid
].last_check
= time_now
;
3852 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3855 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3857 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3864 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3866 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3872 // Drop sessions who have reached idle_timeout seconds
3873 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3875 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3876 STAT(session_timeout
);
3881 // Check for actions requested from the CLI
3882 if ((a
= cli_session_actions
[s
].action
))
3886 cli_session_actions
[s
].action
= 0;
3887 if (a
& CLI_SESS_KILL
)
3889 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3890 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3891 a
= 0; // dead, no need to check for other actions
3895 if (a
& CLI_SESS_NOSNOOP
)
3897 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3898 session
[s
].snoop_ip
= 0;
3899 session
[s
].snoop_port
= 0;
3903 else if (a
& CLI_SESS_SNOOP
)
3905 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3906 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3907 cli_session_actions
[s
].snoop_port
);
3909 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3910 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3915 if (a
& CLI_SESS_NOTHROTTLE
)
3917 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3918 throttle_session(s
, 0, 0);
3922 else if (a
& CLI_SESS_THROTTLE
)
3924 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3925 cli_session_actions
[s
].throttle_in
,
3926 cli_session_actions
[s
].throttle_out
);
3928 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3933 if (a
& CLI_SESS_NOFILTER
)
3935 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3936 filter_session(s
, 0, 0);
3940 else if (a
& CLI_SESS_FILTER
)
3942 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3943 cli_session_actions
[s
].filter_in
,
3944 cli_session_actions
[s
].filter_out
);
3946 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3952 cluster_send_session(s
);
3955 // RADIUS interim accounting
3956 if (config
->radius_accounting
&& config
->radius_interim
> 0
3957 && session
[s
].ip
&& !session
[s
].walled_garden
3958 && !sess_local
[s
].radius
// RADIUS already in progress
3959 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3960 && session
[s
].flags
& SESSION_STARTED
)
3962 int rad
= radiusnew(s
);
3965 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3966 STAT(radius_overflow
);
3970 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3971 session
[s
].user
, session
[s
].unique_id
);
3973 radiussend(rad
, RADIUSINTERIM
);
3974 sess_local
[s
].last_interim
= time_now
;
3979 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3980 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3984 // Are we in the middle of a tunnel update, or radius
3987 static int still_busy(void)
3990 static clockt last_talked
= 0;
3991 static clockt start_busy_wait
= 0;
3994 static time_t stopped_bgp
= 0;
3999 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
4001 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4002 if (bgp_peers
[i
].state
== Established
)
4003 bgp_stop(&bgp_peers
[i
]);
4005 stopped_bgp
= time_now
;
4007 if (!config
->cluster_iam_master
)
4009 // we don't want to become master
4010 cluster_send_ping(0);
4016 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
4021 if (!config
->cluster_iam_master
)
4024 if (main_quit
== QUIT_SHUTDOWN
)
4026 static int dropped
= 0;
4031 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
4032 for (i
= 1; i
< MAXTUNNEL
; i
++)
4033 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
4034 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
4040 if (start_busy_wait
== 0)
4041 start_busy_wait
= TIME
;
4043 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
4045 if (!tunnel
[i
].controlc
)
4048 if (last_talked
!= TIME
)
4050 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
4056 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
4057 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
4059 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
4063 for (i
= 1; i
< MAXRADIUS
; i
++)
4065 if (radius
[i
].state
== RADIUSNULL
)
4067 if (radius
[i
].state
== RADIUSWAIT
)
4070 if (last_talked
!= TIME
)
4072 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
4082 # include <sys/epoll.h>
4084 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
4085 # include "fake_epoll.h"
4088 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
4089 #define BASE_FDS (9 + MAX_UDPFD)
4091 // additional polled fds
4093 # define EXTRA_FDS BGP_NUM_PEERS
4095 # define EXTRA_FDS 0
4098 // main loop - gets packets on tun or udp and processes them
4099 static void mainloop(void)
4103 uint8_t *p
= buf
+ 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4104 // and the forwarded pppoe session
4105 int size_bufp
= sizeof(buf
) - 32;
4106 clockt next_cluster_ping
= 0; // send initial ping immediately
4107 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
4108 int maxevent
= sizeof(events
)/sizeof(*events
);
4110 if ((epollfd
= epoll_create(maxevent
)) < 0)
4112 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
4116 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",
4117 clifd
, cluster_sockfd
, tunfd
, udpfd
[0], controlfd
, daefd
, nlfd
, udplacfd
, pppoediscfd
, pppoesessfd
);
4119 /* setup our fds to poll for input */
4121 static struct event_data d
[BASE_FDS
];
4122 struct epoll_event e
;
4129 d
[i
].type
= FD_TYPE_CLI
;
4130 e
.data
.ptr
= &d
[i
++];
4131 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
4134 d
[i
].type
= FD_TYPE_CLUSTER
;
4135 e
.data
.ptr
= &d
[i
++];
4136 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
4138 d
[i
].type
= FD_TYPE_TUN
;
4139 e
.data
.ptr
= &d
[i
++];
4140 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
4142 d
[i
].type
= FD_TYPE_CONTROL
;
4143 e
.data
.ptr
= &d
[i
++];
4144 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
4146 d
[i
].type
= FD_TYPE_DAE
;
4147 e
.data
.ptr
= &d
[i
++];
4148 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
4150 d
[i
].type
= FD_TYPE_NETLINK
;
4151 e
.data
.ptr
= &d
[i
++];
4152 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
4154 d
[i
].type
= FD_TYPE_PPPOEDISC
;
4155 e
.data
.ptr
= &d
[i
++];
4156 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoediscfd
, &e
);
4158 d
[i
].type
= FD_TYPE_PPPOESESS
;
4159 e
.data
.ptr
= &d
[i
++];
4160 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoesessfd
, &e
);
4162 for (j
= 0; j
< config
->nbudpfd
; j
++)
4164 d
[i
].type
= FD_TYPE_UDP
;
4166 e
.data
.ptr
= &d
[i
++];
4167 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
[j
], &e
);
4172 signal(SIGPIPE
, SIG_IGN
);
4173 bgp_setup(config
->as_number
);
4174 if (config
->bind_address
)
4175 bgp_add_route(config
->bind_address
, 0xffffffff);
4177 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4179 if (config
->neighbour
[i
].name
[0])
4180 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4181 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4182 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4183 0); /* 0 = routing disabled */
4187 while (!main_quit
|| still_busy())
4197 config
->reload_config
++;
4200 if (config
->reload_config
)
4202 config
->reload_config
= 0;
4210 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4211 STAT(select_called
);
4216 if (errno
== EINTR
||
4217 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4220 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4226 struct sockaddr_in addr
;
4227 struct in_addr local
;
4230 int udp_ready
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4231 int pppoesess_ready
= 0;
4232 int pppoesess_pkts
= 0;
4234 int cluster_ready
= 0;
4235 int udp_pkts
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4237 int cluster_pkts
= 0;
4239 uint32_t bgp_events
[BGP_NUM_PEERS
];
4240 memset(bgp_events
, 0, sizeof(bgp_events
));
4243 for (c
= n
, i
= 0; i
< c
; i
++)
4245 struct event_data
*d
= events
[i
].data
.ptr
;
4249 case FD_TYPE_CLI
: // CLI connections
4253 alen
= sizeof(addr
);
4254 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4260 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4266 // these are handled below, with multiple interleaved reads
4267 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4268 case FD_TYPE_TUN
: tun_ready
++; break;
4269 case FD_TYPE_UDP
: udp_ready
[d
->index
]++; break;
4270 case FD_TYPE_PPPOESESS
: pppoesess_ready
++; break;
4272 case FD_TYPE_PPPOEDISC
: // pppoe discovery
4273 s
= read(pppoediscfd
, p
, size_bufp
);
4274 if (s
> 0) process_pppoe_disc(p
, s
);
4278 case FD_TYPE_CONTROL
: // nsctl commands
4279 alen
= sizeof(addr
);
4280 s
= recvfromto(controlfd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4281 if (s
> 0) processcontrol(p
, s
, &addr
, alen
, &local
);
4285 case FD_TYPE_DAE
: // DAE requests
4286 alen
= sizeof(addr
);
4287 s
= recvfromto(daefd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4288 if (s
> 0) processdae(p
, s
, &addr
, alen
, &local
);
4292 case FD_TYPE_RADIUS
: // RADIUS response
4293 alen
= sizeof(addr
);
4294 s
= recvfrom(radfds
[d
->index
], p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4295 if (s
>= 0 && config
->cluster_iam_master
)
4297 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4298 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4299 processrad(p
, s
, d
->index
);
4301 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4302 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4310 bgp_events
[d
->index
] = events
[i
].events
;
4315 case FD_TYPE_NETLINK
:
4317 struct nlmsghdr
*nh
= (struct nlmsghdr
*)p
;
4318 s
= netlink_recv(p
, size_bufp
);
4319 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4321 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4324 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4326 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4330 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4335 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
);
4341 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4346 bgp_process(bgp_events
);
4349 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4351 for (j
= 0; j
< config
->nbudpfd
; j
++)
4353 // L2TP and L2TP REMOTE LNS
4356 alen
= sizeof(addr
);
4357 if ((s
= recvfrom(udpfd
[j
], p
, size_bufp
, 0, (void *) &addr
, &alen
)) > 0)
4359 processudp(p
, s
, &addr
, j
);
4373 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4386 if (pppoesess_ready
)
4388 if ((s
= read(pppoesessfd
, p
, size_bufp
)) > 0)
4390 process_pppoe_sess(p
, s
);
4395 pppoesess_ready
= 0;
4403 alen
= sizeof(addr
);
4404 if ((s
= recvfrom(cluster_sockfd
, p
, size_bufp
, MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4406 processcluster(p
, s
, addr
.sin_addr
.s_addr
);
4417 if (udp_pkts
[0] > 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4418 STAT(multi_read_used
);
4420 if (c
>= config
->multi_read_count
)
4422 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4423 config
->multi_read_count
, udp_pkts
[0], tun_pkts
, cluster_pkts
, pppoesess_pkts
);
4424 STAT(multi_read_exceeded
);
4430 /* no event received, but timers could still have expired */
4431 bgp_process_peers_timers();
4436 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4438 // Log current traffic stats
4439 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4440 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4441 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4442 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4443 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4445 udp_tx
= udp_rx
= 0;
4446 udp_rx_pkt
= eth_rx_pkt
= 0;
4447 eth_tx
= eth_rx
= 0;
4450 if (config
->dump_speed
)
4451 printf("%s\n", config
->bandwidth
);
4453 // Update the internal time counter
4454 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4458 struct param_timer p
= { time_now
};
4459 run_plugins(PLUGIN_TIMER
, &p
);
4463 // Runs on every machine (master and slaves).
4464 if (next_cluster_ping
<= TIME
)
4466 // Check to see which of the cluster is still alive..
4468 cluster_send_ping(basetime
); // Only does anything if we're a slave
4469 cluster_check_master(); // ditto.
4471 cluster_heartbeat(); // Only does anything if we're a master.
4472 cluster_check_slaves(); // ditto.
4474 master_update_counts(); // If we're a slave, send our byte counters to our master.
4476 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4477 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4479 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4482 if (!config
->cluster_iam_master
)
4485 // Run token bucket filtering queue..
4486 // Only run it every 1/10th of a second.
4488 static clockt last_run
= 0;
4489 if (last_run
!= TIME
)
4496 // Handle timeouts, retries etc.
4498 static double last_clean
= 0;
4502 TIME
= now(&this_clean
);
4503 diff
= this_clean
- last_clean
;
4505 // Run during idle time (after we've handled
4506 // all incoming packets) or every 1/10th sec
4507 if (!more
|| diff
> 0.1)
4509 regular_cleanups(diff
);
4510 last_clean
= this_clean
;
4514 if (*config
->accounting_dir
)
4516 static clockt next_acct
= 0;
4517 static clockt next_shut_acct
= 0;
4519 if (next_acct
<= TIME
)
4521 // Dump accounting data
4522 next_acct
= TIME
+ ACCT_TIME
;
4523 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4526 else if (next_shut_acct
<= TIME
)
4528 // Dump accounting data for shutdown sessions
4529 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4536 // Are we the master and shutting down??
4537 if (config
->cluster_iam_master
)
4538 cluster_heartbeat(); // Flush any queued changes..
4540 // Ok. Notify everyone we're shutting down. If we're
4541 // the master, this will force an election.
4542 cluster_send_ping(0);
4545 // Important!!! We MUST not process any packets past this point!
4546 LOG(1, 0, 0, "Shutdown complete\n");
4549 static void stripdomain(char *host
)
4553 if ((p
= strchr(host
, '.')))
4559 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4565 while (fgets(buf
, sizeof(buf
), resolv
))
4567 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4570 if (!isspace(buf
[6]))
4574 while (isspace(*b
)) b
++;
4579 while (*b
&& !isspace(*b
)) b
++;
4581 if (buf
[0] == 'd') // domain is canonical
4587 // first search line
4590 // hold, may be subsequent domain line
4591 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4602 int hl
= strlen(host
);
4603 int dl
= strlen(domain
);
4604 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4605 host
[hl
-dl
- 1] = 0;
4609 *p
= 0; // everything after first dot
4614 // Init data structures
4615 static void initdata(int optdebug
, char *optconfig
)
4619 if (!(config
= shared_malloc(sizeof(configt
))))
4621 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4625 memset(config
, 0, sizeof(configt
));
4626 time(&config
->start_time
);
4627 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4628 config
->debug
= optdebug
;
4629 config
->num_tbfs
= MAXTBFS
;
4630 config
->rl_rate
= 28; // 28kbps
4631 config
->cluster_mcast_ttl
= 1;
4632 config
->cluster_master_min_adv
= 1;
4633 config
->ppp_restart_time
= 3;
4634 config
->ppp_max_configure
= 10;
4635 config
->ppp_max_failure
= 5;
4636 config
->kill_timedout_sessions
= 1;
4637 strcpy(config
->random_device
, RANDOMDEVICE
);
4638 // Set default value echo_timeout and idle_echo_timeout
4639 config
->echo_timeout
= ECHO_TIMEOUT
;
4640 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4642 log_stream
= stderr
;
4645 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4647 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4650 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4653 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4655 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4658 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4660 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4663 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4665 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4668 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4670 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4673 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4675 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4679 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4681 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4685 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4687 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4691 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4693 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4697 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4699 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4702 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4704 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4706 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4709 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4711 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4713 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4716 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4718 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4719 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4720 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4721 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4722 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4724 // Put all the sessions on the free list marked as undefined.
4725 for (i
= 1; i
< MAXSESSION
; i
++)
4727 session
[i
].next
= i
+ 1;
4728 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4730 session
[MAXSESSION
- 1].next
= 0;
4733 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4734 for (i
= 1; i
< MAXTUNNEL
; i
++)
4735 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4737 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4738 bundle
[i
].state
= BUNDLEUNDEF
;
4743 // Grab my hostname unless it's been specified
4744 gethostname(hostname
, sizeof(hostname
));
4745 stripdomain(hostname
);
4748 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4751 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4753 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4758 lac_initremotelnsdata();
4763 static int assign_ip_address(sessionidt s
)
4767 time_t best_time
= time_now
;
4768 char *u
= session
[s
].user
;
4772 CSTAT(assign_ip_address
);
4774 for (i
= 1; i
< ip_pool_size
; i
++)
4776 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4779 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4786 if (ip_address_pool
[i
].last
< best_time
)
4789 if (!(best_time
= ip_address_pool
[i
].last
))
4790 break; // never used, grab this one
4796 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4800 session
[s
].ip
= ip_address_pool
[best
].address
;
4801 session
[s
].ip_pool_index
= best
;
4802 ip_address_pool
[best
].assigned
= 1;
4803 ip_address_pool
[best
].last
= time_now
;
4804 ip_address_pool
[best
].session
= s
;
4805 if (session
[s
].walled_garden
)
4806 /* Don't track addresses of users in walled garden (note: this
4807 means that their address isn't "sticky" even if they get
4809 ip_address_pool
[best
].user
[0] = 0;
4811 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4814 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4815 reuse
? "Reusing" : "Allocating", best
);
4820 static void free_ip_address(sessionidt s
)
4822 int i
= session
[s
].ip_pool_index
;
4825 CSTAT(free_ip_address
);
4828 return; // what the?
4830 if (i
< 0) // Is this actually part of the ip pool?
4834 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4836 ip_address_pool
[i
].assigned
= 0;
4837 ip_address_pool
[i
].session
= 0;
4838 ip_address_pool
[i
].last
= time_now
;
4842 // Fsck the address pool against the session table.
4843 // Normally only called when we become a master.
4845 // This isn't perfect: We aren't keep tracking of which
4846 // users used to have an IP address.
4848 void rebuild_address_pool(void)
4853 // Zero the IP pool allocation, and build
4854 // a map from IP address to pool index.
4855 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4857 ip_address_pool
[i
].assigned
= 0;
4858 ip_address_pool
[i
].session
= 0;
4859 if (!ip_address_pool
[i
].address
)
4862 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4865 for (i
= 0; i
< MAXSESSION
; ++i
)
4868 if (!(session
[i
].opened
&& session
[i
].ip
))
4871 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4873 if (session
[i
].ip_pool_index
< 0)
4875 // Not allocated out of the pool.
4876 if (ipid
< 1) // Not found in the pool either? good.
4879 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4880 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4882 // Fall through and process it as part of the pool.
4886 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4888 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4890 session
[i
].ip_pool_index
= ipid
;
4894 ip_address_pool
[ipid
].assigned
= 1;
4895 ip_address_pool
[ipid
].session
= i
;
4896 ip_address_pool
[ipid
].last
= time_now
;
4897 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4898 session
[i
].ip_pool_index
= ipid
;
4899 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4904 // Fix the address pool to match a changed session.
4905 // (usually when the master sends us an update).
4906 static void fix_address_pool(int sid
)
4910 ipid
= session
[sid
].ip_pool_index
;
4912 if (ipid
> ip_pool_size
)
4913 return; // Ignore it. rebuild_address_pool will fix it up.
4915 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4916 return; // Just ignore it. rebuild_address_pool will take care of it.
4918 ip_address_pool
[ipid
].assigned
= 1;
4919 ip_address_pool
[ipid
].session
= sid
;
4920 ip_address_pool
[ipid
].last
= time_now
;
4921 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4925 // Add a block of addresses to the IP pool to hand out.
4927 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4931 prefixlen
= 32; // Host route only.
4933 addr
&= 0xffffffff << (32 - prefixlen
);
4935 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4938 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4940 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4941 continue; // Skip 0 and broadcast addresses.
4943 ip_address_pool
[ip_pool_size
].address
= i
;
4944 ip_address_pool
[ip_pool_size
].assigned
= 0;
4946 if (ip_pool_size
>= MAXIPPOOL
)
4948 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4954 // Initialize the IP address pool
4955 static void initippool()
4960 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4962 if (!(f
= fopen(IPPOOLFILE
, "r")))
4964 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4968 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4971 buf
[4095] = 0; // Force it to be zero terminated/
4973 if (*buf
== '#' || *buf
== '\n')
4974 continue; // Skip comments / blank lines
4975 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4976 if ((p
= (char *)strchr(buf
, ':')))
4980 src
= inet_addr(buf
);
4981 if (src
== INADDR_NONE
)
4983 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4986 // This entry is for a specific IP only
4987 if (src
!= config
->bind_address
)
4992 if ((p
= (char *)strchr(pool
, '/')))
4996 in_addr_t start
= 0;
4998 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
5000 if (!*p
|| !(numbits
= atoi(p
)))
5002 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
5005 start
= ntohl(inet_addr(pool
));
5007 // Add a static route for this pool
5008 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
5009 fmtaddr(htonl(start
), 0), numbits
);
5011 routeset(0, start
, numbits
, 0, 1);
5013 add_to_ip_pool(start
, numbits
);
5017 // It's a single ip address
5018 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
5022 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
5025 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
5027 struct sockaddr_in snoop_addr
= {0};
5028 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
5031 snoop_addr
.sin_family
= AF_INET
;
5032 snoop_addr
.sin_addr
.s_addr
= destination
;
5033 snoop_addr
.sin_port
= ntohs(port
);
5035 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
5036 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
5037 htons(snoop_addr
.sin_port
));
5039 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
5040 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
5042 STAT(packets_snooped
);
5045 static int dump_session(FILE **f
, sessiont
*s
)
5047 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
5052 char filename
[1024];
5054 time_t now
= time(NULL
);
5056 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
5057 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
5059 if (!(*f
= fopen(filename
, "w")))
5061 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
5065 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
5066 if(config
->account_all_origin
)
5068 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5073 "# format: username ip qos uptxoctets downrxoctets origin(L=LAC, R=Remote LNS, P=PPPOE)\n",
5075 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5081 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5086 "# format: username ip qos uptxoctets downrxoctets\n",
5088 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5094 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
5095 if(config
->account_all_origin
)
5097 fprintf(*f
, "%s %s %d %u %u %s\n",
5098 s
->user
, // username
5099 fmtaddr(htonl(s
->ip
), 0), // ip
5100 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5101 (uint32_t) s
->cin_delta
, // uptxoctets
5102 (uint32_t) s
->cout_delta
, // downrxoctets
5103 (s
->tunnel
== TUNNEL_ID_PPPOE
)?"P":(tunnel
[s
->tunnel
].isremotelns
?"R":"L")); // Origin
5105 else if (!tunnel
[s
->tunnel
].isremotelns
&& (s
->tunnel
!= TUNNEL_ID_PPPOE
))
5107 fprintf(*f
, "%s %s %d %u %u\n",
5108 s
->user
, // username
5109 fmtaddr(htonl(s
->ip
), 0), // ip
5110 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5111 (uint32_t) s
->cin_delta
, // uptxoctets
5112 (uint32_t) s
->cout_delta
); // downrxoctets
5115 s
->cin_delta
= s
->cout_delta
= 0;
5120 static void dump_acct_info(int all
)
5126 CSTAT(dump_acct_info
);
5130 for (i
= 0; i
< shut_acct_n
; i
++)
5131 dump_session(&f
, &shut_acct
[i
]);
5137 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5138 dump_session(&f
, &session
[i
]);
5145 int main(int argc
, char *argv
[])
5149 char *optconfig
= CONFIGFILE
;
5151 time(&basetime
); // start clock
5154 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
5159 if (fork()) exit(0);
5161 if(!freopen("/dev/null", "r", stdin
)) LOG(0, 0, 0, "Error freopen stdin: %s\n", strerror(errno
));
5162 if(!freopen("/dev/null", "w", stdout
)) LOG(0, 0, 0, "Error freopen stdout: %s\n", strerror(errno
));
5163 if(!freopen("/dev/null", "w", stderr
)) LOG(0, 0, 0, "Error freopen stderr: %s\n", strerror(errno
));
5172 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
5175 printf("Args are:\n"
5176 "\t-d\t\tDetach from terminal\n"
5177 "\t-c <file>\tConfig file\n"
5178 "\t-h <hostname>\tForce hostname\n"
5186 // Start the timer routine off
5188 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5191 initdata(optdebug
, optconfig
);
5195 /* set hostname /after/ having read the config file */
5196 if (*config
->hostname
)
5197 strcpy(hostname
, config
->hostname
);
5198 cli_init_complete(hostname
);
5200 init_tbf(config
->num_tbfs
);
5202 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5203 LOG(0, 0, 0, "Copyright (c) 2012, 2013, 2014 ISP FDN & SAMESWIRELESS\n");
5204 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5205 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5208 rlim
.rlim_cur
= RLIM_INFINITY
;
5209 rlim
.rlim_max
= RLIM_INFINITY
;
5210 // Remove the maximum core size
5211 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5212 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5214 // Make core dumps go to /tmp
5215 if(chdir("/tmp")) LOG(0, 0, 0, "Error chdir /tmp: %s\n", strerror(errno
));
5218 if (config
->scheduler_fifo
)
5221 struct sched_param params
= {0};
5222 params
.sched_priority
= 1;
5224 if (get_nprocs() < 2)
5226 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5227 config
->scheduler_fifo
= 0;
5231 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5233 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5237 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5238 config
->scheduler_fifo
= 0;
5245 /* Set up the cluster communications port. */
5246 if (cluster_init() < 0)
5250 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5252 if (*config
->pppoe_if_to_bind
)
5255 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config
->pppoe_if_to_bind
);
5258 if (!config
->nbmultiaddress
)
5260 config
->bind_n_address
[0] = config
->bind_address
;
5261 config
->nbmultiaddress
++;
5263 config
->nbudpfd
= config
->nbmultiaddress
;
5264 for (i
= 0; i
< config
->nbudpfd
; i
++)
5265 initudp(&udpfd
[i
], config
->bind_n_address
[i
]);
5267 config
->indexlacudpfd
= config
->nbudpfd
;
5268 udpfd
[config
->indexlacudpfd
] = udplacfd
;
5275 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
5283 unsigned seed
= time_now
^ getpid();
5284 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5288 signal(SIGHUP
, sighup_handler
);
5289 signal(SIGCHLD
, sigchild_handler
);
5290 signal(SIGTERM
, shutdown_handler
);
5291 signal(SIGINT
, shutdown_handler
);
5292 signal(SIGQUIT
, shutdown_handler
);
5294 // Prevent us from getting paged out
5295 if (config
->lock_pages
)
5297 if (!mlockall(MCL_CURRENT
))
5298 LOG(1, 0, 0, "Locking pages into memory\n");
5300 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5303 //LOG(3, 0, 0, "Debug sizeof struct: sessiont %lu, tunnelt %lu, bundlet %lu, groupsesst %lu\n",
5304 // sizeof(sessiont), sizeof(tunnelt), sizeof(bundlet), sizeof(groupsesst));
5308 /* remove plugins (so cleanup code gets run) */
5311 // Remove the PID file if we wrote it
5312 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5313 unlink(config
->pid_file
);
5315 /* kill CLI children */
5316 signal(SIGTERM
, SIG_IGN
);
5321 static void sighup_handler(int sig
)
5326 static void shutdown_handler(int sig
)
5328 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5331 static void sigchild_handler(int sig
)
5333 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5337 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5340 *challenge_response
= NULL
;
5342 if (!*config
->l2tp_secret
)
5344 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5348 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5350 *challenge_response
= calloc(17, 1);
5353 MD5_Update(&ctx
, &id
, 1);
5354 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5355 MD5_Update(&ctx
, challenge
, challenge_length
);
5356 MD5_Final(*challenge_response
, &ctx
);
5361 static int facility_value(char *name
)
5364 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5366 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5367 return facilitynames
[i
].c_val
;
5372 static void update_config()
5376 static int timeout
= 0;
5377 static int interval
= 0;
5384 if (log_stream
!= stderr
)
5390 if (*config
->log_filename
)
5392 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5394 char *p
= config
->log_filename
+ 7;
5397 openlog("l2tpns", LOG_PID
, facility_value(p
));
5401 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5403 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5405 fseek(log_stream
, 0, SEEK_END
);
5406 setbuf(log_stream
, NULL
);
5410 log_stream
= stderr
;
5411 setbuf(log_stream
, NULL
);
5417 log_stream
= stderr
;
5418 setbuf(log_stream
, NULL
);
5421 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5422 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5424 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5425 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5426 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5428 // reset MRU/MSS globals
5429 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5430 if (MRU
> PPPoE_MRU
)
5433 MSS
= MRU
- TCP_HDRS
;
5436 config
->numradiusservers
= 0;
5437 for (i
= 0; i
< MAXRADSERVER
; i
++)
5438 if (config
->radiusserver
[i
])
5440 config
->numradiusservers
++;
5441 // Set radius port: if not set, take the port from the
5442 // first radius server. For the first radius server,
5443 // take the #defined default value from l2tpns.h
5445 // test twice, In case someone works with
5446 // a secondary radius server without defining
5447 // a primary one, this will work even then.
5448 if (i
> 0 && !config
->radiusport
[i
])
5449 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5450 if (!config
->radiusport
[i
])
5451 config
->radiusport
[i
] = RADPORT
;
5454 if (!config
->numradiusservers
)
5455 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5457 // parse radius_authtypes_s
5458 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5459 p
= config
->radius_authtypes_s
;
5462 char *s
= strpbrk(p
, " \t,");
5468 while (*s
== ' ' || *s
== '\t')
5475 if (!strncasecmp("chap", p
, strlen(p
)))
5477 else if (!strncasecmp("pap", p
, strlen(p
)))
5480 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5482 config
->radius_authtypes
|= type
;
5483 if (!config
->radius_authprefer
)
5484 config
->radius_authprefer
= type
;
5489 if (!config
->radius_authtypes
)
5491 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5492 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5495 // normalise radius_authtypes_s
5496 if (config
->radius_authprefer
== AUTHPAP
)
5498 strcpy(config
->radius_authtypes_s
, "pap");
5499 if (config
->radius_authtypes
& AUTHCHAP
)
5500 strcat(config
->radius_authtypes_s
, ", chap");
5504 strcpy(config
->radius_authtypes_s
, "chap");
5505 if (config
->radius_authtypes
& AUTHPAP
)
5506 strcat(config
->radius_authtypes_s
, ", pap");
5509 if (!config
->radius_dae_port
)
5510 config
->radius_dae_port
= DAEPORT
;
5512 if(!config
->bind_portremotelns
)
5513 config
->bind_portremotelns
= L2TPLACPORT
;
5514 if(!config
->bind_address_remotelns
)
5515 config
->bind_address_remotelns
= INADDR_ANY
;
5517 if (*config
->bind_multi_address
)
5519 char *sip
= config
->bind_multi_address
;
5521 char *e
= config
->bind_multi_address
+ strlen(config
->bind_multi_address
);
5522 config
->nbmultiaddress
= 0;
5524 while (*sip
&& (sip
< e
))
5529 while (n
< e
&& (*n
== ',' || *n
== ' ')) n
++;
5531 while (n
< e
&& (isdigit(*n
) || *n
== '.'))
5539 u
= u
* 10 + *n
- '0';
5547 config
->bind_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5548 config
->iftun_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5549 config
->nbmultiaddress
++;
5550 LOG(1, 0, 0, "Bind address %s\n", fmtaddr(htonl(ip
), 0));
5552 if (config
->nbmultiaddress
>= MAX_BINDADDR
) break;
5558 if (config
->nbmultiaddress
>= 1)
5560 config
->bind_address
= config
->bind_n_address
[0];
5561 config
->iftun_address
= config
->bind_address
;
5565 if(!config
->iftun_address
)
5567 config
->iftun_address
= config
->bind_address
;
5568 config
->iftun_n_address
[0] = config
->iftun_address
;
5571 if (*config
->multi_hostname
)
5573 char *shost
= config
->multi_hostname
;
5575 char *e
= config
->multi_hostname
+ strlen(config
->multi_hostname
);
5576 config
->nbmultihostname
= 0;
5578 while (*shost
&& (shost
< e
))
5580 while ((n
< e
) && (*n
== ' ' || *n
== ',' || *n
== '\t')) n
++;
5583 while (n
< e
&& (*n
!= ',') && (*n
!= '\t'))
5585 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = *n
;
5591 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = 0;
5592 LOG(1, 0, 0, "Bind Hostname %s\n", config
->multi_n_hostname
[config
->nbmultihostname
]);
5593 config
->nbmultihostname
++;
5594 if (config
->nbmultihostname
>= MAX_NBHOSTNAME
) break;
5600 if (config
->nbmultihostname
>= 1)
5602 strcpy(hostname
, config
->multi_n_hostname
[0]);
5603 strcpy(config
->hostname
, hostname
);
5607 if (!*config
->pppoe_ac_name
)
5608 strncpy(config
->pppoe_ac_name
, DEFAULT_PPPOE_AC_NAME
, sizeof(config
->pppoe_ac_name
) - 1);
5610 // re-initialise the random number source
5611 initrandom(config
->random_device
);
5614 for (i
= 0; i
< MAXPLUGINS
; i
++)
5616 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5619 if (*config
->plugins
[i
])
5622 add_plugin(config
->plugins
[i
]);
5624 else if (*config
->old_plugins
[i
])
5627 remove_plugin(config
->old_plugins
[i
]);
5632 guest_accounts_num
= 0;
5633 char *p2
= config
->guest_user
;
5636 char *s
= strpbrk(p2
, " \t,");
5640 while (*s
== ' ' || *s
== '\t')
5647 strcpy(guest_users
[guest_accounts_num
], p2
);
5648 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5649 guest_accounts_num
++;
5652 // Rebuild the guest_user array
5653 strcpy(config
->guest_user
, "");
5655 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5657 strcat(config
->guest_user
, guest_users
[ui
]);
5658 if (ui
<guest_accounts_num
-1)
5660 strcat(config
->guest_user
, ",");
5665 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5666 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5667 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5668 if (!*config
->cluster_interface
)
5669 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5671 if (!config
->cluster_hb_interval
)
5672 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5674 if (!config
->cluster_hb_timeout
)
5675 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5677 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5679 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5680 // late, ensure we're sufficiently larger than that
5681 int t
= 4 * config
->cluster_hb_interval
+ 11;
5683 if (config
->cluster_hb_timeout
< t
)
5685 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5686 config
->cluster_hb_timeout
= t
;
5689 // Push timing changes to the slaves immediately if we're the master
5690 if (config
->cluster_iam_master
)
5691 cluster_heartbeat();
5693 interval
= config
->cluster_hb_interval
;
5694 timeout
= config
->cluster_hb_timeout
;
5698 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5701 if ((f
= fopen(config
->pid_file
, "w")))
5703 fprintf(f
, "%d\n", getpid());
5705 config
->wrote_pid
= 1;
5709 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5714 static void read_config_file()
5718 if (!config
->config_file
) return;
5719 if (!(f
= fopen(config
->config_file
, "r")))
5721 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5725 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5727 LOG(3, 0, 0, "Done reading config file\n");
5731 int sessionsetup(sessionidt s
, tunnelidt t
)
5733 // A session now exists, set it up
5739 CSTAT(sessionsetup
);
5741 LOG(3, s
, t
, "Doing session setup for session\n");
5743 // Join a bundle if the MRRU option is accepted
5744 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5746 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5747 if (join_bundle(s
) > 0)
5748 cluster_send_bundle(session
[s
].bundle
);
5751 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5752 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5759 assign_ip_address(s
);
5762 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5763 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5766 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5767 fmtaddr(htonl(session
[s
].ip
), 0));
5770 // Make sure this is right
5771 session
[s
].tunnel
= t
;
5773 // zap old sessions with same IP and/or username
5774 // Don't kill gardened sessions - doing so leads to a DoS
5775 // from someone who doesn't need to know the password
5778 user
= session
[s
].user
;
5779 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5781 if (i
== s
) continue;
5782 if (!session
[s
].opened
) break;
5783 // Allow duplicate sessions for multilink ones of the same bundle.
5784 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5786 if (ip
== session
[i
].ip
)
5788 sessionshutdown(i
, "Duplicate IP address", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5792 if (config
->allow_duplicate_users
) continue;
5793 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5797 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5799 if (!strcasecmp(user
, guest_users
[gu
]))
5805 if (found
) continue;
5807 // Drop the new session in case of duplicate sessionss, not the old one.
5808 if (!strcasecmp(user
, session
[i
].user
))
5809 sessionshutdown(i
, "Duplicate session for users", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5813 // no need to set a route for the same IP address of the bundle
5814 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5819 // Add the route for this session.
5820 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5822 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5823 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5826 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5829 // Static IPs need to be routed if not already
5830 // convered by a Framed-Route. Anything else is part
5831 // of the IP address pool and is already routed, it
5832 // just needs to be added to the IP cache.
5833 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5834 if (session
[s
].ip_pool_index
== -1) // static ip
5836 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5839 cache_ipmap(session
[s
].ip
, s
);
5841 if ((g
= grp_groupbysession(s
)))
5843 grp_setgrouproute(g
, 1);
5844 cluster_send_groupe(g
);
5848 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5849 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5851 // Run the plugin's against this new session.
5853 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5854 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5857 // Allocate TBFs if throttled
5858 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5859 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5861 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5863 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5864 fmtaddr(htonl(session
[s
].ip
), 0),
5865 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5867 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5869 return 1; // RADIUS OK and IP allocated, done...
5873 // This session just got dropped on us by the master or something.
5874 // Make sure our tables up up to date...
5876 int load_session(sessionidt s
, sessiont
*new)
5882 if (new->ip_pool_index
>= MAXIPPOOL
||
5883 new->tunnel
>= MAXTUNNEL
)
5885 LOG(0, s
, 0, "Strange session update received!\n");
5886 // FIXME! What to do here?
5891 // Ok. All sanity checks passed. Now we're committed to
5892 // loading the new session.
5895 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5897 // See if routes/ip cache need updating
5898 if (new->ip
!= session
[s
].ip
)
5901 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5902 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5903 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5911 // remove old routes...
5912 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5914 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5915 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5918 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5924 if (session
[s
].ip_pool_index
== -1) // static IP
5926 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5928 else // It's part of the IP pool, remove it manually.
5929 uncache_ipmap(session
[s
].ip
);
5932 // remove old IPV6 routes...
5933 for (i
= 0; i
< MAXROUTE6
&& session
[s
].route6
[i
].ipv6route
.s6_addr
[0] && session
[s
].route6
[i
].ipv6prefixlen
; i
++)
5935 route6set(s
, session
[s
].route6
[i
].ipv6route
, session
[s
].route6
[i
].ipv6prefixlen
, 0);
5938 if (session
[s
].ipv6address
.s6_addr
[0])
5940 route6set(s
, session
[s
].ipv6address
, 128, 0);
5945 // add new routes...
5946 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5948 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5949 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5952 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5958 // If there's a new one, add it.
5959 if (new->ip_pool_index
== -1)
5961 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5964 cache_ipmap(new->ip
, s
);
5969 if (new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5971 for (i
= 0; i
< MAXROUTE6
&& new->route6
[i
].ipv6prefixlen
; i
++)
5973 route6set(s
, new->route6
[i
].ipv6route
, new->route6
[i
].ipv6prefixlen
, 1);
5977 if (new->ipv6address
.s6_addr
[0] && new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5979 // Check if included in prefix
5980 if (sessionbyipv6(new->ipv6address
) != s
)
5981 route6set(s
, new->ipv6address
, 128, 1);
5985 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5987 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5991 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5993 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5994 new->filter_out
= 0;
5997 if (new->filter_in
!= session
[s
].filter_in
)
5999 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
6000 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
6003 if (new->filter_out
!= session
[s
].filter_out
)
6005 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
6006 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
6009 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
6010 // for walking the sessions to forward byte counts to the master.
6011 config
->cluster_highest_sessionid
= s
;
6013 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
6015 // Do fixups into address pool.
6016 if (new->ip_pool_index
!= -1)
6017 fix_address_pool(s
);
6022 static void initplugins()
6026 loaded_plugins
= ll_init();
6027 // Initialize the plugins to nothing
6028 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
6029 plugins
[i
] = ll_init();
6032 static void *open_plugin(char *plugin_name
, int load
)
6034 char path
[256] = "";
6036 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
6037 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
6038 return dlopen(path
, RTLD_NOW
);
6041 // plugin callback to get a config value
6042 static void *getconfig(char *key
, enum config_typet type
)
6046 for (i
= 0; config_values
[i
].key
; i
++)
6048 if (!strcmp(config_values
[i
].key
, key
))
6050 if (config_values
[i
].type
== type
)
6051 return ((void *) config
) + config_values
[i
].offset
;
6053 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
6054 key
, type
, config_values
[i
].type
);
6060 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
6064 static int add_plugin(char *plugin_name
)
6066 static struct pluginfuncs funcs
= {
6071 sessiontbysessionidt
,
6072 sessionidtbysessiont
,
6079 cluster_send_session
,
6082 void *p
= open_plugin(plugin_name
, 1);
6083 int (*initfunc
)(struct pluginfuncs
*);
6088 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
6092 if (ll_contains(loaded_plugins
, p
))
6095 return 0; // already loaded
6099 int *v
= dlsym(p
, "plugin_api_version");
6100 if (!v
|| *v
!= PLUGIN_API_VERSION
)
6102 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
6108 if ((initfunc
= dlsym(p
, "plugin_init")))
6110 if (!initfunc(&funcs
))
6112 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
6118 ll_push(loaded_plugins
, p
);
6120 for (i
= 0; i
< max_plugin_functions
; i
++)
6123 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6125 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
6126 ll_push(plugins
[i
], x
);
6130 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
6134 static void run_plugin_done(void *plugin
)
6136 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
6142 static int remove_plugin(char *plugin_name
)
6144 void *p
= open_plugin(plugin_name
, 0);
6150 if (ll_contains(loaded_plugins
, p
))
6153 for (i
= 0; i
< max_plugin_functions
; i
++)
6156 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6157 ll_delete(plugins
[i
], x
);
6160 ll_delete(loaded_plugins
, p
);
6166 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
6170 int run_plugins(int plugin_type
, void *data
)
6172 int (*func
)(void *data
);
6174 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
6175 return PLUGIN_RET_ERROR
;
6177 ll_reset(plugins
[plugin_type
]);
6178 while ((func
= ll_next(plugins
[plugin_type
])))
6182 if (r
!= PLUGIN_RET_OK
)
6183 return r
; // stop here
6186 return PLUGIN_RET_OK
;
6189 static void plugins_done()
6193 ll_reset(loaded_plugins
);
6194 while ((p
= ll_next(loaded_plugins
)))
6198 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
6200 struct nsctl request
;
6201 struct nsctl response
;
6202 int type
= unpack_control(&request
, buf
, len
);
6206 if (log_stream
&& config
->debug
>= 4)
6210 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6211 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
6215 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6216 dump_control(&request
, log_stream
);
6222 case NSCTL_REQ_LOAD
:
6223 if (request
.argc
!= 1)
6225 response
.type
= NSCTL_RES_ERR
;
6227 response
.argv
[0] = "name of plugin required";
6229 else if ((r
= add_plugin(request
.argv
[0])) < 1)
6231 response
.type
= NSCTL_RES_ERR
;
6233 response
.argv
[0] = !r
6234 ? "plugin already loaded"
6235 : "error loading plugin";
6239 response
.type
= NSCTL_RES_OK
;
6245 case NSCTL_REQ_UNLOAD
:
6246 if (request
.argc
!= 1)
6248 response
.type
= NSCTL_RES_ERR
;
6250 response
.argv
[0] = "name of plugin required";
6252 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
6254 response
.type
= NSCTL_RES_ERR
;
6256 response
.argv
[0] = !r
6257 ? "plugin not loaded"
6258 : "plugin not found";
6262 response
.type
= NSCTL_RES_OK
;
6268 case NSCTL_REQ_HELP
:
6269 response
.type
= NSCTL_RES_OK
;
6272 ll_reset(loaded_plugins
);
6273 while ((p
= ll_next(loaded_plugins
)))
6275 char **help
= dlsym(p
, "plugin_control_help");
6276 while (response
.argc
< 0xff && help
&& *help
)
6277 response
.argv
[response
.argc
++] = *help
++;
6282 case NSCTL_REQ_CONTROL
:
6284 struct param_control param
= {
6285 config
->cluster_iam_master
,
6292 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
6294 if (r
== PLUGIN_RET_ERROR
)
6296 response
.type
= NSCTL_RES_ERR
;
6298 response
.argv
[0] = param
.additional
6300 : "error returned by plugin";
6302 else if (r
== PLUGIN_RET_NOTMASTER
)
6304 static char msg
[] = "must be run on master: 000.000.000.000";
6306 response
.type
= NSCTL_RES_ERR
;
6308 if (config
->cluster_master_address
)
6310 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
6311 response
.argv
[0] = msg
;
6315 response
.argv
[0] = "must be run on master: none elected";
6318 else if (!(param
.response
& NSCTL_RESPONSE
))
6320 response
.type
= NSCTL_RES_ERR
;
6322 response
.argv
[0] = param
.response
6323 ? "unrecognised response value from plugin"
6324 : "unhandled action";
6328 response
.type
= param
.response
;
6330 if (param
.additional
)
6333 response
.argv
[0] = param
.additional
;
6341 response
.type
= NSCTL_RES_ERR
;
6343 response
.argv
[0] = "error unpacking control packet";
6346 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6349 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6353 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6356 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6357 if (log_stream
&& config
->debug
>= 4)
6359 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6360 dump_control(&response
, log_stream
);
6364 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6365 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6370 static tunnelidt
new_tunnel()
6373 for (i
= 1; i
< MAXTUNNEL
; i
++)
6375 if ((tunnel
[i
].state
== TUNNELFREE
) && (i
!= TUNNEL_ID_PPPOE
))
6377 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6378 if (i
> config
->cluster_highest_tunnelid
)
6379 config
->cluster_highest_tunnelid
= i
;
6383 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6388 // We're becoming the master. Do any required setup..
6390 // This is principally telling all the plugins that we're
6391 // now a master, and telling them about all the sessions
6392 // that are active too..
6394 void become_master(void)
6397 static struct event_data d
[RADIUS_FDS
];
6398 struct epoll_event e
;
6400 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6402 // running a bunch of iptables commands is slow and can cause
6403 // the master to drop tunnels on takeover--kludge around the
6404 // problem by forking for the moment (note: race)
6405 if (!fork_and_close())
6407 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6409 if (!session
[s
].opened
) // Not an in-use session.
6412 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6419 for (i
= 0; i
< RADIUS_FDS
; i
++)
6421 d
[i
].type
= FD_TYPE_RADIUS
;
6425 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6429 int cmd_show_hist_idle(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6435 if (CLI_HELP_REQUESTED
)
6436 return CLI_HELP_NO_ARGS
;
6439 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6441 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6444 if (!session
[s
].opened
)
6447 idle
= time_now
- session
[s
].last_data
;
6448 idle
/= 5 ; // In multiples of 5 seconds.
6458 for (i
= 0; i
< 63; ++i
)
6460 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6462 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6463 cli_print(cli
, "%d total sessions open.", count
);
6467 int cmd_show_hist_open(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6473 if (CLI_HELP_REQUESTED
)
6474 return CLI_HELP_NO_ARGS
;
6477 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6479 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6482 if (!session
[s
].opened
)
6485 d
= time_now
- session
[s
].opened
;
6488 while (d
> 1 && open
< 32)
6498 for (i
= 0; i
< 30; ++i
)
6500 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6503 cli_print(cli
, "%d total sessions open.", count
);
6509 * This unencodes the AVP using the L2TP secret and the previously
6510 * stored random vector. It overwrites the hidden data with the
6511 * unhidden AVP subformat.
6513 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6519 uint16_t m
= htons(type
);
6521 // Compute initial pad
6523 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6524 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6525 MD5_Update(&ctx
, vector
, vec_len
);
6526 MD5_Final(digest
, &ctx
);
6528 // pointer to last decoded 16 octets
6533 // calculate a new pad based on the last decoded block
6534 if (d
>= sizeof(digest
))
6537 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6538 MD5_Update(&ctx
, last
, sizeof(digest
));
6539 MD5_Final(digest
, &ctx
);
6545 *value
++ ^= digest
[d
++];
6550 int find_filter(char const *name
, size_t len
)
6555 for (i
= 0; i
< MAXFILTER
; i
++)
6557 if (!*ip_filters
[i
].name
)
6565 if (strlen(ip_filters
[i
].name
) != len
)
6568 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6575 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6579 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6580 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6581 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6582 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6583 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6589 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6593 case FILTER_FLAG_OP_ANY
:
6594 return (flags
& sflags
) || (~flags
& cflags
);
6596 case FILTER_FLAG_OP_ALL
:
6597 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6599 case FILTER_FLAG_OP_EST
:
6600 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6606 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6608 uint16_t frag_offset
;
6612 uint16_t src_port
= 0;
6613 uint16_t dst_port
= 0;
6615 ip_filter_rulet
*rule
;
6617 if (len
< 20) // up to end of destination address
6620 if ((*buf
>> 4) != 4) // IPv4
6623 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6625 src_ip
= *(in_addr_t
*) (buf
+ 12);
6626 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6628 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6630 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6631 if (len
< l
+ 4) // ports
6634 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6635 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6636 if (proto
== IPPROTO_TCP
)
6638 if (len
< l
+ 14) // flags
6641 flags
= buf
[l
+ 13] & 0x3f;
6645 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6647 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6650 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6651 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6654 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6655 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6660 // layer 4 deny rules are skipped
6661 if (rule
->action
== FILTER_ACTION_DENY
&&
6662 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6670 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6672 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6675 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6678 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6679 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6686 return rule
->action
== FILTER_ACTION_PERMIT
;
6693 tunnelidt
lac_new_tunnel()
6695 return new_tunnel();
6698 void lac_tunnelclear(tunnelidt t
)
6703 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6705 uint16_t version
= 0x0100; // protocol version
6707 tunnel
[t
].state
= TUNNELOPENING
;
6709 // Sent SCCRQ - Start Control Connection Request
6710 controlt
*c
= controlnew(1); // sending SCCRQ
6711 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
6712 controls(c
, 8, Vendor_name
, 1); // Vendor name
6713 control16(c
, 2, version
, 1); // protocol version
6714 control32(c
, 3, 3, 1); // framing Capabilities
6715 control16(c
, 9, t
, 1); // assigned tunnel
6716 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6717 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6718 controladd(c
, 0, t
); // send
6721 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6723 // Sent ICRQ Incoming-call-request
6724 controlt
*c
= controlnew(10); // ICRQ
6726 control16(c
, 14, s
, 1); // assigned sesion
6727 call_serial_number
++;
6728 control32(c
, 15, call_serial_number
, 1); // call serial number
6729 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6730 controladd(c
, 0, t
); // send
6733 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6735 tunnelshutdown(t
, reason
, result
, error
, msg
);