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
97 union iphash ip_hash
[256]; // Mapping from IP address to session structures.
101 struct ipv6radix
*branch
;
102 } ipv6_hash
[16]; // Mapping from IPv6 address to session structures.
105 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
106 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
109 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
110 time_t time_now
= 0; // Current time in seconds since epoch.
111 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
112 static char time_now_string
[64] = {0}; // Current time as a string.
113 static int time_changed
= 0; // time_now changed
114 char main_quit
= 0; // True if we're in the process of exiting.
115 static char main_reload
= 0; // Re-load pending
116 linked_list
*loaded_plugins
;
117 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
119 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
120 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
122 config_descriptt config_values
[] = {
123 CONFIG("debug", debug
, INT
),
124 CONFIG("log_file", log_filename
, STRING
),
125 CONFIG("pid_file", pid_file
, STRING
),
126 CONFIG("random_device", random_device
, STRING
),
127 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
128 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
129 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
130 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
131 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
132 CONFIG("primary_dns", default_dns1
, IPv4
),
133 CONFIG("secondary_dns", default_dns2
, IPv4
),
134 CONFIG("primary_radius", radiusserver
[0], IPv4
),
135 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
136 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
137 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
138 CONFIG("radius_accounting", radius_accounting
, BOOL
),
139 CONFIG("radius_interim", radius_interim
, INT
),
140 CONFIG("radius_secret", radiussecret
, STRING
),
141 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
142 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
143 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
144 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
145 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
146 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
147 CONFIG("guest_account", guest_user
, STRING
),
148 CONFIG("bind_address", bind_address
, IPv4
),
149 CONFIG("peer_address", peer_address
, IPv4
),
150 CONFIG("send_garp", send_garp
, BOOL
),
151 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
152 CONFIG("throttle_buckets", num_tbfs
, INT
),
153 CONFIG("accounting_dir", accounting_dir
, STRING
),
154 CONFIG("account_all_origin", account_all_origin
, BOOL
),
155 CONFIG("dump_speed", dump_speed
, BOOL
),
156 CONFIG("multi_read_count", multi_read_count
, INT
),
157 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
158 CONFIG("lock_pages", lock_pages
, BOOL
),
159 CONFIG("icmp_rate", icmp_rate
, INT
),
160 CONFIG("packet_limit", max_packets
, INT
),
161 CONFIG("cluster_address", cluster_address
, IPv4
),
162 CONFIG("cluster_interface", cluster_interface
, STRING
),
163 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
164 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
165 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
166 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
167 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
168 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
169 CONFIG("hostname", hostname
, STRING
),
171 CONFIG("nexthop_address", nexthop_address
, IPv4
),
172 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
174 CONFIG("echo_timeout", echo_timeout
, INT
),
175 CONFIG("idle_echo_timeout", idle_echo_timeout
, INT
),
176 CONFIG("iftun_address", iftun_address
, IPv4
),
177 CONFIG("tundevicename", tundevicename
, STRING
),
178 CONFIG("disable_lac_func", disable_lac_func
, BOOL
),
179 CONFIG("auth_tunnel_change_addr_src", auth_tunnel_change_addr_src
, BOOL
),
180 CONFIG("bind_address_remotelns", bind_address_remotelns
, IPv4
),
181 CONFIG("bind_portremotelns", bind_portremotelns
, SHORT
),
182 CONFIG("pppoe_if_to_bind", pppoe_if_to_bind
, STRING
),
183 CONFIG("pppoe_service_name", pppoe_service_name
, STRING
),
184 CONFIG("pppoe_ac_name", pppoe_ac_name
, STRING
),
185 CONFIG("disable_sending_hello", disable_sending_hello
, BOOL
),
186 CONFIG("disable_no_spoof", disable_no_spoof
, BOOL
),
187 CONFIG("bind_multi_address", bind_multi_address
, STRING
),
188 CONFIG("grp_txrate_average_time", grp_txrate_average_time
, INT
),
189 CONFIG("pppoe_only_equal_svc_name", pppoe_only_equal_svc_name
, BOOL
),
190 CONFIG("multi_hostname", multi_hostname
, STRING
),
191 CONFIG("no_throttle_local_IP", no_throttle_local_IP
, BOOL
),
192 CONFIG("dhcp6_preferred_lifetime", dhcp6_preferred_lifetime
, INT
),
193 CONFIG("dhcp6_valid_lifetime", dhcp6_valid_lifetime
, INT
),
194 CONFIG("dhcp6_server_duid", dhcp6_server_duid
, INT
),
195 CONFIG("primary_ipv6_dns", default_ipv6_dns1
, IPv6
),
196 CONFIG("secondary_ipv6_dns", default_ipv6_dns2
, IPv6
),
197 CONFIG("default_ipv6_domain_list", default_ipv6_domain_list
, STRING
),
201 static char *plugin_functions
[] = {
206 "plugin_new_session",
207 "plugin_kill_session",
209 "plugin_radius_response",
210 "plugin_radius_reset",
211 "plugin_radius_account",
212 "plugin_become_master",
213 "plugin_new_session_master",
216 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
218 // Counters for shutdown sessions
219 static sessiont shut_acct
[8192];
220 static sessionidt shut_acct_n
= 0;
222 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
223 bundlet
*bundle
= NULL
; // Array of bundle structures.
224 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
225 sessiont
*session
= NULL
; // Array of session structures.
226 groupsesst
*grpsession
= NULL
; // Array of groupsesst structures.
227 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
228 radiust
*radius
= NULL
; // Array of radius structures.
229 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
230 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
231 static controlt
*controlfree
= 0;
232 struct Tstats
*_statistics
= NULL
;
234 struct Tringbuffer
*ringbuffer
= NULL
;
237 static void uncache_ipmap(in_addr_t ip
);
238 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
239 static void free_ip_address(sessionidt s
);
240 static void dump_acct_info(int all
);
241 static void sighup_handler(int sig
);
242 static void shutdown_handler(int sig
);
243 static void sigchild_handler(int sig
);
244 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
245 static void update_config(void);
246 static void read_config_file(void);
247 static void initplugins(void);
248 static int add_plugin(char *plugin_name
);
249 static int remove_plugin(char *plugin_name
);
250 static void plugins_done(void);
251 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
252 static tunnelidt
new_tunnel(void);
253 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
254 static void bundleclear(bundleidt b
);
256 // return internal time (10ths since process startup), set f if given
257 // as a side-effect sets time_now, and time_changed
258 static clockt
now(double *f
)
262 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
263 if (t
.tv_sec
!= time_now
)
270 // Time in milliseconds
271 // TODO FOR MLPPP DEV
272 //time_now_ms = (t.tv_sec * 1000) + (t.tv_usec/1000);
274 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
277 // work out a retry time based on try number
278 // This is a straight bounded exponential backoff.
279 // Maximum re-try time is 32 seconds. (2^5).
280 clockt
backoff(uint8_t try)
282 if (try > 5) try = 5; // max backoff
283 return now(NULL
) + 10 * (1 << try);
288 // Log a debug message. Typically called via the LOG macro
290 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
292 static char message
[65536] = {0};
298 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
299 ringbuffer
->tail
= 0;
300 if (ringbuffer
->tail
== ringbuffer
->head
)
301 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
302 ringbuffer
->head
= 0;
304 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
305 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
306 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
307 va_start(ap
, format
);
308 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, MAX_LOG_LENGTH
, format
, ap
);
313 if (config
->debug
< level
) return;
315 va_start(ap
, format
);
316 vsnprintf(message
, sizeof(message
), format
, ap
);
319 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
321 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
326 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
329 const uint8_t *d
= data
;
331 if (config
->debug
< level
) return;
333 // No support for _log_hex to syslog
336 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
337 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
339 for (i
= 0; i
< maxsize
; )
341 fprintf(log_stream
, "%4X: ", i
);
342 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
344 fprintf(log_stream
, "%02X ", d
[j
]);
346 fputs(": ", log_stream
);
349 for (; j
< i
+ 16; j
++)
351 fputs(" ", log_stream
);
353 fputs(": ", log_stream
);
356 fputs(" ", log_stream
);
357 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
359 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
360 fputc(d
[j
], log_stream
);
362 fputc('.', log_stream
);
365 fputs(" ", log_stream
);
369 fputs("\n", log_stream
);
373 setbuf(log_stream
, NULL
);
377 // update a counter, accumulating 2^32 wraps
378 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
380 uint32_t new = *counter
+ delta
;
387 // initialise the random generator
388 static void initrandom(char *source
)
390 static char path
[sizeof(config
->random_device
)] = "*undefined*";
392 // reinitialise only if we are forced to do so or if the config has changed
393 if (source
&& !strncmp(path
, source
, sizeof(path
)))
396 // close previous source, if any
405 snprintf(path
, sizeof(path
), "%s", source
);
409 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
411 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
412 path
, strerror(errno
));
417 // fill buffer with random data
418 void random_data(uint8_t *buf
, int len
)
425 n
= read(rand_fd
, buf
, len
);
426 if (n
>= len
) return;
431 LOG(0, 0, 0, "Error reading from random source: %s\n",
434 // fall back to rand()
442 // append missing data
444 // not using the low order bits from the prng stream
445 buf
[n
++] = (rand() >> 4) & 0xff;
450 // This adds it to the routing table, advertises it
451 // via BGP if enabled, and stuffs it into the
452 // 'sessionbyip' cache.
454 // 'ip' must be in _host_ order.
456 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
466 if (!prefixlen
) prefixlen
= 32;
468 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
470 memset(&req
, 0, sizeof(req
));
474 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
475 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
479 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
480 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
483 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
485 req
.rt
.rtm_family
= AF_INET
;
486 req
.rt
.rtm_dst_len
= prefixlen
;
487 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
488 req
.rt
.rtm_protocol
= 42;
489 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
490 req
.rt
.rtm_type
= RTN_UNICAST
;
492 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
494 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
498 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
501 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
502 fmtaddr(htonl(ip
), 0), prefixlen
,
503 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
505 if (netlink_send(&req
.nh
) < 0)
506 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
510 bgp_add_route(htonl(ip
), prefixlen
);
512 bgp_del_route(htonl(ip
), prefixlen
);
515 // Add/Remove the IPs to the 'sessionbyip' cache.
516 // Note that we add the zero address in the case of
517 // a network route. Roll on CIDR.
519 // Note that 's == 0' implies this is the address pool.
520 // We still cache it here, because it will pre-fill
521 // the malloc'ed tree.
525 if (!add
) // Are we deleting a route?
526 s
= 0; // Caching the session as '0' is the same as uncaching.
528 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
533 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
541 char ipv6addr
[INET6_ADDRSTRLEN
];
543 if (!config
->ipv6_prefix
.s6_addr
[0])
545 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
549 memset(&req
, 0, sizeof(req
));
553 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
554 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
558 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
559 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
562 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
564 req
.rt
.rtm_family
= AF_INET6
;
565 req
.rt
.rtm_dst_len
= prefixlen
;
566 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
567 req
.rt
.rtm_protocol
= 42;
568 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
569 req
.rt
.rtm_type
= RTN_UNICAST
;
571 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
572 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
574 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
576 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
578 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
581 if (netlink_send(&req
.nh
) < 0)
582 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
586 bgp_add_route6(ip
, prefixlen
);
588 bgp_del_route6(ip
, prefixlen
);
593 if (!add
) // Are we deleting a route?
594 s
= 0; // Caching the session as '0' is the same as uncaching.
596 cache_ipv6map(ip
, prefixlen
, s
);
603 // Set up netlink socket
604 static void initnetlink(void)
606 struct sockaddr_nl nladdr
;
608 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
611 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
615 memset(&nladdr
, 0, sizeof(nladdr
));
616 nladdr
.nl_family
= AF_NETLINK
;
617 nladdr
.nl_pid
= getpid();
619 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
621 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
626 ssize_t
netlink_send(struct nlmsghdr
*nh
)
628 struct sockaddr_nl nladdr
;
632 nh
->nlmsg_pid
= getpid();
633 nh
->nlmsg_seq
= ++nlseqnum
;
635 // set kernel address
636 memset(&nladdr
, 0, sizeof(nladdr
));
637 nladdr
.nl_family
= AF_NETLINK
;
639 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
640 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
642 return sendmsg(nlfd
, &msg
, 0);
645 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
647 struct sockaddr_nl nladdr
;
651 // set kernel address
652 memset(&nladdr
, 0, sizeof(nladdr
));
653 nladdr
.nl_family
= AF_NETLINK
;
655 iov
= (struct iovec
){ buf
, len
};
656 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
658 return recvmsg(nlfd
, &msg
, 0);
661 /* adapted from iproute2 */
662 void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
664 int len
= RTA_LENGTH(alen
);
667 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
668 rta
->rta_type
= type
;
670 memcpy(RTA_DATA(rta
), data
, alen
);
671 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
674 // messages corresponding to different phases seq number
675 static char *tun_nl_phase_msg
[] = {
677 "getting tun interface index",
678 "setting tun interface parameters",
679 "setting tun IPv4 address",
680 "setting tun LL IPv6 address",
681 "setting tun global IPv6 address",
685 // Set up TUN interface
686 static void inittun(void)
690 memset(&ifr
, 0, sizeof(ifr
));
691 ifr
.ifr_flags
= IFF_TUN
;
693 tunfd
= open(TUNDEVICE
, O_RDWR
);
696 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
700 int flags
= fcntl(tunfd
, F_GETFL
, 0);
701 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
704 if (*config
->tundevicename
)
705 strncpy(ifr
.ifr_name
, config
->tundevicename
, IFNAMSIZ
);
707 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
709 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
712 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevicename
) - 1);
713 strncpy(config
->tundevicename
, ifr
.ifr_name
, sizeof(config
->tundevicename
));
715 tunidx
= if_nametoindex(config
->tundevicename
);
718 LOG(0, 0, 0, "Can't get tun interface index\n");
727 struct ifinfomsg ifinfo
;
728 struct ifaddrmsg ifaddr
;
730 char rtdata
[32]; // 32 should be enough
732 uint32_t txqlen
, mtu
;
735 memset(&req
, 0, sizeof(req
));
737 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
738 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
739 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
741 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
742 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
743 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
744 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
746 /* Bump up the qlen to deal with bursts from the network */
748 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
749 /* set MTU to modem MRU */
751 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
753 if (netlink_send(&req
.nh
) < 0)
756 memset(&req
, 0, sizeof(req
));
758 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
759 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
760 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
762 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
763 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
764 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
765 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
767 if (config
->nbmultiaddress
> 1)
770 for (i
= 0; i
< config
->nbmultiaddress
; i
++)
772 ip
= config
->iftun_n_address
[i
];
773 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
774 if (netlink_send(&req
.nh
) < 0)
780 if (config
->iftun_address
)
781 ip
= config
->iftun_address
;
783 ip
= 0x01010101; // 1.1.1.1
784 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
786 if (netlink_send(&req
.nh
) < 0)
792 // Only setup IPv6 on the tun device if we have a configured prefix
793 if (config
->ipv6_prefix
.s6_addr
[0]) {
796 memset(&req
, 0, sizeof(req
));
798 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
799 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
800 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
802 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
803 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
804 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
805 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
807 // Link local address is FE80::1
808 memset(&ip6
, 0, sizeof(ip6
));
809 ip6
.s6_addr
[0] = 0xFE;
810 ip6
.s6_addr
[1] = 0x80;
812 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
814 if (netlink_send(&req
.nh
) < 0)
817 memset(&req
, 0, sizeof(req
));
819 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
820 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
821 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
823 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
824 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
825 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
826 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
828 // Global address is prefix::1
829 ip6
= config
->ipv6_prefix
;
831 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
833 if (netlink_send(&req
.nh
) < 0)
837 memset(&req
, 0, sizeof(req
));
839 req
.nh
.nlmsg_type
= NLMSG_DONE
;
840 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
842 if (netlink_send(&req
.nh
) < 0)
845 // if we get an error for seqnum < min_initok_nlseqnum,
846 // we must exit as initialization went wrong
847 if (config
->ipv6_prefix
.s6_addr
[0])
848 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
850 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
856 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
860 // set up LAC UDP ports
861 static void initlacudp(void)
864 struct sockaddr_in addr
;
866 // Tunnel to Remote LNS
867 memset(&addr
, 0, sizeof(addr
));
868 addr
.sin_family
= AF_INET
;
869 addr
.sin_port
= htons(config
->bind_portremotelns
);
870 addr
.sin_addr
.s_addr
= config
->bind_address_remotelns
;
871 udplacfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
872 setsockopt(udplacfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
874 int flags
= fcntl(udplacfd
, F_GETFL
, 0);
875 fcntl(udplacfd
, F_SETFL
, flags
| O_NONBLOCK
);
877 if (bind(udplacfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
879 LOG(0, 0, 0, "Error in UDP REMOTE LNS bind: %s\n", strerror(errno
));
884 // set up control ports
885 static void initcontrol(void)
888 struct sockaddr_in addr
;
891 memset(&addr
, 0, sizeof(addr
));
892 addr
.sin_family
= AF_INET
;
893 addr
.sin_port
= htons(NSCTL_PORT
);
894 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
895 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
896 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
897 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
899 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
904 // set up Dynamic Authorization Extensions to RADIUS port
905 static void initdae(void)
908 struct sockaddr_in addr
;
910 // Dynamic Authorization Extensions to RADIUS
911 memset(&addr
, 0, sizeof(addr
));
912 addr
.sin_family
= AF_INET
;
913 addr
.sin_port
= htons(config
->radius_dae_port
);
914 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
915 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
916 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
917 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
919 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
925 static void initudp(int * pudpfd
, in_addr_t ip_bind
)
928 struct sockaddr_in addr
;
931 memset(&addr
, 0, sizeof(addr
));
932 addr
.sin_family
= AF_INET
;
933 addr
.sin_port
= htons(L2TPPORT
);
934 addr
.sin_addr
.s_addr
= ip_bind
;
935 (*pudpfd
) = socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
936 setsockopt((*pudpfd
), SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
938 int flags
= fcntl((*pudpfd
), F_GETFL
, 0);
939 fcntl((*pudpfd
), F_SETFL
, flags
| O_NONBLOCK
);
941 if (bind((*pudpfd
), (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
943 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
949 // Find session by IP, < 1 for not found
951 // Confusingly enough, this 'ip' must be
952 // in _network_ order. This being the common
953 // case when looking it up from IP packet headers.
955 // We actually use this cache for two things.
956 // #1. For used IP addresses, this maps to the
957 // session ID that it's used by.
958 // #2. For un-used IP addresses, this maps to the
959 // index into the pool table that contains that
963 static sessionidt
lookup_ipmap(in_addr_t ip
)
965 uint8_t *a
= (uint8_t *) &ip
;
966 union iphash
*h
= ip_hash
;
968 if (!(h
= h
[*a
++].idx
)) return 0;
969 if (!(h
= h
[*a
++].idx
)) return 0;
970 if (!(h
= h
[*a
++].idx
)) return 0;
975 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
977 struct ipv6radix
*curnode
;
980 char ipv6addr
[INET6_ADDRSTRLEN
];
982 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
983 curnode
= &ipv6_hash
[((ip
.s6_addr
[0]) & 0xF0)>>4];
987 while (s
== 0 && i
< 32 && curnode
->branch
!= NULL
)
990 curnode
= &curnode
->branch
[ip
.s6_addr
[i
>>1] & 0x0F];
992 curnode
= &curnode
->branch
[(ip
.s6_addr
[i
>>1] & 0xF0)>>4];
998 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
999 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1006 sessionidt
sessionbyip(in_addr_t ip
)
1008 sessionidt s
= lookup_ipmap(ip
);
1011 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1017 sessionidt
sessionbyipv6(struct in6_addr ip
)
1020 CSTAT(sessionbyipv6
);
1022 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
1023 (ip
.s6_addr
[0] == 0xFE &&
1024 ip
.s6_addr
[1] == 0x80 &&
1025 ip
.s6_addr16
[1] == 0 &&
1026 ip
.s6_addr16
[2] == 0 &&
1027 ip
.s6_addr16
[3] == 0))
1029 in_addr_t
*pipv4
= (in_addr_t
*) &ip
.s6_addr
[8];
1030 s
= lookup_ipmap(*pipv4
);
1032 s
= lookup_ipv6map(ip
);
1035 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1041 sessionidt
sessionbyipv6new(struct in6_addr ip
)
1044 CSTAT(sessionbyipv6new
);
1046 s
= lookup_ipv6map(ip
);
1048 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1055 // Take an IP address in HOST byte order and
1056 // add it to the sessionid by IP cache.
1058 // (It's actually cached in network order)
1060 void cache_ipmap(in_addr_t ip
, sessionidt s
)
1062 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
1063 uint8_t *a
= (uint8_t *) &nip
;
1064 union iphash
*h
= ip_hash
;
1067 for (i
= 0; i
< 3; i
++)
1069 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1078 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1081 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1082 // else a map to an ip pool index.
1085 static void uncache_ipmap(in_addr_t ip
)
1087 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1090 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1094 struct ipv6radix
*curnode
;
1095 char ipv6addr
[INET6_ADDRSTRLEN
];
1097 curnode
= &ipv6_hash
[((ip
.s6_addr
[0]) & 0xF0)>>4];
1099 niblles
= prefixlen
>> 2;
1104 if (curnode
->branch
== NULL
)
1106 if (!(curnode
->branch
= calloc(16, sizeof (struct ipv6radix
))))
1111 curnode
= &curnode
->branch
[ip
.s6_addr
[i
>>1] & 0x0F];
1113 curnode
= &curnode
->branch
[(ip
.s6_addr
[i
>>1] & 0xF0)>>4];
1121 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1122 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1126 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1127 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1133 // CLI list to dump current ipcache.
1135 int cmd_show_ipcache(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
1137 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1141 if (CLI_HELP_REQUESTED
)
1142 return CLI_HELP_NO_ARGS
;
1144 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1146 for (i
= 0; i
< 256; ++i
)
1152 for (j
= 0; j
< 256; ++j
)
1158 for (k
= 0; k
< 256; ++k
)
1164 for (l
= 0; l
< 256; ++l
)
1169 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1175 cli_print(cli
, "%d entries in cache", count
);
1179 // Find session by username, 0 for not found
1180 // walled garden users aren't authenticated, so the username is
1181 // reasonably useless. Ignore them to avoid incorrect actions
1183 // This is VERY inefficent. Don't call it often. :)
1185 sessionidt
sessionbyuser(char *username
)
1188 CSTAT(sessionbyuser
);
1190 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1192 if (!session
[s
].opened
)
1195 if (session
[s
].walled_garden
)
1196 continue; // Skip walled garden users.
1198 if (!strncmp(session
[s
].user
, username
, 128))
1202 return 0; // Not found.
1205 void send_garp(in_addr_t ip
)
1211 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1214 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1217 memset(&ifr
, 0, sizeof(ifr
));
1218 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1219 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1221 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1225 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1226 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1228 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1233 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1236 static sessiont
*sessiontbysessionidt(sessionidt s
)
1238 if (!s
|| s
>= MAXSESSION
) return NULL
;
1242 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1244 sessionidt val
= s
-session
;
1245 if (s
< session
|| val
>= MAXSESSION
) return 0;
1249 // actually send a control message for a specific tunnel
1250 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1252 struct sockaddr_in addr
;
1258 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1259 STAT(tunnel_tx_errors
);
1263 if (t
== TUNNEL_ID_PPPOE
)
1265 pppoe_sess_send(buf
, l
, t
);
1271 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1272 STAT(tunnel_tx_errors
);
1276 memset(&addr
, 0, sizeof(addr
));
1277 addr
.sin_family
= AF_INET
;
1278 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1279 addr
.sin_port
= htons(tunnel
[t
].port
);
1281 // sequence expected, if sequence in message
1282 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1284 // If this is a control message, deal with retries
1287 tunnel
[t
].last
= time_now
; // control message sent
1288 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1291 STAT(tunnel_retries
);
1292 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1296 if (sendto(udpfd
[tunnel
[t
].indexudp
], buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1298 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1299 strerror(errno
), udpfd
[tunnel
[t
].indexudp
], buf
, l
, inet_ntoa(addr
.sin_addr
));
1300 STAT(tunnel_tx_errors
);
1304 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1305 STAT(tunnel_tx_packets
);
1306 INC_STAT(tunnel_tx_bytes
, l
);
1310 // Tiny helper function to write data to
1311 // the 'tun' device.
1313 int tun_write(uint8_t * data
, int size
)
1315 return write(tunfd
, data
, size
);
1318 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1319 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1321 int d
= (tcp
[12] >> 4) * 4;
1328 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1331 if (tcp
+ d
> buf
+ len
) // short?
1339 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1342 if (mss
+ 2 > data
) return; // short?
1346 if (*opts
== 0) return; // end of options
1347 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1350 opts
+= opts
[1]; // skip over option
1353 if (!mss
) return; // not found
1354 orig
= ntohs(*(uint16_t *) mss
);
1356 if (orig
<= MSS
) return; // mss OK
1358 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1359 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1360 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1361 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1364 *(int16_t *) mss
= htons(MSS
);
1366 // adjust checksum (see rfc1141)
1367 sum
= orig
+ (~MSS
& 0xffff);
1368 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1369 sum
= (sum
& 0xffff) + (sum
>> 16);
1370 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1373 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1377 // Skip the four extra bytes
1389 proto
= ntohs(*(uint16_t *) p
);
1397 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1398 return; // closing session, PPP not processed
1400 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1401 processipin(s
, t
, p
, l
);
1403 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1407 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1408 return; // closing session, PPP not processed
1411 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1412 processipv6in(s
, t
, p
, l
);
1414 else if (proto
== PPPIPCP
)
1416 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1417 processipcp(s
, t
, p
, l
);
1419 else if (proto
== PPPCCP
)
1421 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1422 processccp(s
, t
, p
, l
);
1426 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1430 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1432 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1433 sp
->cout_delta
+= len
;
1435 sp
->last_data
= time_now
;
1437 sess_local
[s
].cout
+= len
; // To send to master..
1438 sess_local
[s
].pout
++;
1441 // process outgoing (to tunnel) IP
1443 // (i.e. this routine writes to data[-8]).
1444 void processipout(uint8_t *buf
, int len
)
1450 in_addr_t ip
, ip_src
;
1452 uint8_t *data
= buf
; // Keep a copy of the originals.
1455 uint8_t fragbuf
[MAXETHER
+ 20];
1457 CSTAT(processipout
);
1459 if (len
< MIN_IP_SIZE
)
1461 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1462 STAT(tun_rx_errors
);
1465 if (len
>= MAXETHER
)
1467 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1468 STAT(tun_rx_errors
);
1472 // Skip the tun header
1476 // Got an IP header now
1477 if (*(uint8_t *)(buf
) >> 4 != 4)
1479 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1483 ip_src
= *(uint32_t *)(buf
+ 12);
1484 ip
= *(uint32_t *)(buf
+ 16);
1485 if ((g
= grp_groupbyip(ip
)))
1487 s
= grp_getnextsession(g
, ip
, ip_src
);
1490 // Is this a packet for a session that doesn't exist?
1491 static int rate
= 0; // Number of ICMP packets we've sent this second.
1492 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1494 if (last
!= time_now
)
1500 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1502 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1503 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1504 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1509 else if (!(s
= sessionbyip(ip
)))
1511 // Is this a packet for a session that doesn't exist?
1512 static int rate
= 0; // Number of ICMP packets we've sent this second.
1513 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1515 if (last
!= time_now
)
1521 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1523 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1524 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1525 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1530 t
= session
[s
].tunnel
;
1531 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1533 LOG(3, s
, t
, "Packet size more than session MRU\n");
1539 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1540 if (config
->max_packets
> 0)
1542 if (sess_local
[s
].last_packet_out
== TIME
)
1544 int max
= config
->max_packets
;
1546 // All packets for throttled sessions are handled by the
1547 // master, so further limit by using the throttle rate.
1548 // A bit of a kludge, since throttle rate is in kbps,
1549 // but should still be generous given our average DSL
1550 // packet size is 200 bytes: a limit of 28kbps equates
1551 // to around 180 packets per second.
1552 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1553 max
= sp
->throttle_out
;
1555 if (++sess_local
[s
].packets_out
> max
)
1557 sess_local
[s
].packets_dropped
++;
1563 if (sess_local
[s
].packets_dropped
)
1565 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1566 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1567 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1568 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1572 sess_local
[s
].last_packet_out
= TIME
;
1573 sess_local
[s
].packets_out
= 1;
1574 sess_local
[s
].packets_dropped
= 0;
1578 // run access-list if any
1579 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1582 // adjust MSS on SYN and SYN,ACK packets with options
1583 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1585 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1586 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1587 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1592 if (!config
->no_throttle_local_IP
|| !sessionbyip(ip_src
))
1594 // Are we throttling this session?
1595 if (config
->cluster_iam_master
)
1596 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1598 master_throttle_packet(sp
->tbf_out
, data
, size
);
1603 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1605 // We are walled-gardening this
1606 master_garden_packet(s
, data
, size
);
1610 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1613 if (!config
->cluster_iam_master
)
1615 // The MPPP packets must be managed by the Master.
1616 master_forward_mppp_packet(s
, data
, size
);
1620 // Add on L2TP header
1621 sessionidt members
[MAXBUNDLESES
];
1622 bundleidt bid
= session
[s
].bundle
;
1623 bundlet
*b
= &bundle
[bid
];
1624 uint32_t num_of_links
, nb_opened
;
1627 num_of_links
= b
->num_of_links
;
1629 for (i
= 0;i
< num_of_links
;i
++)
1632 if (session
[s
].ppp
.lcp
== Opened
)
1634 members
[nb_opened
] = s
;
1641 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1645 num_of_links
= nb_opened
;
1646 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1647 s
= members
[b
->current_ses
];
1648 t
= session
[s
].tunnel
;
1650 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1652 if (num_of_links
> 1)
1654 if(len
> MINFRAGLEN
)
1656 //for rotate traffic among the member links
1657 uint32_t divisor
= num_of_links
;
1659 divisor
= divisor
/2 + (divisor
& 1);
1661 // Partition the packet to "num_of_links" fragments
1662 uint32_t fraglen
= len
/ divisor
;
1663 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1664 uint32_t remain
= len
;
1666 // send the first packet
1667 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1669 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1672 update_session_out_stat(s
, sp
, fraglen
);
1675 while (remain
> last_fraglen
)
1677 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1678 s
= members
[b
->current_ses
];
1679 t
= session
[s
].tunnel
;
1681 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1682 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1684 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1685 update_session_out_stat(s
, sp
, fraglen
);
1688 // send the last fragment
1689 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1690 s
= members
[b
->current_ses
];
1691 t
= session
[s
].tunnel
;
1693 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1694 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1696 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1697 update_session_out_stat(s
, sp
, remain
);
1698 if (remain
!= last_fraglen
)
1699 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1703 // Send it as one frame
1704 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1706 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1707 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1708 update_session_out_stat(s
, sp
, len
);
1713 // Send it as one frame (NO MPPP Frame)
1714 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1715 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1716 update_session_out_stat(s
, sp
, len
);
1721 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1722 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1723 update_session_out_stat(s
, sp
, len
);
1726 // Snooping this session, send it to intercept box
1727 if (sp
->snoop_ip
&& sp
->snoop_port
)
1728 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1733 // process outgoing (to tunnel) IPv6
1735 static void processipv6out(uint8_t * buf
, int len
)
1740 struct in6_addr ip6
;
1742 uint8_t *data
= buf
; // Keep a copy of the originals.
1745 uint8_t b
[MAXETHER
+ 20];
1747 CSTAT(processipv6out
);
1749 if (len
< MIN_IP_SIZE
)
1751 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1752 STAT(tunnel_tx_errors
);
1755 if (len
>= MAXETHER
)
1757 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1758 STAT(tunnel_tx_errors
);
1762 // Skip the tun header
1766 // Got an IP header now
1767 if (*(uint8_t *)(buf
) >> 4 != 6)
1769 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1773 ip6
= *(struct in6_addr
*)(buf
+24);
1774 s
= sessionbyipv6(ip6
);
1778 s
= sessionbyipv6new(ip6
);
1783 // Is this a packet for a session that doesn't exist?
1784 static int rate
= 0; // Number of ICMP packets we've sent this second.
1785 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1787 if (last
!= time_now
)
1793 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1795 // FIXME: Should send icmp6 host unreachable
1799 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1801 bundleidt bid
= session
[s
].bundle
;
1802 bundlet
*b
= &bundle
[bid
];
1804 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1805 s
= b
->members
[b
->current_ses
];
1806 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1808 t
= session
[s
].tunnel
;
1810 sp
->last_data
= time_now
;
1812 // FIXME: add DoS prevention/filters?
1816 // Are we throttling this session?
1817 if (config
->cluster_iam_master
)
1818 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1820 master_throttle_packet(sp
->tbf_out
, data
, size
);
1823 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1825 // We are walled-gardening this
1826 master_garden_packet(s
, data
, size
);
1830 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1832 // Add on L2TP header
1834 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1836 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1839 // Snooping this session, send it to intercept box
1840 if (sp
->snoop_ip
&& sp
->snoop_port
)
1841 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1843 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1844 sp
->cout_delta
+= len
;
1848 sess_local
[s
].cout
+= len
; // To send to master..
1849 sess_local
[s
].pout
++;
1853 // Helper routine for the TBF filters.
1854 // Used to send queued data in to the user!
1856 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1861 uint8_t *data
= buf
; // Keep a copy of the originals.
1863 uint8_t b
[MAXETHER
+ 20];
1865 if (len
< 0 || len
> MAXETHER
)
1867 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1871 // Skip the tun header
1878 t
= session
[s
].tunnel
;
1881 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1883 // Add on L2TP header
1884 if (*(uint16_t *) (data
+ 2) == htons(PKTIPV6
))
1885 p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0); // IPV6
1887 p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0); // IPV4
1891 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1893 // Snooping this session.
1894 if (sp
->snoop_ip
&& sp
->snoop_port
)
1895 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1897 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1898 sp
->cout_delta
+= len
;
1902 sess_local
[s
].cout
+= len
; // To send to master..
1903 sess_local
[s
].pout
++;
1906 // add an AVP (16 bit)
1907 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1909 uint16_t l
= (m
? 0x8008 : 0x0008);
1910 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1911 pint16
[0] = htons(l
);
1912 pint16
[1] = htons(0);
1913 pint16
[2] = htons(avp
);
1914 pint16
[3] = htons(val
);
1918 // add an AVP (32 bit)
1919 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1921 uint16_t l
= (m
? 0x800A : 0x000A);
1922 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1923 uint32_t *pint32
= (uint32_t *) (c
->buf
+ c
->length
+ 6);
1924 pint16
[0] = htons(l
);
1925 pint16
[1] = htons(0);
1926 pint16
[2] = htons(avp
);
1927 pint32
[0] = htonl(val
);
1931 // add an AVP (string)
1932 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1934 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1935 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1936 pint16
[0] = htons(l
);
1937 pint16
[1] = htons(0);
1938 pint16
[2] = htons(avp
);
1939 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1940 c
->length
+= 6 + strlen(val
);
1944 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1946 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1947 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1948 pint16
[0] = htons(l
);
1949 pint16
[1] = htons(0);
1950 pint16
[2] = htons(avp
);
1951 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1952 c
->length
+= 6 + len
;
1955 // new control connection
1956 static controlt
*controlnew(uint16_t mtype
)
1960 c
= malloc(sizeof(controlt
));
1964 controlfree
= c
->next
;
1968 c
->buf
[0] = 0xC8; // flags
1969 c
->buf
[1] = 0x02; // ver
1971 control16(c
, 0, mtype
, 1);
1975 // send zero block if nothing is waiting
1977 static void controlnull(tunnelidt t
)
1980 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1983 buf
[0] = htons(0xC802); // flags/ver
1984 buf
[1] = htons(12); // length
1985 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1986 buf
[3] = htons(0); // session
1987 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1988 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1989 tunnelsend((uint8_t *)buf
, 12, t
);
1992 // add a control message to a tunnel, and send if within window
1993 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1995 uint16_t *pint16
= (uint16_t *) (c
->buf
+ 2);
1996 pint16
[0] = htons(c
->length
); // length
1997 pint16
[1] = htons(tunnel
[t
].far
); // tunnel
1998 pint16
[2] = htons(far
); // session
1999 pint16
[3] = htons(tunnel
[t
].ns
); // sequence
2000 tunnel
[t
].ns
++; // advance sequence
2001 // link in message in to queue
2002 if (tunnel
[t
].controlc
)
2003 tunnel
[t
].controle
->next
= c
;
2005 tunnel
[t
].controls
= c
;
2007 tunnel
[t
].controle
= c
;
2008 tunnel
[t
].controlc
++;
2010 // send now if space in window
2011 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
2013 tunnel
[t
].try = 0; // first send
2014 tunnelsend(c
->buf
, c
->length
, t
);
2019 // Throttle or Unthrottle a session
2021 // Throttle the data from/to through a session to no more than
2022 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
2025 // If either value is -1, the current value is retained for that
2028 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
2030 if (!session
[s
].opened
)
2031 return; // No-one home.
2033 if (!*session
[s
].user
)
2034 return; // User not logged in
2038 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
2039 if (session
[s
].tbf_in
)
2040 free_tbf(session
[s
].tbf_in
);
2043 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
2045 session
[s
].tbf_in
= 0;
2047 session
[s
].throttle_in
= rate_in
;
2052 int bytes
= rate_out
* 1024 / 8;
2053 if (session
[s
].tbf_out
)
2054 free_tbf(session
[s
].tbf_out
);
2057 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
2059 session
[s
].tbf_out
= 0;
2061 session
[s
].throttle_out
= rate_out
;
2065 // add/remove filters from session (-1 = no change)
2066 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
2068 if (!session
[s
].opened
)
2069 return; // No-one home.
2071 if (!*session
[s
].user
)
2072 return; // User not logged in
2075 if (filter_in
> MAXFILTER
) filter_in
= -1;
2076 if (filter_out
> MAXFILTER
) filter_out
= -1;
2077 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
2078 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
2082 if (session
[s
].filter_in
)
2083 ip_filters
[session
[s
].filter_in
- 1].used
--;
2086 ip_filters
[filter_in
- 1].used
++;
2088 session
[s
].filter_in
= filter_in
;
2091 if (filter_out
>= 0)
2093 if (session
[s
].filter_out
)
2094 ip_filters
[session
[s
].filter_out
- 1].used
--;
2097 ip_filters
[filter_out
- 1].used
++;
2099 session
[s
].filter_out
= filter_out
;
2103 // start tidy shutdown of session
2104 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
2106 int walled_garden
= session
[s
].walled_garden
;
2107 bundleidt b
= session
[s
].bundle
;
2108 //delete routes only for last session in bundle (in case of MPPP)
2109 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
2111 CSTAT(sessionshutdown
);
2113 if (!session
[s
].opened
)
2115 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2116 return; // not a live session
2119 if (!session
[s
].die
)
2121 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2122 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2123 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2126 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2128 // RADIUS Stop message
2129 uint16_t r
= radiusnew(s
);
2132 // stop, if not already trying
2133 if (radius
[r
].state
!= RADIUSSTOP
)
2135 radius
[r
].term_cause
= term_cause
;
2136 radius
[r
].term_msg
= reason
;
2137 radiussend(r
, RADIUSSTOP
);
2141 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2143 // Save counters to dump to accounting file
2144 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2145 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2148 if (!session
[s
].die
)
2149 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2152 { // IP allocated, clear and unroute
2155 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2157 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2158 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2161 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2162 session
[s
].route
[r
].ip
= 0;
2165 if (session
[s
].ip_pool_index
== -1) // static ip
2167 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2173 // unroute IPv6, if setup
2174 for (r
= 0; r
< MAXROUTE6
&& session
[s
].route6
[r
].ipv6route
.s6_addr
[0] && session
[s
].route6
[r
].ipv6prefixlen
; r
++)
2176 if (del_routes
) route6set(s
, session
[s
].route6
[r
].ipv6route
, session
[s
].route6
[r
].ipv6prefixlen
, 0);
2177 memset(&session
[s
].route6
[r
], 0, sizeof(session
[s
].route6
[r
]));
2180 if (session
[s
].ipv6address
.s6_addr
[0] && del_routes
)
2182 route6set(s
, session
[s
].ipv6address
, 128, 0);
2187 // This session was part of a bundle
2188 bundle
[b
].num_of_links
--;
2189 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2190 if(bundle
[b
].num_of_links
== 0)
2193 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2197 // Adjust the members array to accomodate the new change
2198 uint8_t mem_num
= 0;
2199 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2200 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2203 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2204 if(bundle
[b
].members
[ml
] == s
)
2209 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2210 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2212 // If the killed session is the first of the bundle,
2213 // the new first session must be stored in the cache_ipmap
2214 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2217 sessionidt new_s
= bundle
[b
].members
[0];
2220 // Add the route for this session.
2221 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2226 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2227 ip
= session
[new_s
].route
[r
].ip
;
2229 if (!prefixlen
) prefixlen
= 32;
2230 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2232 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2233 cache_ipmap(i
, new_s
);
2235 cache_ipmap(session
[new_s
].ip
, new_s
);
2238 for (r
= 0; r
< MAXROUTE6
&& session
[new_s
].route6
[r
].ipv6prefixlen
; r
++)
2240 cache_ipv6map(session
[new_s
].route6
[r
].ipv6route
, session
[new_s
].route6
[r
].ipv6prefixlen
, new_s
);
2243 if (session
[new_s
].ipv6address
.s6_addr
[0])
2245 cache_ipv6map(session
[new_s
].ipv6address
, 128, new_s
);
2251 cluster_send_bundle(b
);
2255 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2256 throttle_session(s
, 0, 0);
2260 if (session
[s
].tunnel
== TUNNEL_ID_PPPOE
)
2262 pppoe_shutdown_session(s
);
2267 controlt
*c
= controlnew(14); // sending CDN
2271 buf
[0] = htons(cdn_result
);
2272 buf
[1] = htons(cdn_error
);
2273 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2276 control16(c
, 1, cdn_result
, 1);
2278 control16(c
, 14, s
, 1); // assigned session (our end)
2279 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2283 // update filter refcounts
2284 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2285 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2288 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2289 sess_local
[s
].lcp
.restart
= 0;
2290 sess_local
[s
].ipcp
.restart
= 0;
2291 sess_local
[s
].ipv6cp
.restart
= 0;
2292 sess_local
[s
].ccp
.restart
= 0;
2294 cluster_send_session(s
);
2297 void sendipcp(sessionidt s
, tunnelidt t
)
2299 uint8_t buf
[MAXETHER
];
2303 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2305 if (!session
[s
].unique_id
)
2307 if (!++last_id
) ++last_id
; // skip zero
2308 session
[s
].unique_id
= last_id
;
2311 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2315 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2316 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2317 q
[4] = 3; // ip address option
2318 q
[5] = 6; // option length
2319 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2320 config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] :
2321 my_address
; // send my IP
2323 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2324 restart_timer(s
, ipcp
);
2327 void sendipv6cp(sessionidt s
, tunnelidt t
)
2329 uint8_t buf
[MAXETHER
];
2333 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2335 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2339 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2340 // only send one type
2342 *(uint16_t *) (q
+ 2) = htons(14);
2343 q
[4] = 1; // interface identifier option
2344 q
[5] = 10; // option length
2345 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2346 *(uint32_t *) (q
+ 10) = 0;
2349 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2350 restart_timer(s
, ipv6cp
);
2353 static void sessionclear(sessionidt s
)
2355 memset(&session
[s
], 0, sizeof(session
[s
]));
2356 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2357 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2359 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2360 session
[s
].next
= sessionfree
;
2364 // kill a session now
2365 void sessionkill(sessionidt s
, char *reason
)
2371 if (!session
[s
].opened
) // not alive
2374 if (session
[s
].next
)
2376 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2380 if (!session
[s
].die
)
2381 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2383 if (sess_local
[s
].radius
)
2384 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2386 if (session
[s
].forwardtosession
)
2388 sessionidt sess
= session
[s
].forwardtosession
;
2389 if (session
[sess
].forwardtosession
== s
)
2391 // Shutdown the linked session also.
2392 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2396 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2398 if ((g
= grp_groupbysession(s
)))
2400 grp_removesession(g
, s
);
2404 cluster_send_session(s
);
2407 static void tunnelclear(tunnelidt t
)
2410 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2411 tunnel
[t
].state
= TUNNELFREE
;
2414 static void bundleclear(bundleidt b
)
2417 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2418 bundle
[b
].state
= BUNDLEFREE
;
2421 // kill a tunnel now
2422 static void tunnelkill(tunnelidt t
, char *reason
)
2429 tunnel
[t
].state
= TUNNELDIE
;
2431 // free control messages
2432 while ((c
= tunnel
[t
].controls
))
2434 controlt
* n
= c
->next
;
2435 tunnel
[t
].controls
= n
;
2436 tunnel
[t
].controlc
--;
2437 c
->next
= controlfree
;
2441 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2442 if (session
[s
].tunnel
== t
)
2443 sessionkill(s
, reason
);
2447 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2448 cli_tunnel_actions
[t
].action
= 0;
2449 cluster_send_tunnel(t
);
2452 // shut down a tunnel cleanly
2453 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2457 CSTAT(tunnelshutdown
);
2459 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2461 // never set up, can immediately kill
2462 tunnelkill(t
, reason
);
2465 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2468 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2469 if (session
[s
].tunnel
== t
)
2470 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2472 tunnel
[t
].state
= TUNNELDIE
;
2473 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2474 cluster_send_tunnel(t
);
2475 // TBA - should we wait for sessions to stop?
2478 controlt
*c
= controlnew(4); // sending StopCCN
2483 buf
[0] = htons(result
);
2484 buf
[1] = htons(error
);
2487 int m
= strlen(msg
);
2488 if (m
+ 4 > sizeof(buf
))
2489 m
= sizeof(buf
) - 4;
2491 memcpy(buf
+2, msg
, m
);
2495 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2498 control16(c
, 1, result
, 1);
2500 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2501 controladd(c
, 0, t
); // send the message
2505 // read and process packet on tunnel (UDP)
2506 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, uint16_t indexudpfd
)
2508 uint8_t *sendchalresponse
= NULL
;
2509 uint8_t *recvchalresponse
= NULL
;
2510 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2511 uint8_t *p
= buf
+ 2;
2518 LOG_HEX(5, "UDP Data", buf
, len
);
2519 STAT(tunnel_rx_packets
);
2520 INC_STAT(tunnel_rx_bytes
, len
);
2523 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2524 STAT(tunnel_rx_errors
);
2527 if ((buf
[1] & 0x0F) != 2)
2529 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2530 STAT(tunnel_rx_errors
);
2535 l
= ntohs(*(uint16_t *) p
);
2538 t
= ntohs(*(uint16_t *) p
);
2540 s
= ntohs(*(uint16_t *) p
);
2542 if (s
>= MAXSESSION
)
2544 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2545 STAT(tunnel_rx_errors
);
2550 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2551 STAT(tunnel_rx_errors
);
2554 if (t
== TUNNEL_ID_PPPOE
)
2556 LOG(1, s
, t
, "Received UDP packet with tunnel ID reserved for pppoe\n");
2557 STAT(tunnel_rx_errors
);
2562 ns
= ntohs(*(uint16_t *) p
);
2564 nr
= ntohs(*(uint16_t *) p
);
2569 uint16_t o
= ntohs(*(uint16_t *) p
);
2574 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2575 STAT(tunnel_rx_errors
);
2580 // used to time out old tunnels
2581 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2582 tunnel
[t
].lastrec
= time_now
;
2586 uint16_t message
= 0xFFFF; // message type
2588 uint8_t mandatory
= 0;
2589 uint16_t asession
= 0; // assigned session
2590 uint32_t amagic
= 0; // magic number
2591 uint8_t aflags
= 0; // flags from last LCF
2592 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2593 char called
[MAXTEL
] = ""; // called number
2594 char calling
[MAXTEL
] = ""; // calling number
2596 if (!config
->cluster_iam_master
)
2598 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
2602 // control messages must have bits 0x80|0x40|0x08
2603 // (type, length and sequence) set, and bits 0x02|0x01
2604 // (offset and priority) clear
2605 if ((*buf
& 0xCB) != 0xC8)
2607 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2608 STAT(tunnel_rx_errors
);
2612 // check for duplicate tunnel open message
2618 // Is this a duplicate of the first packet? (SCCRQ)
2620 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2622 if (tunnel
[i
].state
!= TUNNELOPENING
||
2623 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2624 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2627 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2632 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2633 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2635 // if no tunnel specified, assign one
2638 if (!(t
= new_tunnel()))
2640 LOG(1, 0, 0, "No more tunnels\n");
2641 STAT(tunnel_overflow
);
2645 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2646 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2647 tunnel
[t
].window
= 4; // default window
2648 tunnel
[t
].indexudp
= indexudpfd
;
2649 STAT(tunnel_created
);
2650 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2651 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2654 // If the 'ns' just received is not the 'nr' we're
2655 // expecting, just send an ack and drop it.
2657 // if 'ns' is less, then we got a retransmitted packet.
2658 // if 'ns' is greater than missed a packet. Either way
2659 // we should ignore it.
2660 if (ns
!= tunnel
[t
].nr
)
2662 // is this the sequence we were expecting?
2663 STAT(tunnel_rx_errors
);
2664 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2665 t
, ns
, tunnel
[t
].nr
);
2667 if (l
) // Is this not a ZLB?
2672 // check sequence of this message
2674 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2675 // some to clear maybe?
2676 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2678 controlt
*c
= tunnel
[t
].controls
;
2679 tunnel
[t
].controls
= c
->next
;
2680 tunnel
[t
].controlc
--;
2681 c
->next
= controlfree
;
2684 tunnel
[t
].try = 0; // we have progress
2687 // receiver advance (do here so quoted correctly in any sends below)
2688 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2689 if (skip
< 0) skip
= 0;
2690 if (skip
< tunnel
[t
].controlc
)
2692 // some control packets can now be sent that were previous stuck out of window
2693 int tosend
= tunnel
[t
].window
- skip
;
2694 controlt
*c
= tunnel
[t
].controls
;
2702 tunnel
[t
].try = 0; // first send
2703 tunnelsend(c
->buf
, c
->length
, t
);
2708 if (!tunnel
[t
].controlc
)
2709 tunnel
[t
].retry
= 0; // caught up
2712 { // if not a null message
2717 // Default disconnect cause/message on receipt of CDN. Set to
2718 // more specific value from attribute 1 (result code) or 46
2719 // (disconnect cause) if present below.
2720 int disc_cause_set
= 0;
2721 int disc_cause
= TERM_NAS_REQUEST
;
2722 char const *disc_reason
= "Closed (Received CDN).";
2725 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2727 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2734 LOG(1, s
, t
, "Invalid length in AVP\n");
2735 STAT(tunnel_rx_errors
);
2740 if (flags
& 0x3C) // reserved bits, should be clear
2742 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2744 result
= 2; // general error
2745 error
= 3; // reserved field non-zero
2750 if (*(uint16_t *) (b
))
2752 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2754 result
= 2; // general error
2755 error
= 6; // generic vendor-specific error
2756 msg
= "unsupported vendor-specific";
2760 mtype
= ntohs(*(uint16_t *) (b
));
2768 // handle hidden AVPs
2769 if (!*config
->l2tp_secret
)
2771 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2773 result
= 2; // general error
2774 error
= 6; // generic vendor-specific error
2775 msg
= "secret not specified";
2778 if (!session
[s
].random_vector_length
)
2780 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2782 result
= 2; // general error
2783 error
= 6; // generic
2784 msg
= "no random vector";
2789 LOG(2, s
, t
, "Short hidden AVP.\n");
2791 result
= 2; // general error
2792 error
= 2; // length is wrong
2798 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2800 orig_len
= ntohs(*(uint16_t *) b
);
2801 if (orig_len
> n
+ 2)
2803 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2807 result
= 2; // general error
2808 error
= 2; // length is wrong
2817 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2818 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2822 case 0: // message type
2823 message
= ntohs(*(uint16_t *) b
);
2824 mandatory
= flags
& 0x80;
2825 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2827 case 1: // result code
2829 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2830 char const *resdesc
= "(unknown)";
2831 char const *errdesc
= NULL
;
2836 resdesc
= l2tp_stopccn_result_code(rescode
);
2837 cause
= TERM_LOST_SERVICE
;
2839 else if (message
== 14)
2841 resdesc
= l2tp_cdn_result_code(rescode
);
2843 cause
= TERM_LOST_CARRIER
;
2845 cause
= TERM_ADMIN_RESET
;
2848 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2851 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2852 errdesc
= l2tp_error_code(errcode
);
2853 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2856 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2858 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2860 disc_cause_set
= mtype
;
2861 disc_reason
= errdesc
? errdesc
: resdesc
;
2868 case 2: // protocol version
2870 version
= ntohs(*(uint16_t *) (b
));
2871 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2872 if (version
&& version
!= 0x0100)
2873 { // allow 0.0 and 1.0
2874 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2876 result
= 5; // unspported protocol version
2877 error
= 0x0100; // supported version
2883 case 3: // framing capabilities
2885 case 4: // bearer capabilities
2887 case 5: // tie breaker
2888 // We never open tunnels, so we don't care about tie breakers
2890 case 6: // firmware revision
2892 case 7: // host name
2893 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2894 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2895 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2896 // TBA - to send to RADIUS
2898 case 8: // vendor name
2899 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2900 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2901 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2903 case 9: // assigned tunnel
2904 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2905 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2907 case 10: // rx window
2908 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2909 if (!tunnel
[t
].window
)
2910 tunnel
[t
].window
= 1; // window of 0 is silly
2911 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2913 case 11: // Request Challenge
2915 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2917 build_chap_response(b
, 2, n
, &sendchalresponse
);
2918 else if (message
== 2)
2919 build_chap_response(b
, 3, n
, &sendchalresponse
);
2922 case 13: // receive challenge Response
2923 if (tunnel
[t
].isremotelns
)
2925 recvchalresponse
= calloc(17, 1);
2926 memcpy(recvchalresponse
, b
, (n
< 17) ? n
: 16);
2927 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2930 // Why did they send a response? We never challenge.
2931 LOG(2, s
, t
, " received unexpected challenge response\n");
2934 case 14: // assigned session
2935 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2936 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2938 case 15: // call serial number
2939 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2941 case 18: // bearer type
2942 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2945 case 19: // framing type
2946 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2949 case 21: // called number
2950 memset(called
, 0, sizeof(called
));
2951 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2952 LOG(4, s
, t
, " Called <%s>\n", called
);
2954 case 22: // calling number
2955 memset(calling
, 0, sizeof(calling
));
2956 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2957 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2961 case 24: // tx connect speed
2964 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2968 // AS5300s send connect speed as a string
2970 memset(tmp
, 0, sizeof(tmp
));
2971 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2972 session
[s
].tx_connect_speed
= atol(tmp
);
2974 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2976 case 38: // rx connect speed
2979 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2983 // AS5300s send connect speed as a string
2985 memset(tmp
, 0, sizeof(tmp
));
2986 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2987 session
[s
].rx_connect_speed
= atol(tmp
);
2989 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2991 case 25: // Physical Channel ID
2993 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2994 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2997 case 29: // Proxy Authentication Type
2999 uint16_t atype
= ntohs(*(uint16_t *)b
);
3000 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
3003 case 30: // Proxy Authentication Name
3006 memset(authname
, 0, sizeof(authname
));
3007 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
3008 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
3012 case 31: // Proxy Authentication Challenge
3014 LOG(4, s
, t
, " Proxy Auth Challenge\n");
3017 case 32: // Proxy Authentication ID
3019 uint16_t authid
= ntohs(*(uint16_t *)(b
));
3020 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
3023 case 33: // Proxy Authentication Response
3024 LOG(4, s
, t
, " Proxy Auth Response\n");
3026 case 27: // last sent lcp
3027 { // find magic number
3028 uint8_t *p
= b
, *e
= p
+ n
;
3029 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
3031 if (*p
== 5 && p
[1] == 6) // Magic-Number
3032 amagic
= ntohl(*(uint32_t *) (p
+ 2));
3033 else if (*p
== 7) // Protocol-Field-Compression
3034 aflags
|= SESSION_PFC
;
3035 else if (*p
== 8) // Address-and-Control-Field-Compression
3036 aflags
|= SESSION_ACFC
;
3041 case 28: // last recv lcp confreq
3043 case 26: // Initial Received LCP CONFREQ
3045 case 39: // seq required - we control it as an LNS anyway...
3047 case 36: // Random Vector
3048 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
3049 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
3050 if (n
> sizeof(session
[s
].random_vector
))
3051 n
= sizeof(session
[s
].random_vector
);
3052 memcpy(session
[s
].random_vector
, b
, n
);
3053 session
[s
].random_vector_length
= n
;
3055 case 46: // ppp disconnect cause
3058 uint16_t code
= ntohs(*(uint16_t *) b
);
3059 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
3060 uint8_t dir
= *(b
+ 4);
3062 LOG(4, s
, t
, " PPP disconnect cause "
3063 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
3064 code
, proto
, dir
, n
- 5, b
+ 5);
3066 disc_cause_set
= mtype
;
3070 case 1: // admin disconnect
3071 disc_cause
= TERM_ADMIN_RESET
;
3072 disc_reason
= "Administrative disconnect";
3074 case 3: // lcp terminate
3075 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
3076 disc_cause
= TERM_USER_REQUEST
;
3077 disc_reason
= "Normal disconnection";
3079 case 4: // compulsory encryption unavailable
3080 if (dir
!= 1) break; // 1=refused by peer, 2=local
3081 disc_cause
= TERM_USER_ERROR
;
3082 disc_reason
= "Compulsory encryption refused";
3084 case 5: // lcp: fsm timeout
3085 disc_cause
= TERM_PORT_ERROR
;
3086 disc_reason
= "LCP: FSM timeout";
3088 case 6: // lcp: no recognisable lcp packets received
3089 disc_cause
= TERM_PORT_ERROR
;
3090 disc_reason
= "LCP: no recognisable LCP packets";
3092 case 7: // lcp: magic-no error (possibly looped back)
3093 disc_cause
= TERM_PORT_ERROR
;
3094 disc_reason
= "LCP: magic-no error (possible loop)";
3096 case 8: // lcp: echo request timeout
3097 disc_cause
= TERM_PORT_ERROR
;
3098 disc_reason
= "LCP: echo request timeout";
3100 case 13: // auth: fsm timeout
3101 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3102 disc_reason
= "Authentication: FSM timeout";
3104 case 15: // auth: unacceptable auth protocol
3105 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3106 disc_reason
= "Unacceptable authentication protocol";
3108 case 16: // auth: authentication failed
3109 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3110 disc_reason
= "Authentication failed";
3112 case 17: // ncp: fsm timeout
3113 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3114 disc_reason
= "NCP: FSM timeout";
3116 case 18: // ncp: no ncps available
3117 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3118 disc_reason
= "NCP: no NCPs available";
3120 case 19: // ncp: failure to converge on acceptable address
3121 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3122 disc_reason
= (dir
== 1)
3123 ? "NCP: too many Configure-Naks received from peer"
3124 : "NCP: too many Configure-Naks sent to peer";
3126 case 20: // ncp: user not permitted to use any address
3127 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3128 disc_reason
= (dir
== 1)
3129 ? "NCP: local link address not acceptable to peer"
3130 : "NCP: remote link address not acceptable";
3137 static char e
[] = "unknown AVP 0xXXXX";
3138 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
3140 result
= 2; // general error
3141 error
= 8; // unknown mandatory AVP
3142 sprintf((msg
= e
) + 14, "%04x", mtype
);
3149 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3153 case 1: // SCCRQ - Start Control Connection Request
3154 tunnel
[t
].state
= TUNNELOPENING
;
3155 LOG(3, s
, t
, "Received SCCRQ\n");
3156 if (main_quit
!= QUIT_SHUTDOWN
)
3158 LOG(3, s
, t
, "sending SCCRP\n");
3159 controlt
*c
= controlnew(2); // sending SCCRP
3160 control16(c
, 2, version
, 1); // protocol version
3161 control32(c
, 3, 3, 1); // framing
3162 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3163 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Send Challenge response
3164 control16(c
, 9, t
, 1); // assigned tunnel
3165 controladd(c
, 0, t
); // send the resply
3169 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3173 tunnel
[t
].state
= TUNNELOPEN
;
3174 tunnel
[t
].lastrec
= time_now
;
3175 LOG(3, s
, t
, "Received SCCRP\n");
3176 if (main_quit
!= QUIT_SHUTDOWN
)
3178 if (tunnel
[t
].isremotelns
&& recvchalresponse
)
3182 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3183 // check authenticator
3184 if (memcmp(hash
, recvchalresponse
, 16) == 0)
3186 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3187 controlt
*c
= controlnew(3); // sending SCCCN
3188 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3189 controls(c
, 8, Vendor_name
, 1); // Vendor name
3190 control16(c
, 2, version
, 1); // protocol version
3191 control32(c
, 3, 3, 1); // framing Capabilities
3192 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Challenge response
3193 control16(c
, 9, t
, 1); // assigned tunnel
3194 controladd(c
, 0, t
); // send
3198 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3204 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3208 LOG(3, s
, t
, "Received SCCN\n");
3209 tunnel
[t
].state
= TUNNELOPEN
;
3210 tunnel
[t
].lastrec
= time_now
;
3211 controlnull(t
); // ack
3214 LOG(3, s
, t
, "Received StopCCN\n");
3215 controlnull(t
); // ack
3216 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3219 LOG(3, s
, t
, "Received HELLO\n");
3220 controlnull(t
); // simply ACK
3224 LOG(3, s
, t
, "Received OCRQ\n");
3228 LOG(3, s
, t
, "Received OCRO\n");
3232 LOG(3, s
, t
, "Received OCCN\n");
3235 LOG(3, s
, t
, "Received ICRQ\n");
3236 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3238 controlt
*c
= controlnew(11); // ICRP
3240 LOG(3, s
, t
, "Sending ICRP\n");
3243 sessionfree
= session
[s
].next
;
3244 memset(&session
[s
], 0, sizeof(session
[s
]));
3246 if (s
> config
->cluster_highest_sessionid
)
3247 config
->cluster_highest_sessionid
= s
;
3249 session
[s
].opened
= time_now
;
3250 session
[s
].tunnel
= t
;
3251 session
[s
].far
= asession
;
3252 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3253 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3254 control16(c
, 14, s
, 1); // assigned session
3255 controladd(c
, asession
, t
); // send the reply
3257 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3258 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3260 session
[s
].ppp
.phase
= Establish
;
3261 session
[s
].ppp
.lcp
= Starting
;
3263 STAT(session_created
);
3268 controlt
*c
= controlnew(14); // CDN
3269 LOG(3, s
, t
, "Sending CDN\n");
3272 STAT(session_overflow
);
3273 LOG(1, 0, t
, "No free sessions\n");
3274 control16(c
, 1, 4, 0); // temporary lack of resources
3277 control16(c
, 1, 2, 7); // shutting down, try another
3279 controladd(c
, asession
, t
); // send the message
3283 LOG(3, s
, t
, "Received ICRP\n");
3284 if (session
[s
].forwardtosession
)
3286 controlt
*c
= controlnew(12); // ICCN
3288 session
[s
].opened
= time_now
;
3289 session
[s
].tunnel
= t
;
3290 session
[s
].far
= asession
;
3291 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3293 control32(c
, 19, 1, 1); // Framing Type
3294 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3295 controladd(c
, asession
, t
); // send the message
3296 LOG(3, s
, t
, "Sending ICCN\n");
3300 LOG(3, s
, t
, "Received ICCN\n");
3301 if (amagic
== 0) amagic
= time_now
;
3302 session
[s
].magic
= amagic
; // set magic number
3303 session
[s
].flags
= aflags
; // set flags received
3304 session
[s
].mru
= PPPoE_MRU
; // default
3305 controlnull(t
); // ack
3308 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3309 sess_local
[s
].ppp_mru
= MRU
;
3311 // Set multilink options before sending initial LCP packet
3312 sess_local
[s
].mp_mrru
= 1614;
3313 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_address
? config
->iftun_address
: my_address
);
3316 change_state(s
, lcp
, RequestSent
);
3320 LOG(3, s
, t
, "Received CDN\n");
3321 controlnull(t
); // ack
3322 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3325 LOG(1, s
, t
, "Missing message type\n");
3328 STAT(tunnel_rx_errors
);
3330 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3332 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3335 if (sendchalresponse
) free(sendchalresponse
);
3336 if (recvchalresponse
) free(recvchalresponse
);
3337 cluster_send_tunnel(t
);
3341 LOG(4, s
, t
, " Got a ZLB ack\n");
3348 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3349 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3350 { // HDLC address header, discard
3356 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3357 STAT(tunnel_rx_errors
);
3367 proto
= ntohs(*(uint16_t *) p
);
3372 if (session
[s
].forwardtosession
)
3374 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3375 // Forward to LAC/BAS or Remote LNS session
3376 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3379 else if (config
->auth_tunnel_change_addr_src
)
3381 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3382 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3384 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3385 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3386 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3388 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3392 if (s
&& !session
[s
].opened
) // Is something wrong??
3394 if (!config
->cluster_iam_master
)
3396 // Pass it off to the master to deal with..
3397 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3401 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3402 STAT(tunnel_rx_errors
);
3406 if (proto
== PPPPAP
)
3408 session
[s
].last_packet
= time_now
;
3409 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3410 processpap(s
, t
, p
, l
);
3412 else if (proto
== PPPCHAP
)
3414 session
[s
].last_packet
= time_now
;
3415 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3416 processchap(s
, t
, p
, l
);
3418 else if (proto
== PPPLCP
)
3420 session
[s
].last_packet
= time_now
;
3421 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3422 processlcp(s
, t
, p
, l
);
3424 else if (proto
== PPPIPCP
)
3426 session
[s
].last_packet
= time_now
;
3427 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3428 processipcp(s
, t
, p
, l
);
3430 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3432 session
[s
].last_packet
= time_now
;
3433 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3434 processipv6cp(s
, t
, p
, l
);
3436 else if (proto
== PPPCCP
)
3438 session
[s
].last_packet
= time_now
;
3439 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3440 processccp(s
, t
, p
, l
);
3442 else if (proto
== PPPIP
)
3446 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3447 return; // closing session, PPP not processed
3450 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3451 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3453 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3457 processipin(s
, t
, p
, l
);
3459 else if (proto
== PPPMP
)
3463 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3464 return; // closing session, PPP not processed
3467 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3468 if (!config
->cluster_iam_master
)
3470 // The fragments reconstruction is managed by the Master.
3471 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3475 processmpin(s
, t
, p
, l
);
3477 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3481 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3482 return; // closing session, PPP not processed
3485 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3486 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3488 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3492 if (!config
->cluster_iam_master
)
3494 // Check if DhcpV6, IP dst: FF02::1:2, Src Port 0x0222 (546), Dst Port 0x0223 (547)
3495 if (*(p
+ 6) == 17 && *(p
+ 24) == 0xFF && *(p
+ 25) == 2 &&
3496 *(uint32_t *)(p
+ 26) == 0 && *(uint32_t *)(p
+ 30) == 0 &&
3497 *(uint16_t *)(p
+ 34) == 0 && *(p
+ 36) == 0 && *(p
+ 37) == 1 && *(p
+ 38) == 0 && *(p
+ 39) == 2 &&
3498 *(p
+ 40) == 2 && *(p
+ 41) == 0x22 && *(p
+ 42) == 2 && *(p
+ 43) == 0x23)
3500 // DHCPV6 must be managed by the Master.
3501 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3506 processipv6in(s
, t
, p
, l
);
3508 else if (session
[s
].ppp
.lcp
== Opened
)
3510 session
[s
].last_packet
= time_now
;
3511 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3512 protoreject(s
, t
, p
, l
, proto
);
3516 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3517 proto
, ppp_state(session
[s
].ppp
.lcp
));
3522 // read and process packet on tun
3523 // (i.e. this routine writes to buf[-8]).
3524 static void processtun(uint8_t * buf
, int len
)
3526 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3527 STAT(tun_rx_packets
);
3528 INC_STAT(tun_rx_bytes
, len
);
3536 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3537 STAT(tun_rx_errors
);
3541 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3542 processipout(buf
, len
);
3543 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3544 && config
->ipv6_prefix
.s6_addr
[0])
3545 processipv6out(buf
, len
);
3550 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3551 // that we look at the whole of the tunnel, radius and session tables
3553 static void regular_cleanups(double period
)
3555 // Next tunnel, radius and session to check for actions on.
3556 static tunnelidt t
= 0;
3558 static sessionidt s
= 0;
3571 // divide up tables into slices based on the last run
3572 t_slice
= config
->cluster_highest_tunnelid
* period
;
3573 r_slice
= (MAXRADIUS
- 1) * period
;
3574 s_slice
= config
->cluster_highest_sessionid
* period
;
3578 else if (t_slice
> config
->cluster_highest_tunnelid
)
3579 t_slice
= config
->cluster_highest_tunnelid
;
3583 else if (r_slice
> (MAXRADIUS
- 1))
3584 r_slice
= MAXRADIUS
- 1;
3588 else if (s_slice
> config
->cluster_highest_sessionid
)
3589 s_slice
= config
->cluster_highest_sessionid
;
3591 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3593 for (i
= 0; i
< t_slice
; i
++)
3596 if (t
> config
->cluster_highest_tunnelid
)
3599 if (t
== TUNNEL_ID_PPPOE
)
3602 // check for expired tunnels
3603 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3605 STAT(tunnel_timeout
);
3606 tunnelkill(t
, "Expired");
3610 // check for message resend
3611 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3613 // resend pending messages as timeout on reply
3614 if (tunnel
[t
].retry
<= TIME
)
3616 controlt
*c
= tunnel
[t
].controls
;
3617 uint16_t w
= tunnel
[t
].window
;
3618 tunnel
[t
].try++; // another try
3619 if (tunnel
[t
].try > 5)
3620 tunnelkill(t
, "Timeout on control message"); // game over
3624 tunnelsend(c
->buf
, c
->length
, t
);
3632 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3634 if (!config
->disable_sending_hello
)
3636 controlt
*c
= controlnew(6); // sending HELLO
3637 controladd(c
, 0, t
); // send the message
3638 LOG(3, 0, t
, "Sending HELLO message\n");
3643 // Check for tunnel changes requested from the CLI
3644 if ((a
= cli_tunnel_actions
[t
].action
))
3646 cli_tunnel_actions
[t
].action
= 0;
3647 if (a
& CLI_TUN_KILL
)
3649 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3650 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3656 for (i
= 0; i
< r_slice
; i
++)
3662 if (!radius
[r
].state
)
3665 if (radius
[r
].retry
<= TIME
)
3672 for (i
= 0; i
< s_slice
; i
++)
3675 if (s
> config
->cluster_highest_sessionid
)
3678 if (!session
[s
].opened
) // Session isn't in use
3681 // check for expired sessions
3684 if (session
[s
].die
<= TIME
)
3686 sessionkill(s
, "Expired");
3693 if (sess_local
[s
].lcp
.restart
<= time_now
)
3695 int next_state
= session
[s
].ppp
.lcp
;
3696 switch (session
[s
].ppp
.lcp
)
3700 next_state
= RequestSent
;
3703 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3705 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3706 sendlcp(s
, session
[s
].tunnel
);
3707 change_state(s
, lcp
, next_state
);
3711 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3712 STAT(session_timeout
);
3722 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3724 int next_state
= session
[s
].ppp
.ipcp
;
3725 switch (session
[s
].ppp
.ipcp
)
3729 next_state
= RequestSent
;
3732 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3734 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3735 sendipcp(s
, session
[s
].tunnel
);
3736 change_state(s
, ipcp
, next_state
);
3740 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3741 STAT(session_timeout
);
3751 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3753 int next_state
= session
[s
].ppp
.ipv6cp
;
3754 switch (session
[s
].ppp
.ipv6cp
)
3758 next_state
= RequestSent
;
3761 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3763 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3764 sendipv6cp(s
, session
[s
].tunnel
);
3765 change_state(s
, ipv6cp
, next_state
);
3769 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3770 change_state(s
, ipv6cp
, Stopped
);
3777 if (sess_local
[s
].ccp
.restart
<= time_now
)
3779 int next_state
= session
[s
].ppp
.ccp
;
3780 switch (session
[s
].ppp
.ccp
)
3784 next_state
= RequestSent
;
3787 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3789 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3790 sendccp(s
, session
[s
].tunnel
);
3791 change_state(s
, ccp
, next_state
);
3795 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3796 change_state(s
, ccp
, Stopped
);
3803 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3804 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3806 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3807 STAT(session_timeout
);
3812 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3813 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= config
->echo_timeout
) &&
3814 (time_now
- sess_local
[s
].last_echo
>= config
->echo_timeout
))
3816 uint8_t b
[MAXETHER
];
3818 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3822 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3823 *(uint16_t *)(q
+ 2) = htons(8); // Length
3824 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3826 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3827 (int)(time_now
- session
[s
].last_packet
));
3829 tunnelsend(b
, (q
- b
) + 8, session
[s
].tunnel
); // send it
3830 sess_local
[s
].last_echo
= time_now
;
3834 // Drop sessions who have reached session_timeout seconds
3835 if (session
[s
].session_timeout
)
3837 bundleidt bid
= session
[s
].bundle
;
3840 if (time_now
- bundle
[bid
].last_check
>= 1)
3842 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3843 bundle
[bid
].last_check
= time_now
;
3844 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3847 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3849 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3856 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3858 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3864 // Drop sessions who have reached idle_timeout seconds
3865 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3867 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3868 STAT(session_timeout
);
3873 // Check for actions requested from the CLI
3874 if ((a
= cli_session_actions
[s
].action
))
3878 cli_session_actions
[s
].action
= 0;
3879 if (a
& CLI_SESS_KILL
)
3881 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3882 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3883 a
= 0; // dead, no need to check for other actions
3887 if (a
& CLI_SESS_NOSNOOP
)
3889 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3890 session
[s
].snoop_ip
= 0;
3891 session
[s
].snoop_port
= 0;
3895 else if (a
& CLI_SESS_SNOOP
)
3897 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3898 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3899 cli_session_actions
[s
].snoop_port
);
3901 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3902 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3907 if (a
& CLI_SESS_NOTHROTTLE
)
3909 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3910 throttle_session(s
, 0, 0);
3914 else if (a
& CLI_SESS_THROTTLE
)
3916 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3917 cli_session_actions
[s
].throttle_in
,
3918 cli_session_actions
[s
].throttle_out
);
3920 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3925 if (a
& CLI_SESS_NOFILTER
)
3927 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3928 filter_session(s
, 0, 0);
3932 else if (a
& CLI_SESS_FILTER
)
3934 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3935 cli_session_actions
[s
].filter_in
,
3936 cli_session_actions
[s
].filter_out
);
3938 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3944 cluster_send_session(s
);
3947 // RADIUS interim accounting
3948 if (config
->radius_accounting
&& config
->radius_interim
> 0
3949 && session
[s
].ip
&& !session
[s
].walled_garden
3950 && !sess_local
[s
].radius
// RADIUS already in progress
3951 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3952 && session
[s
].flags
& SESSION_STARTED
)
3954 int rad
= radiusnew(s
);
3957 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3958 STAT(radius_overflow
);
3962 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3963 session
[s
].user
, session
[s
].unique_id
);
3965 radiussend(rad
, RADIUSINTERIM
);
3966 sess_local
[s
].last_interim
= time_now
;
3971 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3972 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3976 // Are we in the middle of a tunnel update, or radius
3979 static int still_busy(void)
3982 static clockt last_talked
= 0;
3983 static clockt start_busy_wait
= 0;
3986 static time_t stopped_bgp
= 0;
3991 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3993 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3994 if (bgp_peers
[i
].state
== Established
)
3995 bgp_stop(&bgp_peers
[i
]);
3997 stopped_bgp
= time_now
;
3999 if (!config
->cluster_iam_master
)
4001 // we don't want to become master
4002 cluster_send_ping(0);
4008 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
4013 if (!config
->cluster_iam_master
)
4016 if (main_quit
== QUIT_SHUTDOWN
)
4018 static int dropped
= 0;
4023 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
4024 for (i
= 1; i
< MAXTUNNEL
; i
++)
4025 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
4026 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
4032 if (start_busy_wait
== 0)
4033 start_busy_wait
= TIME
;
4035 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
4037 if (!tunnel
[i
].controlc
)
4040 if (last_talked
!= TIME
)
4042 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
4048 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
4049 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
4051 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
4055 for (i
= 1; i
< MAXRADIUS
; i
++)
4057 if (radius
[i
].state
== RADIUSNULL
)
4059 if (radius
[i
].state
== RADIUSWAIT
)
4062 if (last_talked
!= TIME
)
4064 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
4074 # include <sys/epoll.h>
4076 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
4077 # include "fake_epoll.h"
4080 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
4081 #define BASE_FDS (9 + MAX_UDPFD)
4083 // additional polled fds
4085 # define EXTRA_FDS BGP_NUM_PEERS
4087 # define EXTRA_FDS 0
4090 // main loop - gets packets on tun or udp and processes them
4091 static void mainloop(void)
4095 uint8_t *p
= buf
+ 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4096 // and the forwarded pppoe session
4097 int size_bufp
= sizeof(buf
) - 32;
4098 clockt next_cluster_ping
= 0; // send initial ping immediately
4099 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
4100 int maxevent
= sizeof(events
)/sizeof(*events
);
4102 if ((epollfd
= epoll_create(maxevent
)) < 0)
4104 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
4108 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",
4109 clifd
, cluster_sockfd
, tunfd
, udpfd
[0], controlfd
, daefd
, nlfd
, udplacfd
, pppoediscfd
, pppoesessfd
);
4111 /* setup our fds to poll for input */
4113 static struct event_data d
[BASE_FDS
];
4114 struct epoll_event e
;
4121 d
[i
].type
= FD_TYPE_CLI
;
4122 e
.data
.ptr
= &d
[i
++];
4123 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
4126 d
[i
].type
= FD_TYPE_CLUSTER
;
4127 e
.data
.ptr
= &d
[i
++];
4128 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
4130 d
[i
].type
= FD_TYPE_TUN
;
4131 e
.data
.ptr
= &d
[i
++];
4132 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
4134 d
[i
].type
= FD_TYPE_CONTROL
;
4135 e
.data
.ptr
= &d
[i
++];
4136 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
4138 d
[i
].type
= FD_TYPE_DAE
;
4139 e
.data
.ptr
= &d
[i
++];
4140 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
4142 d
[i
].type
= FD_TYPE_NETLINK
;
4143 e
.data
.ptr
= &d
[i
++];
4144 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
4146 d
[i
].type
= FD_TYPE_PPPOEDISC
;
4147 e
.data
.ptr
= &d
[i
++];
4148 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoediscfd
, &e
);
4150 d
[i
].type
= FD_TYPE_PPPOESESS
;
4151 e
.data
.ptr
= &d
[i
++];
4152 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoesessfd
, &e
);
4154 for (j
= 0; j
< config
->nbudpfd
; j
++)
4156 d
[i
].type
= FD_TYPE_UDP
;
4158 e
.data
.ptr
= &d
[i
++];
4159 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
[j
], &e
);
4164 signal(SIGPIPE
, SIG_IGN
);
4165 bgp_setup(config
->as_number
);
4166 if (config
->bind_address
)
4167 bgp_add_route(config
->bind_address
, 0xffffffff);
4169 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4171 if (config
->neighbour
[i
].name
[0])
4172 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4173 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4174 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4175 0); /* 0 = routing disabled */
4179 while (!main_quit
|| still_busy())
4189 config
->reload_config
++;
4192 if (config
->reload_config
)
4194 config
->reload_config
= 0;
4202 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4203 STAT(select_called
);
4208 if (errno
== EINTR
||
4209 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4212 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4218 struct sockaddr_in addr
;
4219 struct in_addr local
;
4222 int udp_ready
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4223 int pppoesess_ready
= 0;
4224 int pppoesess_pkts
= 0;
4226 int cluster_ready
= 0;
4227 int udp_pkts
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4229 int cluster_pkts
= 0;
4231 uint32_t bgp_events
[BGP_NUM_PEERS
];
4232 memset(bgp_events
, 0, sizeof(bgp_events
));
4235 for (c
= n
, i
= 0; i
< c
; i
++)
4237 struct event_data
*d
= events
[i
].data
.ptr
;
4241 case FD_TYPE_CLI
: // CLI connections
4245 alen
= sizeof(addr
);
4246 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4252 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4258 // these are handled below, with multiple interleaved reads
4259 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4260 case FD_TYPE_TUN
: tun_ready
++; break;
4261 case FD_TYPE_UDP
: udp_ready
[d
->index
]++; break;
4262 case FD_TYPE_PPPOESESS
: pppoesess_ready
++; break;
4264 case FD_TYPE_PPPOEDISC
: // pppoe discovery
4265 s
= read(pppoediscfd
, p
, size_bufp
);
4266 if (s
> 0) process_pppoe_disc(p
, s
);
4270 case FD_TYPE_CONTROL
: // nsctl commands
4271 alen
= sizeof(addr
);
4272 s
= recvfromto(controlfd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4273 if (s
> 0) processcontrol(p
, s
, &addr
, alen
, &local
);
4277 case FD_TYPE_DAE
: // DAE requests
4278 alen
= sizeof(addr
);
4279 s
= recvfromto(daefd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4280 if (s
> 0) processdae(p
, s
, &addr
, alen
, &local
);
4284 case FD_TYPE_RADIUS
: // RADIUS response
4285 alen
= sizeof(addr
);
4286 s
= recvfrom(radfds
[d
->index
], p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4287 if (s
>= 0 && config
->cluster_iam_master
)
4289 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4290 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4291 processrad(p
, s
, d
->index
);
4293 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4294 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4302 bgp_events
[d
->index
] = events
[i
].events
;
4307 case FD_TYPE_NETLINK
:
4309 struct nlmsghdr
*nh
= (struct nlmsghdr
*)p
;
4310 s
= netlink_recv(p
, size_bufp
);
4311 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4313 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4316 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4318 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4322 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4327 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
);
4333 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4338 bgp_process(bgp_events
);
4341 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4343 for (j
= 0; j
< config
->nbudpfd
; j
++)
4345 // L2TP and L2TP REMOTE LNS
4348 alen
= sizeof(addr
);
4349 if ((s
= recvfrom(udpfd
[j
], p
, size_bufp
, 0, (void *) &addr
, &alen
)) > 0)
4351 processudp(p
, s
, &addr
, j
);
4365 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4378 if (pppoesess_ready
)
4380 if ((s
= read(pppoesessfd
, p
, size_bufp
)) > 0)
4382 process_pppoe_sess(p
, s
);
4387 pppoesess_ready
= 0;
4395 alen
= sizeof(addr
);
4396 if ((s
= recvfrom(cluster_sockfd
, p
, size_bufp
, MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4398 processcluster(p
, s
, addr
.sin_addr
.s_addr
);
4409 if (udp_pkts
[0] > 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4410 STAT(multi_read_used
);
4412 if (c
>= config
->multi_read_count
)
4414 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4415 config
->multi_read_count
, udp_pkts
[0], tun_pkts
, cluster_pkts
, pppoesess_pkts
);
4416 STAT(multi_read_exceeded
);
4422 /* no event received, but timers could still have expired */
4423 bgp_process_peers_timers();
4428 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4430 // Log current traffic stats
4431 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4432 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4433 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4434 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4435 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4437 udp_tx
= udp_rx
= 0;
4438 udp_rx_pkt
= eth_rx_pkt
= 0;
4439 eth_tx
= eth_rx
= 0;
4442 if (config
->dump_speed
)
4443 printf("%s\n", config
->bandwidth
);
4445 // Update the internal time counter
4446 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4450 struct param_timer p
= { time_now
};
4451 run_plugins(PLUGIN_TIMER
, &p
);
4455 // Runs on every machine (master and slaves).
4456 if (next_cluster_ping
<= TIME
)
4458 // Check to see which of the cluster is still alive..
4460 cluster_send_ping(basetime
); // Only does anything if we're a slave
4461 cluster_check_master(); // ditto.
4463 cluster_heartbeat(); // Only does anything if we're a master.
4464 cluster_check_slaves(); // ditto.
4466 master_update_counts(); // If we're a slave, send our byte counters to our master.
4468 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4469 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4471 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4474 if (!config
->cluster_iam_master
)
4477 // Run token bucket filtering queue..
4478 // Only run it every 1/10th of a second.
4480 static clockt last_run
= 0;
4481 if (last_run
!= TIME
)
4488 // Handle timeouts, retries etc.
4490 static double last_clean
= 0;
4494 TIME
= now(&this_clean
);
4495 diff
= this_clean
- last_clean
;
4497 // Run during idle time (after we've handled
4498 // all incoming packets) or every 1/10th sec
4499 if (!more
|| diff
> 0.1)
4501 regular_cleanups(diff
);
4502 last_clean
= this_clean
;
4506 if (*config
->accounting_dir
)
4508 static clockt next_acct
= 0;
4509 static clockt next_shut_acct
= 0;
4511 if (next_acct
<= TIME
)
4513 // Dump accounting data
4514 next_acct
= TIME
+ ACCT_TIME
;
4515 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4518 else if (next_shut_acct
<= TIME
)
4520 // Dump accounting data for shutdown sessions
4521 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4528 // Are we the master and shutting down??
4529 if (config
->cluster_iam_master
)
4530 cluster_heartbeat(); // Flush any queued changes..
4532 // Ok. Notify everyone we're shutting down. If we're
4533 // the master, this will force an election.
4534 cluster_send_ping(0);
4537 // Important!!! We MUST not process any packets past this point!
4538 LOG(1, 0, 0, "Shutdown complete\n");
4541 static void stripdomain(char *host
)
4545 if ((p
= strchr(host
, '.')))
4551 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4557 while (fgets(buf
, sizeof(buf
), resolv
))
4559 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4562 if (!isspace(buf
[6]))
4566 while (isspace(*b
)) b
++;
4571 while (*b
&& !isspace(*b
)) b
++;
4573 if (buf
[0] == 'd') // domain is canonical
4579 // first search line
4582 // hold, may be subsequent domain line
4583 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4594 int hl
= strlen(host
);
4595 int dl
= strlen(domain
);
4596 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4597 host
[hl
-dl
- 1] = 0;
4601 *p
= 0; // everything after first dot
4606 // Init data structures
4607 static void initdata(int optdebug
, char *optconfig
)
4611 if (!(config
= shared_malloc(sizeof(configt
))))
4613 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4617 memset(config
, 0, sizeof(configt
));
4618 time(&config
->start_time
);
4619 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4620 config
->debug
= optdebug
;
4621 config
->num_tbfs
= MAXTBFS
;
4622 config
->rl_rate
= 28; // 28kbps
4623 config
->cluster_mcast_ttl
= 1;
4624 config
->cluster_master_min_adv
= 1;
4625 config
->ppp_restart_time
= 3;
4626 config
->ppp_max_configure
= 10;
4627 config
->ppp_max_failure
= 5;
4628 config
->kill_timedout_sessions
= 1;
4629 strcpy(config
->random_device
, RANDOMDEVICE
);
4630 // Set default value echo_timeout and idle_echo_timeout
4631 config
->echo_timeout
= ECHO_TIMEOUT
;
4632 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4634 log_stream
= stderr
;
4637 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4639 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4642 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4645 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4647 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4650 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4652 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4655 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4657 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4660 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4662 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4665 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4667 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4671 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4673 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4677 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4679 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4683 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4685 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4689 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4691 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4694 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4696 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4698 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4701 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4703 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4705 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4708 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4710 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4711 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4712 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4713 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4714 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4716 // Put all the sessions on the free list marked as undefined.
4717 for (i
= 1; i
< MAXSESSION
; i
++)
4719 session
[i
].next
= i
+ 1;
4720 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4722 session
[MAXSESSION
- 1].next
= 0;
4725 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4726 for (i
= 1; i
< MAXTUNNEL
; i
++)
4727 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4729 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4730 bundle
[i
].state
= BUNDLEUNDEF
;
4735 // Grab my hostname unless it's been specified
4736 gethostname(hostname
, sizeof(hostname
));
4737 stripdomain(hostname
);
4740 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4743 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4745 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4750 lac_initremotelnsdata();
4755 static int assign_ip_address(sessionidt s
)
4759 time_t best_time
= time_now
;
4760 char *u
= session
[s
].user
;
4764 CSTAT(assign_ip_address
);
4766 for (i
= 1; i
< ip_pool_size
; i
++)
4768 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4771 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4778 if (ip_address_pool
[i
].last
< best_time
)
4781 if (!(best_time
= ip_address_pool
[i
].last
))
4782 break; // never used, grab this one
4788 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4792 session
[s
].ip
= ip_address_pool
[best
].address
;
4793 session
[s
].ip_pool_index
= best
;
4794 ip_address_pool
[best
].assigned
= 1;
4795 ip_address_pool
[best
].last
= time_now
;
4796 ip_address_pool
[best
].session
= s
;
4797 if (session
[s
].walled_garden
)
4798 /* Don't track addresses of users in walled garden (note: this
4799 means that their address isn't "sticky" even if they get
4801 ip_address_pool
[best
].user
[0] = 0;
4803 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4806 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4807 reuse
? "Reusing" : "Allocating", best
);
4812 static void free_ip_address(sessionidt s
)
4814 int i
= session
[s
].ip_pool_index
;
4817 CSTAT(free_ip_address
);
4820 return; // what the?
4822 if (i
< 0) // Is this actually part of the ip pool?
4826 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4828 ip_address_pool
[i
].assigned
= 0;
4829 ip_address_pool
[i
].session
= 0;
4830 ip_address_pool
[i
].last
= time_now
;
4834 // Fsck the address pool against the session table.
4835 // Normally only called when we become a master.
4837 // This isn't perfect: We aren't keep tracking of which
4838 // users used to have an IP address.
4840 void rebuild_address_pool(void)
4845 // Zero the IP pool allocation, and build
4846 // a map from IP address to pool index.
4847 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4849 ip_address_pool
[i
].assigned
= 0;
4850 ip_address_pool
[i
].session
= 0;
4851 if (!ip_address_pool
[i
].address
)
4854 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4857 for (i
= 0; i
< MAXSESSION
; ++i
)
4860 if (!(session
[i
].opened
&& session
[i
].ip
))
4863 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4865 if (session
[i
].ip_pool_index
< 0)
4867 // Not allocated out of the pool.
4868 if (ipid
< 1) // Not found in the pool either? good.
4871 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4872 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4874 // Fall through and process it as part of the pool.
4878 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4880 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4882 session
[i
].ip_pool_index
= ipid
;
4886 ip_address_pool
[ipid
].assigned
= 1;
4887 ip_address_pool
[ipid
].session
= i
;
4888 ip_address_pool
[ipid
].last
= time_now
;
4889 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4890 session
[i
].ip_pool_index
= ipid
;
4891 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4896 // Fix the address pool to match a changed session.
4897 // (usually when the master sends us an update).
4898 static void fix_address_pool(int sid
)
4902 ipid
= session
[sid
].ip_pool_index
;
4904 if (ipid
> ip_pool_size
)
4905 return; // Ignore it. rebuild_address_pool will fix it up.
4907 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4908 return; // Just ignore it. rebuild_address_pool will take care of it.
4910 ip_address_pool
[ipid
].assigned
= 1;
4911 ip_address_pool
[ipid
].session
= sid
;
4912 ip_address_pool
[ipid
].last
= time_now
;
4913 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4917 // Add a block of addresses to the IP pool to hand out.
4919 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4923 prefixlen
= 32; // Host route only.
4925 addr
&= 0xffffffff << (32 - prefixlen
);
4927 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4930 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4932 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4933 continue; // Skip 0 and broadcast addresses.
4935 ip_address_pool
[ip_pool_size
].address
= i
;
4936 ip_address_pool
[ip_pool_size
].assigned
= 0;
4938 if (ip_pool_size
>= MAXIPPOOL
)
4940 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4946 // Initialize the IP address pool
4947 static void initippool()
4952 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4954 if (!(f
= fopen(IPPOOLFILE
, "r")))
4956 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4960 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4963 buf
[4095] = 0; // Force it to be zero terminated/
4965 if (*buf
== '#' || *buf
== '\n')
4966 continue; // Skip comments / blank lines
4967 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4968 if ((p
= (char *)strchr(buf
, ':')))
4972 src
= inet_addr(buf
);
4973 if (src
== INADDR_NONE
)
4975 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4978 // This entry is for a specific IP only
4979 if (src
!= config
->bind_address
)
4984 if ((p
= (char *)strchr(pool
, '/')))
4988 in_addr_t start
= 0;
4990 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4992 if (!*p
|| !(numbits
= atoi(p
)))
4994 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4997 start
= ntohl(inet_addr(pool
));
4999 // Add a static route for this pool
5000 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
5001 fmtaddr(htonl(start
), 0), numbits
);
5003 routeset(0, start
, numbits
, 0, 1);
5005 add_to_ip_pool(start
, numbits
);
5009 // It's a single ip address
5010 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
5014 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
5017 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
5019 struct sockaddr_in snoop_addr
= {0};
5020 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
5023 snoop_addr
.sin_family
= AF_INET
;
5024 snoop_addr
.sin_addr
.s_addr
= destination
;
5025 snoop_addr
.sin_port
= ntohs(port
);
5027 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
5028 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
5029 htons(snoop_addr
.sin_port
));
5031 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
5032 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
5034 STAT(packets_snooped
);
5037 static int dump_session(FILE **f
, sessiont
*s
)
5039 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
5044 char filename
[1024];
5046 time_t now
= time(NULL
);
5048 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
5049 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
5051 if (!(*f
= fopen(filename
, "w")))
5053 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
5057 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
5058 if(config
->account_all_origin
)
5060 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5065 "# format: username ip qos uptxoctets downrxoctets origin(L=LAC, R=Remote LNS, P=PPPOE)\n",
5067 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5073 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5078 "# format: username ip qos uptxoctets downrxoctets\n",
5080 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5086 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
5087 if(config
->account_all_origin
)
5089 fprintf(*f
, "%s %s %d %u %u %s\n",
5090 s
->user
, // username
5091 fmtaddr(htonl(s
->ip
), 0), // ip
5092 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5093 (uint32_t) s
->cin_delta
, // uptxoctets
5094 (uint32_t) s
->cout_delta
, // downrxoctets
5095 (s
->tunnel
== TUNNEL_ID_PPPOE
)?"P":(tunnel
[s
->tunnel
].isremotelns
?"R":"L")); // Origin
5097 else if (!tunnel
[s
->tunnel
].isremotelns
&& (s
->tunnel
!= TUNNEL_ID_PPPOE
))
5099 fprintf(*f
, "%s %s %d %u %u\n",
5100 s
->user
, // username
5101 fmtaddr(htonl(s
->ip
), 0), // ip
5102 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5103 (uint32_t) s
->cin_delta
, // uptxoctets
5104 (uint32_t) s
->cout_delta
); // downrxoctets
5107 s
->cin_delta
= s
->cout_delta
= 0;
5112 static void dump_acct_info(int all
)
5118 CSTAT(dump_acct_info
);
5122 for (i
= 0; i
< shut_acct_n
; i
++)
5123 dump_session(&f
, &shut_acct
[i
]);
5129 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5130 dump_session(&f
, &session
[i
]);
5137 int main(int argc
, char *argv
[])
5141 char *optconfig
= CONFIGFILE
;
5143 time(&basetime
); // start clock
5146 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
5151 if (fork()) exit(0);
5153 if(!freopen("/dev/null", "r", stdin
)) LOG(0, 0, 0, "Error freopen stdin: %s\n", strerror(errno
));
5154 if(!freopen("/dev/null", "w", stdout
)) LOG(0, 0, 0, "Error freopen stdout: %s\n", strerror(errno
));
5155 if(!freopen("/dev/null", "w", stderr
)) LOG(0, 0, 0, "Error freopen stderr: %s\n", strerror(errno
));
5164 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
5167 printf("Args are:\n"
5168 "\t-d\t\tDetach from terminal\n"
5169 "\t-c <file>\tConfig file\n"
5170 "\t-h <hostname>\tForce hostname\n"
5178 // Start the timer routine off
5180 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5183 initdata(optdebug
, optconfig
);
5187 /* set hostname /after/ having read the config file */
5188 if (*config
->hostname
)
5189 strcpy(hostname
, config
->hostname
);
5190 cli_init_complete(hostname
);
5192 init_tbf(config
->num_tbfs
);
5194 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5195 LOG(0, 0, 0, "Copyright (c) 2012, 2013, 2014 ISP FDN & SAMESWIRELESS\n");
5196 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5197 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5200 rlim
.rlim_cur
= RLIM_INFINITY
;
5201 rlim
.rlim_max
= RLIM_INFINITY
;
5202 // Remove the maximum core size
5203 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5204 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5206 // Make core dumps go to /tmp
5207 if(chdir("/tmp")) LOG(0, 0, 0, "Error chdir /tmp: %s\n", strerror(errno
));
5210 if (config
->scheduler_fifo
)
5213 struct sched_param params
= {0};
5214 params
.sched_priority
= 1;
5216 if (get_nprocs() < 2)
5218 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5219 config
->scheduler_fifo
= 0;
5223 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5225 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5229 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5230 config
->scheduler_fifo
= 0;
5237 /* Set up the cluster communications port. */
5238 if (cluster_init() < 0)
5242 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5244 if (*config
->pppoe_if_to_bind
)
5247 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config
->pppoe_if_to_bind
);
5250 if (!config
->nbmultiaddress
)
5252 config
->bind_n_address
[0] = config
->bind_address
;
5253 config
->nbmultiaddress
++;
5255 config
->nbudpfd
= config
->nbmultiaddress
;
5256 for (i
= 0; i
< config
->nbudpfd
; i
++)
5257 initudp(&udpfd
[i
], config
->bind_n_address
[i
]);
5259 config
->indexlacudpfd
= config
->nbudpfd
;
5260 udpfd
[config
->indexlacudpfd
] = udplacfd
;
5267 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
5275 unsigned seed
= time_now
^ getpid();
5276 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5280 signal(SIGHUP
, sighup_handler
);
5281 signal(SIGCHLD
, sigchild_handler
);
5282 signal(SIGTERM
, shutdown_handler
);
5283 signal(SIGINT
, shutdown_handler
);
5284 signal(SIGQUIT
, shutdown_handler
);
5286 // Prevent us from getting paged out
5287 if (config
->lock_pages
)
5289 if (!mlockall(MCL_CURRENT
))
5290 LOG(1, 0, 0, "Locking pages into memory\n");
5292 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5295 //LOG(3, 0, 0, "Debug sizeof struct: sessiont %lu, tunnelt %lu, bundlet %lu, groupsesst %lu\n",
5296 // sizeof(sessiont), sizeof(tunnelt), sizeof(bundlet), sizeof(groupsesst));
5300 /* remove plugins (so cleanup code gets run) */
5303 // Remove the PID file if we wrote it
5304 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5305 unlink(config
->pid_file
);
5307 /* kill CLI children */
5308 signal(SIGTERM
, SIG_IGN
);
5313 static void sighup_handler(int sig
)
5318 static void shutdown_handler(int sig
)
5320 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5323 static void sigchild_handler(int sig
)
5325 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5329 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5332 *challenge_response
= NULL
;
5334 if (!*config
->l2tp_secret
)
5336 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5340 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5342 *challenge_response
= calloc(17, 1);
5345 MD5_Update(&ctx
, &id
, 1);
5346 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5347 MD5_Update(&ctx
, challenge
, challenge_length
);
5348 MD5_Final(*challenge_response
, &ctx
);
5353 static int facility_value(char *name
)
5356 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5358 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5359 return facilitynames
[i
].c_val
;
5364 static void update_config()
5368 static int timeout
= 0;
5369 static int interval
= 0;
5376 if (log_stream
!= stderr
)
5382 if (*config
->log_filename
)
5384 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5386 char *p
= config
->log_filename
+ 7;
5389 openlog("l2tpns", LOG_PID
, facility_value(p
));
5393 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5395 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5397 fseek(log_stream
, 0, SEEK_END
);
5398 setbuf(log_stream
, NULL
);
5402 log_stream
= stderr
;
5403 setbuf(log_stream
, NULL
);
5409 log_stream
= stderr
;
5410 setbuf(log_stream
, NULL
);
5413 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5414 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5416 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5417 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5418 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5420 // reset MRU/MSS globals
5421 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5422 if (MRU
> PPPoE_MRU
)
5425 MSS
= MRU
- TCP_HDRS
;
5428 config
->numradiusservers
= 0;
5429 for (i
= 0; i
< MAXRADSERVER
; i
++)
5430 if (config
->radiusserver
[i
])
5432 config
->numradiusservers
++;
5433 // Set radius port: if not set, take the port from the
5434 // first radius server. For the first radius server,
5435 // take the #defined default value from l2tpns.h
5437 // test twice, In case someone works with
5438 // a secondary radius server without defining
5439 // a primary one, this will work even then.
5440 if (i
> 0 && !config
->radiusport
[i
])
5441 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5442 if (!config
->radiusport
[i
])
5443 config
->radiusport
[i
] = RADPORT
;
5446 if (!config
->numradiusservers
)
5447 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5449 // parse radius_authtypes_s
5450 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5451 p
= config
->radius_authtypes_s
;
5454 char *s
= strpbrk(p
, " \t,");
5460 while (*s
== ' ' || *s
== '\t')
5467 if (!strncasecmp("chap", p
, strlen(p
)))
5469 else if (!strncasecmp("pap", p
, strlen(p
)))
5472 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5474 config
->radius_authtypes
|= type
;
5475 if (!config
->radius_authprefer
)
5476 config
->radius_authprefer
= type
;
5481 if (!config
->radius_authtypes
)
5483 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5484 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5487 // normalise radius_authtypes_s
5488 if (config
->radius_authprefer
== AUTHPAP
)
5490 strcpy(config
->radius_authtypes_s
, "pap");
5491 if (config
->radius_authtypes
& AUTHCHAP
)
5492 strcat(config
->radius_authtypes_s
, ", chap");
5496 strcpy(config
->radius_authtypes_s
, "chap");
5497 if (config
->radius_authtypes
& AUTHPAP
)
5498 strcat(config
->radius_authtypes_s
, ", pap");
5501 if (!config
->radius_dae_port
)
5502 config
->radius_dae_port
= DAEPORT
;
5504 if(!config
->bind_portremotelns
)
5505 config
->bind_portremotelns
= L2TPLACPORT
;
5506 if(!config
->bind_address_remotelns
)
5507 config
->bind_address_remotelns
= INADDR_ANY
;
5509 if (*config
->bind_multi_address
)
5511 char *sip
= config
->bind_multi_address
;
5513 char *e
= config
->bind_multi_address
+ strlen(config
->bind_multi_address
);
5514 config
->nbmultiaddress
= 0;
5516 while (*sip
&& (sip
< e
))
5521 while (n
< e
&& (*n
== ',' || *n
== ' ')) n
++;
5523 while (n
< e
&& (isdigit(*n
) || *n
== '.'))
5531 u
= u
* 10 + *n
- '0';
5539 config
->bind_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5540 config
->iftun_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5541 config
->nbmultiaddress
++;
5542 LOG(1, 0, 0, "Bind address %s\n", fmtaddr(htonl(ip
), 0));
5544 if (config
->nbmultiaddress
>= MAX_BINDADDR
) break;
5550 if (config
->nbmultiaddress
>= 1)
5552 config
->bind_address
= config
->bind_n_address
[0];
5553 config
->iftun_address
= config
->bind_address
;
5557 if(!config
->iftun_address
)
5559 config
->iftun_address
= config
->bind_address
;
5560 config
->iftun_n_address
[0] = config
->iftun_address
;
5563 if (*config
->multi_hostname
)
5565 char *shost
= config
->multi_hostname
;
5567 char *e
= config
->multi_hostname
+ strlen(config
->multi_hostname
);
5568 config
->nbmultihostname
= 0;
5570 while (*shost
&& (shost
< e
))
5572 while ((n
< e
) && (*n
== ' ' || *n
== ',' || *n
== '\t')) n
++;
5575 while (n
< e
&& (*n
!= ',') && (*n
!= '\t'))
5577 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = *n
;
5583 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = 0;
5584 LOG(1, 0, 0, "Bind Hostname %s\n", config
->multi_n_hostname
[config
->nbmultihostname
]);
5585 config
->nbmultihostname
++;
5586 if (config
->nbmultihostname
>= MAX_NBHOSTNAME
) break;
5592 if (config
->nbmultihostname
>= 1)
5594 strcpy(hostname
, config
->multi_n_hostname
[0]);
5595 strcpy(config
->hostname
, hostname
);
5599 if (!*config
->pppoe_ac_name
)
5600 strncpy(config
->pppoe_ac_name
, DEFAULT_PPPOE_AC_NAME
, sizeof(config
->pppoe_ac_name
) - 1);
5602 // re-initialise the random number source
5603 initrandom(config
->random_device
);
5606 for (i
= 0; i
< MAXPLUGINS
; i
++)
5608 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5611 if (*config
->plugins
[i
])
5614 add_plugin(config
->plugins
[i
]);
5616 else if (*config
->old_plugins
[i
])
5619 remove_plugin(config
->old_plugins
[i
]);
5624 guest_accounts_num
= 0;
5625 char *p2
= config
->guest_user
;
5628 char *s
= strpbrk(p2
, " \t,");
5632 while (*s
== ' ' || *s
== '\t')
5639 strcpy(guest_users
[guest_accounts_num
], p2
);
5640 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5641 guest_accounts_num
++;
5644 // Rebuild the guest_user array
5645 strcpy(config
->guest_user
, "");
5647 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5649 strcat(config
->guest_user
, guest_users
[ui
]);
5650 if (ui
<guest_accounts_num
-1)
5652 strcat(config
->guest_user
, ",");
5657 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5658 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5659 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5660 if (!*config
->cluster_interface
)
5661 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5663 if (!config
->cluster_hb_interval
)
5664 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5666 if (!config
->cluster_hb_timeout
)
5667 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5669 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5671 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5672 // late, ensure we're sufficiently larger than that
5673 int t
= 4 * config
->cluster_hb_interval
+ 11;
5675 if (config
->cluster_hb_timeout
< t
)
5677 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5678 config
->cluster_hb_timeout
= t
;
5681 // Push timing changes to the slaves immediately if we're the master
5682 if (config
->cluster_iam_master
)
5683 cluster_heartbeat();
5685 interval
= config
->cluster_hb_interval
;
5686 timeout
= config
->cluster_hb_timeout
;
5690 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5693 if ((f
= fopen(config
->pid_file
, "w")))
5695 fprintf(f
, "%d\n", getpid());
5697 config
->wrote_pid
= 1;
5701 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5706 static void read_config_file()
5710 if (!config
->config_file
) return;
5711 if (!(f
= fopen(config
->config_file
, "r")))
5713 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5717 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5719 LOG(3, 0, 0, "Done reading config file\n");
5723 int sessionsetup(sessionidt s
, tunnelidt t
)
5725 // A session now exists, set it up
5731 CSTAT(sessionsetup
);
5733 LOG(3, s
, t
, "Doing session setup for session\n");
5735 // Join a bundle if the MRRU option is accepted
5736 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5738 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5739 if (join_bundle(s
) > 0)
5740 cluster_send_bundle(session
[s
].bundle
);
5743 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5744 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5751 assign_ip_address(s
);
5754 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5755 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5758 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5759 fmtaddr(htonl(session
[s
].ip
), 0));
5762 // Make sure this is right
5763 session
[s
].tunnel
= t
;
5765 // zap old sessions with same IP and/or username
5766 // Don't kill gardened sessions - doing so leads to a DoS
5767 // from someone who doesn't need to know the password
5770 user
= session
[s
].user
;
5771 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5773 if (i
== s
) continue;
5774 if (!session
[s
].opened
) break;
5775 // Allow duplicate sessions for multilink ones of the same bundle.
5776 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5778 if (ip
== session
[i
].ip
)
5780 sessionshutdown(i
, "Duplicate IP address", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5784 if (config
->allow_duplicate_users
) continue;
5785 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5789 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5791 if (!strcasecmp(user
, guest_users
[gu
]))
5797 if (found
) continue;
5799 // Drop the new session in case of duplicate sessionss, not the old one.
5800 if (!strcasecmp(user
, session
[i
].user
))
5801 sessionshutdown(i
, "Duplicate session for users", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5805 // no need to set a route for the same IP address of the bundle
5806 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5811 // Add the route for this session.
5812 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5814 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5815 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5818 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5821 // Static IPs need to be routed if not already
5822 // convered by a Framed-Route. Anything else is part
5823 // of the IP address pool and is already routed, it
5824 // just needs to be added to the IP cache.
5825 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5826 if (session
[s
].ip_pool_index
== -1) // static ip
5828 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5831 cache_ipmap(session
[s
].ip
, s
);
5833 if ((g
= grp_groupbysession(s
)))
5835 grp_setgrouproute(g
, 1);
5836 cluster_send_groupe(g
);
5840 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5841 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5843 // Run the plugin's against this new session.
5845 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5846 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5849 // Allocate TBFs if throttled
5850 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5851 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5853 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5855 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5856 fmtaddr(htonl(session
[s
].ip
), 0),
5857 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5859 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5861 return 1; // RADIUS OK and IP allocated, done...
5865 // This session just got dropped on us by the master or something.
5866 // Make sure our tables up up to date...
5868 int load_session(sessionidt s
, sessiont
*new)
5874 if (new->ip_pool_index
>= MAXIPPOOL
||
5875 new->tunnel
>= MAXTUNNEL
)
5877 LOG(0, s
, 0, "Strange session update received!\n");
5878 // FIXME! What to do here?
5883 // Ok. All sanity checks passed. Now we're committed to
5884 // loading the new session.
5887 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5889 // See if routes/ip cache need updating
5890 if (new->ip
!= session
[s
].ip
)
5893 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5894 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5895 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5903 // remove old routes...
5904 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5906 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5907 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5910 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5916 if (session
[s
].ip_pool_index
== -1) // static IP
5918 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5920 else // It's part of the IP pool, remove it manually.
5921 uncache_ipmap(session
[s
].ip
);
5924 // remove old IPV6 routes...
5925 for (i
= 0; i
< MAXROUTE6
&& session
[s
].route6
[i
].ipv6route
.s6_addr
[0] && session
[s
].route6
[i
].ipv6prefixlen
; i
++)
5927 route6set(s
, session
[s
].route6
[i
].ipv6route
, session
[s
].route6
[i
].ipv6prefixlen
, 0);
5930 if (session
[s
].ipv6address
.s6_addr
[0])
5932 route6set(s
, session
[s
].ipv6address
, 128, 0);
5937 // add new routes...
5938 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5940 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5941 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5944 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5950 // If there's a new one, add it.
5951 if (new->ip_pool_index
== -1)
5953 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5956 cache_ipmap(new->ip
, s
);
5961 for (i
= 0; i
< MAXROUTE6
&& new->route6
[i
].ipv6prefixlen
; i
++)
5963 route6set(s
, new->route6
[i
].ipv6route
, new->route6
[i
].ipv6prefixlen
, 1);
5966 if (new->ipv6address
.s6_addr
[0] && new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5968 // Check if included in prefix
5969 if (sessionbyipv6(new->ipv6address
) != s
)
5970 route6set(s
, new->ipv6address
, 128, 1);
5974 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5976 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5980 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5982 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5983 new->filter_out
= 0;
5986 if (new->filter_in
!= session
[s
].filter_in
)
5988 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5989 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5992 if (new->filter_out
!= session
[s
].filter_out
)
5994 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5995 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5998 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5999 // for walking the sessions to forward byte counts to the master.
6000 config
->cluster_highest_sessionid
= s
;
6002 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
6004 // Do fixups into address pool.
6005 if (new->ip_pool_index
!= -1)
6006 fix_address_pool(s
);
6011 static void initplugins()
6015 loaded_plugins
= ll_init();
6016 // Initialize the plugins to nothing
6017 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
6018 plugins
[i
] = ll_init();
6021 static void *open_plugin(char *plugin_name
, int load
)
6023 char path
[256] = "";
6025 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
6026 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
6027 return dlopen(path
, RTLD_NOW
);
6030 // plugin callback to get a config value
6031 static void *getconfig(char *key
, enum config_typet type
)
6035 for (i
= 0; config_values
[i
].key
; i
++)
6037 if (!strcmp(config_values
[i
].key
, key
))
6039 if (config_values
[i
].type
== type
)
6040 return ((void *) config
) + config_values
[i
].offset
;
6042 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
6043 key
, type
, config_values
[i
].type
);
6049 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
6053 static int add_plugin(char *plugin_name
)
6055 static struct pluginfuncs funcs
= {
6060 sessiontbysessionidt
,
6061 sessionidtbysessiont
,
6068 cluster_send_session
,
6071 void *p
= open_plugin(plugin_name
, 1);
6072 int (*initfunc
)(struct pluginfuncs
*);
6077 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
6081 if (ll_contains(loaded_plugins
, p
))
6084 return 0; // already loaded
6088 int *v
= dlsym(p
, "plugin_api_version");
6089 if (!v
|| *v
!= PLUGIN_API_VERSION
)
6091 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
6097 if ((initfunc
= dlsym(p
, "plugin_init")))
6099 if (!initfunc(&funcs
))
6101 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
6107 ll_push(loaded_plugins
, p
);
6109 for (i
= 0; i
< max_plugin_functions
; i
++)
6112 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6114 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
6115 ll_push(plugins
[i
], x
);
6119 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
6123 static void run_plugin_done(void *plugin
)
6125 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
6131 static int remove_plugin(char *plugin_name
)
6133 void *p
= open_plugin(plugin_name
, 0);
6139 if (ll_contains(loaded_plugins
, p
))
6142 for (i
= 0; i
< max_plugin_functions
; i
++)
6145 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6146 ll_delete(plugins
[i
], x
);
6149 ll_delete(loaded_plugins
, p
);
6155 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
6159 int run_plugins(int plugin_type
, void *data
)
6161 int (*func
)(void *data
);
6163 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
6164 return PLUGIN_RET_ERROR
;
6166 ll_reset(plugins
[plugin_type
]);
6167 while ((func
= ll_next(plugins
[plugin_type
])))
6171 if (r
!= PLUGIN_RET_OK
)
6172 return r
; // stop here
6175 return PLUGIN_RET_OK
;
6178 static void plugins_done()
6182 ll_reset(loaded_plugins
);
6183 while ((p
= ll_next(loaded_plugins
)))
6187 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
6189 struct nsctl request
;
6190 struct nsctl response
;
6191 int type
= unpack_control(&request
, buf
, len
);
6195 if (log_stream
&& config
->debug
>= 4)
6199 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6200 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
6204 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6205 dump_control(&request
, log_stream
);
6211 case NSCTL_REQ_LOAD
:
6212 if (request
.argc
!= 1)
6214 response
.type
= NSCTL_RES_ERR
;
6216 response
.argv
[0] = "name of plugin required";
6218 else if ((r
= add_plugin(request
.argv
[0])) < 1)
6220 response
.type
= NSCTL_RES_ERR
;
6222 response
.argv
[0] = !r
6223 ? "plugin already loaded"
6224 : "error loading plugin";
6228 response
.type
= NSCTL_RES_OK
;
6234 case NSCTL_REQ_UNLOAD
:
6235 if (request
.argc
!= 1)
6237 response
.type
= NSCTL_RES_ERR
;
6239 response
.argv
[0] = "name of plugin required";
6241 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
6243 response
.type
= NSCTL_RES_ERR
;
6245 response
.argv
[0] = !r
6246 ? "plugin not loaded"
6247 : "plugin not found";
6251 response
.type
= NSCTL_RES_OK
;
6257 case NSCTL_REQ_HELP
:
6258 response
.type
= NSCTL_RES_OK
;
6261 ll_reset(loaded_plugins
);
6262 while ((p
= ll_next(loaded_plugins
)))
6264 char **help
= dlsym(p
, "plugin_control_help");
6265 while (response
.argc
< 0xff && help
&& *help
)
6266 response
.argv
[response
.argc
++] = *help
++;
6271 case NSCTL_REQ_CONTROL
:
6273 struct param_control param
= {
6274 config
->cluster_iam_master
,
6281 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
6283 if (r
== PLUGIN_RET_ERROR
)
6285 response
.type
= NSCTL_RES_ERR
;
6287 response
.argv
[0] = param
.additional
6289 : "error returned by plugin";
6291 else if (r
== PLUGIN_RET_NOTMASTER
)
6293 static char msg
[] = "must be run on master: 000.000.000.000";
6295 response
.type
= NSCTL_RES_ERR
;
6297 if (config
->cluster_master_address
)
6299 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
6300 response
.argv
[0] = msg
;
6304 response
.argv
[0] = "must be run on master: none elected";
6307 else if (!(param
.response
& NSCTL_RESPONSE
))
6309 response
.type
= NSCTL_RES_ERR
;
6311 response
.argv
[0] = param
.response
6312 ? "unrecognised response value from plugin"
6313 : "unhandled action";
6317 response
.type
= param
.response
;
6319 if (param
.additional
)
6322 response
.argv
[0] = param
.additional
;
6330 response
.type
= NSCTL_RES_ERR
;
6332 response
.argv
[0] = "error unpacking control packet";
6335 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6338 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6342 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6345 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6346 if (log_stream
&& config
->debug
>= 4)
6348 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6349 dump_control(&response
, log_stream
);
6353 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6354 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6359 static tunnelidt
new_tunnel()
6362 for (i
= 1; i
< MAXTUNNEL
; i
++)
6364 if ((tunnel
[i
].state
== TUNNELFREE
) && (i
!= TUNNEL_ID_PPPOE
))
6366 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6367 if (i
> config
->cluster_highest_tunnelid
)
6368 config
->cluster_highest_tunnelid
= i
;
6372 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6377 // We're becoming the master. Do any required setup..
6379 // This is principally telling all the plugins that we're
6380 // now a master, and telling them about all the sessions
6381 // that are active too..
6383 void become_master(void)
6386 static struct event_data d
[RADIUS_FDS
];
6387 struct epoll_event e
;
6389 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6391 // running a bunch of iptables commands is slow and can cause
6392 // the master to drop tunnels on takeover--kludge around the
6393 // problem by forking for the moment (note: race)
6394 if (!fork_and_close())
6396 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6398 if (!session
[s
].opened
) // Not an in-use session.
6401 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6408 for (i
= 0; i
< RADIUS_FDS
; i
++)
6410 d
[i
].type
= FD_TYPE_RADIUS
;
6414 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6418 int cmd_show_hist_idle(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6424 if (CLI_HELP_REQUESTED
)
6425 return CLI_HELP_NO_ARGS
;
6428 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6430 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6433 if (!session
[s
].opened
)
6436 idle
= time_now
- session
[s
].last_data
;
6437 idle
/= 5 ; // In multiples of 5 seconds.
6447 for (i
= 0; i
< 63; ++i
)
6449 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6451 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6452 cli_print(cli
, "%d total sessions open.", count
);
6456 int cmd_show_hist_open(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6462 if (CLI_HELP_REQUESTED
)
6463 return CLI_HELP_NO_ARGS
;
6466 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6468 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6471 if (!session
[s
].opened
)
6474 d
= time_now
- session
[s
].opened
;
6477 while (d
> 1 && open
< 32)
6487 for (i
= 0; i
< 30; ++i
)
6489 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6492 cli_print(cli
, "%d total sessions open.", count
);
6498 * This unencodes the AVP using the L2TP secret and the previously
6499 * stored random vector. It overwrites the hidden data with the
6500 * unhidden AVP subformat.
6502 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6508 uint16_t m
= htons(type
);
6510 // Compute initial pad
6512 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6513 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6514 MD5_Update(&ctx
, vector
, vec_len
);
6515 MD5_Final(digest
, &ctx
);
6517 // pointer to last decoded 16 octets
6522 // calculate a new pad based on the last decoded block
6523 if (d
>= sizeof(digest
))
6526 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6527 MD5_Update(&ctx
, last
, sizeof(digest
));
6528 MD5_Final(digest
, &ctx
);
6534 *value
++ ^= digest
[d
++];
6539 int find_filter(char const *name
, size_t len
)
6544 for (i
= 0; i
< MAXFILTER
; i
++)
6546 if (!*ip_filters
[i
].name
)
6554 if (strlen(ip_filters
[i
].name
) != len
)
6557 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6564 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6568 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6569 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6570 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6571 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6572 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6578 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6582 case FILTER_FLAG_OP_ANY
:
6583 return (flags
& sflags
) || (~flags
& cflags
);
6585 case FILTER_FLAG_OP_ALL
:
6586 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6588 case FILTER_FLAG_OP_EST
:
6589 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6595 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6597 uint16_t frag_offset
;
6601 uint16_t src_port
= 0;
6602 uint16_t dst_port
= 0;
6604 ip_filter_rulet
*rule
;
6606 if (len
< 20) // up to end of destination address
6609 if ((*buf
>> 4) != 4) // IPv4
6612 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6614 src_ip
= *(in_addr_t
*) (buf
+ 12);
6615 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6617 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6619 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6620 if (len
< l
+ 4) // ports
6623 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6624 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6625 if (proto
== IPPROTO_TCP
)
6627 if (len
< l
+ 14) // flags
6630 flags
= buf
[l
+ 13] & 0x3f;
6634 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6636 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6639 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6640 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6643 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6644 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6649 // layer 4 deny rules are skipped
6650 if (rule
->action
== FILTER_ACTION_DENY
&&
6651 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6659 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6661 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6664 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6667 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6668 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6675 return rule
->action
== FILTER_ACTION_PERMIT
;
6682 tunnelidt
lac_new_tunnel()
6684 return new_tunnel();
6687 void lac_tunnelclear(tunnelidt t
)
6692 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6694 uint16_t version
= 0x0100; // protocol version
6696 tunnel
[t
].state
= TUNNELOPENING
;
6698 // Sent SCCRQ - Start Control Connection Request
6699 controlt
*c
= controlnew(1); // sending SCCRQ
6700 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
6701 controls(c
, 8, Vendor_name
, 1); // Vendor name
6702 control16(c
, 2, version
, 1); // protocol version
6703 control32(c
, 3, 3, 1); // framing Capabilities
6704 control16(c
, 9, t
, 1); // assigned tunnel
6705 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6706 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6707 controladd(c
, 0, t
); // send
6710 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6712 // Sent ICRQ Incoming-call-request
6713 controlt
*c
= controlnew(10); // ICRQ
6715 control16(c
, 14, s
, 1); // assigned sesion
6716 call_serial_number
++;
6717 control32(c
, 15, call_serial_number
, 1); // call serial number
6718 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6719 controladd(c
, 0, t
); // send
6722 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6724 tunnelshutdown(t
, reason
, result
, error
, msg
);