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>
47 #include "constants.h"
59 char * Vendor_name
= "Linux L2TPNS";
60 uint32_t call_serial_number
= 0;
63 configt
*config
= NULL
; // all configuration
64 int nlfd
= -1; // netlink socket
65 int tunfd
= -1; // tun interface file handle. (network device)
66 int udpfd
[MAX_UDPFD
+ 1] = INIT_TABUDPFD
; // array UDP file handle + 1 for lac udp
67 int udplacfd
= -1; // UDP LAC file handle
68 int controlfd
= -1; // Control signal handle
69 int clifd
= -1; // Socket listening for CLI connections.
70 int daefd
= -1; // Socket listening for DAE connections.
71 int snoopfd
= -1; // UDP file handle for sending out intercept data
72 int *radfds
= NULL
; // RADIUS requests file handles
73 int rand_fd
= -1; // Random data source
74 int cluster_sockfd
= -1; // Intra-cluster communications socket.
75 int epollfd
= -1; // event polling
76 time_t basetime
= 0; // base clock
77 char hostname
[MAXHOSTNAME
] = ""; // us.
78 int tunidx
; // ifr_ifindex of tun device
79 int nlseqnum
= 0; // netlink sequence number
80 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
81 static int syslog_log
= 0; // are we logging to syslog
82 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
83 uint32_t last_id
= 0; // Unique ID for radius accounting
85 char guest_users
[10][32]; // Array of guest users
86 int guest_accounts_num
= 0; // Number of guest users
88 // calculated from config->l2tp_mtu
89 uint16_t MRU
= 0; // PPP MRU
90 uint16_t MSS
= 0; // TCP MSS
92 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
93 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
95 union iphash ip_hash
[256]; // Mapping from IP address to session structures.
99 struct ipv6radix
*branch
;
100 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
103 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
104 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
107 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
108 time_t time_now
= 0; // Current time in seconds since epoch.
109 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
110 static char time_now_string
[64] = {0}; // Current time as a string.
111 static int time_changed
= 0; // time_now changed
112 char main_quit
= 0; // True if we're in the process of exiting.
113 static char main_reload
= 0; // Re-load pending
114 linked_list
*loaded_plugins
;
115 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
117 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
118 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
120 config_descriptt config_values
[] = {
121 CONFIG("debug", debug
, INT
),
122 CONFIG("log_file", log_filename
, STRING
),
123 CONFIG("pid_file", pid_file
, STRING
),
124 CONFIG("random_device", random_device
, STRING
),
125 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
126 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
127 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
128 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
129 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
130 CONFIG("primary_dns", default_dns1
, IPv4
),
131 CONFIG("secondary_dns", default_dns2
, IPv4
),
132 CONFIG("primary_radius", radiusserver
[0], IPv4
),
133 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
134 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
135 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
136 CONFIG("radius_accounting", radius_accounting
, BOOL
),
137 CONFIG("radius_interim", radius_interim
, INT
),
138 CONFIG("radius_secret", radiussecret
, STRING
),
139 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
140 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
141 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
142 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
143 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
144 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
145 CONFIG("guest_account", guest_user
, STRING
),
146 CONFIG("bind_address", bind_address
, IPv4
),
147 CONFIG("peer_address", peer_address
, IPv4
),
148 CONFIG("send_garp", send_garp
, BOOL
),
149 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
150 CONFIG("throttle_buckets", num_tbfs
, INT
),
151 CONFIG("accounting_dir", accounting_dir
, STRING
),
152 CONFIG("account_all_origin", account_all_origin
, BOOL
),
153 CONFIG("dump_speed", dump_speed
, BOOL
),
154 CONFIG("multi_read_count", multi_read_count
, INT
),
155 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
156 CONFIG("lock_pages", lock_pages
, BOOL
),
157 CONFIG("icmp_rate", icmp_rate
, INT
),
158 CONFIG("packet_limit", max_packets
, INT
),
159 CONFIG("cluster_address", cluster_address
, IPv4
),
160 CONFIG("cluster_interface", cluster_interface
, STRING
),
161 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
162 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
163 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
164 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
165 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
166 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
167 CONFIG("hostname", hostname
, STRING
),
169 CONFIG("nexthop_address", nexthop_address
, IPv4
),
170 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
172 CONFIG("echo_timeout", echo_timeout
, INT
),
173 CONFIG("idle_echo_timeout", idle_echo_timeout
, INT
),
174 CONFIG("iftun_address", iftun_address
, IPv4
),
175 CONFIG("tundevicename", tundevicename
, STRING
),
176 CONFIG("disable_lac_func", disable_lac_func
, BOOL
),
177 CONFIG("auth_tunnel_change_addr_src", auth_tunnel_change_addr_src
, BOOL
),
178 CONFIG("bind_address_remotelns", bind_address_remotelns
, IPv4
),
179 CONFIG("bind_portremotelns", bind_portremotelns
, SHORT
),
180 CONFIG("pppoe_if_to_bind", pppoe_if_to_bind
, STRING
),
181 CONFIG("pppoe_service_name", pppoe_service_name
, STRING
),
182 CONFIG("pppoe_ac_name", pppoe_ac_name
, STRING
),
183 CONFIG("disable_sending_hello", disable_sending_hello
, BOOL
),
184 CONFIG("disable_no_spoof", disable_no_spoof
, BOOL
),
185 CONFIG("bind_multi_address", bind_multi_address
, STRING
),
186 CONFIG("grp_txrate_average_time", grp_txrate_average_time
, INT
),
187 CONFIG("pppoe_only_equal_svc_name", pppoe_only_equal_svc_name
, BOOL
),
188 CONFIG("multi_hostname", multi_hostname
, STRING
),
189 CONFIG("no_throttle_local_IP", no_throttle_local_IP
, BOOL
),
193 static char *plugin_functions
[] = {
198 "plugin_new_session",
199 "plugin_kill_session",
201 "plugin_radius_response",
202 "plugin_radius_reset",
203 "plugin_radius_account",
204 "plugin_become_master",
205 "plugin_new_session_master",
208 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
210 // Counters for shutdown sessions
211 static sessiont shut_acct
[8192];
212 static sessionidt shut_acct_n
= 0;
214 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
215 bundlet
*bundle
= NULL
; // Array of bundle structures.
216 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
217 sessiont
*session
= NULL
; // Array of session structures.
218 groupsesst
*grpsession
= NULL
; // Array of groupsesst structures.
219 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
220 radiust
*radius
= NULL
; // Array of radius structures.
221 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
222 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
223 static controlt
*controlfree
= 0;
224 struct Tstats
*_statistics
= NULL
;
226 struct Tringbuffer
*ringbuffer
= NULL
;
229 static void uncache_ipmap(in_addr_t ip
);
230 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
231 static void free_ip_address(sessionidt s
);
232 static void dump_acct_info(int all
);
233 static void sighup_handler(int sig
);
234 static void shutdown_handler(int sig
);
235 static void sigchild_handler(int sig
);
236 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
237 static void update_config(void);
238 static void read_config_file(void);
239 static void initplugins(void);
240 static int add_plugin(char *plugin_name
);
241 static int remove_plugin(char *plugin_name
);
242 static void plugins_done(void);
243 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
244 static tunnelidt
new_tunnel(void);
245 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
246 static void bundleclear(bundleidt b
);
248 // return internal time (10ths since process startup), set f if given
249 // as a side-effect sets time_now, and time_changed
250 static clockt
now(double *f
)
254 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
255 if (t
.tv_sec
!= time_now
)
262 // Time in milliseconds
263 // TODO FOR MLPPP DEV
264 //time_now_ms = (t.tv_sec * 1000) + (t.tv_usec/1000);
266 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
269 // work out a retry time based on try number
270 // This is a straight bounded exponential backoff.
271 // Maximum re-try time is 32 seconds. (2^5).
272 clockt
backoff(uint8_t try)
274 if (try > 5) try = 5; // max backoff
275 return now(NULL
) + 10 * (1 << try);
280 // Log a debug message. Typically called via the LOG macro
282 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
284 static char message
[65536] = {0};
290 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
291 ringbuffer
->tail
= 0;
292 if (ringbuffer
->tail
== ringbuffer
->head
)
293 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
294 ringbuffer
->head
= 0;
296 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
297 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
298 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
299 va_start(ap
, format
);
300 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, MAX_LOG_LENGTH
, format
, ap
);
305 if (config
->debug
< level
) return;
307 va_start(ap
, format
);
308 vsnprintf(message
, sizeof(message
), format
, ap
);
311 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
313 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
318 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
321 const uint8_t *d
= data
;
323 if (config
->debug
< level
) return;
325 // No support for _log_hex to syslog
328 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
329 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
331 for (i
= 0; i
< maxsize
; )
333 fprintf(log_stream
, "%4X: ", i
);
334 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
336 fprintf(log_stream
, "%02X ", d
[j
]);
338 fputs(": ", log_stream
);
341 for (; j
< i
+ 16; j
++)
343 fputs(" ", log_stream
);
345 fputs(": ", log_stream
);
348 fputs(" ", log_stream
);
349 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
351 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
352 fputc(d
[j
], log_stream
);
354 fputc('.', log_stream
);
357 fputs(" ", log_stream
);
361 fputs("\n", log_stream
);
365 setbuf(log_stream
, NULL
);
369 // update a counter, accumulating 2^32 wraps
370 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
372 uint32_t new = *counter
+ delta
;
379 // initialise the random generator
380 static void initrandom(char *source
)
382 static char path
[sizeof(config
->random_device
)] = "*undefined*";
384 // reinitialise only if we are forced to do so or if the config has changed
385 if (source
&& !strncmp(path
, source
, sizeof(path
)))
388 // close previous source, if any
397 snprintf(path
, sizeof(path
), "%s", source
);
401 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
403 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
404 path
, strerror(errno
));
409 // fill buffer with random data
410 void random_data(uint8_t *buf
, int len
)
417 n
= read(rand_fd
, buf
, len
);
418 if (n
>= len
) return;
423 LOG(0, 0, 0, "Error reading from random source: %s\n",
426 // fall back to rand()
434 // append missing data
436 // not using the low order bits from the prng stream
437 buf
[n
++] = (rand() >> 4) & 0xff;
442 // This adds it to the routing table, advertises it
443 // via BGP if enabled, and stuffs it into the
444 // 'sessionbyip' cache.
446 // 'ip' must be in _host_ order.
448 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
458 if (!prefixlen
) prefixlen
= 32;
460 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
462 memset(&req
, 0, sizeof(req
));
466 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
467 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
471 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
472 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
475 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
477 req
.rt
.rtm_family
= AF_INET
;
478 req
.rt
.rtm_dst_len
= prefixlen
;
479 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
480 req
.rt
.rtm_protocol
= 42;
481 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
482 req
.rt
.rtm_type
= RTN_UNICAST
;
484 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
486 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
490 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
493 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
494 fmtaddr(htonl(ip
), 0), prefixlen
,
495 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
497 if (netlink_send(&req
.nh
) < 0)
498 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
502 bgp_add_route(htonl(ip
), prefixlen
);
504 bgp_del_route(htonl(ip
), prefixlen
);
507 // Add/Remove the IPs to the 'sessionbyip' cache.
508 // Note that we add the zero address in the case of
509 // a network route. Roll on CIDR.
511 // Note that 's == 0' implies this is the address pool.
512 // We still cache it here, because it will pre-fill
513 // the malloc'ed tree.
517 if (!add
) // Are we deleting a route?
518 s
= 0; // Caching the session as '0' is the same as uncaching.
520 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
525 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
533 char ipv6addr
[INET6_ADDRSTRLEN
];
535 if (!config
->ipv6_prefix
.s6_addr
[0])
537 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
541 memset(&req
, 0, sizeof(req
));
545 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
546 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
550 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
551 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
554 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
556 req
.rt
.rtm_family
= AF_INET6
;
557 req
.rt
.rtm_dst_len
= prefixlen
;
558 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
559 req
.rt
.rtm_protocol
= 42;
560 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
561 req
.rt
.rtm_type
= RTN_UNICAST
;
563 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
564 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
566 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
568 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
570 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
573 if (netlink_send(&req
.nh
) < 0)
574 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
578 bgp_add_route6(ip
, prefixlen
);
580 bgp_del_route6(ip
, prefixlen
);
585 if (!add
) // Are we deleting a route?
586 s
= 0; // Caching the session as '0' is the same as uncaching.
588 cache_ipv6map(ip
, prefixlen
, s
);
595 // Set up netlink socket
596 static void initnetlink(void)
598 struct sockaddr_nl nladdr
;
600 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
603 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
607 memset(&nladdr
, 0, sizeof(nladdr
));
608 nladdr
.nl_family
= AF_NETLINK
;
609 nladdr
.nl_pid
= getpid();
611 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
613 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
618 ssize_t
netlink_send(struct nlmsghdr
*nh
)
620 struct sockaddr_nl nladdr
;
624 nh
->nlmsg_pid
= getpid();
625 nh
->nlmsg_seq
= ++nlseqnum
;
627 // set kernel address
628 memset(&nladdr
, 0, sizeof(nladdr
));
629 nladdr
.nl_family
= AF_NETLINK
;
631 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
632 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
634 return sendmsg(nlfd
, &msg
, 0);
637 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
639 struct sockaddr_nl nladdr
;
643 // set kernel address
644 memset(&nladdr
, 0, sizeof(nladdr
));
645 nladdr
.nl_family
= AF_NETLINK
;
647 iov
= (struct iovec
){ buf
, len
};
648 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
650 return recvmsg(nlfd
, &msg
, 0);
653 /* adapted from iproute2 */
654 void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
656 int len
= RTA_LENGTH(alen
);
659 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
660 rta
->rta_type
= type
;
662 memcpy(RTA_DATA(rta
), data
, alen
);
663 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
666 // messages corresponding to different phases seq number
667 static char *tun_nl_phase_msg
[] = {
669 "getting tun interface index",
670 "setting tun interface parameters",
671 "setting tun IPv4 address",
672 "setting tun LL IPv6 address",
673 "setting tun global IPv6 address",
677 // Set up TUN interface
678 static void inittun(void)
682 memset(&ifr
, 0, sizeof(ifr
));
683 ifr
.ifr_flags
= IFF_TUN
;
685 tunfd
= open(TUNDEVICE
, O_RDWR
);
688 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
692 int flags
= fcntl(tunfd
, F_GETFL
, 0);
693 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
696 if (*config
->tundevicename
)
697 strncpy(ifr
.ifr_name
, config
->tundevicename
, IFNAMSIZ
);
699 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
701 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
704 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevicename
) - 1);
705 strncpy(config
->tundevicename
, ifr
.ifr_name
, sizeof(config
->tundevicename
));
707 tunidx
= if_nametoindex(config
->tundevicename
);
710 LOG(0, 0, 0, "Can't get tun interface index\n");
719 struct ifinfomsg ifinfo
;
720 struct ifaddrmsg ifaddr
;
722 char rtdata
[32]; // 32 should be enough
724 uint32_t txqlen
, mtu
;
727 memset(&req
, 0, sizeof(req
));
729 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
730 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
731 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
733 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
734 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
735 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
736 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
738 /* Bump up the qlen to deal with bursts from the network */
740 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
741 /* set MTU to modem MRU */
743 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
745 if (netlink_send(&req
.nh
) < 0)
748 memset(&req
, 0, sizeof(req
));
750 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
751 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
752 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
754 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
755 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
756 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
757 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
759 if (config
->nbmultiaddress
> 1)
762 for (i
= 0; i
< config
->nbmultiaddress
; i
++)
764 ip
= config
->iftun_n_address
[i
];
765 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
766 if (netlink_send(&req
.nh
) < 0)
772 if (config
->iftun_address
)
773 ip
= config
->iftun_address
;
775 ip
= 0x01010101; // 1.1.1.1
776 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
778 if (netlink_send(&req
.nh
) < 0)
784 // Only setup IPv6 on the tun device if we have a configured prefix
785 if (config
->ipv6_prefix
.s6_addr
[0]) {
788 memset(&req
, 0, sizeof(req
));
790 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
791 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
792 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
794 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
795 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
796 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
797 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
799 // Link local address is FE80::1
800 memset(&ip6
, 0, sizeof(ip6
));
801 ip6
.s6_addr
[0] = 0xFE;
802 ip6
.s6_addr
[1] = 0x80;
804 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
806 if (netlink_send(&req
.nh
) < 0)
809 memset(&req
, 0, sizeof(req
));
811 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
812 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
813 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
815 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
816 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
817 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
818 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
820 // Global address is prefix::1
821 ip6
= config
->ipv6_prefix
;
823 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
825 if (netlink_send(&req
.nh
) < 0)
829 memset(&req
, 0, sizeof(req
));
831 req
.nh
.nlmsg_type
= NLMSG_DONE
;
832 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
834 if (netlink_send(&req
.nh
) < 0)
837 // if we get an error for seqnum < min_initok_nlseqnum,
838 // we must exit as initialization went wrong
839 if (config
->ipv6_prefix
.s6_addr
[0])
840 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
842 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
848 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
852 // set up LAC UDP ports
853 static void initlacudp(void)
856 struct sockaddr_in addr
;
858 // Tunnel to Remote LNS
859 memset(&addr
, 0, sizeof(addr
));
860 addr
.sin_family
= AF_INET
;
861 addr
.sin_port
= htons(config
->bind_portremotelns
);
862 addr
.sin_addr
.s_addr
= config
->bind_address_remotelns
;
863 udplacfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
864 setsockopt(udplacfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
866 int flags
= fcntl(udplacfd
, F_GETFL
, 0);
867 fcntl(udplacfd
, F_SETFL
, flags
| O_NONBLOCK
);
869 if (bind(udplacfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
871 LOG(0, 0, 0, "Error in UDP REMOTE LNS bind: %s\n", strerror(errno
));
876 // set up control ports
877 static void initcontrol(void)
880 struct sockaddr_in addr
;
883 memset(&addr
, 0, sizeof(addr
));
884 addr
.sin_family
= AF_INET
;
885 addr
.sin_port
= htons(NSCTL_PORT
);
886 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
887 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
888 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
889 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
891 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
896 // set up Dynamic Authorization Extensions to RADIUS port
897 static void initdae(void)
900 struct sockaddr_in addr
;
902 // Dynamic Authorization Extensions to RADIUS
903 memset(&addr
, 0, sizeof(addr
));
904 addr
.sin_family
= AF_INET
;
905 addr
.sin_port
= htons(config
->radius_dae_port
);
906 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
907 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
908 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
909 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
911 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
917 static void initudp(int * pudpfd
, in_addr_t ip_bind
)
920 struct sockaddr_in addr
;
923 memset(&addr
, 0, sizeof(addr
));
924 addr
.sin_family
= AF_INET
;
925 addr
.sin_port
= htons(L2TPPORT
);
926 addr
.sin_addr
.s_addr
= ip_bind
;
927 (*pudpfd
) = socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
928 setsockopt((*pudpfd
), SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
930 int flags
= fcntl((*pudpfd
), F_GETFL
, 0);
931 fcntl((*pudpfd
), F_SETFL
, flags
| O_NONBLOCK
);
933 if (bind((*pudpfd
), (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
935 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
941 // Find session by IP, < 1 for not found
943 // Confusingly enough, this 'ip' must be
944 // in _network_ order. This being the common
945 // case when looking it up from IP packet headers.
947 // We actually use this cache for two things.
948 // #1. For used IP addresses, this maps to the
949 // session ID that it's used by.
950 // #2. For un-used IP addresses, this maps to the
951 // index into the pool table that contains that
955 static sessionidt
lookup_ipmap(in_addr_t ip
)
957 uint8_t *a
= (uint8_t *) &ip
;
958 union iphash
*h
= ip_hash
;
960 if (!(h
= h
[*a
++].idx
)) return 0;
961 if (!(h
= h
[*a
++].idx
)) return 0;
962 if (!(h
= h
[*a
++].idx
)) return 0;
967 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
969 struct ipv6radix
*curnode
;
972 char ipv6addr
[INET6_ADDRSTRLEN
];
974 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
978 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
980 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
985 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
986 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
993 sessionidt
sessionbyip(in_addr_t ip
)
995 sessionidt s
= lookup_ipmap(ip
);
998 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1004 sessionidt
sessionbyipv6(struct in6_addr ip
)
1007 CSTAT(sessionbyipv6
);
1009 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
1010 (ip
.s6_addr
[0] == 0xFE &&
1011 ip
.s6_addr
[1] == 0x80 &&
1012 ip
.s6_addr16
[1] == 0 &&
1013 ip
.s6_addr16
[2] == 0 &&
1014 ip
.s6_addr16
[3] == 0))
1016 in_addr_t
*pipv4
= (in_addr_t
*) &ip
.s6_addr
[8];
1017 s
= lookup_ipmap(*pipv4
);
1019 s
= lookup_ipv6map(ip
);
1022 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
1029 // Take an IP address in HOST byte order and
1030 // add it to the sessionid by IP cache.
1032 // (It's actually cached in network order)
1034 void cache_ipmap(in_addr_t ip
, sessionidt s
)
1036 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
1037 uint8_t *a
= (uint8_t *) &nip
;
1038 union iphash
*h
= ip_hash
;
1041 for (i
= 0; i
< 3; i
++)
1043 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1052 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1055 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1056 // else a map to an ip pool index.
1059 static void uncache_ipmap(in_addr_t ip
)
1061 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1064 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1068 struct ipv6radix
*curnode
;
1069 char ipv6addr
[INET6_ADDRSTRLEN
];
1071 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
1073 bytes
= prefixlen
>> 3;
1076 if (curnode
->branch
== NULL
)
1078 if (!(curnode
->branch
= calloc(256,
1079 sizeof (struct ipv6radix
))))
1082 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1089 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1090 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1094 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1095 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1101 // CLI list to dump current ipcache.
1103 int cmd_show_ipcache(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
1105 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1109 if (CLI_HELP_REQUESTED
)
1110 return CLI_HELP_NO_ARGS
;
1112 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1114 for (i
= 0; i
< 256; ++i
)
1120 for (j
= 0; j
< 256; ++j
)
1126 for (k
= 0; k
< 256; ++k
)
1132 for (l
= 0; l
< 256; ++l
)
1137 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1143 cli_print(cli
, "%d entries in cache", count
);
1148 // Find session by username, 0 for not found
1149 // walled garden users aren't authenticated, so the username is
1150 // reasonably useless. Ignore them to avoid incorrect actions
1152 // This is VERY inefficent. Don't call it often. :)
1154 sessionidt
sessionbyuser(char *username
)
1157 CSTAT(sessionbyuser
);
1159 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1161 if (!session
[s
].opened
)
1164 if (session
[s
].walled_garden
)
1165 continue; // Skip walled garden users.
1167 if (!strncmp(session
[s
].user
, username
, 128))
1171 return 0; // Not found.
1174 void send_garp(in_addr_t ip
)
1180 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1183 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1186 memset(&ifr
, 0, sizeof(ifr
));
1187 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1188 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1190 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1194 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1195 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1197 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1202 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1205 static sessiont
*sessiontbysessionidt(sessionidt s
)
1207 if (!s
|| s
>= MAXSESSION
) return NULL
;
1211 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1213 sessionidt val
= s
-session
;
1214 if (s
< session
|| val
>= MAXSESSION
) return 0;
1218 // actually send a control message for a specific tunnel
1219 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1221 struct sockaddr_in addr
;
1227 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1228 STAT(tunnel_tx_errors
);
1232 if (t
== TUNNEL_ID_PPPOE
)
1234 pppoe_sess_send(buf
, l
, t
);
1240 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1241 STAT(tunnel_tx_errors
);
1245 memset(&addr
, 0, sizeof(addr
));
1246 addr
.sin_family
= AF_INET
;
1247 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1248 addr
.sin_port
= htons(tunnel
[t
].port
);
1250 // sequence expected, if sequence in message
1251 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1253 // If this is a control message, deal with retries
1256 tunnel
[t
].last
= time_now
; // control message sent
1257 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1260 STAT(tunnel_retries
);
1261 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1265 if (sendto(udpfd
[tunnel
[t
].indexudp
], buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1267 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1268 strerror(errno
), udpfd
[tunnel
[t
].indexudp
], buf
, l
, inet_ntoa(addr
.sin_addr
));
1269 STAT(tunnel_tx_errors
);
1273 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1274 STAT(tunnel_tx_packets
);
1275 INC_STAT(tunnel_tx_bytes
, l
);
1279 // Tiny helper function to write data to
1280 // the 'tun' device.
1282 int tun_write(uint8_t * data
, int size
)
1284 return write(tunfd
, data
, size
);
1287 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1288 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1290 int d
= (tcp
[12] >> 4) * 4;
1297 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1300 if (tcp
+ d
> buf
+ len
) // short?
1308 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1311 if (mss
+ 2 > data
) return; // short?
1315 if (*opts
== 0) return; // end of options
1316 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1319 opts
+= opts
[1]; // skip over option
1322 if (!mss
) return; // not found
1323 orig
= ntohs(*(uint16_t *) mss
);
1325 if (orig
<= MSS
) return; // mss OK
1327 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1328 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1329 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1330 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1333 *(int16_t *) mss
= htons(MSS
);
1335 // adjust checksum (see rfc1141)
1336 sum
= orig
+ (~MSS
& 0xffff);
1337 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1338 sum
= (sum
& 0xffff) + (sum
>> 16);
1339 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1342 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1346 // Skip the four extra bytes
1358 proto
= ntohs(*(uint16_t *) p
);
1366 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1367 return; // closing session, PPP not processed
1369 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1370 processipin(s
, t
, p
, l
);
1372 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1376 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1377 return; // closing session, PPP not processed
1380 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1381 processipv6in(s
, t
, p
, l
);
1383 else if (proto
== PPPIPCP
)
1385 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1386 processipcp(s
, t
, p
, l
);
1388 else if (proto
== PPPCCP
)
1390 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1391 processccp(s
, t
, p
, l
);
1395 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1399 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1401 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1402 sp
->cout_delta
+= len
;
1404 sp
->last_data
= time_now
;
1406 sess_local
[s
].cout
+= len
; // To send to master..
1407 sess_local
[s
].pout
++;
1410 // process outgoing (to tunnel) IP
1412 // (i.e. this routine writes to data[-8]).
1413 void processipout(uint8_t *buf
, int len
)
1419 in_addr_t ip
, ip_src
;
1421 uint8_t *data
= buf
; // Keep a copy of the originals.
1424 uint8_t fragbuf
[MAXETHER
+ 20];
1426 CSTAT(processipout
);
1428 if (len
< MIN_IP_SIZE
)
1430 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1431 STAT(tun_rx_errors
);
1434 if (len
>= MAXETHER
)
1436 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1437 STAT(tun_rx_errors
);
1441 // Skip the tun header
1445 // Got an IP header now
1446 if (*(uint8_t *)(buf
) >> 4 != 4)
1448 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1452 ip_src
= *(uint32_t *)(buf
+ 12);
1453 ip
= *(uint32_t *)(buf
+ 16);
1454 if ((g
= grp_groupbyip(ip
)))
1456 s
= grp_getnextsession(g
, ip
, ip_src
);
1459 // Is this a packet for a session that doesn't exist?
1460 static int rate
= 0; // Number of ICMP packets we've sent this second.
1461 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1463 if (last
!= time_now
)
1469 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1471 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1472 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1473 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1478 else if (!(s
= sessionbyip(ip
)))
1480 // Is this a packet for a session that doesn't exist?
1481 static int rate
= 0; // Number of ICMP packets we've sent this second.
1482 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1484 if (last
!= time_now
)
1490 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1492 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1493 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1494 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1499 t
= session
[s
].tunnel
;
1500 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1502 LOG(3, s
, t
, "Packet size more than session MRU\n");
1508 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1509 if (config
->max_packets
> 0)
1511 if (sess_local
[s
].last_packet_out
== TIME
)
1513 int max
= config
->max_packets
;
1515 // All packets for throttled sessions are handled by the
1516 // master, so further limit by using the throttle rate.
1517 // A bit of a kludge, since throttle rate is in kbps,
1518 // but should still be generous given our average DSL
1519 // packet size is 200 bytes: a limit of 28kbps equates
1520 // to around 180 packets per second.
1521 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1522 max
= sp
->throttle_out
;
1524 if (++sess_local
[s
].packets_out
> max
)
1526 sess_local
[s
].packets_dropped
++;
1532 if (sess_local
[s
].packets_dropped
)
1534 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1535 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1536 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1537 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1541 sess_local
[s
].last_packet_out
= TIME
;
1542 sess_local
[s
].packets_out
= 1;
1543 sess_local
[s
].packets_dropped
= 0;
1547 // run access-list if any
1548 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1551 // adjust MSS on SYN and SYN,ACK packets with options
1552 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1554 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1555 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1556 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1561 if (!config
->no_throttle_local_IP
|| !sessionbyip(ip_src
))
1563 // Are we throttling this session?
1564 if (config
->cluster_iam_master
)
1565 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1567 master_throttle_packet(sp
->tbf_out
, data
, size
);
1572 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1574 // We are walled-gardening this
1575 master_garden_packet(s
, data
, size
);
1579 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1582 if (!config
->cluster_iam_master
)
1584 // The MPPP packets must be managed by the Master.
1585 master_forward_mppp_packet(s
, data
, size
);
1589 // Add on L2TP header
1590 sessionidt members
[MAXBUNDLESES
];
1591 bundleidt bid
= session
[s
].bundle
;
1592 bundlet
*b
= &bundle
[bid
];
1593 uint32_t num_of_links
, nb_opened
;
1596 num_of_links
= b
->num_of_links
;
1598 for (i
= 0;i
< num_of_links
;i
++)
1601 if (session
[s
].ppp
.lcp
== Opened
)
1603 members
[nb_opened
] = s
;
1610 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1614 num_of_links
= nb_opened
;
1615 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1616 s
= members
[b
->current_ses
];
1617 t
= session
[s
].tunnel
;
1619 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1621 if (num_of_links
> 1)
1623 if(len
> MINFRAGLEN
)
1625 //for rotate traffic among the member links
1626 uint32_t divisor
= num_of_links
;
1628 divisor
= divisor
/2 + (divisor
& 1);
1630 // Partition the packet to "num_of_links" fragments
1631 uint32_t fraglen
= len
/ divisor
;
1632 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1633 uint32_t remain
= len
;
1635 // send the first packet
1636 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1638 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1641 update_session_out_stat(s
, sp
, fraglen
);
1644 while (remain
> last_fraglen
)
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: (2)Session number becomes: %d\n", s
);
1651 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1653 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1654 update_session_out_stat(s
, sp
, fraglen
);
1657 // send the last fragment
1658 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1659 s
= members
[b
->current_ses
];
1660 t
= session
[s
].tunnel
;
1662 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1663 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1665 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1666 update_session_out_stat(s
, sp
, remain
);
1667 if (remain
!= last_fraglen
)
1668 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1672 // Send it as one frame
1673 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1675 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1676 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1677 update_session_out_stat(s
, sp
, len
);
1682 // Send it as one frame (NO MPPP Frame)
1683 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1684 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1685 update_session_out_stat(s
, sp
, len
);
1690 uint8_t *p
= opt_makeppp(buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1691 tunnelsend(p
, len
+ (buf
-p
), t
); // send it...
1692 update_session_out_stat(s
, sp
, len
);
1695 // Snooping this session, send it to intercept box
1696 if (sp
->snoop_ip
&& sp
->snoop_port
)
1697 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1702 // process outgoing (to tunnel) IPv6
1704 static void processipv6out(uint8_t * buf
, int len
)
1710 struct in6_addr ip6
;
1712 uint8_t *data
= buf
; // Keep a copy of the originals.
1715 uint8_t b
[MAXETHER
+ 20];
1717 CSTAT(processipv6out
);
1719 if (len
< MIN_IP_SIZE
)
1721 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1722 STAT(tunnel_tx_errors
);
1725 if (len
>= MAXETHER
)
1727 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1728 STAT(tunnel_tx_errors
);
1732 // Skip the tun header
1736 // Got an IP header now
1737 if (*(uint8_t *)(buf
) >> 4 != 6)
1739 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1743 ip6
= *(struct in6_addr
*)(buf
+24);
1744 s
= sessionbyipv6(ip6
);
1748 ip
= *(uint32_t *)(buf
+ 32);
1749 s
= sessionbyip(ip
);
1754 // Is this a packet for a session that doesn't exist?
1755 static int rate
= 0; // Number of ICMP packets we've sent this second.
1756 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1758 if (last
!= time_now
)
1764 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1766 // FIXME: Should send icmp6 host unreachable
1770 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1772 bundleidt bid
= session
[s
].bundle
;
1773 bundlet
*b
= &bundle
[bid
];
1775 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1776 s
= b
->members
[b
->current_ses
];
1777 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1779 t
= session
[s
].tunnel
;
1781 sp
->last_data
= time_now
;
1783 // FIXME: add DoS prevention/filters?
1787 // Are we throttling this session?
1788 if (config
->cluster_iam_master
)
1789 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1791 master_throttle_packet(sp
->tbf_out
, data
, size
);
1794 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1796 // We are walled-gardening this
1797 master_garden_packet(s
, data
, size
);
1801 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1803 // Add on L2TP header
1805 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1807 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1810 // Snooping this session, send it to intercept box
1811 if (sp
->snoop_ip
&& sp
->snoop_port
)
1812 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1814 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1815 sp
->cout_delta
+= len
;
1819 sess_local
[s
].cout
+= len
; // To send to master..
1820 sess_local
[s
].pout
++;
1824 // Helper routine for the TBF filters.
1825 // Used to send queued data in to the user!
1827 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1832 uint8_t *data
= buf
; // Keep a copy of the originals.
1834 uint8_t b
[MAXETHER
+ 20];
1836 if (len
< 0 || len
> MAXETHER
)
1838 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1842 // Skip the tun header
1849 t
= session
[s
].tunnel
;
1852 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1854 // Add on L2TP header
1855 if (*(uint16_t *) (data
+ 2) == htons(PKTIPV6
))
1856 p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0); // IPV6
1858 p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0); // IPV4
1862 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1864 // Snooping this session.
1865 if (sp
->snoop_ip
&& sp
->snoop_port
)
1866 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1868 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1869 sp
->cout_delta
+= len
;
1873 sess_local
[s
].cout
+= len
; // To send to master..
1874 sess_local
[s
].pout
++;
1877 // add an AVP (16 bit)
1878 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1880 uint16_t l
= (m
? 0x8008 : 0x0008);
1881 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1882 pint16
[0] = htons(l
);
1883 pint16
[1] = htons(0);
1884 pint16
[2] = htons(avp
);
1885 pint16
[3] = htons(val
);
1889 // add an AVP (32 bit)
1890 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1892 uint16_t l
= (m
? 0x800A : 0x000A);
1893 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1894 uint32_t *pint32
= (uint32_t *) (c
->buf
+ c
->length
+ 6);
1895 pint16
[0] = htons(l
);
1896 pint16
[1] = htons(0);
1897 pint16
[2] = htons(avp
);
1898 pint32
[0] = htonl(val
);
1902 // add an AVP (string)
1903 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1905 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1906 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1907 pint16
[0] = htons(l
);
1908 pint16
[1] = htons(0);
1909 pint16
[2] = htons(avp
);
1910 memcpy(c
->buf
+ c
->length
+ 6, val
, strlen(val
));
1911 c
->length
+= 6 + strlen(val
);
1915 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1917 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1918 uint16_t *pint16
= (uint16_t *) (c
->buf
+ c
->length
+ 0);
1919 pint16
[0] = htons(l
);
1920 pint16
[1] = htons(0);
1921 pint16
[2] = htons(avp
);
1922 memcpy(c
->buf
+ c
->length
+ 6, val
, len
);
1923 c
->length
+= 6 + len
;
1926 // new control connection
1927 static controlt
*controlnew(uint16_t mtype
)
1931 c
= malloc(sizeof(controlt
));
1935 controlfree
= c
->next
;
1939 c
->buf
[0] = 0xC8; // flags
1940 c
->buf
[1] = 0x02; // ver
1942 control16(c
, 0, mtype
, 1);
1946 // send zero block if nothing is waiting
1948 static void controlnull(tunnelidt t
)
1951 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1954 buf
[0] = htons(0xC802); // flags/ver
1955 buf
[1] = htons(12); // length
1956 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1957 buf
[3] = htons(0); // session
1958 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1959 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1960 tunnelsend((uint8_t *)buf
, 12, t
);
1963 // add a control message to a tunnel, and send if within window
1964 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1966 uint16_t *pint16
= (uint16_t *) (c
->buf
+ 2);
1967 pint16
[0] = htons(c
->length
); // length
1968 pint16
[1] = htons(tunnel
[t
].far
); // tunnel
1969 pint16
[2] = htons(far
); // session
1970 pint16
[3] = htons(tunnel
[t
].ns
); // sequence
1971 tunnel
[t
].ns
++; // advance sequence
1972 // link in message in to queue
1973 if (tunnel
[t
].controlc
)
1974 tunnel
[t
].controle
->next
= c
;
1976 tunnel
[t
].controls
= c
;
1978 tunnel
[t
].controle
= c
;
1979 tunnel
[t
].controlc
++;
1981 // send now if space in window
1982 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1984 tunnel
[t
].try = 0; // first send
1985 tunnelsend(c
->buf
, c
->length
, t
);
1990 // Throttle or Unthrottle a session
1992 // Throttle the data from/to through a session to no more than
1993 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1996 // If either value is -1, the current value is retained for that
1999 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
2001 if (!session
[s
].opened
)
2002 return; // No-one home.
2004 if (!*session
[s
].user
)
2005 return; // User not logged in
2009 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
2010 if (session
[s
].tbf_in
)
2011 free_tbf(session
[s
].tbf_in
);
2014 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
2016 session
[s
].tbf_in
= 0;
2018 session
[s
].throttle_in
= rate_in
;
2023 int bytes
= rate_out
* 1024 / 8;
2024 if (session
[s
].tbf_out
)
2025 free_tbf(session
[s
].tbf_out
);
2028 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
2030 session
[s
].tbf_out
= 0;
2032 session
[s
].throttle_out
= rate_out
;
2036 // add/remove filters from session (-1 = no change)
2037 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
2039 if (!session
[s
].opened
)
2040 return; // No-one home.
2042 if (!*session
[s
].user
)
2043 return; // User not logged in
2046 if (filter_in
> MAXFILTER
) filter_in
= -1;
2047 if (filter_out
> MAXFILTER
) filter_out
= -1;
2048 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
2049 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
2053 if (session
[s
].filter_in
)
2054 ip_filters
[session
[s
].filter_in
- 1].used
--;
2057 ip_filters
[filter_in
- 1].used
++;
2059 session
[s
].filter_in
= filter_in
;
2062 if (filter_out
>= 0)
2064 if (session
[s
].filter_out
)
2065 ip_filters
[session
[s
].filter_out
- 1].used
--;
2068 ip_filters
[filter_out
- 1].used
++;
2070 session
[s
].filter_out
= filter_out
;
2074 // start tidy shutdown of session
2075 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
2077 int walled_garden
= session
[s
].walled_garden
;
2078 bundleidt b
= session
[s
].bundle
;
2079 //delete routes only for last session in bundle (in case of MPPP)
2080 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
2082 CSTAT(sessionshutdown
);
2084 if (!session
[s
].opened
)
2086 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2087 return; // not a live session
2090 if (!session
[s
].die
)
2092 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2093 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2094 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2097 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2099 // RADIUS Stop message
2100 uint16_t r
= radiusnew(s
);
2103 // stop, if not already trying
2104 if (radius
[r
].state
!= RADIUSSTOP
)
2106 radius
[r
].term_cause
= term_cause
;
2107 radius
[r
].term_msg
= reason
;
2108 radiussend(r
, RADIUSSTOP
);
2112 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2114 // Save counters to dump to accounting file
2115 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2116 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2119 if (!session
[s
].die
)
2120 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2123 { // IP allocated, clear and unroute
2126 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2128 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2129 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2132 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2133 session
[s
].route
[r
].ip
= 0;
2136 if (session
[s
].ip_pool_index
== -1) // static ip
2138 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2144 // unroute IPv6, if setup
2145 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
2146 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2150 // This session was part of a bundle
2151 bundle
[b
].num_of_links
--;
2152 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2153 if(bundle
[b
].num_of_links
== 0)
2156 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2160 // Adjust the members array to accomodate the new change
2161 uint8_t mem_num
= 0;
2162 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2163 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2166 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2167 if(bundle
[b
].members
[ml
] == s
)
2172 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2173 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2175 // If the killed session is the first of the bundle,
2176 // the new first session must be stored in the cache_ipmap
2177 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2180 sessionidt new_s
= bundle
[b
].members
[0];
2183 // Add the route for this session.
2184 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2189 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2190 ip
= session
[new_s
].route
[r
].ip
;
2192 if (!prefixlen
) prefixlen
= 32;
2193 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2195 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2196 cache_ipmap(i
, new_s
);
2198 cache_ipmap(session
[new_s
].ip
, new_s
);
2201 if (session
[new_s
].ipv6prefixlen
)
2202 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2207 cluster_send_bundle(b
);
2211 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2212 throttle_session(s
, 0, 0);
2216 if (session
[s
].tunnel
== TUNNEL_ID_PPPOE
)
2218 pppoe_shutdown_session(s
);
2223 controlt
*c
= controlnew(14); // sending CDN
2227 buf
[0] = htons(cdn_result
);
2228 buf
[1] = htons(cdn_error
);
2229 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2232 control16(c
, 1, cdn_result
, 1);
2234 control16(c
, 14, s
, 1); // assigned session (our end)
2235 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2239 // update filter refcounts
2240 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2241 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2244 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2245 sess_local
[s
].lcp
.restart
= 0;
2246 sess_local
[s
].ipcp
.restart
= 0;
2247 sess_local
[s
].ipv6cp
.restart
= 0;
2248 sess_local
[s
].ccp
.restart
= 0;
2250 cluster_send_session(s
);
2253 void sendipcp(sessionidt s
, tunnelidt t
)
2255 uint8_t buf
[MAXETHER
];
2259 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2261 if (!session
[s
].unique_id
)
2263 if (!++last_id
) ++last_id
; // skip zero
2264 session
[s
].unique_id
= last_id
;
2267 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2271 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2272 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2273 q
[4] = 3; // ip address option
2274 q
[5] = 6; // option length
2275 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2276 config
->iftun_n_address
[tunnel
[t
].indexudp
] ? config
->iftun_n_address
[tunnel
[t
].indexudp
] :
2277 my_address
; // send my IP
2279 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2280 restart_timer(s
, ipcp
);
2283 void sendipv6cp(sessionidt s
, tunnelidt t
)
2285 uint8_t buf
[MAXETHER
];
2289 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2291 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2295 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2296 // only send one type
2298 *(uint16_t *) (q
+ 2) = htons(14);
2299 q
[4] = 1; // interface identifier option
2300 q
[5] = 10; // option length
2301 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2302 *(uint32_t *) (q
+ 10) = 0;
2305 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2306 restart_timer(s
, ipv6cp
);
2309 static void sessionclear(sessionidt s
)
2311 memset(&session
[s
], 0, sizeof(session
[s
]));
2312 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2313 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2315 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2316 session
[s
].next
= sessionfree
;
2320 // kill a session now
2321 void sessionkill(sessionidt s
, char *reason
)
2327 if (!session
[s
].opened
) // not alive
2330 if (session
[s
].next
)
2332 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2336 if (!session
[s
].die
)
2337 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2339 if (sess_local
[s
].radius
)
2340 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2342 if (session
[s
].forwardtosession
)
2344 sessionidt sess
= session
[s
].forwardtosession
;
2345 if (session
[sess
].forwardtosession
== s
)
2347 // Shutdown the linked session also.
2348 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2352 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2354 if ((g
= grp_groupbysession(s
)))
2356 grp_removesession(g
, s
);
2360 cluster_send_session(s
);
2363 static void tunnelclear(tunnelidt t
)
2366 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2367 tunnel
[t
].state
= TUNNELFREE
;
2370 static void bundleclear(bundleidt b
)
2373 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2374 bundle
[b
].state
= BUNDLEFREE
;
2377 // kill a tunnel now
2378 static void tunnelkill(tunnelidt t
, char *reason
)
2385 tunnel
[t
].state
= TUNNELDIE
;
2387 // free control messages
2388 while ((c
= tunnel
[t
].controls
))
2390 controlt
* n
= c
->next
;
2391 tunnel
[t
].controls
= n
;
2392 tunnel
[t
].controlc
--;
2393 c
->next
= controlfree
;
2397 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2398 if (session
[s
].tunnel
== t
)
2399 sessionkill(s
, reason
);
2403 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2404 cli_tunnel_actions
[t
].action
= 0;
2405 cluster_send_tunnel(t
);
2408 // shut down a tunnel cleanly
2409 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2413 CSTAT(tunnelshutdown
);
2415 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2417 // never set up, can immediately kill
2418 tunnelkill(t
, reason
);
2421 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2424 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2425 if (session
[s
].tunnel
== t
)
2426 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2428 tunnel
[t
].state
= TUNNELDIE
;
2429 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2430 cluster_send_tunnel(t
);
2431 // TBA - should we wait for sessions to stop?
2434 controlt
*c
= controlnew(4); // sending StopCCN
2439 buf
[0] = htons(result
);
2440 buf
[1] = htons(error
);
2443 int m
= strlen(msg
);
2444 if (m
+ 4 > sizeof(buf
))
2445 m
= sizeof(buf
) - 4;
2447 memcpy(buf
+2, msg
, m
);
2451 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2454 control16(c
, 1, result
, 1);
2456 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2457 controladd(c
, 0, t
); // send the message
2461 // read and process packet on tunnel (UDP)
2462 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, uint16_t indexudpfd
)
2464 uint8_t *sendchalresponse
= NULL
;
2465 uint8_t *recvchalresponse
= NULL
;
2466 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2467 uint8_t *p
= buf
+ 2;
2474 LOG_HEX(5, "UDP Data", buf
, len
);
2475 STAT(tunnel_rx_packets
);
2476 INC_STAT(tunnel_rx_bytes
, len
);
2479 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2480 STAT(tunnel_rx_errors
);
2483 if ((buf
[1] & 0x0F) != 2)
2485 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2486 STAT(tunnel_rx_errors
);
2491 l
= ntohs(*(uint16_t *) p
);
2494 t
= ntohs(*(uint16_t *) p
);
2496 s
= ntohs(*(uint16_t *) p
);
2498 if (s
>= MAXSESSION
)
2500 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2501 STAT(tunnel_rx_errors
);
2506 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2507 STAT(tunnel_rx_errors
);
2510 if (t
== TUNNEL_ID_PPPOE
)
2512 LOG(1, s
, t
, "Received UDP packet with tunnel ID reserved for pppoe\n");
2513 STAT(tunnel_rx_errors
);
2518 ns
= ntohs(*(uint16_t *) p
);
2520 nr
= ntohs(*(uint16_t *) p
);
2525 uint16_t o
= ntohs(*(uint16_t *) p
);
2530 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2531 STAT(tunnel_rx_errors
);
2536 // used to time out old tunnels
2537 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2538 tunnel
[t
].lastrec
= time_now
;
2542 uint16_t message
= 0xFFFF; // message type
2544 uint8_t mandatory
= 0;
2545 uint16_t asession
= 0; // assigned session
2546 uint32_t amagic
= 0; // magic number
2547 uint8_t aflags
= 0; // flags from last LCF
2548 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2549 char called
[MAXTEL
] = ""; // called number
2550 char calling
[MAXTEL
] = ""; // calling number
2552 if (!config
->cluster_iam_master
)
2554 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
2558 // control messages must have bits 0x80|0x40|0x08
2559 // (type, length and sequence) set, and bits 0x02|0x01
2560 // (offset and priority) clear
2561 if ((*buf
& 0xCB) != 0xC8)
2563 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2564 STAT(tunnel_rx_errors
);
2568 // check for duplicate tunnel open message
2574 // Is this a duplicate of the first packet? (SCCRQ)
2576 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2578 if (tunnel
[i
].state
!= TUNNELOPENING
||
2579 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2580 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2583 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2588 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2589 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2591 // if no tunnel specified, assign one
2594 if (!(t
= new_tunnel()))
2596 LOG(1, 0, 0, "No more tunnels\n");
2597 STAT(tunnel_overflow
);
2601 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2602 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2603 tunnel
[t
].window
= 4; // default window
2604 tunnel
[t
].indexudp
= indexudpfd
;
2605 STAT(tunnel_created
);
2606 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2607 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2610 // If the 'ns' just received is not the 'nr' we're
2611 // expecting, just send an ack and drop it.
2613 // if 'ns' is less, then we got a retransmitted packet.
2614 // if 'ns' is greater than missed a packet. Either way
2615 // we should ignore it.
2616 if (ns
!= tunnel
[t
].nr
)
2618 // is this the sequence we were expecting?
2619 STAT(tunnel_rx_errors
);
2620 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2621 t
, ns
, tunnel
[t
].nr
);
2623 if (l
) // Is this not a ZLB?
2628 // check sequence of this message
2630 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2631 // some to clear maybe?
2632 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2634 controlt
*c
= tunnel
[t
].controls
;
2635 tunnel
[t
].controls
= c
->next
;
2636 tunnel
[t
].controlc
--;
2637 c
->next
= controlfree
;
2640 tunnel
[t
].try = 0; // we have progress
2643 // receiver advance (do here so quoted correctly in any sends below)
2644 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2645 if (skip
< 0) skip
= 0;
2646 if (skip
< tunnel
[t
].controlc
)
2648 // some control packets can now be sent that were previous stuck out of window
2649 int tosend
= tunnel
[t
].window
- skip
;
2650 controlt
*c
= tunnel
[t
].controls
;
2658 tunnel
[t
].try = 0; // first send
2659 tunnelsend(c
->buf
, c
->length
, t
);
2664 if (!tunnel
[t
].controlc
)
2665 tunnel
[t
].retry
= 0; // caught up
2668 { // if not a null message
2673 // Default disconnect cause/message on receipt of CDN. Set to
2674 // more specific value from attribute 1 (result code) or 46
2675 // (disconnect cause) if present below.
2676 int disc_cause_set
= 0;
2677 int disc_cause
= TERM_NAS_REQUEST
;
2678 char const *disc_reason
= "Closed (Received CDN).";
2681 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2683 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2690 LOG(1, s
, t
, "Invalid length in AVP\n");
2691 STAT(tunnel_rx_errors
);
2696 if (flags
& 0x3C) // reserved bits, should be clear
2698 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2700 result
= 2; // general error
2701 error
= 3; // reserved field non-zero
2706 if (*(uint16_t *) (b
))
2708 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2710 result
= 2; // general error
2711 error
= 6; // generic vendor-specific error
2712 msg
= "unsupported vendor-specific";
2716 mtype
= ntohs(*(uint16_t *) (b
));
2724 // handle hidden AVPs
2725 if (!*config
->l2tp_secret
)
2727 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2729 result
= 2; // general error
2730 error
= 6; // generic vendor-specific error
2731 msg
= "secret not specified";
2734 if (!session
[s
].random_vector_length
)
2736 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2738 result
= 2; // general error
2739 error
= 6; // generic
2740 msg
= "no random vector";
2745 LOG(2, s
, t
, "Short hidden AVP.\n");
2747 result
= 2; // general error
2748 error
= 2; // length is wrong
2754 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2756 orig_len
= ntohs(*(uint16_t *) b
);
2757 if (orig_len
> n
+ 2)
2759 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2763 result
= 2; // general error
2764 error
= 2; // length is wrong
2773 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2774 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2778 case 0: // message type
2779 message
= ntohs(*(uint16_t *) b
);
2780 mandatory
= flags
& 0x80;
2781 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2783 case 1: // result code
2785 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2786 char const *resdesc
= "(unknown)";
2787 char const *errdesc
= NULL
;
2792 resdesc
= l2tp_stopccn_result_code(rescode
);
2793 cause
= TERM_LOST_SERVICE
;
2795 else if (message
== 14)
2797 resdesc
= l2tp_cdn_result_code(rescode
);
2799 cause
= TERM_LOST_CARRIER
;
2801 cause
= TERM_ADMIN_RESET
;
2804 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2807 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2808 errdesc
= l2tp_error_code(errcode
);
2809 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2812 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2814 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2816 disc_cause_set
= mtype
;
2817 disc_reason
= errdesc
? errdesc
: resdesc
;
2824 case 2: // protocol version
2826 version
= ntohs(*(uint16_t *) (b
));
2827 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2828 if (version
&& version
!= 0x0100)
2829 { // allow 0.0 and 1.0
2830 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2832 result
= 5; // unspported protocol version
2833 error
= 0x0100; // supported version
2839 case 3: // framing capabilities
2841 case 4: // bearer capabilities
2843 case 5: // tie breaker
2844 // We never open tunnels, so we don't care about tie breakers
2846 case 6: // firmware revision
2848 case 7: // host name
2849 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2850 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2851 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2852 // TBA - to send to RADIUS
2854 case 8: // vendor name
2855 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2856 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2857 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2859 case 9: // assigned tunnel
2860 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2861 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2863 case 10: // rx window
2864 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2865 if (!tunnel
[t
].window
)
2866 tunnel
[t
].window
= 1; // window of 0 is silly
2867 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2869 case 11: // Request Challenge
2871 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2873 build_chap_response(b
, 2, n
, &sendchalresponse
);
2874 else if (message
== 2)
2875 build_chap_response(b
, 3, n
, &sendchalresponse
);
2878 case 13: // receive challenge Response
2879 if (tunnel
[t
].isremotelns
)
2881 recvchalresponse
= calloc(17, 1);
2882 memcpy(recvchalresponse
, b
, (n
< 17) ? n
: 16);
2883 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2886 // Why did they send a response? We never challenge.
2887 LOG(2, s
, t
, " received unexpected challenge response\n");
2890 case 14: // assigned session
2891 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2892 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2894 case 15: // call serial number
2895 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2897 case 18: // bearer type
2898 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2901 case 19: // framing type
2902 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2905 case 21: // called number
2906 memset(called
, 0, sizeof(called
));
2907 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2908 LOG(4, s
, t
, " Called <%s>\n", called
);
2910 case 22: // calling number
2911 memset(calling
, 0, sizeof(calling
));
2912 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2913 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2917 case 24: // tx connect speed
2920 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2924 // AS5300s send connect speed as a string
2926 memset(tmp
, 0, sizeof(tmp
));
2927 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2928 session
[s
].tx_connect_speed
= atol(tmp
);
2930 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2932 case 38: // rx connect speed
2935 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2939 // AS5300s send connect speed as a string
2941 memset(tmp
, 0, sizeof(tmp
));
2942 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2943 session
[s
].rx_connect_speed
= atol(tmp
);
2945 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2947 case 25: // Physical Channel ID
2949 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2950 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2953 case 29: // Proxy Authentication Type
2955 uint16_t atype
= ntohs(*(uint16_t *)b
);
2956 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2959 case 30: // Proxy Authentication Name
2962 memset(authname
, 0, sizeof(authname
));
2963 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2964 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2968 case 31: // Proxy Authentication Challenge
2970 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2973 case 32: // Proxy Authentication ID
2975 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2976 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2979 case 33: // Proxy Authentication Response
2980 LOG(4, s
, t
, " Proxy Auth Response\n");
2982 case 27: // last sent lcp
2983 { // find magic number
2984 uint8_t *p
= b
, *e
= p
+ n
;
2985 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2987 if (*p
== 5 && p
[1] == 6) // Magic-Number
2988 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2989 else if (*p
== 7) // Protocol-Field-Compression
2990 aflags
|= SESSION_PFC
;
2991 else if (*p
== 8) // Address-and-Control-Field-Compression
2992 aflags
|= SESSION_ACFC
;
2997 case 28: // last recv lcp confreq
2999 case 26: // Initial Received LCP CONFREQ
3001 case 39: // seq required - we control it as an LNS anyway...
3003 case 36: // Random Vector
3004 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
3005 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
3006 if (n
> sizeof(session
[s
].random_vector
))
3007 n
= sizeof(session
[s
].random_vector
);
3008 memcpy(session
[s
].random_vector
, b
, n
);
3009 session
[s
].random_vector_length
= n
;
3011 case 46: // ppp disconnect cause
3014 uint16_t code
= ntohs(*(uint16_t *) b
);
3015 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
3016 uint8_t dir
= *(b
+ 4);
3018 LOG(4, s
, t
, " PPP disconnect cause "
3019 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
3020 code
, proto
, dir
, n
- 5, b
+ 5);
3022 disc_cause_set
= mtype
;
3026 case 1: // admin disconnect
3027 disc_cause
= TERM_ADMIN_RESET
;
3028 disc_reason
= "Administrative disconnect";
3030 case 3: // lcp terminate
3031 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
3032 disc_cause
= TERM_USER_REQUEST
;
3033 disc_reason
= "Normal disconnection";
3035 case 4: // compulsory encryption unavailable
3036 if (dir
!= 1) break; // 1=refused by peer, 2=local
3037 disc_cause
= TERM_USER_ERROR
;
3038 disc_reason
= "Compulsory encryption refused";
3040 case 5: // lcp: fsm timeout
3041 disc_cause
= TERM_PORT_ERROR
;
3042 disc_reason
= "LCP: FSM timeout";
3044 case 6: // lcp: no recognisable lcp packets received
3045 disc_cause
= TERM_PORT_ERROR
;
3046 disc_reason
= "LCP: no recognisable LCP packets";
3048 case 7: // lcp: magic-no error (possibly looped back)
3049 disc_cause
= TERM_PORT_ERROR
;
3050 disc_reason
= "LCP: magic-no error (possible loop)";
3052 case 8: // lcp: echo request timeout
3053 disc_cause
= TERM_PORT_ERROR
;
3054 disc_reason
= "LCP: echo request timeout";
3056 case 13: // auth: fsm timeout
3057 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3058 disc_reason
= "Authentication: FSM timeout";
3060 case 15: // auth: unacceptable auth protocol
3061 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3062 disc_reason
= "Unacceptable authentication protocol";
3064 case 16: // auth: authentication failed
3065 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3066 disc_reason
= "Authentication failed";
3068 case 17: // ncp: fsm timeout
3069 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3070 disc_reason
= "NCP: FSM timeout";
3072 case 18: // ncp: no ncps available
3073 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3074 disc_reason
= "NCP: no NCPs available";
3076 case 19: // ncp: failure to converge on acceptable address
3077 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3078 disc_reason
= (dir
== 1)
3079 ? "NCP: too many Configure-Naks received from peer"
3080 : "NCP: too many Configure-Naks sent to peer";
3082 case 20: // ncp: user not permitted to use any address
3083 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
3084 disc_reason
= (dir
== 1)
3085 ? "NCP: local link address not acceptable to peer"
3086 : "NCP: remote link address not acceptable";
3093 static char e
[] = "unknown AVP 0xXXXX";
3094 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
3096 result
= 2; // general error
3097 error
= 8; // unknown mandatory AVP
3098 sprintf((msg
= e
) + 14, "%04x", mtype
);
3105 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
3109 case 1: // SCCRQ - Start Control Connection Request
3110 tunnel
[t
].state
= TUNNELOPENING
;
3111 LOG(3, s
, t
, "Received SCCRQ\n");
3112 if (main_quit
!= QUIT_SHUTDOWN
)
3114 LOG(3, s
, t
, "sending SCCRP\n");
3115 controlt
*c
= controlnew(2); // sending SCCRP
3116 control16(c
, 2, version
, 1); // protocol version
3117 control32(c
, 3, 3, 1); // framing
3118 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3119 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Send Challenge response
3120 control16(c
, 9, t
, 1); // assigned tunnel
3121 controladd(c
, 0, t
); // send the resply
3125 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3129 tunnel
[t
].state
= TUNNELOPEN
;
3130 tunnel
[t
].lastrec
= time_now
;
3131 LOG(3, s
, t
, "Received SCCRP\n");
3132 if (main_quit
!= QUIT_SHUTDOWN
)
3134 if (tunnel
[t
].isremotelns
&& recvchalresponse
)
3138 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3139 // check authenticator
3140 if (memcmp(hash
, recvchalresponse
, 16) == 0)
3142 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3143 controlt
*c
= controlnew(3); // sending SCCCN
3144 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
3145 controls(c
, 8, Vendor_name
, 1); // Vendor name
3146 control16(c
, 2, version
, 1); // protocol version
3147 control32(c
, 3, 3, 1); // framing Capabilities
3148 if (sendchalresponse
) controlb(c
, 13, sendchalresponse
, 16, 1); // Challenge response
3149 control16(c
, 9, t
, 1); // assigned tunnel
3150 controladd(c
, 0, t
); // send
3154 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3160 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3164 LOG(3, s
, t
, "Received SCCN\n");
3165 tunnel
[t
].state
= TUNNELOPEN
;
3166 tunnel
[t
].lastrec
= time_now
;
3167 controlnull(t
); // ack
3170 LOG(3, s
, t
, "Received StopCCN\n");
3171 controlnull(t
); // ack
3172 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3175 LOG(3, s
, t
, "Received HELLO\n");
3176 controlnull(t
); // simply ACK
3180 LOG(3, s
, t
, "Received OCRQ\n");
3184 LOG(3, s
, t
, "Received OCRO\n");
3188 LOG(3, s
, t
, "Received OCCN\n");
3191 LOG(3, s
, t
, "Received ICRQ\n");
3192 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3194 controlt
*c
= controlnew(11); // ICRP
3196 LOG(3, s
, t
, "Sending ICRP\n");
3199 sessionfree
= session
[s
].next
;
3200 memset(&session
[s
], 0, sizeof(session
[s
]));
3202 if (s
> config
->cluster_highest_sessionid
)
3203 config
->cluster_highest_sessionid
= s
;
3205 session
[s
].opened
= time_now
;
3206 session
[s
].tunnel
= t
;
3207 session
[s
].far
= asession
;
3208 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3209 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3210 control16(c
, 14, s
, 1); // assigned session
3211 controladd(c
, asession
, t
); // send the reply
3213 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3214 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3216 session
[s
].ppp
.phase
= Establish
;
3217 session
[s
].ppp
.lcp
= Starting
;
3219 STAT(session_created
);
3224 controlt
*c
= controlnew(14); // CDN
3225 LOG(3, s
, t
, "Sending CDN\n");
3228 STAT(session_overflow
);
3229 LOG(1, 0, t
, "No free sessions\n");
3230 control16(c
, 1, 4, 0); // temporary lack of resources
3233 control16(c
, 1, 2, 7); // shutting down, try another
3235 controladd(c
, asession
, t
); // send the message
3239 LOG(3, s
, t
, "Received ICRP\n");
3240 if (session
[s
].forwardtosession
)
3242 controlt
*c
= controlnew(12); // ICCN
3244 session
[s
].opened
= time_now
;
3245 session
[s
].tunnel
= t
;
3246 session
[s
].far
= asession
;
3247 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3249 control32(c
, 19, 1, 1); // Framing Type
3250 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3251 controladd(c
, asession
, t
); // send the message
3252 LOG(3, s
, t
, "Sending ICCN\n");
3256 LOG(3, s
, t
, "Received ICCN\n");
3257 if (amagic
== 0) amagic
= time_now
;
3258 session
[s
].magic
= amagic
; // set magic number
3259 session
[s
].flags
= aflags
; // set flags received
3260 session
[s
].mru
= PPPoE_MRU
; // default
3261 controlnull(t
); // ack
3264 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3265 sess_local
[s
].ppp_mru
= MRU
;
3267 // Set multilink options before sending initial LCP packet
3268 sess_local
[s
].mp_mrru
= 1614;
3269 sess_local
[s
].mp_epdis
= ntohl(config
->iftun_address
? config
->iftun_address
: my_address
);
3272 change_state(s
, lcp
, RequestSent
);
3276 LOG(3, s
, t
, "Received CDN\n");
3277 controlnull(t
); // ack
3278 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3281 LOG(1, s
, t
, "Missing message type\n");
3284 STAT(tunnel_rx_errors
);
3286 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3288 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3291 if (sendchalresponse
) free(sendchalresponse
);
3292 if (recvchalresponse
) free(recvchalresponse
);
3293 cluster_send_tunnel(t
);
3297 LOG(4, s
, t
, " Got a ZLB ack\n");
3304 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3305 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3306 { // HDLC address header, discard
3312 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3313 STAT(tunnel_rx_errors
);
3323 proto
= ntohs(*(uint16_t *) p
);
3328 if (session
[s
].forwardtosession
)
3330 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3331 // Forward to LAC/BAS or Remote LNS session
3332 lac_session_forward(buf
, len
, s
, proto
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3335 else if (config
->auth_tunnel_change_addr_src
)
3337 if (tunnel
[t
].ip
!= ntohl(addr
->sin_addr
.s_addr
) &&
3338 tunnel
[t
].port
== ntohs(addr
->sin_port
))
3340 // The remotes BAS are a clustered l2tpns server and the source IP has changed
3341 LOG(5, s
, t
, "The tunnel IP source (%s) has changed by new IP (%s)\n",
3342 fmtaddr(htonl(tunnel
[t
].ip
), 0), fmtaddr(addr
->sin_addr
.s_addr
, 0));
3344 tunnel
[t
].ip
= ntohl(addr
->sin_addr
.s_addr
);
3348 if (s
&& !session
[s
].opened
) // Is something wrong??
3350 if (!config
->cluster_iam_master
)
3352 // Pass it off to the master to deal with..
3353 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3357 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3358 STAT(tunnel_rx_errors
);
3362 if (proto
== PPPPAP
)
3364 session
[s
].last_packet
= time_now
;
3365 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3366 processpap(s
, t
, p
, l
);
3368 else if (proto
== PPPCHAP
)
3370 session
[s
].last_packet
= time_now
;
3371 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3372 processchap(s
, t
, p
, l
);
3374 else if (proto
== PPPLCP
)
3376 session
[s
].last_packet
= time_now
;
3377 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3378 processlcp(s
, t
, p
, l
);
3380 else if (proto
== PPPIPCP
)
3382 session
[s
].last_packet
= time_now
;
3383 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3384 processipcp(s
, t
, p
, l
);
3386 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3388 session
[s
].last_packet
= time_now
;
3389 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3390 processipv6cp(s
, t
, p
, l
);
3392 else if (proto
== PPPCCP
)
3394 session
[s
].last_packet
= time_now
;
3395 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3396 processccp(s
, t
, p
, l
);
3398 else if (proto
== PPPIP
)
3402 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3403 return; // closing session, PPP not processed
3406 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3407 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3409 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3413 processipin(s
, t
, p
, l
);
3415 else if (proto
== PPPMP
)
3419 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3420 return; // closing session, PPP not processed
3423 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3424 if (!config
->cluster_iam_master
)
3426 // The fragments reconstruction is managed by the Master.
3427 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3431 processmpin(s
, t
, p
, l
);
3433 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3437 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3438 return; // closing session, PPP not processed
3441 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3442 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3444 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
);
3448 processipv6in(s
, t
, p
, l
);
3450 else if (session
[s
].ppp
.lcp
== Opened
)
3452 session
[s
].last_packet
= time_now
;
3453 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
, indexudpfd
); return; }
3454 protoreject(s
, t
, p
, l
, proto
);
3458 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3459 proto
, ppp_state(session
[s
].ppp
.lcp
));
3464 // read and process packet on tun
3465 // (i.e. this routine writes to buf[-8]).
3466 static void processtun(uint8_t * buf
, int len
)
3468 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3469 STAT(tun_rx_packets
);
3470 INC_STAT(tun_rx_bytes
, len
);
3478 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3479 STAT(tun_rx_errors
);
3483 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3484 processipout(buf
, len
);
3485 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3486 && config
->ipv6_prefix
.s6_addr
[0])
3487 processipv6out(buf
, len
);
3492 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3493 // that we look at the whole of the tunnel, radius and session tables
3495 static void regular_cleanups(double period
)
3497 // Next tunnel, radius and session to check for actions on.
3498 static tunnelidt t
= 0;
3500 static sessionidt s
= 0;
3513 // divide up tables into slices based on the last run
3514 t_slice
= config
->cluster_highest_tunnelid
* period
;
3515 r_slice
= (MAXRADIUS
- 1) * period
;
3516 s_slice
= config
->cluster_highest_sessionid
* period
;
3520 else if (t_slice
> config
->cluster_highest_tunnelid
)
3521 t_slice
= config
->cluster_highest_tunnelid
;
3525 else if (r_slice
> (MAXRADIUS
- 1))
3526 r_slice
= MAXRADIUS
- 1;
3530 else if (s_slice
> config
->cluster_highest_sessionid
)
3531 s_slice
= config
->cluster_highest_sessionid
;
3533 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3535 for (i
= 0; i
< t_slice
; i
++)
3538 if (t
> config
->cluster_highest_tunnelid
)
3541 if (t
== TUNNEL_ID_PPPOE
)
3544 // check for expired tunnels
3545 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3547 STAT(tunnel_timeout
);
3548 tunnelkill(t
, "Expired");
3552 // check for message resend
3553 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3555 // resend pending messages as timeout on reply
3556 if (tunnel
[t
].retry
<= TIME
)
3558 controlt
*c
= tunnel
[t
].controls
;
3559 uint16_t w
= tunnel
[t
].window
;
3560 tunnel
[t
].try++; // another try
3561 if (tunnel
[t
].try > 5)
3562 tunnelkill(t
, "Timeout on control message"); // game over
3566 tunnelsend(c
->buf
, c
->length
, t
);
3574 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3576 if (!config
->disable_sending_hello
)
3578 controlt
*c
= controlnew(6); // sending HELLO
3579 controladd(c
, 0, t
); // send the message
3580 LOG(3, 0, t
, "Sending HELLO message\n");
3585 // Check for tunnel changes requested from the CLI
3586 if ((a
= cli_tunnel_actions
[t
].action
))
3588 cli_tunnel_actions
[t
].action
= 0;
3589 if (a
& CLI_TUN_KILL
)
3591 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3592 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3598 for (i
= 0; i
< r_slice
; i
++)
3604 if (!radius
[r
].state
)
3607 if (radius
[r
].retry
<= TIME
)
3614 for (i
= 0; i
< s_slice
; i
++)
3617 if (s
> config
->cluster_highest_sessionid
)
3620 if (!session
[s
].opened
) // Session isn't in use
3623 // check for expired sessions
3626 if (session
[s
].die
<= TIME
)
3628 sessionkill(s
, "Expired");
3635 if (sess_local
[s
].lcp
.restart
<= time_now
)
3637 int next_state
= session
[s
].ppp
.lcp
;
3638 switch (session
[s
].ppp
.lcp
)
3642 next_state
= RequestSent
;
3645 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3647 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3648 sendlcp(s
, session
[s
].tunnel
);
3649 change_state(s
, lcp
, next_state
);
3653 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3654 STAT(session_timeout
);
3664 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3666 int next_state
= session
[s
].ppp
.ipcp
;
3667 switch (session
[s
].ppp
.ipcp
)
3671 next_state
= RequestSent
;
3674 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3676 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3677 sendipcp(s
, session
[s
].tunnel
);
3678 change_state(s
, ipcp
, next_state
);
3682 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3683 STAT(session_timeout
);
3693 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3695 int next_state
= session
[s
].ppp
.ipv6cp
;
3696 switch (session
[s
].ppp
.ipv6cp
)
3700 next_state
= RequestSent
;
3703 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3705 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3706 sendipv6cp(s
, session
[s
].tunnel
);
3707 change_state(s
, ipv6cp
, next_state
);
3711 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3712 change_state(s
, ipv6cp
, Stopped
);
3719 if (sess_local
[s
].ccp
.restart
<= time_now
)
3721 int next_state
= session
[s
].ppp
.ccp
;
3722 switch (session
[s
].ppp
.ccp
)
3726 next_state
= RequestSent
;
3729 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3731 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3732 sendccp(s
, session
[s
].tunnel
);
3733 change_state(s
, ccp
, next_state
);
3737 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3738 change_state(s
, ccp
, Stopped
);
3745 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3746 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3748 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3749 STAT(session_timeout
);
3754 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3755 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= config
->echo_timeout
) &&
3756 (time_now
- sess_local
[s
].last_echo
>= config
->echo_timeout
))
3758 uint8_t b
[MAXETHER
];
3760 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3764 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3765 *(uint16_t *)(q
+ 2) = htons(8); // Length
3766 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3768 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3769 (int)(time_now
- session
[s
].last_packet
));
3771 tunnelsend(b
, (q
- b
) + 8, session
[s
].tunnel
); // send it
3772 sess_local
[s
].last_echo
= time_now
;
3776 // Drop sessions who have reached session_timeout seconds
3777 if (session
[s
].session_timeout
)
3779 bundleidt bid
= session
[s
].bundle
;
3782 if (time_now
- bundle
[bid
].last_check
>= 1)
3784 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3785 bundle
[bid
].last_check
= time_now
;
3786 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3789 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3791 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3798 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3800 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3806 // Drop sessions who have reached idle_timeout seconds
3807 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3809 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3810 STAT(session_timeout
);
3815 // Check for actions requested from the CLI
3816 if ((a
= cli_session_actions
[s
].action
))
3820 cli_session_actions
[s
].action
= 0;
3821 if (a
& CLI_SESS_KILL
)
3823 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3824 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3825 a
= 0; // dead, no need to check for other actions
3829 if (a
& CLI_SESS_NOSNOOP
)
3831 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3832 session
[s
].snoop_ip
= 0;
3833 session
[s
].snoop_port
= 0;
3837 else if (a
& CLI_SESS_SNOOP
)
3839 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3840 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3841 cli_session_actions
[s
].snoop_port
);
3843 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3844 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3849 if (a
& CLI_SESS_NOTHROTTLE
)
3851 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3852 throttle_session(s
, 0, 0);
3856 else if (a
& CLI_SESS_THROTTLE
)
3858 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3859 cli_session_actions
[s
].throttle_in
,
3860 cli_session_actions
[s
].throttle_out
);
3862 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3867 if (a
& CLI_SESS_NOFILTER
)
3869 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3870 filter_session(s
, 0, 0);
3874 else if (a
& CLI_SESS_FILTER
)
3876 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3877 cli_session_actions
[s
].filter_in
,
3878 cli_session_actions
[s
].filter_out
);
3880 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3886 cluster_send_session(s
);
3889 // RADIUS interim accounting
3890 if (config
->radius_accounting
&& config
->radius_interim
> 0
3891 && session
[s
].ip
&& !session
[s
].walled_garden
3892 && !sess_local
[s
].radius
// RADIUS already in progress
3893 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3894 && session
[s
].flags
& SESSION_STARTED
)
3896 int rad
= radiusnew(s
);
3899 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3900 STAT(radius_overflow
);
3904 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3905 session
[s
].user
, session
[s
].unique_id
);
3907 radiussend(rad
, RADIUSINTERIM
);
3908 sess_local
[s
].last_interim
= time_now
;
3913 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3914 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3918 // Are we in the middle of a tunnel update, or radius
3921 static int still_busy(void)
3924 static clockt last_talked
= 0;
3925 static clockt start_busy_wait
= 0;
3928 static time_t stopped_bgp
= 0;
3933 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3935 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3936 if (bgp_peers
[i
].state
== Established
)
3937 bgp_stop(&bgp_peers
[i
]);
3939 stopped_bgp
= time_now
;
3941 if (!config
->cluster_iam_master
)
3943 // we don't want to become master
3944 cluster_send_ping(0);
3950 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3955 if (!config
->cluster_iam_master
)
3958 if (main_quit
== QUIT_SHUTDOWN
)
3960 static int dropped
= 0;
3965 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3966 for (i
= 1; i
< MAXTUNNEL
; i
++)
3967 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3968 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3974 if (start_busy_wait
== 0)
3975 start_busy_wait
= TIME
;
3977 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3979 if (!tunnel
[i
].controlc
)
3982 if (last_talked
!= TIME
)
3984 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3990 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3991 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3993 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3997 for (i
= 1; i
< MAXRADIUS
; i
++)
3999 if (radius
[i
].state
== RADIUSNULL
)
4001 if (radius
[i
].state
== RADIUSWAIT
)
4004 if (last_talked
!= TIME
)
4006 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
4016 # include <sys/epoll.h>
4018 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
4019 # include "fake_epoll.h"
4022 // the base set of fds polled: cli, cluster, tun, udp (MAX_UDPFD), control, dae, netlink, udplac, pppoedisc, pppoesess
4023 #define BASE_FDS (9 + MAX_UDPFD)
4025 // additional polled fds
4027 # define EXTRA_FDS BGP_NUM_PEERS
4029 # define EXTRA_FDS 0
4032 // main loop - gets packets on tun or udp and processes them
4033 static void mainloop(void)
4037 uint8_t *p
= buf
+ 32; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
4038 // and the forwarded pppoe session
4039 int size_bufp
= sizeof(buf
) - 32;
4040 clockt next_cluster_ping
= 0; // send initial ping immediately
4041 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
4042 int maxevent
= sizeof(events
)/sizeof(*events
);
4044 if ((epollfd
= epoll_create(maxevent
)) < 0)
4046 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
4050 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",
4051 clifd
, cluster_sockfd
, tunfd
, udpfd
[0], controlfd
, daefd
, nlfd
, udplacfd
, pppoediscfd
, pppoesessfd
);
4053 /* setup our fds to poll for input */
4055 static struct event_data d
[BASE_FDS
];
4056 struct epoll_event e
;
4063 d
[i
].type
= FD_TYPE_CLI
;
4064 e
.data
.ptr
= &d
[i
++];
4065 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
4068 d
[i
].type
= FD_TYPE_CLUSTER
;
4069 e
.data
.ptr
= &d
[i
++];
4070 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
4072 d
[i
].type
= FD_TYPE_TUN
;
4073 e
.data
.ptr
= &d
[i
++];
4074 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
4076 d
[i
].type
= FD_TYPE_CONTROL
;
4077 e
.data
.ptr
= &d
[i
++];
4078 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
4080 d
[i
].type
= FD_TYPE_DAE
;
4081 e
.data
.ptr
= &d
[i
++];
4082 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
4084 d
[i
].type
= FD_TYPE_NETLINK
;
4085 e
.data
.ptr
= &d
[i
++];
4086 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
4088 d
[i
].type
= FD_TYPE_PPPOEDISC
;
4089 e
.data
.ptr
= &d
[i
++];
4090 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoediscfd
, &e
);
4092 d
[i
].type
= FD_TYPE_PPPOESESS
;
4093 e
.data
.ptr
= &d
[i
++];
4094 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, pppoesessfd
, &e
);
4096 for (j
= 0; j
< config
->nbudpfd
; j
++)
4098 d
[i
].type
= FD_TYPE_UDP
;
4100 e
.data
.ptr
= &d
[i
++];
4101 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
[j
], &e
);
4106 signal(SIGPIPE
, SIG_IGN
);
4107 bgp_setup(config
->as_number
);
4108 if (config
->bind_address
)
4109 bgp_add_route(config
->bind_address
, 0xffffffff);
4111 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
4113 if (config
->neighbour
[i
].name
[0])
4114 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
4115 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
4116 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
4117 0); /* 0 = routing disabled */
4121 while (!main_quit
|| still_busy())
4131 config
->reload_config
++;
4134 if (config
->reload_config
)
4136 config
->reload_config
= 0;
4144 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4145 STAT(select_called
);
4150 if (errno
== EINTR
||
4151 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4154 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4160 struct sockaddr_in addr
;
4161 struct in_addr local
;
4164 int udp_ready
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4165 int pppoesess_ready
= 0;
4166 int pppoesess_pkts
= 0;
4168 int cluster_ready
= 0;
4169 int udp_pkts
[MAX_UDPFD
+ 1] = INIT_TABUDPVAR
;
4171 int cluster_pkts
= 0;
4173 uint32_t bgp_events
[BGP_NUM_PEERS
];
4174 memset(bgp_events
, 0, sizeof(bgp_events
));
4177 for (c
= n
, i
= 0; i
< c
; i
++)
4179 struct event_data
*d
= events
[i
].data
.ptr
;
4183 case FD_TYPE_CLI
: // CLI connections
4187 alen
= sizeof(addr
);
4188 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4194 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4200 // these are handled below, with multiple interleaved reads
4201 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4202 case FD_TYPE_TUN
: tun_ready
++; break;
4203 case FD_TYPE_UDP
: udp_ready
[d
->index
]++; break;
4204 case FD_TYPE_PPPOESESS
: pppoesess_ready
++; break;
4206 case FD_TYPE_PPPOEDISC
: // pppoe discovery
4207 s
= read(pppoediscfd
, p
, size_bufp
);
4208 if (s
> 0) process_pppoe_disc(p
, s
);
4212 case FD_TYPE_CONTROL
: // nsctl commands
4213 alen
= sizeof(addr
);
4214 s
= recvfromto(controlfd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4215 if (s
> 0) processcontrol(p
, s
, &addr
, alen
, &local
);
4219 case FD_TYPE_DAE
: // DAE requests
4220 alen
= sizeof(addr
);
4221 s
= recvfromto(daefd
, p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4222 if (s
> 0) processdae(p
, s
, &addr
, alen
, &local
);
4226 case FD_TYPE_RADIUS
: // RADIUS response
4227 alen
= sizeof(addr
);
4228 s
= recvfrom(radfds
[d
->index
], p
, size_bufp
, MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4229 if (s
>= 0 && config
->cluster_iam_master
)
4231 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4232 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4233 processrad(p
, s
, d
->index
);
4235 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4236 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4244 bgp_events
[d
->index
] = events
[i
].events
;
4249 case FD_TYPE_NETLINK
:
4251 struct nlmsghdr
*nh
= (struct nlmsghdr
*)p
;
4252 s
= netlink_recv(p
, size_bufp
);
4253 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4255 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4258 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4260 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4264 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4269 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
);
4275 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4280 bgp_process(bgp_events
);
4283 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4285 for (j
= 0; j
< config
->nbudpfd
; j
++)
4287 // L2TP and L2TP REMOTE LNS
4290 alen
= sizeof(addr
);
4291 if ((s
= recvfrom(udpfd
[j
], p
, size_bufp
, 0, (void *) &addr
, &alen
)) > 0)
4293 processudp(p
, s
, &addr
, j
);
4307 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4320 if (pppoesess_ready
)
4322 if ((s
= read(pppoesessfd
, p
, size_bufp
)) > 0)
4324 process_pppoe_sess(p
, s
);
4329 pppoesess_ready
= 0;
4337 alen
= sizeof(addr
);
4338 if ((s
= recvfrom(cluster_sockfd
, p
, size_bufp
, MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4340 processcluster(p
, s
, addr
.sin_addr
.s_addr
);
4351 if (udp_pkts
[0] > 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4352 STAT(multi_read_used
);
4354 if (c
>= config
->multi_read_count
)
4356 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun %d cluster and %d pppoe packets\n",
4357 config
->multi_read_count
, udp_pkts
[0], tun_pkts
, cluster_pkts
, pppoesess_pkts
);
4358 STAT(multi_read_exceeded
);
4364 /* no event received, but timers could still have expired */
4365 bgp_process_peers_timers();
4370 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4372 // Log current traffic stats
4373 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4374 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4375 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4376 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4377 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4379 udp_tx
= udp_rx
= 0;
4380 udp_rx_pkt
= eth_rx_pkt
= 0;
4381 eth_tx
= eth_rx
= 0;
4384 if (config
->dump_speed
)
4385 printf("%s\n", config
->bandwidth
);
4387 // Update the internal time counter
4388 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4392 struct param_timer p
= { time_now
};
4393 run_plugins(PLUGIN_TIMER
, &p
);
4397 // Runs on every machine (master and slaves).
4398 if (next_cluster_ping
<= TIME
)
4400 // Check to see which of the cluster is still alive..
4402 cluster_send_ping(basetime
); // Only does anything if we're a slave
4403 cluster_check_master(); // ditto.
4405 cluster_heartbeat(); // Only does anything if we're a master.
4406 cluster_check_slaves(); // ditto.
4408 master_update_counts(); // If we're a slave, send our byte counters to our master.
4410 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4411 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4413 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4416 if (!config
->cluster_iam_master
)
4419 // Run token bucket filtering queue..
4420 // Only run it every 1/10th of a second.
4422 static clockt last_run
= 0;
4423 if (last_run
!= TIME
)
4430 // Handle timeouts, retries etc.
4432 static double last_clean
= 0;
4436 TIME
= now(&this_clean
);
4437 diff
= this_clean
- last_clean
;
4439 // Run during idle time (after we've handled
4440 // all incoming packets) or every 1/10th sec
4441 if (!more
|| diff
> 0.1)
4443 regular_cleanups(diff
);
4444 last_clean
= this_clean
;
4448 if (*config
->accounting_dir
)
4450 static clockt next_acct
= 0;
4451 static clockt next_shut_acct
= 0;
4453 if (next_acct
<= TIME
)
4455 // Dump accounting data
4456 next_acct
= TIME
+ ACCT_TIME
;
4457 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4460 else if (next_shut_acct
<= TIME
)
4462 // Dump accounting data for shutdown sessions
4463 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4470 // Are we the master and shutting down??
4471 if (config
->cluster_iam_master
)
4472 cluster_heartbeat(); // Flush any queued changes..
4474 // Ok. Notify everyone we're shutting down. If we're
4475 // the master, this will force an election.
4476 cluster_send_ping(0);
4479 // Important!!! We MUST not process any packets past this point!
4480 LOG(1, 0, 0, "Shutdown complete\n");
4483 static void stripdomain(char *host
)
4487 if ((p
= strchr(host
, '.')))
4493 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4499 while (fgets(buf
, sizeof(buf
), resolv
))
4501 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4504 if (!isspace(buf
[6]))
4508 while (isspace(*b
)) b
++;
4513 while (*b
&& !isspace(*b
)) b
++;
4515 if (buf
[0] == 'd') // domain is canonical
4521 // first search line
4524 // hold, may be subsequent domain line
4525 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4536 int hl
= strlen(host
);
4537 int dl
= strlen(domain
);
4538 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4539 host
[hl
-dl
- 1] = 0;
4543 *p
= 0; // everything after first dot
4548 // Init data structures
4549 static void initdata(int optdebug
, char *optconfig
)
4553 if (!(config
= shared_malloc(sizeof(configt
))))
4555 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4559 memset(config
, 0, sizeof(configt
));
4560 time(&config
->start_time
);
4561 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4562 config
->debug
= optdebug
;
4563 config
->num_tbfs
= MAXTBFS
;
4564 config
->rl_rate
= 28; // 28kbps
4565 config
->cluster_mcast_ttl
= 1;
4566 config
->cluster_master_min_adv
= 1;
4567 config
->ppp_restart_time
= 3;
4568 config
->ppp_max_configure
= 10;
4569 config
->ppp_max_failure
= 5;
4570 config
->kill_timedout_sessions
= 1;
4571 strcpy(config
->random_device
, RANDOMDEVICE
);
4572 // Set default value echo_timeout and idle_echo_timeout
4573 config
->echo_timeout
= ECHO_TIMEOUT
;
4574 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4576 log_stream
= stderr
;
4579 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4581 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4584 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4587 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4589 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4592 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4594 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4597 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4599 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4602 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4604 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4607 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4609 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4613 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4615 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4619 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4621 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4625 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4627 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4631 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4633 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4636 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4638 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4640 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4643 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4645 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4647 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4650 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4652 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4653 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4654 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4655 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4656 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4658 // Put all the sessions on the free list marked as undefined.
4659 for (i
= 1; i
< MAXSESSION
; i
++)
4661 session
[i
].next
= i
+ 1;
4662 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4664 session
[MAXSESSION
- 1].next
= 0;
4667 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4668 for (i
= 1; i
< MAXTUNNEL
; i
++)
4669 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4671 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4672 bundle
[i
].state
= BUNDLEUNDEF
;
4677 // Grab my hostname unless it's been specified
4678 gethostname(hostname
, sizeof(hostname
));
4679 stripdomain(hostname
);
4682 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4685 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4687 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4692 lac_initremotelnsdata();
4697 static int assign_ip_address(sessionidt s
)
4701 time_t best_time
= time_now
;
4702 char *u
= session
[s
].user
;
4706 CSTAT(assign_ip_address
);
4708 for (i
= 1; i
< ip_pool_size
; i
++)
4710 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4713 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4720 if (ip_address_pool
[i
].last
< best_time
)
4723 if (!(best_time
= ip_address_pool
[i
].last
))
4724 break; // never used, grab this one
4730 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4734 session
[s
].ip
= ip_address_pool
[best
].address
;
4735 session
[s
].ip_pool_index
= best
;
4736 ip_address_pool
[best
].assigned
= 1;
4737 ip_address_pool
[best
].last
= time_now
;
4738 ip_address_pool
[best
].session
= s
;
4739 if (session
[s
].walled_garden
)
4740 /* Don't track addresses of users in walled garden (note: this
4741 means that their address isn't "sticky" even if they get
4743 ip_address_pool
[best
].user
[0] = 0;
4745 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4748 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4749 reuse
? "Reusing" : "Allocating", best
);
4754 static void free_ip_address(sessionidt s
)
4756 int i
= session
[s
].ip_pool_index
;
4759 CSTAT(free_ip_address
);
4762 return; // what the?
4764 if (i
< 0) // Is this actually part of the ip pool?
4768 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4770 ip_address_pool
[i
].assigned
= 0;
4771 ip_address_pool
[i
].session
= 0;
4772 ip_address_pool
[i
].last
= time_now
;
4776 // Fsck the address pool against the session table.
4777 // Normally only called when we become a master.
4779 // This isn't perfect: We aren't keep tracking of which
4780 // users used to have an IP address.
4782 void rebuild_address_pool(void)
4787 // Zero the IP pool allocation, and build
4788 // a map from IP address to pool index.
4789 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4791 ip_address_pool
[i
].assigned
= 0;
4792 ip_address_pool
[i
].session
= 0;
4793 if (!ip_address_pool
[i
].address
)
4796 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4799 for (i
= 0; i
< MAXSESSION
; ++i
)
4802 if (!(session
[i
].opened
&& session
[i
].ip
))
4805 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4807 if (session
[i
].ip_pool_index
< 0)
4809 // Not allocated out of the pool.
4810 if (ipid
< 1) // Not found in the pool either? good.
4813 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4814 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4816 // Fall through and process it as part of the pool.
4820 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4822 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4824 session
[i
].ip_pool_index
= ipid
;
4828 ip_address_pool
[ipid
].assigned
= 1;
4829 ip_address_pool
[ipid
].session
= i
;
4830 ip_address_pool
[ipid
].last
= time_now
;
4831 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4832 session
[i
].ip_pool_index
= ipid
;
4833 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4838 // Fix the address pool to match a changed session.
4839 // (usually when the master sends us an update).
4840 static void fix_address_pool(int sid
)
4844 ipid
= session
[sid
].ip_pool_index
;
4846 if (ipid
> ip_pool_size
)
4847 return; // Ignore it. rebuild_address_pool will fix it up.
4849 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4850 return; // Just ignore it. rebuild_address_pool will take care of it.
4852 ip_address_pool
[ipid
].assigned
= 1;
4853 ip_address_pool
[ipid
].session
= sid
;
4854 ip_address_pool
[ipid
].last
= time_now
;
4855 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4859 // Add a block of addresses to the IP pool to hand out.
4861 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4865 prefixlen
= 32; // Host route only.
4867 addr
&= 0xffffffff << (32 - prefixlen
);
4869 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4872 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4874 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4875 continue; // Skip 0 and broadcast addresses.
4877 ip_address_pool
[ip_pool_size
].address
= i
;
4878 ip_address_pool
[ip_pool_size
].assigned
= 0;
4880 if (ip_pool_size
>= MAXIPPOOL
)
4882 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4888 // Initialize the IP address pool
4889 static void initippool()
4894 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4896 if (!(f
= fopen(IPPOOLFILE
, "r")))
4898 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4902 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4905 buf
[4095] = 0; // Force it to be zero terminated/
4907 if (*buf
== '#' || *buf
== '\n')
4908 continue; // Skip comments / blank lines
4909 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4910 if ((p
= (char *)strchr(buf
, ':')))
4914 src
= inet_addr(buf
);
4915 if (src
== INADDR_NONE
)
4917 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4920 // This entry is for a specific IP only
4921 if (src
!= config
->bind_address
)
4926 if ((p
= (char *)strchr(pool
, '/')))
4930 in_addr_t start
= 0;
4932 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4934 if (!*p
|| !(numbits
= atoi(p
)))
4936 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4939 start
= ntohl(inet_addr(pool
));
4941 // Add a static route for this pool
4942 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4943 fmtaddr(htonl(start
), 0), numbits
);
4945 routeset(0, start
, numbits
, 0, 1);
4947 add_to_ip_pool(start
, numbits
);
4951 // It's a single ip address
4952 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4956 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4959 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4961 struct sockaddr_in snoop_addr
= {0};
4962 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4965 snoop_addr
.sin_family
= AF_INET
;
4966 snoop_addr
.sin_addr
.s_addr
= destination
;
4967 snoop_addr
.sin_port
= ntohs(port
);
4969 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4970 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4971 htons(snoop_addr
.sin_port
));
4973 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4974 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4976 STAT(packets_snooped
);
4979 static int dump_session(FILE **f
, sessiont
*s
)
4981 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4986 char filename
[1024];
4988 time_t now
= time(NULL
);
4990 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4991 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4993 if (!(*f
= fopen(filename
, "w")))
4995 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4999 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
5000 if(config
->account_all_origin
)
5002 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5007 "# format: username ip qos uptxoctets downrxoctets origin(L=LAC, R=Remote LNS, P=PPPOE)\n",
5009 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5015 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
5020 "# format: username ip qos uptxoctets downrxoctets\n",
5022 fmtaddr(config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] ? config
->iftun_n_address
[tunnel
[s
->tunnel
].indexudp
] : my_address
, 0),
5028 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
5029 if(config
->account_all_origin
)
5031 fprintf(*f
, "%s %s %d %u %u %s\n",
5032 s
->user
, // username
5033 fmtaddr(htonl(s
->ip
), 0), // ip
5034 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5035 (uint32_t) s
->cin_delta
, // uptxoctets
5036 (uint32_t) s
->cout_delta
, // downrxoctets
5037 (s
->tunnel
== TUNNEL_ID_PPPOE
)?"P":(tunnel
[s
->tunnel
].isremotelns
?"R":"L")); // Origin
5039 else if (!tunnel
[s
->tunnel
].isremotelns
&& (s
->tunnel
!= TUNNEL_ID_PPPOE
))
5041 fprintf(*f
, "%s %s %d %u %u\n",
5042 s
->user
, // username
5043 fmtaddr(htonl(s
->ip
), 0), // ip
5044 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
5045 (uint32_t) s
->cin_delta
, // uptxoctets
5046 (uint32_t) s
->cout_delta
); // downrxoctets
5049 s
->cin_delta
= s
->cout_delta
= 0;
5054 static void dump_acct_info(int all
)
5060 CSTAT(dump_acct_info
);
5064 for (i
= 0; i
< shut_acct_n
; i
++)
5065 dump_session(&f
, &shut_acct
[i
]);
5071 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5072 dump_session(&f
, &session
[i
]);
5079 int main(int argc
, char *argv
[])
5083 char *optconfig
= CONFIGFILE
;
5085 time(&basetime
); // start clock
5088 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
5093 if (fork()) exit(0);
5095 if(!freopen("/dev/null", "r", stdin
)) LOG(0, 0, 0, "Error freopen stdin: %s\n", strerror(errno
));
5096 if(!freopen("/dev/null", "w", stdout
)) LOG(0, 0, 0, "Error freopen stdout: %s\n", strerror(errno
));
5097 if(!freopen("/dev/null", "w", stderr
)) LOG(0, 0, 0, "Error freopen stderr: %s\n", strerror(errno
));
5106 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
5109 printf("Args are:\n"
5110 "\t-d\t\tDetach from terminal\n"
5111 "\t-c <file>\tConfig file\n"
5112 "\t-h <hostname>\tForce hostname\n"
5120 // Start the timer routine off
5122 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
5125 initdata(optdebug
, optconfig
);
5129 /* set hostname /after/ having read the config file */
5130 if (*config
->hostname
)
5131 strcpy(hostname
, config
->hostname
);
5132 cli_init_complete(hostname
);
5134 init_tbf(config
->num_tbfs
);
5136 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
5137 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
5138 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
5141 rlim
.rlim_cur
= RLIM_INFINITY
;
5142 rlim
.rlim_max
= RLIM_INFINITY
;
5143 // Remove the maximum core size
5144 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
5145 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5147 // Make core dumps go to /tmp
5148 if(chdir("/tmp")) LOG(0, 0, 0, "Error chdir /tmp: %s\n", strerror(errno
));
5151 if (config
->scheduler_fifo
)
5154 struct sched_param params
= {0};
5155 params
.sched_priority
= 1;
5157 if (get_nprocs() < 2)
5159 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5160 config
->scheduler_fifo
= 0;
5164 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5166 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5170 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5171 config
->scheduler_fifo
= 0;
5178 /* Set up the cluster communications port. */
5179 if (cluster_init() < 0)
5183 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevicename
);
5185 if (*config
->pppoe_if_to_bind
)
5188 LOG(1, 0, 0, "Set up on pppoe interface %s\n", config
->pppoe_if_to_bind
);
5191 if (!config
->nbmultiaddress
)
5193 config
->bind_n_address
[0] = config
->bind_address
;
5194 config
->nbmultiaddress
++;
5196 config
->nbudpfd
= config
->nbmultiaddress
;
5197 for (i
= 0; i
< config
->nbudpfd
; i
++)
5198 initudp(&udpfd
[i
], config
->bind_n_address
[i
]);
5200 config
->indexlacudpfd
= config
->nbudpfd
;
5201 udpfd
[config
->indexlacudpfd
] = udplacfd
;
5208 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
5215 unsigned seed
= time_now
^ getpid();
5216 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5220 signal(SIGHUP
, sighup_handler
);
5221 signal(SIGCHLD
, sigchild_handler
);
5222 signal(SIGTERM
, shutdown_handler
);
5223 signal(SIGINT
, shutdown_handler
);
5224 signal(SIGQUIT
, shutdown_handler
);
5226 // Prevent us from getting paged out
5227 if (config
->lock_pages
)
5229 if (!mlockall(MCL_CURRENT
))
5230 LOG(1, 0, 0, "Locking pages into memory\n");
5232 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5235 //LOG(3, 0, 0, "Debug sizeof struct: sessiont %lu, tunnelt %lu, bundlet %lu, groupsesst %lu\n",
5236 // sizeof(sessiont), sizeof(tunnelt), sizeof(bundlet), sizeof(groupsesst));
5240 /* remove plugins (so cleanup code gets run) */
5243 // Remove the PID file if we wrote it
5244 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5245 unlink(config
->pid_file
);
5247 /* kill CLI children */
5248 signal(SIGTERM
, SIG_IGN
);
5253 static void sighup_handler(int sig
)
5258 static void shutdown_handler(int sig
)
5260 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5263 static void sigchild_handler(int sig
)
5265 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5269 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5272 *challenge_response
= NULL
;
5274 if (!*config
->l2tp_secret
)
5276 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5280 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5282 *challenge_response
= calloc(17, 1);
5285 MD5_Update(&ctx
, &id
, 1);
5286 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5287 MD5_Update(&ctx
, challenge
, challenge_length
);
5288 MD5_Final(*challenge_response
, &ctx
);
5293 static int facility_value(char *name
)
5296 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5298 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5299 return facilitynames
[i
].c_val
;
5304 static void update_config()
5308 static int timeout
= 0;
5309 static int interval
= 0;
5316 if (log_stream
!= stderr
)
5322 if (*config
->log_filename
)
5324 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5326 char *p
= config
->log_filename
+ 7;
5329 openlog("l2tpns", LOG_PID
, facility_value(p
));
5333 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5335 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5337 fseek(log_stream
, 0, SEEK_END
);
5338 setbuf(log_stream
, NULL
);
5342 log_stream
= stderr
;
5343 setbuf(log_stream
, NULL
);
5349 log_stream
= stderr
;
5350 setbuf(log_stream
, NULL
);
5353 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5354 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5356 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5357 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5358 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5360 // reset MRU/MSS globals
5361 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5362 if (MRU
> PPPoE_MRU
)
5365 MSS
= MRU
- TCP_HDRS
;
5368 config
->numradiusservers
= 0;
5369 for (i
= 0; i
< MAXRADSERVER
; i
++)
5370 if (config
->radiusserver
[i
])
5372 config
->numradiusservers
++;
5373 // Set radius port: if not set, take the port from the
5374 // first radius server. For the first radius server,
5375 // take the #defined default value from l2tpns.h
5377 // test twice, In case someone works with
5378 // a secondary radius server without defining
5379 // a primary one, this will work even then.
5380 if (i
> 0 && !config
->radiusport
[i
])
5381 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5382 if (!config
->radiusport
[i
])
5383 config
->radiusport
[i
] = RADPORT
;
5386 if (!config
->numradiusservers
)
5387 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5389 // parse radius_authtypes_s
5390 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5391 p
= config
->radius_authtypes_s
;
5394 char *s
= strpbrk(p
, " \t,");
5400 while (*s
== ' ' || *s
== '\t')
5407 if (!strncasecmp("chap", p
, strlen(p
)))
5409 else if (!strncasecmp("pap", p
, strlen(p
)))
5412 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5414 config
->radius_authtypes
|= type
;
5415 if (!config
->radius_authprefer
)
5416 config
->radius_authprefer
= type
;
5421 if (!config
->radius_authtypes
)
5423 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5424 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5427 // normalise radius_authtypes_s
5428 if (config
->radius_authprefer
== AUTHPAP
)
5430 strcpy(config
->radius_authtypes_s
, "pap");
5431 if (config
->radius_authtypes
& AUTHCHAP
)
5432 strcat(config
->radius_authtypes_s
, ", chap");
5436 strcpy(config
->radius_authtypes_s
, "chap");
5437 if (config
->radius_authtypes
& AUTHPAP
)
5438 strcat(config
->radius_authtypes_s
, ", pap");
5441 if (!config
->radius_dae_port
)
5442 config
->radius_dae_port
= DAEPORT
;
5444 if(!config
->bind_portremotelns
)
5445 config
->bind_portremotelns
= L2TPLACPORT
;
5446 if(!config
->bind_address_remotelns
)
5447 config
->bind_address_remotelns
= INADDR_ANY
;
5449 if (*config
->bind_multi_address
)
5451 char *sip
= config
->bind_multi_address
;
5453 char *e
= config
->bind_multi_address
+ strlen(config
->bind_multi_address
);
5454 config
->nbmultiaddress
= 0;
5456 while (*sip
&& (sip
< e
))
5461 while (n
< e
&& (*n
== ',' || *n
== ' ')) n
++;
5463 while (n
< e
&& (isdigit(*n
) || *n
== '.'))
5471 u
= u
* 10 + *n
- '0';
5479 config
->bind_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5480 config
->iftun_n_address
[config
->nbmultiaddress
] = htonl(ip
);
5481 config
->nbmultiaddress
++;
5482 LOG(1, 0, 0, "Bind address %s\n", fmtaddr(htonl(ip
), 0));
5484 if (config
->nbmultiaddress
>= MAX_BINDADDR
) break;
5490 if (config
->nbmultiaddress
>= 1)
5492 config
->bind_address
= config
->bind_n_address
[0];
5493 config
->iftun_address
= config
->bind_address
;
5497 if(!config
->iftun_address
)
5499 config
->iftun_address
= config
->bind_address
;
5500 config
->iftun_n_address
[0] = config
->iftun_address
;
5503 if (*config
->multi_hostname
)
5505 char *shost
= config
->multi_hostname
;
5507 char *e
= config
->multi_hostname
+ strlen(config
->multi_hostname
);
5508 config
->nbmultihostname
= 0;
5510 while (*shost
&& (shost
< e
))
5512 while ((n
< e
) && (*n
== ' ' || *n
== ',' || *n
== '\t')) n
++;
5515 while (n
< e
&& (*n
!= ',') && (*n
!= '\t'))
5517 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = *n
;
5523 config
->multi_n_hostname
[config
->nbmultihostname
][i
] = 0;
5524 LOG(1, 0, 0, "Bind Hostname %s\n", config
->multi_n_hostname
[config
->nbmultihostname
]);
5525 config
->nbmultihostname
++;
5526 if (config
->nbmultihostname
>= MAX_NBHOSTNAME
) break;
5532 if (config
->nbmultihostname
>= 1)
5534 strcpy(hostname
, config
->multi_n_hostname
[0]);
5535 strcpy(config
->hostname
, hostname
);
5539 if (!*config
->pppoe_ac_name
)
5540 strncpy(config
->pppoe_ac_name
, DEFAULT_PPPOE_AC_NAME
, sizeof(config
->pppoe_ac_name
) - 1);
5542 // re-initialise the random number source
5543 initrandom(config
->random_device
);
5546 for (i
= 0; i
< MAXPLUGINS
; i
++)
5548 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5551 if (*config
->plugins
[i
])
5554 add_plugin(config
->plugins
[i
]);
5556 else if (*config
->old_plugins
[i
])
5559 remove_plugin(config
->old_plugins
[i
]);
5564 guest_accounts_num
= 0;
5565 char *p2
= config
->guest_user
;
5568 char *s
= strpbrk(p2
, " \t,");
5572 while (*s
== ' ' || *s
== '\t')
5579 strcpy(guest_users
[guest_accounts_num
], p2
);
5580 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5581 guest_accounts_num
++;
5584 // Rebuild the guest_user array
5585 strcpy(config
->guest_user
, "");
5587 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5589 strcat(config
->guest_user
, guest_users
[ui
]);
5590 if (ui
<guest_accounts_num
-1)
5592 strcat(config
->guest_user
, ",");
5597 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5598 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5599 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5600 if (!*config
->cluster_interface
)
5601 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5603 if (!config
->cluster_hb_interval
)
5604 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5606 if (!config
->cluster_hb_timeout
)
5607 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5609 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5611 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5612 // late, ensure we're sufficiently larger than that
5613 int t
= 4 * config
->cluster_hb_interval
+ 11;
5615 if (config
->cluster_hb_timeout
< t
)
5617 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5618 config
->cluster_hb_timeout
= t
;
5621 // Push timing changes to the slaves immediately if we're the master
5622 if (config
->cluster_iam_master
)
5623 cluster_heartbeat();
5625 interval
= config
->cluster_hb_interval
;
5626 timeout
= config
->cluster_hb_timeout
;
5630 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5633 if ((f
= fopen(config
->pid_file
, "w")))
5635 fprintf(f
, "%d\n", getpid());
5637 config
->wrote_pid
= 1;
5641 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5646 static void read_config_file()
5650 if (!config
->config_file
) return;
5651 if (!(f
= fopen(config
->config_file
, "r")))
5653 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5657 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5659 LOG(3, 0, 0, "Done reading config file\n");
5663 int sessionsetup(sessionidt s
, tunnelidt t
)
5665 // A session now exists, set it up
5671 CSTAT(sessionsetup
);
5673 LOG(3, s
, t
, "Doing session setup for session\n");
5675 // Join a bundle if the MRRU option is accepted
5676 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5678 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5679 if (join_bundle(s
) > 0)
5680 cluster_send_bundle(session
[s
].bundle
);
5683 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5684 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5691 assign_ip_address(s
);
5694 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5695 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5698 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5699 fmtaddr(htonl(session
[s
].ip
), 0));
5702 // Make sure this is right
5703 session
[s
].tunnel
= t
;
5705 // zap old sessions with same IP and/or username
5706 // Don't kill gardened sessions - doing so leads to a DoS
5707 // from someone who doesn't need to know the password
5710 user
= session
[s
].user
;
5711 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5713 if (i
== s
) continue;
5714 if (!session
[s
].opened
) break;
5715 // Allow duplicate sessions for multilink ones of the same bundle.
5716 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5718 if (ip
== session
[i
].ip
)
5720 sessionshutdown(i
, "Duplicate IP address", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5724 if (config
->allow_duplicate_users
) continue;
5725 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5729 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5731 if (!strcasecmp(user
, guest_users
[gu
]))
5737 if (found
) continue;
5739 // Drop the new session in case of duplicate sessionss, not the old one.
5740 if (!strcasecmp(user
, session
[i
].user
))
5741 sessionshutdown(i
, "Duplicate session for users", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
5745 // no need to set a route for the same IP address of the bundle
5746 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5751 // Add the route for this session.
5752 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5754 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5755 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5758 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5761 // Static IPs need to be routed if not already
5762 // convered by a Framed-Route. Anything else is part
5763 // of the IP address pool and is already routed, it
5764 // just needs to be added to the IP cache.
5765 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5766 if (session
[s
].ip_pool_index
== -1) // static ip
5768 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5771 cache_ipmap(session
[s
].ip
, s
);
5773 if ((g
= grp_groupbysession(s
)))
5775 grp_setgrouproute(g
, 1);
5776 cluster_send_groupe(g
);
5780 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5781 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5783 // Run the plugin's against this new session.
5785 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5786 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5789 // Allocate TBFs if throttled
5790 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5791 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5793 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5795 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5796 fmtaddr(htonl(session
[s
].ip
), 0),
5797 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5799 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5801 return 1; // RADIUS OK and IP allocated, done...
5805 // This session just got dropped on us by the master or something.
5806 // Make sure our tables up up to date...
5808 int load_session(sessionidt s
, sessiont
*new)
5814 if (new->ip_pool_index
>= MAXIPPOOL
||
5815 new->tunnel
>= MAXTUNNEL
)
5817 LOG(0, s
, 0, "Strange session update received!\n");
5818 // FIXME! What to do here?
5823 // Ok. All sanity checks passed. Now we're committed to
5824 // loading the new session.
5827 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5829 // See if routes/ip cache need updating
5830 if (new->ip
!= session
[s
].ip
)
5833 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5834 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5835 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5843 // remove old routes...
5844 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5846 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5847 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5850 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5856 if (session
[s
].ip_pool_index
== -1) // static IP
5858 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5860 else // It's part of the IP pool, remove it manually.
5861 uncache_ipmap(session
[s
].ip
);
5864 // remove old IPV6 routes...
5865 if (session
[s
].ipv6route
.s6_addr
[0] && session
[s
].ipv6prefixlen
)
5866 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
5870 // add new routes...
5871 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5873 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5874 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5877 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5883 // If there's a new one, add it.
5884 if (new->ip_pool_index
== -1)
5886 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5889 cache_ipmap(new->ip
, s
);
5894 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5895 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5898 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5900 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5904 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5906 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5907 new->filter_out
= 0;
5910 if (new->filter_in
!= session
[s
].filter_in
)
5912 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5913 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5916 if (new->filter_out
!= session
[s
].filter_out
)
5918 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5919 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5922 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5923 // for walking the sessions to forward byte counts to the master.
5924 config
->cluster_highest_sessionid
= s
;
5926 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5928 // Do fixups into address pool.
5929 if (new->ip_pool_index
!= -1)
5930 fix_address_pool(s
);
5935 static void initplugins()
5939 loaded_plugins
= ll_init();
5940 // Initialize the plugins to nothing
5941 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5942 plugins
[i
] = ll_init();
5945 static void *open_plugin(char *plugin_name
, int load
)
5947 char path
[256] = "";
5949 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5950 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5951 return dlopen(path
, RTLD_NOW
);
5954 // plugin callback to get a config value
5955 static void *getconfig(char *key
, enum config_typet type
)
5959 for (i
= 0; config_values
[i
].key
; i
++)
5961 if (!strcmp(config_values
[i
].key
, key
))
5963 if (config_values
[i
].type
== type
)
5964 return ((void *) config
) + config_values
[i
].offset
;
5966 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5967 key
, type
, config_values
[i
].type
);
5973 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5977 static int add_plugin(char *plugin_name
)
5979 static struct pluginfuncs funcs
= {
5984 sessiontbysessionidt
,
5985 sessionidtbysessiont
,
5992 cluster_send_session
,
5995 void *p
= open_plugin(plugin_name
, 1);
5996 int (*initfunc
)(struct pluginfuncs
*);
6001 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
6005 if (ll_contains(loaded_plugins
, p
))
6008 return 0; // already loaded
6012 int *v
= dlsym(p
, "plugin_api_version");
6013 if (!v
|| *v
!= PLUGIN_API_VERSION
)
6015 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
6021 if ((initfunc
= dlsym(p
, "plugin_init")))
6023 if (!initfunc(&funcs
))
6025 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
6031 ll_push(loaded_plugins
, p
);
6033 for (i
= 0; i
< max_plugin_functions
; i
++)
6036 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6038 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
6039 ll_push(plugins
[i
], x
);
6043 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
6047 static void run_plugin_done(void *plugin
)
6049 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
6055 static int remove_plugin(char *plugin_name
)
6057 void *p
= open_plugin(plugin_name
, 0);
6063 if (ll_contains(loaded_plugins
, p
))
6066 for (i
= 0; i
< max_plugin_functions
; i
++)
6069 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
6070 ll_delete(plugins
[i
], x
);
6073 ll_delete(loaded_plugins
, p
);
6079 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
6083 int run_plugins(int plugin_type
, void *data
)
6085 int (*func
)(void *data
);
6087 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
6088 return PLUGIN_RET_ERROR
;
6090 ll_reset(plugins
[plugin_type
]);
6091 while ((func
= ll_next(plugins
[plugin_type
])))
6095 if (r
!= PLUGIN_RET_OK
)
6096 return r
; // stop here
6099 return PLUGIN_RET_OK
;
6102 static void plugins_done()
6106 ll_reset(loaded_plugins
);
6107 while ((p
= ll_next(loaded_plugins
)))
6111 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
6113 struct nsctl request
;
6114 struct nsctl response
;
6115 int type
= unpack_control(&request
, buf
, len
);
6119 if (log_stream
&& config
->debug
>= 4)
6123 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
6124 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
6128 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6129 dump_control(&request
, log_stream
);
6135 case NSCTL_REQ_LOAD
:
6136 if (request
.argc
!= 1)
6138 response
.type
= NSCTL_RES_ERR
;
6140 response
.argv
[0] = "name of plugin required";
6142 else if ((r
= add_plugin(request
.argv
[0])) < 1)
6144 response
.type
= NSCTL_RES_ERR
;
6146 response
.argv
[0] = !r
6147 ? "plugin already loaded"
6148 : "error loading plugin";
6152 response
.type
= NSCTL_RES_OK
;
6158 case NSCTL_REQ_UNLOAD
:
6159 if (request
.argc
!= 1)
6161 response
.type
= NSCTL_RES_ERR
;
6163 response
.argv
[0] = "name of plugin required";
6165 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
6167 response
.type
= NSCTL_RES_ERR
;
6169 response
.argv
[0] = !r
6170 ? "plugin not loaded"
6171 : "plugin not found";
6175 response
.type
= NSCTL_RES_OK
;
6181 case NSCTL_REQ_HELP
:
6182 response
.type
= NSCTL_RES_OK
;
6185 ll_reset(loaded_plugins
);
6186 while ((p
= ll_next(loaded_plugins
)))
6188 char **help
= dlsym(p
, "plugin_control_help");
6189 while (response
.argc
< 0xff && help
&& *help
)
6190 response
.argv
[response
.argc
++] = *help
++;
6195 case NSCTL_REQ_CONTROL
:
6197 struct param_control param
= {
6198 config
->cluster_iam_master
,
6205 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
6207 if (r
== PLUGIN_RET_ERROR
)
6209 response
.type
= NSCTL_RES_ERR
;
6211 response
.argv
[0] = param
.additional
6213 : "error returned by plugin";
6215 else if (r
== PLUGIN_RET_NOTMASTER
)
6217 static char msg
[] = "must be run on master: 000.000.000.000";
6219 response
.type
= NSCTL_RES_ERR
;
6221 if (config
->cluster_master_address
)
6223 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
6224 response
.argv
[0] = msg
;
6228 response
.argv
[0] = "must be run on master: none elected";
6231 else if (!(param
.response
& NSCTL_RESPONSE
))
6233 response
.type
= NSCTL_RES_ERR
;
6235 response
.argv
[0] = param
.response
6236 ? "unrecognised response value from plugin"
6237 : "unhandled action";
6241 response
.type
= param
.response
;
6243 if (param
.additional
)
6246 response
.argv
[0] = param
.additional
;
6254 response
.type
= NSCTL_RES_ERR
;
6256 response
.argv
[0] = "error unpacking control packet";
6259 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
6262 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
6266 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
6269 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
6270 if (log_stream
&& config
->debug
>= 4)
6272 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
6273 dump_control(&response
, log_stream
);
6277 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6278 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6283 static tunnelidt
new_tunnel()
6286 for (i
= 1; i
< MAXTUNNEL
; i
++)
6288 if ((tunnel
[i
].state
== TUNNELFREE
) && (i
!= TUNNEL_ID_PPPOE
))
6290 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6291 if (i
> config
->cluster_highest_tunnelid
)
6292 config
->cluster_highest_tunnelid
= i
;
6296 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6301 // We're becoming the master. Do any required setup..
6303 // This is principally telling all the plugins that we're
6304 // now a master, and telling them about all the sessions
6305 // that are active too..
6307 void become_master(void)
6310 static struct event_data d
[RADIUS_FDS
];
6311 struct epoll_event e
;
6313 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6315 // running a bunch of iptables commands is slow and can cause
6316 // the master to drop tunnels on takeover--kludge around the
6317 // problem by forking for the moment (note: race)
6318 if (!fork_and_close())
6320 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6322 if (!session
[s
].opened
) // Not an in-use session.
6325 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6332 for (i
= 0; i
< RADIUS_FDS
; i
++)
6334 d
[i
].type
= FD_TYPE_RADIUS
;
6338 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6342 int cmd_show_hist_idle(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6348 if (CLI_HELP_REQUESTED
)
6349 return CLI_HELP_NO_ARGS
;
6352 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6354 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6357 if (!session
[s
].opened
)
6360 idle
= time_now
- session
[s
].last_data
;
6361 idle
/= 5 ; // In multiples of 5 seconds.
6371 for (i
= 0; i
< 63; ++i
)
6373 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6375 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6376 cli_print(cli
, "%d total sessions open.", count
);
6380 int cmd_show_hist_open(struct cli_def
*cli
, const char *command
, char **argv
, int argc
)
6386 if (CLI_HELP_REQUESTED
)
6387 return CLI_HELP_NO_ARGS
;
6390 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6392 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6395 if (!session
[s
].opened
)
6398 d
= time_now
- session
[s
].opened
;
6401 while (d
> 1 && open
< 32)
6411 for (i
= 0; i
< 30; ++i
)
6413 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6416 cli_print(cli
, "%d total sessions open.", count
);
6422 * This unencodes the AVP using the L2TP secret and the previously
6423 * stored random vector. It overwrites the hidden data with the
6424 * unhidden AVP subformat.
6426 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6432 uint16_t m
= htons(type
);
6434 // Compute initial pad
6436 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6437 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6438 MD5_Update(&ctx
, vector
, vec_len
);
6439 MD5_Final(digest
, &ctx
);
6441 // pointer to last decoded 16 octets
6446 // calculate a new pad based on the last decoded block
6447 if (d
>= sizeof(digest
))
6450 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6451 MD5_Update(&ctx
, last
, sizeof(digest
));
6452 MD5_Final(digest
, &ctx
);
6458 *value
++ ^= digest
[d
++];
6463 int find_filter(char const *name
, size_t len
)
6468 for (i
= 0; i
< MAXFILTER
; i
++)
6470 if (!*ip_filters
[i
].name
)
6478 if (strlen(ip_filters
[i
].name
) != len
)
6481 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6488 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6492 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6493 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6494 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6495 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6496 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6502 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6506 case FILTER_FLAG_OP_ANY
:
6507 return (flags
& sflags
) || (~flags
& cflags
);
6509 case FILTER_FLAG_OP_ALL
:
6510 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6512 case FILTER_FLAG_OP_EST
:
6513 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6519 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6521 uint16_t frag_offset
;
6525 uint16_t src_port
= 0;
6526 uint16_t dst_port
= 0;
6528 ip_filter_rulet
*rule
;
6530 if (len
< 20) // up to end of destination address
6533 if ((*buf
>> 4) != 4) // IPv4
6536 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6538 src_ip
= *(in_addr_t
*) (buf
+ 12);
6539 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6541 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6543 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6544 if (len
< l
+ 4) // ports
6547 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6548 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6549 if (proto
== IPPROTO_TCP
)
6551 if (len
< l
+ 14) // flags
6554 flags
= buf
[l
+ 13] & 0x3f;
6558 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6560 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6563 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6564 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6567 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6568 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6573 // layer 4 deny rules are skipped
6574 if (rule
->action
== FILTER_ACTION_DENY
&&
6575 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6583 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6585 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6588 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6591 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6592 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6599 return rule
->action
== FILTER_ACTION_PERMIT
;
6606 tunnelidt
lac_new_tunnel()
6608 return new_tunnel();
6611 void lac_tunnelclear(tunnelidt t
)
6616 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6618 uint16_t version
= 0x0100; // protocol version
6620 tunnel
[t
].state
= TUNNELOPENING
;
6622 // Sent SCCRQ - Start Control Connection Request
6623 controlt
*c
= controlnew(1); // sending SCCRQ
6624 controls(c
, 7, config
->multi_n_hostname
[tunnel
[t
].indexudp
][0]?config
->multi_n_hostname
[tunnel
[t
].indexudp
]:hostname
, 1); // host name
6625 controls(c
, 8, Vendor_name
, 1); // Vendor name
6626 control16(c
, 2, version
, 1); // protocol version
6627 control32(c
, 3, 3, 1); // framing Capabilities
6628 control16(c
, 9, t
, 1); // assigned tunnel
6629 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6630 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6631 controladd(c
, 0, t
); // send
6634 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6636 // Sent ICRQ Incoming-call-request
6637 controlt
*c
= controlnew(10); // ICRQ
6639 control16(c
, 14, s
, 1); // assigned sesion
6640 call_serial_number
++;
6641 control32(c
, 15, call_serial_number
, 1); // call serial number
6642 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6643 controladd(c
, 0, t
); // send
6646 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6648 tunnelshutdown(t
, reason
, result
, error
, msg
);