3 // Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering
4 // Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced
11 #include <linux/if_tun.h>
15 #include <net/route.h>
18 #include <netinet/in.h>
19 #include <netinet/ip6.h>
25 #include <sys/ioctl.h>
26 #include <sys/socket.h>
29 #include <sys/resource.h>
37 #include <sys/sysinfo.h>
39 #include <linux/netlink.h>
40 #include <linux/rtnetlink.h>
47 #include "constants.h"
61 char * Vendor_name
= "Linux L2TPNS";
62 uint32_t call_serial_number
= 0;
66 configt
*config
= NULL
; // all configuration
67 int nlfd
= -1; // netlink socket
68 int tunfd
= -1; // tun interface file handle. (network device)
69 int udpfd
= -1; // UDP file handle
71 int udplacfd
= -1; // UDP LAC file handle
73 int controlfd
= -1; // Control signal handle
74 int clifd
= -1; // Socket listening for CLI connections.
75 int daefd
= -1; // Socket listening for DAE connections.
76 int snoopfd
= -1; // UDP file handle for sending out intercept data
77 int *radfds
= NULL
; // RADIUS requests file handles
78 int rand_fd
= -1; // Random data source
79 int cluster_sockfd
= -1; // Intra-cluster communications socket.
80 int epollfd
= -1; // event polling
81 time_t basetime
= 0; // base clock
82 char hostname
[MAXHOSTNAME
] = ""; // us.
83 static int tunidx
; // ifr_ifindex of tun device
84 int nlseqnum
= 0; // netlink sequence number
85 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
86 static int syslog_log
= 0; // are we logging to syslog
87 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
88 uint32_t last_id
= 0; // Unique ID for radius accounting
90 char guest_users
[10][32]; // Array of guest users
91 int guest_accounts_num
= 0; // Number of guest users
93 // calculated from config->l2tp_mtu
94 uint16_t MRU
= 0; // PPP MRU
95 uint16_t MSS
= 0; // TCP MSS
97 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
98 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
103 } ip_hash
[256]; // Mapping from IP address to session structures.
107 struct ipv6radix
*branch
;
108 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
111 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
112 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
115 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
116 time_t time_now
= 0; // Current time in seconds since epoch.
117 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
118 static char time_now_string
[64] = {0}; // Current time as a string.
119 static int time_changed
= 0; // time_now changed
120 char main_quit
= 0; // True if we're in the process of exiting.
121 static char main_reload
= 0; // Re-load pending
122 linked_list
*loaded_plugins
;
123 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
125 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
126 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
128 config_descriptt config_values
[] = {
129 CONFIG("debug", debug
, INT
),
130 CONFIG("log_file", log_filename
, STRING
),
131 CONFIG("pid_file", pid_file
, STRING
),
132 CONFIG("random_device", random_device
, STRING
),
133 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
134 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
135 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
136 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
137 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
138 CONFIG("primary_dns", default_dns1
, IPv4
),
139 CONFIG("secondary_dns", default_dns2
, IPv4
),
140 CONFIG("primary_radius", radiusserver
[0], IPv4
),
141 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
142 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
143 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
144 CONFIG("radius_accounting", radius_accounting
, BOOL
),
145 CONFIG("radius_interim", radius_interim
, INT
),
146 CONFIG("radius_secret", radiussecret
, STRING
),
147 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
148 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
149 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
150 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
151 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
152 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
153 CONFIG("guest_account", guest_user
, STRING
),
154 CONFIG("bind_address", bind_address
, IPv4
),
155 CONFIG("peer_address", peer_address
, IPv4
),
156 CONFIG("send_garp", send_garp
, BOOL
),
157 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
158 CONFIG("throttle_buckets", num_tbfs
, INT
),
159 CONFIG("accounting_dir", accounting_dir
, STRING
),
160 CONFIG("dump_speed", dump_speed
, BOOL
),
161 CONFIG("multi_read_count", multi_read_count
, INT
),
162 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
163 CONFIG("lock_pages", lock_pages
, BOOL
),
164 CONFIG("icmp_rate", icmp_rate
, INT
),
165 CONFIG("packet_limit", max_packets
, INT
),
166 CONFIG("cluster_address", cluster_address
, IPv4
),
167 CONFIG("cluster_interface", cluster_interface
, STRING
),
168 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
169 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
170 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
171 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
172 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
173 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
174 CONFIG("hostname", hostname
, STRING
),
176 CONFIG("nexthop_address", nexthop_address
, IPv4
),
177 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
179 CONFIG("echo_timeout", echo_timeout
, INT
),
180 CONFIG("idle_echo_timeout", idle_echo_timeout
, INT
),
182 CONFIG("disable_lac_func", disable_lac_func
, BOOL
),
183 CONFIG("bind_portremotelns", bind_portremotelns
, SHORT
),
188 static char *plugin_functions
[] = {
193 "plugin_new_session",
194 "plugin_kill_session",
196 "plugin_radius_response",
197 "plugin_radius_reset",
198 "plugin_radius_account",
199 "plugin_become_master",
200 "plugin_new_session_master",
203 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
205 // Counters for shutdown sessions
206 static sessiont shut_acct
[8192];
207 static sessionidt shut_acct_n
= 0;
209 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
210 bundlet
*bundle
= NULL
; // Array of bundle structures.
211 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
212 sessiont
*session
= NULL
; // Array of session structures.
213 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
214 radiust
*radius
= NULL
; // Array of radius structures.
215 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
216 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
217 static controlt
*controlfree
= 0;
218 struct Tstats
*_statistics
= NULL
;
220 struct Tringbuffer
*ringbuffer
= NULL
;
223 static ssize_t
netlink_send(struct nlmsghdr
*nh
);
224 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
);
225 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
226 static void uncache_ipmap(in_addr_t ip
);
227 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
228 static void free_ip_address(sessionidt s
);
229 static void dump_acct_info(int all
);
230 static void sighup_handler(int sig
);
231 static void shutdown_handler(int sig
);
232 static void sigchild_handler(int sig
);
233 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
234 static void update_config(void);
235 static void read_config_file(void);
236 static void initplugins(void);
237 static int add_plugin(char *plugin_name
);
238 static int remove_plugin(char *plugin_name
);
239 static void plugins_done(void);
240 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
241 static tunnelidt
new_tunnel(void);
242 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
243 static void bundleclear(bundleidt b
);
245 // return internal time (10ths since process startup), set f if given
246 // as a side-effect sets time_now, and time_changed
247 static clockt
now(double *f
)
251 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
252 if (t
.tv_sec
!= time_now
)
258 // Time in milliseconds
259 time_now_ms
= (t
.tv_sec
* 1000) + (t
.tv_usec
/1000);
261 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
264 // work out a retry time based on try number
265 // This is a straight bounded exponential backoff.
266 // Maximum re-try time is 32 seconds. (2^5).
267 clockt
backoff(uint8_t try)
269 if (try > 5) try = 5; // max backoff
270 return now(NULL
) + 10 * (1 << try);
275 // Log a debug message. Typically called via the LOG macro
277 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
279 static char message
[65536] = {0};
285 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
286 ringbuffer
->tail
= 0;
287 if (ringbuffer
->tail
== ringbuffer
->head
)
288 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
289 ringbuffer
->head
= 0;
291 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
292 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
293 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
294 va_start(ap
, format
);
295 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
300 if (config
->debug
< level
) return;
302 va_start(ap
, format
);
303 vsnprintf(message
, sizeof(message
), format
, ap
);
306 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
308 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
313 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
316 const uint8_t *d
= data
;
318 if (config
->debug
< level
) return;
320 // No support for _log_hex to syslog
323 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
324 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
326 for (i
= 0; i
< maxsize
; )
328 fprintf(log_stream
, "%4X: ", i
);
329 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
331 fprintf(log_stream
, "%02X ", d
[j
]);
333 fputs(": ", log_stream
);
336 for (; j
< i
+ 16; j
++)
338 fputs(" ", log_stream
);
340 fputs(": ", log_stream
);
343 fputs(" ", log_stream
);
344 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
346 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
347 fputc(d
[j
], log_stream
);
349 fputc('.', log_stream
);
352 fputs(" ", log_stream
);
356 fputs("\n", log_stream
);
360 setbuf(log_stream
, NULL
);
364 // update a counter, accumulating 2^32 wraps
365 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
367 uint32_t new = *counter
+ delta
;
374 // initialise the random generator
375 static void initrandom(char *source
)
377 static char path
[sizeof(config
->random_device
)] = "*undefined*";
379 // reinitialise only if we are forced to do so or if the config has changed
380 if (source
&& !strncmp(path
, source
, sizeof(path
)))
383 // close previous source, if any
392 snprintf(path
, sizeof(path
), "%s", source
);
396 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
398 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
399 path
, strerror(errno
));
404 // fill buffer with random data
405 void random_data(uint8_t *buf
, int len
)
412 n
= read(rand_fd
, buf
, len
);
413 if (n
>= len
) return;
418 LOG(0, 0, 0, "Error reading from random source: %s\n",
421 // fall back to rand()
429 // append missing data
431 // not using the low order bits from the prng stream
432 buf
[n
++] = (rand() >> 4) & 0xff;
437 // This adds it to the routing table, advertises it
438 // via BGP if enabled, and stuffs it into the
439 // 'sessionbyip' cache.
441 // 'ip' must be in _host_ order.
443 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
453 if (!prefixlen
) prefixlen
= 32;
455 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
457 memset(&req
, 0, sizeof(req
));
461 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
462 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
466 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
467 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
470 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
472 req
.rt
.rtm_family
= AF_INET
;
473 req
.rt
.rtm_dst_len
= prefixlen
;
474 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
475 req
.rt
.rtm_protocol
= 42;
476 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
477 req
.rt
.rtm_type
= RTN_UNICAST
;
479 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
481 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
485 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
488 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
489 fmtaddr(htonl(ip
), 0), prefixlen
,
490 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
492 if (netlink_send(&req
.nh
) < 0)
493 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
497 bgp_add_route(htonl(ip
), prefixlen
);
499 bgp_del_route(htonl(ip
), prefixlen
);
502 // Add/Remove the IPs to the 'sessionbyip' cache.
503 // Note that we add the zero address in the case of
504 // a network route. Roll on CIDR.
506 // Note that 's == 0' implies this is the address pool.
507 // We still cache it here, because it will pre-fill
508 // the malloc'ed tree.
512 if (!add
) // Are we deleting a route?
513 s
= 0; // Caching the session as '0' is the same as uncaching.
515 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
520 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
528 char ipv6addr
[INET6_ADDRSTRLEN
];
530 if (!config
->ipv6_prefix
.s6_addr
[0])
532 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
536 memset(&req
, 0, sizeof(req
));
540 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
541 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
545 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
546 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
549 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
551 req
.rt
.rtm_family
= AF_INET6
;
552 req
.rt
.rtm_dst_len
= prefixlen
;
553 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
554 req
.rt
.rtm_protocol
= 42;
555 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
556 req
.rt
.rtm_type
= RTN_UNICAST
;
558 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
559 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
561 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
563 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
565 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
568 if (netlink_send(&req
.nh
) < 0)
569 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
573 bgp_add_route6(ip
, prefixlen
);
575 bgp_del_route6(ip
, prefixlen
);
580 if (!add
) // Are we deleting a route?
581 s
= 0; // Caching the session as '0' is the same as uncaching.
583 cache_ipv6map(ip
, prefixlen
, s
);
590 // Set up netlink socket
591 static void initnetlink(void)
593 struct sockaddr_nl nladdr
;
595 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
598 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
602 memset(&nladdr
, 0, sizeof(nladdr
));
603 nladdr
.nl_family
= AF_NETLINK
;
604 nladdr
.nl_pid
= getpid();
606 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
608 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
613 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
615 struct sockaddr_nl nladdr
;
619 nh
->nlmsg_pid
= getpid();
620 nh
->nlmsg_seq
= ++nlseqnum
;
622 // set kernel address
623 memset(&nladdr
, 0, sizeof(nladdr
));
624 nladdr
.nl_family
= AF_NETLINK
;
626 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
627 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
629 return sendmsg(nlfd
, &msg
, 0);
632 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
634 struct sockaddr_nl nladdr
;
638 // set kernel address
639 memset(&nladdr
, 0, sizeof(nladdr
));
640 nladdr
.nl_family
= AF_NETLINK
;
642 iov
= (struct iovec
){ buf
, len
};
643 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
645 return recvmsg(nlfd
, &msg
, 0);
648 /* adapted from iproute2 */
649 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
651 int len
= RTA_LENGTH(alen
);
654 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
655 rta
->rta_type
= type
;
657 memcpy(RTA_DATA(rta
), data
, alen
);
658 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
661 // messages corresponding to different phases seq number
662 static char *tun_nl_phase_msg
[] = {
664 "getting tun interface index",
665 "setting tun interface parameters",
666 "setting tun IPv4 address",
667 "setting tun LL IPv6 address",
668 "setting tun global IPv6 address",
672 // Set up TUN interface
673 static void inittun(void)
677 memset(&ifr
, 0, sizeof(ifr
));
678 ifr
.ifr_flags
= IFF_TUN
;
680 tunfd
= open(TUNDEVICE
, O_RDWR
);
683 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
687 int flags
= fcntl(tunfd
, F_GETFL
, 0);
688 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
690 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
692 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
695 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
) - 1);
696 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
));
698 tunidx
= if_nametoindex(config
->tundevice
);
701 LOG(0, 0, 0, "Can't get tun interface index\n");
710 struct ifinfomsg ifinfo
;
711 struct ifaddrmsg ifaddr
;
713 char rtdata
[32]; // 32 should be enough
715 uint32_t txqlen
, mtu
;
718 memset(&req
, 0, sizeof(req
));
720 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
721 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
722 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
724 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
725 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
726 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
727 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
729 /* Bump up the qlen to deal with bursts from the network */
731 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
732 /* set MTU to modem MRU */
734 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
736 if (netlink_send(&req
.nh
) < 0)
739 memset(&req
, 0, sizeof(req
));
741 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
742 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
743 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
745 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
746 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
747 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
748 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
750 if (config
->bind_address
)
751 ip
= config
->bind_address
;
753 ip
= 0x01010101; // 1.1.1.1
754 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
756 if (netlink_send(&req
.nh
) < 0)
759 // Only setup IPv6 on the tun device if we have a configured prefix
760 if (config
->ipv6_prefix
.s6_addr
[0]) {
763 memset(&req
, 0, sizeof(req
));
765 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
766 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
767 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
769 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
770 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
771 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
772 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
774 // Link local address is FE80::1
775 memset(&ip6
, 0, sizeof(ip6
));
776 ip6
.s6_addr
[0] = 0xFE;
777 ip6
.s6_addr
[1] = 0x80;
779 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
781 if (netlink_send(&req
.nh
) < 0)
784 memset(&req
, 0, sizeof(req
));
786 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
787 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
788 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
790 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
791 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
792 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
793 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
795 // Global address is prefix::1
796 ip6
= config
->ipv6_prefix
;
798 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
800 if (netlink_send(&req
.nh
) < 0)
804 memset(&req
, 0, sizeof(req
));
806 req
.nh
.nlmsg_type
= NLMSG_DONE
;
807 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
809 if (netlink_send(&req
.nh
) < 0)
812 // if we get an error for seqnum < min_initok_nlseqnum,
813 // we must exit as initialization went wrong
814 if (config
->ipv6_prefix
.s6_addr
[0])
815 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
817 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
823 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
828 static void initudp(void)
831 struct sockaddr_in addr
;
834 memset(&addr
, 0, sizeof(addr
));
835 addr
.sin_family
= AF_INET
;
836 addr
.sin_port
= htons(L2TPPORT
);
837 addr
.sin_addr
.s_addr
= config
->bind_address
;
838 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
839 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
841 int flags
= fcntl(udpfd
, F_GETFL
, 0);
842 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
844 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
846 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
851 memset(&addr
, 0, sizeof(addr
));
852 addr
.sin_family
= AF_INET
;
853 addr
.sin_port
= htons(NSCTL_PORT
);
854 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
855 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
856 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
857 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
859 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
863 // Dynamic Authorization Extensions to RADIUS
864 memset(&addr
, 0, sizeof(addr
));
865 addr
.sin_family
= AF_INET
;
866 addr
.sin_port
= htons(config
->radius_dae_port
);
867 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
868 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
869 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
870 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
872 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
877 // Tunnel to Remote LNS
878 memset(&addr
, 0, sizeof(addr
));
879 addr
.sin_family
= AF_INET
;
880 addr
.sin_port
= htons(config
->bind_portremotelns
);
881 udplacfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
882 setsockopt(udplacfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
884 int flags
= fcntl(udplacfd
, F_GETFL
, 0);
885 fcntl(udplacfd
, F_SETFL
, flags
| O_NONBLOCK
);
887 if (bind(udplacfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
889 LOG(0, 0, 0, "Error in UDP REMOTE LNS bind: %s\n", strerror(errno
));
895 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
899 // Find session by IP, < 1 for not found
901 // Confusingly enough, this 'ip' must be
902 // in _network_ order. This being the common
903 // case when looking it up from IP packet headers.
905 // We actually use this cache for two things.
906 // #1. For used IP addresses, this maps to the
907 // session ID that it's used by.
908 // #2. For un-used IP addresses, this maps to the
909 // index into the pool table that contains that
913 static sessionidt
lookup_ipmap(in_addr_t ip
)
915 uint8_t *a
= (uint8_t *) &ip
;
916 union iphash
*h
= ip_hash
;
918 if (!(h
= h
[*a
++].idx
)) return 0;
919 if (!(h
= h
[*a
++].idx
)) return 0;
920 if (!(h
= h
[*a
++].idx
)) return 0;
925 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
927 struct ipv6radix
*curnode
;
930 char ipv6addr
[INET6_ADDRSTRLEN
];
932 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
936 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
938 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
943 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
944 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
951 sessionidt
sessionbyip(in_addr_t ip
)
953 sessionidt s
= lookup_ipmap(ip
);
956 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
962 sessionidt
sessionbyipv6(struct in6_addr ip
)
965 CSTAT(sessionbyipv6
);
967 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
968 (ip
.s6_addr
[0] == 0xFE &&
969 ip
.s6_addr
[1] == 0x80 &&
970 ip
.s6_addr16
[1] == 0 &&
971 ip
.s6_addr16
[2] == 0 &&
972 ip
.s6_addr16
[3] == 0)) {
973 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
975 s
= lookup_ipv6map(ip
);
978 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
985 // Take an IP address in HOST byte order and
986 // add it to the sessionid by IP cache.
988 // (It's actually cached in network order)
990 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
992 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
993 uint8_t *a
= (uint8_t *) &nip
;
994 union iphash
*h
= ip_hash
;
997 for (i
= 0; i
< 3; i
++)
999 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
1008 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
1011 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
1012 // else a map to an ip pool index.
1015 static void uncache_ipmap(in_addr_t ip
)
1017 cache_ipmap(ip
, 0); // Assign it to the NULL session.
1020 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
1024 struct ipv6radix
*curnode
;
1025 char ipv6addr
[INET6_ADDRSTRLEN
];
1027 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
1029 bytes
= prefixlen
>> 3;
1032 if (curnode
->branch
== NULL
)
1034 if (!(curnode
->branch
= calloc(256,
1035 sizeof (struct ipv6radix
))))
1038 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1045 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1046 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1050 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1051 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1057 // CLI list to dump current ipcache.
1059 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1061 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1065 if (CLI_HELP_REQUESTED
)
1066 return CLI_HELP_NO_ARGS
;
1068 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1070 for (i
= 0; i
< 256; ++i
)
1076 for (j
= 0; j
< 256; ++j
)
1082 for (k
= 0; k
< 256; ++k
)
1088 for (l
= 0; l
< 256; ++l
)
1093 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1099 cli_print(cli
, "%d entries in cache", count
);
1104 // Find session by username, 0 for not found
1105 // walled garden users aren't authenticated, so the username is
1106 // reasonably useless. Ignore them to avoid incorrect actions
1108 // This is VERY inefficent. Don't call it often. :)
1110 sessionidt
sessionbyuser(char *username
)
1113 CSTAT(sessionbyuser
);
1115 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1117 if (!session
[s
].opened
)
1120 if (session
[s
].walled_garden
)
1121 continue; // Skip walled garden users.
1123 if (!strncmp(session
[s
].user
, username
, 128))
1127 return 0; // Not found.
1130 void send_garp(in_addr_t ip
)
1136 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1139 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1142 memset(&ifr
, 0, sizeof(ifr
));
1143 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1144 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1146 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1150 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1151 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1153 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1158 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1161 static sessiont
*sessiontbysessionidt(sessionidt s
)
1163 if (!s
|| s
>= MAXSESSION
) return NULL
;
1167 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1169 sessionidt val
= s
-session
;
1170 if (s
< session
|| val
>= MAXSESSION
) return 0;
1174 // actually send a control message for a specific tunnel
1175 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1177 struct sockaddr_in addr
;
1183 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1184 STAT(tunnel_tx_errors
);
1190 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1191 STAT(tunnel_tx_errors
);
1195 memset(&addr
, 0, sizeof(addr
));
1196 addr
.sin_family
= AF_INET
;
1197 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1198 addr
.sin_port
= htons(tunnel
[t
].port
);
1200 // sequence expected, if sequence in message
1201 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1203 // If this is a control message, deal with retries
1206 tunnel
[t
].last
= time_now
; // control message sent
1207 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1210 STAT(tunnel_retries
);
1211 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1215 if (sendto((tunnel
[t
].isremotelns
?udplacfd
:udpfd
), buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1217 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1220 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1221 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1222 STAT(tunnel_tx_errors
);
1226 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1227 STAT(tunnel_tx_packets
);
1228 INC_STAT(tunnel_tx_bytes
, l
);
1232 // Tiny helper function to write data to
1233 // the 'tun' device.
1235 int tun_write(uint8_t * data
, int size
)
1237 return write(tunfd
, data
, size
);
1240 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1241 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1243 int d
= (tcp
[12] >> 4) * 4;
1250 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1253 if (tcp
+ d
> buf
+ len
) // short?
1261 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1264 if (mss
+ 2 > data
) return; // short?
1268 if (*opts
== 0) return; // end of options
1269 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1272 opts
+= opts
[1]; // skip over option
1275 if (!mss
) return; // not found
1276 orig
= ntohs(*(uint16_t *) mss
);
1278 if (orig
<= MSS
) return; // mss OK
1280 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1281 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1282 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1283 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1286 *(int16_t *) mss
= htons(MSS
);
1288 // adjust checksum (see rfc1141)
1289 sum
= orig
+ (~MSS
& 0xffff);
1290 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1291 sum
= (sum
& 0xffff) + (sum
>> 16);
1292 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1295 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1299 // Skip the four extra bytes
1311 proto
= ntohs(*(uint16_t *) p
);
1319 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1320 return; // closing session, PPP not processed
1322 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1323 processipin(s
, t
, p
, l
);
1325 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1329 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1330 return; // closing session, PPP not processed
1333 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1334 processipv6in(s
, t
, p
, l
);
1336 else if (proto
== PPPIPCP
)
1338 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1339 processipcp(s
, t
, p
, l
);
1341 else if (proto
== PPPCCP
)
1343 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1344 processccp(s
, t
, p
, l
);
1348 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1352 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1354 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1355 sp
->cout_delta
+= len
;
1357 sp
->last_data
= time_now
;
1359 sess_local
[s
].cout
+= len
; // To send to master..
1360 sess_local
[s
].pout
++;
1363 // process outgoing (to tunnel) IP
1365 // (i.e. this routine writes to data[-8]).
1366 void processipout(uint8_t *buf
, int len
)
1373 uint8_t *data
= buf
; // Keep a copy of the originals.
1376 uint8_t fragbuf
[MAXETHER
+ 20];
1378 CSTAT(processipout
);
1380 if (len
< MIN_IP_SIZE
)
1382 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1383 STAT(tun_rx_errors
);
1386 if (len
>= MAXETHER
)
1388 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1389 STAT(tun_rx_errors
);
1393 // Skip the tun header
1397 // Got an IP header now
1398 if (*(uint8_t *)(buf
) >> 4 != 4)
1400 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1404 ip
= *(uint32_t *)(buf
+ 16);
1405 if (!(s
= sessionbyip(ip
)))
1407 // Is this a packet for a session that doesn't exist?
1408 static int rate
= 0; // Number of ICMP packets we've sent this second.
1409 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1411 if (last
!= time_now
)
1417 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1419 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1420 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1421 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1426 t
= session
[s
].tunnel
;
1427 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1429 LOG(3, s
, t
, "Packet size more than session MRU\n");
1435 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1436 if (config
->max_packets
> 0)
1438 if (sess_local
[s
].last_packet_out
== TIME
)
1440 int max
= config
->max_packets
;
1442 // All packets for throttled sessions are handled by the
1443 // master, so further limit by using the throttle rate.
1444 // A bit of a kludge, since throttle rate is in kbps,
1445 // but should still be generous given our average DSL
1446 // packet size is 200 bytes: a limit of 28kbps equates
1447 // to around 180 packets per second.
1448 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1449 max
= sp
->throttle_out
;
1451 if (++sess_local
[s
].packets_out
> max
)
1453 sess_local
[s
].packets_dropped
++;
1459 if (sess_local
[s
].packets_dropped
)
1461 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1462 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1463 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1464 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1468 sess_local
[s
].last_packet_out
= TIME
;
1469 sess_local
[s
].packets_out
= 1;
1470 sess_local
[s
].packets_dropped
= 0;
1474 // run access-list if any
1475 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1478 // adjust MSS on SYN and SYN,ACK packets with options
1479 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1481 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1482 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1483 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1488 // Are we throttling this session?
1489 if (config
->cluster_iam_master
)
1490 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1492 master_throttle_packet(sp
->tbf_out
, data
, size
);
1496 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1498 // We are walled-gardening this
1499 master_garden_packet(s
, data
, size
);
1503 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1506 if (!config
->cluster_iam_master
)
1508 // The MPPP packets must be managed by the Master.
1509 master_forward_mppp_packet(s
, data
, size
);
1513 // Add on L2TP header
1514 sessionidt members
[MAXBUNDLESES
];
1515 bundleidt bid
= session
[s
].bundle
;
1516 bundlet
*b
= &bundle
[bid
];
1517 uint32_t num_of_links
, nb_opened
;
1520 num_of_links
= b
->num_of_links
;
1522 for (i
= 0;i
< num_of_links
;i
++)
1525 if (session
[s
].ppp
.lcp
== Opened
)
1527 members
[nb_opened
] = s
;
1534 LOG(3, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1538 num_of_links
= nb_opened
;
1539 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1540 s
= members
[b
->current_ses
];
1541 t
= session
[s
].tunnel
;
1543 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1545 if (num_of_links
> 1)
1547 if(len
> MINFRAGLEN
)
1549 //for rotate traffic among the member links
1550 uint32_t divisor
= num_of_links
;
1552 divisor
= divisor
/2 + (divisor
& 1);
1554 // Partition the packet to "num_of_links" fragments
1555 uint32_t fraglen
= len
/ divisor
;
1556 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1557 uint32_t remain
= len
;
1559 // send the first packet
1560 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1562 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1565 update_session_out_stat(s
, sp
, fraglen
);
1568 while (remain
> last_fraglen
)
1570 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1571 s
= members
[b
->current_ses
];
1572 t
= session
[s
].tunnel
;
1574 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1575 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1577 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1578 update_session_out_stat(s
, sp
, fraglen
);
1581 // send the last fragment
1582 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1583 s
= members
[b
->current_ses
];
1584 t
= session
[s
].tunnel
;
1586 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1587 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1589 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1590 update_session_out_stat(s
, sp
, remain
);
1591 if (remain
!= last_fraglen
)
1592 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1596 // Send it as one frame
1597 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1599 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1600 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1601 update_session_out_stat(s
, sp
, len
);
1606 // Send it as one frame (NO MPPP Frame)
1607 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1609 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1610 update_session_out_stat(s
, sp
, len
);
1615 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1617 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1618 update_session_out_stat(s
, sp
, len
);
1621 // Snooping this session, send it to intercept box
1622 if (sp
->snoop_ip
&& sp
->snoop_port
)
1623 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1628 // process outgoing (to tunnel) IPv6
1630 static void processipv6out(uint8_t * buf
, int len
)
1636 struct in6_addr ip6
;
1638 uint8_t *data
= buf
; // Keep a copy of the originals.
1641 uint8_t b
[MAXETHER
+ 20];
1643 CSTAT(processipv6out
);
1645 if (len
< MIN_IP_SIZE
)
1647 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1648 STAT(tunnel_tx_errors
);
1651 if (len
>= MAXETHER
)
1653 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1654 STAT(tunnel_tx_errors
);
1658 // Skip the tun header
1662 // Got an IP header now
1663 if (*(uint8_t *)(buf
) >> 4 != 6)
1665 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1669 ip6
= *(struct in6_addr
*)(buf
+24);
1670 s
= sessionbyipv6(ip6
);
1674 ip
= *(uint32_t *)(buf
+ 32);
1675 s
= sessionbyip(ip
);
1680 // Is this a packet for a session that doesn't exist?
1681 static int rate
= 0; // Number of ICMP packets we've sent this second.
1682 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1684 if (last
!= time_now
)
1690 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1692 // FIXME: Should send icmp6 host unreachable
1696 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1698 bundleidt bid
= session
[s
].bundle
;
1699 bundlet
*b
= &bundle
[bid
];
1701 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1702 s
= b
->members
[b
->current_ses
];
1703 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1705 t
= session
[s
].tunnel
;
1707 sp
->last_data
= time_now
;
1709 // FIXME: add DoS prevention/filters?
1713 // Are we throttling this session?
1714 if (config
->cluster_iam_master
)
1715 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1717 master_throttle_packet(sp
->tbf_out
, data
, size
);
1720 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1722 // We are walled-gardening this
1723 master_garden_packet(s
, data
, size
);
1727 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1729 // Add on L2TP header
1731 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1733 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1736 // Snooping this session, send it to intercept box
1737 if (sp
->snoop_ip
&& sp
->snoop_port
)
1738 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1740 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1741 sp
->cout_delta
+= len
;
1745 sess_local
[s
].cout
+= len
; // To send to master..
1746 sess_local
[s
].pout
++;
1750 // Helper routine for the TBF filters.
1751 // Used to send queued data in to the user!
1753 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1758 uint8_t b
[MAXETHER
+ 20];
1760 if (len
< 0 || len
> MAXETHER
)
1762 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1766 // Skip the tun header
1773 t
= session
[s
].tunnel
;
1776 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1778 // Add on L2TP header
1780 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1782 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1785 // Snooping this session.
1786 if (sp
->snoop_ip
&& sp
->snoop_port
)
1787 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1789 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1790 sp
->cout_delta
+= len
;
1794 sess_local
[s
].cout
+= len
; // To send to master..
1795 sess_local
[s
].pout
++;
1798 // add an AVP (16 bit)
1799 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1801 uint16_t l
= (m
? 0x8008 : 0x0008);
1802 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1803 c
->buf16
[c
->length
/2 + 1] = htons(0);
1804 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1805 c
->buf16
[c
->length
/2 + 3] = htons(val
);
1809 // add an AVP (32 bit)
1810 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1812 uint16_t l
= (m
? 0x800A : 0x000A);
1813 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1814 c
->buf16
[c
->length
/2 + 1] = htons(0);
1815 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1816 *(uint32_t *) &c
->buf
[c
->length
+ 6] = htonl(val
);
1820 // add an AVP (string)
1821 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1823 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1824 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1825 c
->buf16
[c
->length
/2 + 1] = htons(0);
1826 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1827 memcpy(&c
->buf
[c
->length
+ 6], val
, strlen(val
));
1828 c
->length
+= 6 + strlen(val
);
1832 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1834 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1835 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1836 c
->buf16
[c
->length
/2 + 1] = htons(0);
1837 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1838 memcpy(&c
->buf
[c
->length
+ 6], val
, len
);
1839 c
->length
+= 6 + len
;
1842 // new control connection
1843 static controlt
*controlnew(uint16_t mtype
)
1847 c
= malloc(sizeof(controlt
));
1851 controlfree
= c
->next
;
1855 c
->buf16
[0] = htons(0xC802); // flags/ver
1857 control16(c
, 0, mtype
, 1);
1861 // send zero block if nothing is waiting
1863 static void controlnull(tunnelidt t
)
1866 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1869 buf
[0] = htons(0xC802); // flags/ver
1870 buf
[1] = htons(12); // length
1871 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1872 buf
[3] = htons(0); // session
1873 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1874 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1875 tunnelsend((uint8_t *)buf
, 12, t
);
1878 // add a control message to a tunnel, and send if within window
1879 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1881 c
->buf16
[1] = htons(c
->length
); // length
1882 c
->buf16
[2] = htons(tunnel
[t
].far
); // tunnel
1883 c
->buf16
[3] = htons(far
); // session
1884 c
->buf16
[4] = htons(tunnel
[t
].ns
); // sequence
1885 tunnel
[t
].ns
++; // advance sequence
1886 // link in message in to queue
1887 if (tunnel
[t
].controlc
)
1888 tunnel
[t
].controle
->next
= c
;
1890 tunnel
[t
].controls
= c
;
1892 tunnel
[t
].controle
= c
;
1893 tunnel
[t
].controlc
++;
1895 // send now if space in window
1896 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1898 tunnel
[t
].try = 0; // first send
1899 tunnelsend(c
->buf
, c
->length
, t
);
1904 // Throttle or Unthrottle a session
1906 // Throttle the data from/to through a session to no more than
1907 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1910 // If either value is -1, the current value is retained for that
1913 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1915 if (!session
[s
].opened
)
1916 return; // No-one home.
1918 if (!*session
[s
].user
)
1919 return; // User not logged in
1923 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1924 if (session
[s
].tbf_in
)
1925 free_tbf(session
[s
].tbf_in
);
1928 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1930 session
[s
].tbf_in
= 0;
1932 session
[s
].throttle_in
= rate_in
;
1937 int bytes
= rate_out
* 1024 / 8;
1938 if (session
[s
].tbf_out
)
1939 free_tbf(session
[s
].tbf_out
);
1942 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1944 session
[s
].tbf_out
= 0;
1946 session
[s
].throttle_out
= rate_out
;
1950 // add/remove filters from session (-1 = no change)
1951 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1953 if (!session
[s
].opened
)
1954 return; // No-one home.
1956 if (!*session
[s
].user
)
1957 return; // User not logged in
1960 if (filter_in
> MAXFILTER
) filter_in
= -1;
1961 if (filter_out
> MAXFILTER
) filter_out
= -1;
1962 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1963 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1967 if (session
[s
].filter_in
)
1968 ip_filters
[session
[s
].filter_in
- 1].used
--;
1971 ip_filters
[filter_in
- 1].used
++;
1973 session
[s
].filter_in
= filter_in
;
1976 if (filter_out
>= 0)
1978 if (session
[s
].filter_out
)
1979 ip_filters
[session
[s
].filter_out
- 1].used
--;
1982 ip_filters
[filter_out
- 1].used
++;
1984 session
[s
].filter_out
= filter_out
;
1988 // start tidy shutdown of session
1989 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1991 int walled_garden
= session
[s
].walled_garden
;
1992 bundleidt b
= session
[s
].bundle
;
1993 //delete routes only for last session in bundle (in case of MPPP)
1994 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1996 CSTAT(sessionshutdown
);
1998 if (!session
[s
].opened
)
2000 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
2001 return; // not a live session
2004 if (!session
[s
].die
)
2006 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
2007 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
2008 run_plugins(PLUGIN_KILL_SESSION
, &data
);
2009 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
2012 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
2014 // RADIUS Stop message
2015 uint16_t r
= radiusnew(s
);
2018 // stop, if not already trying
2019 if (radius
[r
].state
!= RADIUSSTOP
)
2021 radius
[r
].term_cause
= term_cause
;
2022 radius
[r
].term_msg
= reason
;
2023 radiussend(r
, RADIUSSTOP
);
2027 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
2029 // Save counters to dump to accounting file
2030 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
2031 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
2035 { // IP allocated, clear and unroute
2038 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
2040 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
2041 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2044 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2045 session
[s
].route
[r
].ip
= 0;
2048 if (session
[s
].ip_pool_index
== -1) // static ip
2050 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2056 // unroute IPv6, if setup
2057 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
2058 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2062 // This session was part of a bundle
2063 bundle
[b
].num_of_links
--;
2064 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2065 if(bundle
[b
].num_of_links
== 0)
2068 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2072 // Adjust the members array to accomodate the new change
2073 uint8_t mem_num
= 0;
2074 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2075 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2078 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2079 if(bundle
[b
].members
[ml
] == s
)
2084 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2085 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2087 // If the killed session is the first of the bundle,
2088 // the new first session must be stored in the cache_ipmap
2089 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2092 sessionidt new_s
= bundle
[b
].members
[0];
2095 // Add the route for this session.
2096 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2101 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2102 ip
= session
[new_s
].route
[r
].ip
;
2104 if (!prefixlen
) prefixlen
= 32;
2105 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2107 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2108 cache_ipmap(i
, new_s
);
2110 cache_ipmap(session
[new_s
].ip
, new_s
);
2113 if (session
[new_s
].ipv6prefixlen
)
2114 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2119 cluster_send_bundle(b
);
2123 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2124 throttle_session(s
, 0, 0);
2128 controlt
*c
= controlnew(14); // sending CDN
2132 buf
[0] = htons(cdn_result
);
2133 buf
[1] = htons(cdn_error
);
2134 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2137 control16(c
, 1, cdn_result
, 1);
2139 control16(c
, 14, s
, 1); // assigned session (our end)
2140 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2143 // update filter refcounts
2144 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2145 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2148 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2149 sess_local
[s
].lcp
.restart
= 0;
2150 sess_local
[s
].ipcp
.restart
= 0;
2151 sess_local
[s
].ipv6cp
.restart
= 0;
2152 sess_local
[s
].ccp
.restart
= 0;
2154 cluster_send_session(s
);
2157 void sendipcp(sessionidt s
, tunnelidt t
)
2159 uint8_t buf
[MAXETHER
];
2163 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2165 if (!session
[s
].unique_id
)
2167 if (!++last_id
) ++last_id
; // skip zero
2168 session
[s
].unique_id
= last_id
;
2171 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2175 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2176 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2177 q
[4] = 3; // ip address option
2178 q
[5] = 6; // option length
2179 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2180 config
->bind_address
? config
->bind_address
:
2181 my_address
; // send my IP
2183 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2184 restart_timer(s
, ipcp
);
2187 void sendipv6cp(sessionidt s
, tunnelidt t
)
2189 uint8_t buf
[MAXETHER
];
2193 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2195 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2199 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2200 // only send one type
2202 *(uint16_t *) (q
+ 2) = htons(14);
2203 q
[4] = 1; // interface identifier option
2204 q
[5] = 10; // option length
2205 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2206 *(uint32_t *) (q
+ 10) = 0;
2209 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2210 restart_timer(s
, ipv6cp
);
2213 static void sessionclear(sessionidt s
)
2215 memset(&session
[s
], 0, sizeof(session
[s
]));
2216 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2217 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2219 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2220 session
[s
].next
= sessionfree
;
2224 // kill a session now
2225 void sessionkill(sessionidt s
, char *reason
)
2229 if (!session
[s
].opened
) // not alive
2232 if (session
[s
].next
)
2234 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2238 if (!session
[s
].die
)
2239 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2241 if (sess_local
[s
].radius
)
2242 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2245 if (session
[s
].forwardtosession
)
2247 sessionidt sess
= session
[s
].forwardtosession
;
2248 if (session
[sess
].forwardtosession
== s
)
2250 // Shutdown the linked session also.
2251 sessionshutdown(sess
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
2256 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2258 cluster_send_session(s
);
2261 static void tunnelclear(tunnelidt t
)
2264 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2265 tunnel
[t
].state
= TUNNELFREE
;
2268 static void bundleclear(bundleidt b
)
2271 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2272 bundle
[b
].state
= BUNDLEFREE
;
2275 // kill a tunnel now
2276 static void tunnelkill(tunnelidt t
, char *reason
)
2283 tunnel
[t
].state
= TUNNELDIE
;
2285 // free control messages
2286 while ((c
= tunnel
[t
].controls
))
2288 controlt
* n
= c
->next
;
2289 tunnel
[t
].controls
= n
;
2290 tunnel
[t
].controlc
--;
2291 c
->next
= controlfree
;
2295 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2296 if (session
[s
].tunnel
== t
)
2297 sessionkill(s
, reason
);
2301 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2302 cli_tunnel_actions
[t
].action
= 0;
2303 cluster_send_tunnel(t
);
2306 // shut down a tunnel cleanly
2307 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2311 CSTAT(tunnelshutdown
);
2313 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2315 // never set up, can immediately kill
2316 tunnelkill(t
, reason
);
2319 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2322 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2323 if (session
[s
].tunnel
== t
)
2324 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2326 tunnel
[t
].state
= TUNNELDIE
;
2327 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2328 cluster_send_tunnel(t
);
2329 // TBA - should we wait for sessions to stop?
2332 controlt
*c
= controlnew(4); // sending StopCCN
2337 buf
[0] = htons(result
);
2338 buf
[1] = htons(error
);
2341 int m
= strlen(msg
);
2342 if (m
+ 4 > sizeof(buf
))
2343 m
= sizeof(buf
) - 4;
2345 memcpy(buf
+2, msg
, m
);
2349 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2352 control16(c
, 1, result
, 1);
2354 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2355 controladd(c
, 0, t
); // send the message
2359 // read and process packet on tunnel (UDP)
2360 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2362 uint8_t *chapresponse
= NULL
;
2363 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2364 uint8_t *p
= buf
+ 2;
2371 LOG_HEX(5, "UDP Data", buf
, len
);
2372 STAT(tunnel_rx_packets
);
2373 INC_STAT(tunnel_rx_bytes
, len
);
2376 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2377 STAT(tunnel_rx_errors
);
2380 if ((buf
[1] & 0x0F) != 2)
2382 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2383 STAT(tunnel_rx_errors
);
2388 l
= ntohs(*(uint16_t *) p
);
2391 t
= ntohs(*(uint16_t *) p
);
2393 s
= ntohs(*(uint16_t *) p
);
2395 if (s
>= MAXSESSION
)
2397 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2398 STAT(tunnel_rx_errors
);
2403 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2404 STAT(tunnel_rx_errors
);
2409 ns
= ntohs(*(uint16_t *) p
);
2411 nr
= ntohs(*(uint16_t *) p
);
2416 uint16_t o
= ntohs(*(uint16_t *) p
);
2421 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2422 STAT(tunnel_rx_errors
);
2427 // used to time out old tunnels
2428 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2429 tunnel
[t
].lastrec
= time_now
;
2433 uint16_t message
= 0xFFFF; // message type
2435 uint8_t mandatory
= 0;
2436 uint16_t asession
= 0; // assigned session
2437 uint32_t amagic
= 0; // magic number
2438 uint8_t aflags
= 0; // flags from last LCF
2439 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2440 char called
[MAXTEL
] = ""; // called number
2441 char calling
[MAXTEL
] = ""; // calling number
2443 if (!config
->cluster_iam_master
)
2445 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2449 // control messages must have bits 0x80|0x40|0x08
2450 // (type, length and sequence) set, and bits 0x02|0x01
2451 // (offset and priority) clear
2452 if ((*buf
& 0xCB) != 0xC8)
2454 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2455 STAT(tunnel_rx_errors
);
2459 // check for duplicate tunnel open message
2465 // Is this a duplicate of the first packet? (SCCRQ)
2467 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2469 if (tunnel
[i
].state
!= TUNNELOPENING
||
2470 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2471 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2474 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2479 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2480 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2482 // if no tunnel specified, assign one
2485 if (!(t
= new_tunnel()))
2487 LOG(1, 0, 0, "No more tunnels\n");
2488 STAT(tunnel_overflow
);
2492 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2493 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2494 tunnel
[t
].window
= 4; // default window
2495 STAT(tunnel_created
);
2496 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2497 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2500 // If the 'ns' just received is not the 'nr' we're
2501 // expecting, just send an ack and drop it.
2503 // if 'ns' is less, then we got a retransmitted packet.
2504 // if 'ns' is greater than missed a packet. Either way
2505 // we should ignore it.
2506 if (ns
!= tunnel
[t
].nr
)
2508 // is this the sequence we were expecting?
2509 STAT(tunnel_rx_errors
);
2510 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2511 t
, ns
, tunnel
[t
].nr
);
2513 if (l
) // Is this not a ZLB?
2518 // check sequence of this message
2520 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2521 // some to clear maybe?
2522 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2524 controlt
*c
= tunnel
[t
].controls
;
2525 tunnel
[t
].controls
= c
->next
;
2526 tunnel
[t
].controlc
--;
2527 c
->next
= controlfree
;
2530 tunnel
[t
].try = 0; // we have progress
2533 // receiver advance (do here so quoted correctly in any sends below)
2534 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2535 if (skip
< 0) skip
= 0;
2536 if (skip
< tunnel
[t
].controlc
)
2538 // some control packets can now be sent that were previous stuck out of window
2539 int tosend
= tunnel
[t
].window
- skip
;
2540 controlt
*c
= tunnel
[t
].controls
;
2548 tunnel
[t
].try = 0; // first send
2549 tunnelsend(c
->buf
, c
->length
, t
);
2554 if (!tunnel
[t
].controlc
)
2555 tunnel
[t
].retry
= 0; // caught up
2558 { // if not a null message
2563 // Default disconnect cause/message on receipt of CDN. Set to
2564 // more specific value from attribute 1 (result code) or 46
2565 // (disconnect cause) if present below.
2566 int disc_cause_set
= 0;
2567 int disc_cause
= TERM_NAS_REQUEST
;
2568 char const *disc_reason
= "Closed (Received CDN).";
2571 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2573 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2580 LOG(1, s
, t
, "Invalid length in AVP\n");
2581 STAT(tunnel_rx_errors
);
2586 if (flags
& 0x3C) // reserved bits, should be clear
2588 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2590 result
= 2; // general error
2591 error
= 3; // reserved field non-zero
2596 if (*(uint16_t *) (b
))
2598 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2600 result
= 2; // general error
2601 error
= 6; // generic vendor-specific error
2602 msg
= "unsupported vendor-specific";
2606 mtype
= ntohs(*(uint16_t *) (b
));
2614 // handle hidden AVPs
2615 if (!*config
->l2tp_secret
)
2617 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2619 result
= 2; // general error
2620 error
= 6; // generic vendor-specific error
2621 msg
= "secret not specified";
2624 if (!session
[s
].random_vector_length
)
2626 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2628 result
= 2; // general error
2629 error
= 6; // generic
2630 msg
= "no random vector";
2635 LOG(2, s
, t
, "Short hidden AVP.\n");
2637 result
= 2; // general error
2638 error
= 2; // length is wrong
2644 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2646 orig_len
= ntohs(*(uint16_t *) b
);
2647 if (orig_len
> n
+ 2)
2649 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2653 result
= 2; // general error
2654 error
= 2; // length is wrong
2663 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2664 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2668 case 0: // message type
2669 message
= ntohs(*(uint16_t *) b
);
2670 mandatory
= flags
& 0x80;
2671 LOG(4, s
, t
, " Message type = %u (%s)\n", message
, l2tp_code(message
));
2673 case 1: // result code
2675 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2676 char const *resdesc
= "(unknown)";
2677 char const *errdesc
= NULL
;
2682 resdesc
= l2tp_stopccn_result_code(rescode
);
2683 cause
= TERM_LOST_SERVICE
;
2685 else if (message
== 14)
2687 resdesc
= l2tp_cdn_result_code(rescode
);
2689 cause
= TERM_LOST_CARRIER
;
2691 cause
= TERM_ADMIN_RESET
;
2694 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2697 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2698 errdesc
= l2tp_error_code(errcode
);
2699 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2702 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2704 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2706 disc_cause_set
= mtype
;
2707 disc_reason
= errdesc
? errdesc
: resdesc
;
2714 case 2: // protocol version
2716 version
= ntohs(*(uint16_t *) (b
));
2717 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2718 if (version
&& version
!= 0x0100)
2719 { // allow 0.0 and 1.0
2720 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2722 result
= 5; // unspported protocol version
2723 error
= 0x0100; // supported version
2729 case 3: // framing capabilities
2731 case 4: // bearer capabilities
2733 case 5: // tie breaker
2734 // We never open tunnels, so we don't care about tie breakers
2736 case 6: // firmware revision
2738 case 7: // host name
2739 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2740 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2741 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2742 // TBA - to send to RADIUS
2744 case 8: // vendor name
2745 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2746 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2747 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2749 case 9: // assigned tunnel
2750 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2751 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2753 case 10: // rx window
2754 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2755 if (!tunnel
[t
].window
)
2756 tunnel
[t
].window
= 1; // window of 0 is silly
2757 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2759 case 11: // Challenge
2761 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2762 build_chap_response(b
, 2, n
, &chapresponse
);
2765 case 13: // Response
2767 if (tunnel
[t
].isremotelns
)
2769 chapresponse
= calloc(17, 1);
2770 memcpy(chapresponse
, b
, (n
< 17) ? n
: 16);
2771 LOG(3, s
, t
, "received challenge response from REMOTE LNS\n");
2775 // Why did they send a response? We never challenge.
2776 LOG(2, s
, t
, " received unexpected challenge response\n");
2779 case 14: // assigned session
2780 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2781 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2783 case 15: // call serial number
2784 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2786 case 18: // bearer type
2787 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2790 case 19: // framing type
2791 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2794 case 21: // called number
2795 memset(called
, 0, sizeof(called
));
2796 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2797 LOG(4, s
, t
, " Called <%s>\n", called
);
2799 case 22: // calling number
2800 memset(calling
, 0, sizeof(calling
));
2801 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2802 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2806 case 24: // tx connect speed
2809 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2813 // AS5300s send connect speed as a string
2815 memset(tmp
, 0, sizeof(tmp
));
2816 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2817 session
[s
].tx_connect_speed
= atol(tmp
);
2819 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2821 case 38: // rx connect speed
2824 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2828 // AS5300s send connect speed as a string
2830 memset(tmp
, 0, sizeof(tmp
));
2831 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2832 session
[s
].rx_connect_speed
= atol(tmp
);
2834 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2836 case 25: // Physical Channel ID
2838 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2839 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2842 case 29: // Proxy Authentication Type
2844 uint16_t atype
= ntohs(*(uint16_t *)b
);
2845 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2848 case 30: // Proxy Authentication Name
2851 memset(authname
, 0, sizeof(authname
));
2852 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2853 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2857 case 31: // Proxy Authentication Challenge
2859 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2862 case 32: // Proxy Authentication ID
2864 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2865 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2868 case 33: // Proxy Authentication Response
2869 LOG(4, s
, t
, " Proxy Auth Response\n");
2871 case 27: // last sent lcp
2872 { // find magic number
2873 uint8_t *p
= b
, *e
= p
+ n
;
2874 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2876 if (*p
== 5 && p
[1] == 6) // Magic-Number
2877 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2878 else if (*p
== 7) // Protocol-Field-Compression
2879 aflags
|= SESSION_PFC
;
2880 else if (*p
== 8) // Address-and-Control-Field-Compression
2881 aflags
|= SESSION_ACFC
;
2886 case 28: // last recv lcp confreq
2888 case 26: // Initial Received LCP CONFREQ
2890 case 39: // seq required - we control it as an LNS anyway...
2892 case 36: // Random Vector
2893 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2894 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2895 if (n
> sizeof(session
[s
].random_vector
))
2896 n
= sizeof(session
[s
].random_vector
);
2897 memcpy(session
[s
].random_vector
, b
, n
);
2898 session
[s
].random_vector_length
= n
;
2900 case 46: // ppp disconnect cause
2903 uint16_t code
= ntohs(*(uint16_t *) b
);
2904 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2905 uint8_t dir
= *(b
+ 4);
2907 LOG(4, s
, t
, " PPP disconnect cause "
2908 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2909 code
, proto
, dir
, n
- 5, b
+ 5);
2911 disc_cause_set
= mtype
;
2915 case 1: // admin disconnect
2916 disc_cause
= TERM_ADMIN_RESET
;
2917 disc_reason
= "Administrative disconnect";
2919 case 3: // lcp terminate
2920 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2921 disc_cause
= TERM_USER_REQUEST
;
2922 disc_reason
= "Normal disconnection";
2924 case 4: // compulsory encryption unavailable
2925 if (dir
!= 1) break; // 1=refused by peer, 2=local
2926 disc_cause
= TERM_USER_ERROR
;
2927 disc_reason
= "Compulsory encryption refused";
2929 case 5: // lcp: fsm timeout
2930 disc_cause
= TERM_PORT_ERROR
;
2931 disc_reason
= "LCP: FSM timeout";
2933 case 6: // lcp: no recognisable lcp packets received
2934 disc_cause
= TERM_PORT_ERROR
;
2935 disc_reason
= "LCP: no recognisable LCP packets";
2937 case 7: // lcp: magic-no error (possibly looped back)
2938 disc_cause
= TERM_PORT_ERROR
;
2939 disc_reason
= "LCP: magic-no error (possible loop)";
2941 case 8: // lcp: echo request timeout
2942 disc_cause
= TERM_PORT_ERROR
;
2943 disc_reason
= "LCP: echo request timeout";
2945 case 13: // auth: fsm timeout
2946 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2947 disc_reason
= "Authentication: FSM timeout";
2949 case 15: // auth: unacceptable auth protocol
2950 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2951 disc_reason
= "Unacceptable authentication protocol";
2953 case 16: // auth: authentication failed
2954 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2955 disc_reason
= "Authentication failed";
2957 case 17: // ncp: fsm timeout
2958 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2959 disc_reason
= "NCP: FSM timeout";
2961 case 18: // ncp: no ncps available
2962 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2963 disc_reason
= "NCP: no NCPs available";
2965 case 19: // ncp: failure to converge on acceptable address
2966 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2967 disc_reason
= (dir
== 1)
2968 ? "NCP: too many Configure-Naks received from peer"
2969 : "NCP: too many Configure-Naks sent to peer";
2971 case 20: // ncp: user not permitted to use any address
2972 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2973 disc_reason
= (dir
== 1)
2974 ? "NCP: local link address not acceptable to peer"
2975 : "NCP: remote link address not acceptable";
2982 static char e
[] = "unknown AVP 0xXXXX";
2983 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2985 result
= 2; // general error
2986 error
= 8; // unknown mandatory AVP
2987 sprintf((msg
= e
) + 14, "%04x", mtype
);
2994 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2998 case 1: // SCCRQ - Start Control Connection Request
2999 tunnel
[t
].state
= TUNNELOPENING
;
3000 LOG(3, s
, t
, "Received SCCRQ\n");
3001 if (main_quit
!= QUIT_SHUTDOWN
)
3003 LOG(3, s
, t
, "sending SCCRP\n");
3004 controlt
*c
= controlnew(2); // sending SCCRP
3005 control16(c
, 2, version
, 1); // protocol version
3006 control32(c
, 3, 3, 1); // framing
3007 controls(c
, 7, hostname
, 1); // host name
3008 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
3009 control16(c
, 9, t
, 1); // assigned tunnel
3010 controladd(c
, 0, t
); // send the resply
3014 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3018 tunnel
[t
].state
= TUNNELOPEN
;
3019 tunnel
[t
].lastrec
= time_now
;
3021 LOG(3, s
, t
, "Received SCCRP\n");
3022 if (main_quit
!= QUIT_SHUTDOWN
)
3024 if (tunnel
[t
].isremotelns
&& chapresponse
)
3028 lac_calc_rlns_auth(t
, 2, hash
); // id = 2 (SCCRP)
3029 // check authenticator
3030 if (memcmp(hash
, chapresponse
, 16) == 0)
3032 LOG(3, s
, t
, "sending SCCCN to REMOTE LNS\n");
3033 controlt
*c
= controlnew(3); // sending SCCCN
3034 controls(c
, 7, hostname
, 1); // host name
3035 controls(c
, 8, Vendor_name
, 1); // Vendor name
3036 control16(c
, 2, version
, 1); // protocol version
3037 control32(c
, 3, 3, 1); // framing Capabilities
3038 control16(c
, 9, t
, 1); // assigned tunnel
3039 controladd(c
, 0, t
); // send
3043 tunnelshutdown(t
, "Bad chap response from REMOTE LNS", 4, 0, 0);
3049 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
3054 LOG(3, s
, t
, "Received SCCN\n");
3055 tunnel
[t
].state
= TUNNELOPEN
;
3056 tunnel
[t
].lastrec
= time_now
;
3057 controlnull(t
); // ack
3060 LOG(3, s
, t
, "Received StopCCN\n");
3061 controlnull(t
); // ack
3062 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
3065 controlnull(t
); // simply ACK
3069 LOG(3, s
, t
, "Received OCRQ\n");
3073 LOG(3, s
, t
, "Received OCRO\n");
3077 LOG(3, s
, t
, "Received OCCN\n");
3080 LOG(3, s
, t
, "Received ICRQ\n");
3081 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
3083 controlt
*c
= controlnew(11); // ICRP
3085 LOG(3, s
, t
, "Sending ICRP\n");
3088 sessionfree
= session
[s
].next
;
3089 memset(&session
[s
], 0, sizeof(session
[s
]));
3091 if (s
> config
->cluster_highest_sessionid
)
3092 config
->cluster_highest_sessionid
= s
;
3094 session
[s
].opened
= time_now
;
3095 session
[s
].tunnel
= t
;
3096 session
[s
].far
= asession
;
3097 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3098 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
3099 control16(c
, 14, s
, 1); // assigned session
3100 controladd(c
, asession
, t
); // send the reply
3102 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
3103 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
3105 session
[s
].ppp
.phase
= Establish
;
3106 session
[s
].ppp
.lcp
= Starting
;
3108 STAT(session_created
);
3113 controlt
*c
= controlnew(14); // CDN
3114 LOG(3, s
, t
, "Sending CDN\n");
3117 STAT(session_overflow
);
3118 LOG(1, 0, t
, "No free sessions\n");
3119 control16(c
, 1, 4, 0); // temporary lack of resources
3122 control16(c
, 1, 2, 7); // shutting down, try another
3124 controladd(c
, asession
, t
); // send the message
3129 LOG(3, s
, t
, "Received ICRP\n");
3130 if (session
[s
].forwardtosession
)
3132 controlt
*c
= controlnew(12); // ICCN
3134 session
[s
].opened
= time_now
;
3135 session
[s
].tunnel
= t
;
3136 session
[s
].far
= asession
;
3137 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3139 control32(c
, 19, 1, 1); // Framing Type
3140 control32(c
, 24, 10000000, 1); // Tx Connect Speed
3141 controladd(c
, asession
, t
); // send the message
3142 LOG(3, s
, t
, "Sending ICCN\n");
3147 LOG(3, s
, t
, "Received ICCN\n");
3148 if (amagic
== 0) amagic
= time_now
;
3149 session
[s
].magic
= amagic
; // set magic number
3150 session
[s
].flags
= aflags
; // set flags received
3151 session
[s
].mru
= PPPoE_MRU
; // default
3152 controlnull(t
); // ack
3155 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3156 sess_local
[s
].ppp_mru
= MRU
;
3158 // Set multilink options before sending initial LCP packet
3159 sess_local
[s
].mp_mrru
= 1614;
3160 sess_local
[s
].mp_epdis
= ntohl(config
->bind_address
? config
->bind_address
: my_address
);
3163 change_state(s
, lcp
, RequestSent
);
3167 LOG(3, s
, t
, "Received CDN\n");
3168 controlnull(t
); // ack
3169 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3172 LOG(1, s
, t
, "Missing message type\n");
3175 STAT(tunnel_rx_errors
);
3177 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3179 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3182 if (chapresponse
) free(chapresponse
);
3183 cluster_send_tunnel(t
);
3187 LOG(4, s
, t
, " Got a ZLB ack\n");
3194 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3195 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3196 { // HDLC address header, discard
3202 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3203 STAT(tunnel_rx_errors
);
3213 proto
= ntohs(*(uint16_t *) p
);
3219 if (session
[s
].forwardtosession
)
3221 LOG(5, s
, t
, "Forwarding data session to session %u\n", session
[s
].forwardtosession
);
3222 // Forward to LAC or Remote LNS session
3223 lac_session_forward(buf
, len
, s
, proto
);
3228 if (s
&& !session
[s
].opened
) // Is something wrong??
3230 if (!config
->cluster_iam_master
)
3232 // Pass it off to the master to deal with..
3233 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3237 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3238 STAT(tunnel_rx_errors
);
3242 if (proto
== PPPPAP
)
3244 session
[s
].last_packet
= time_now
;
3245 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3246 processpap(s
, t
, p
, l
);
3248 else if (proto
== PPPCHAP
)
3250 session
[s
].last_packet
= time_now
;
3251 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3252 processchap(s
, t
, p
, l
);
3254 else if (proto
== PPPLCP
)
3256 session
[s
].last_packet
= time_now
;
3257 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3258 processlcp(s
, t
, p
, l
);
3260 else if (proto
== PPPIPCP
)
3262 session
[s
].last_packet
= time_now
;
3263 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3264 processipcp(s
, t
, p
, l
);
3266 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3268 session
[s
].last_packet
= time_now
;
3269 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3270 processipv6cp(s
, t
, p
, l
);
3272 else if (proto
== PPPCCP
)
3274 session
[s
].last_packet
= time_now
;
3275 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3276 processccp(s
, t
, p
, l
);
3278 else if (proto
== PPPIP
)
3282 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3283 return; // closing session, PPP not processed
3286 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3287 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3289 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3293 processipin(s
, t
, p
, l
);
3295 else if (proto
== PPPMP
)
3299 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3300 return; // closing session, PPP not processed
3303 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3304 if (!config
->cluster_iam_master
)
3306 // The fragments reconstruction is managed by the Master.
3307 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3311 processmpin(s
, t
, p
, l
);
3313 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3317 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3318 return; // closing session, PPP not processed
3321 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3322 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3324 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3328 processipv6in(s
, t
, p
, l
);
3330 else if (session
[s
].ppp
.lcp
== Opened
)
3332 session
[s
].last_packet
= time_now
;
3333 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3334 protoreject(s
, t
, p
, l
, proto
);
3338 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3339 proto
, ppp_state(session
[s
].ppp
.lcp
));
3344 // read and process packet on tun
3345 // (i.e. this routine writes to buf[-8]).
3346 static void processtun(uint8_t * buf
, int len
)
3348 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3349 STAT(tun_rx_packets
);
3350 INC_STAT(tun_rx_bytes
, len
);
3358 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3359 STAT(tun_rx_errors
);
3363 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3364 processipout(buf
, len
);
3365 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3366 && config
->ipv6_prefix
.s6_addr
[0])
3367 processipv6out(buf
, len
);
3372 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3373 // that we look at the whole of the tunnel, radius and session tables
3375 static void regular_cleanups(double period
)
3377 // Next tunnel, radius and session to check for actions on.
3378 static tunnelidt t
= 0;
3380 static sessionidt s
= 0;
3393 // divide up tables into slices based on the last run
3394 t_slice
= config
->cluster_highest_tunnelid
* period
;
3395 r_slice
= (MAXRADIUS
- 1) * period
;
3396 s_slice
= config
->cluster_highest_sessionid
* period
;
3400 else if (t_slice
> config
->cluster_highest_tunnelid
)
3401 t_slice
= config
->cluster_highest_tunnelid
;
3405 else if (r_slice
> (MAXRADIUS
- 1))
3406 r_slice
= MAXRADIUS
- 1;
3410 else if (s_slice
> config
->cluster_highest_sessionid
)
3411 s_slice
= config
->cluster_highest_sessionid
;
3413 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3415 for (i
= 0; i
< t_slice
; i
++)
3418 if (t
> config
->cluster_highest_tunnelid
)
3421 // check for expired tunnels
3422 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3424 STAT(tunnel_timeout
);
3425 tunnelkill(t
, "Expired");
3429 // check for message resend
3430 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3432 // resend pending messages as timeout on reply
3433 if (tunnel
[t
].retry
<= TIME
)
3435 controlt
*c
= tunnel
[t
].controls
;
3436 uint16_t w
= tunnel
[t
].window
;
3437 tunnel
[t
].try++; // another try
3438 if (tunnel
[t
].try > 5)
3439 tunnelkill(t
, "Timeout on control message"); // game over
3443 tunnelsend(c
->buf
, c
->length
, t
);
3451 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3453 controlt
*c
= controlnew(6); // sending HELLO
3454 controladd(c
, 0, t
); // send the message
3455 LOG(3, 0, t
, "Sending HELLO message\n");
3459 // Check for tunnel changes requested from the CLI
3460 if ((a
= cli_tunnel_actions
[t
].action
))
3462 cli_tunnel_actions
[t
].action
= 0;
3463 if (a
& CLI_TUN_KILL
)
3465 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3466 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3472 for (i
= 0; i
< r_slice
; i
++)
3478 if (!radius
[r
].state
)
3481 if (radius
[r
].retry
<= TIME
)
3488 for (i
= 0; i
< s_slice
; i
++)
3491 if (s
> config
->cluster_highest_sessionid
)
3494 if (!session
[s
].opened
) // Session isn't in use
3497 // check for expired sessions
3500 if (session
[s
].die
<= TIME
)
3502 sessionkill(s
, "Expired");
3509 if (sess_local
[s
].lcp
.restart
<= time_now
)
3511 int next_state
= session
[s
].ppp
.lcp
;
3512 switch (session
[s
].ppp
.lcp
)
3516 next_state
= RequestSent
;
3519 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3521 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3522 sendlcp(s
, session
[s
].tunnel
);
3523 change_state(s
, lcp
, next_state
);
3527 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3528 STAT(session_timeout
);
3538 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3540 int next_state
= session
[s
].ppp
.ipcp
;
3541 switch (session
[s
].ppp
.ipcp
)
3545 next_state
= RequestSent
;
3548 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3550 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3551 sendipcp(s
, session
[s
].tunnel
);
3552 change_state(s
, ipcp
, next_state
);
3556 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3557 STAT(session_timeout
);
3567 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3569 int next_state
= session
[s
].ppp
.ipv6cp
;
3570 switch (session
[s
].ppp
.ipv6cp
)
3574 next_state
= RequestSent
;
3577 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3579 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3580 sendipv6cp(s
, session
[s
].tunnel
);
3581 change_state(s
, ipv6cp
, next_state
);
3585 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3586 change_state(s
, ipv6cp
, Stopped
);
3593 if (sess_local
[s
].ccp
.restart
<= time_now
)
3595 int next_state
= session
[s
].ppp
.ccp
;
3596 switch (session
[s
].ppp
.ccp
)
3600 next_state
= RequestSent
;
3603 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3605 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3606 sendccp(s
, session
[s
].tunnel
);
3607 change_state(s
, ccp
, next_state
);
3611 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3612 change_state(s
, ccp
, Stopped
);
3619 // Drop sessions who have not responded within IDLE_ECHO_TIMEOUT seconds
3620 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= config
->idle_echo_timeout
))
3622 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3623 STAT(session_timeout
);
3628 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3629 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= config
->echo_timeout
) &&
3630 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3632 uint8_t b
[MAXETHER
];
3634 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3638 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3639 *(uint16_t *)(q
+ 2) = htons(8); // Length
3640 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3642 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3643 (int)(time_now
- session
[s
].last_packet
));
3644 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3645 sess_local
[s
].last_echo
= time_now
;
3649 // Drop sessions who have reached session_timeout seconds
3650 if (session
[s
].session_timeout
)
3652 bundleidt bid
= session
[s
].bundle
;
3655 if (time_now
- bundle
[bid
].last_check
>= 1)
3657 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3658 bundle
[bid
].last_check
= time_now
;
3659 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3662 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3664 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3671 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3673 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3679 // Drop sessions who have reached idle_timeout seconds
3680 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3682 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3683 STAT(session_timeout
);
3688 // Check for actions requested from the CLI
3689 if ((a
= cli_session_actions
[s
].action
))
3693 cli_session_actions
[s
].action
= 0;
3694 if (a
& CLI_SESS_KILL
)
3696 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3697 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3698 a
= 0; // dead, no need to check for other actions
3702 if (a
& CLI_SESS_NOSNOOP
)
3704 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3705 session
[s
].snoop_ip
= 0;
3706 session
[s
].snoop_port
= 0;
3710 else if (a
& CLI_SESS_SNOOP
)
3712 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3713 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3714 cli_session_actions
[s
].snoop_port
);
3716 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3717 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3722 if (a
& CLI_SESS_NOTHROTTLE
)
3724 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3725 throttle_session(s
, 0, 0);
3729 else if (a
& CLI_SESS_THROTTLE
)
3731 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3732 cli_session_actions
[s
].throttle_in
,
3733 cli_session_actions
[s
].throttle_out
);
3735 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3740 if (a
& CLI_SESS_NOFILTER
)
3742 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3743 filter_session(s
, 0, 0);
3747 else if (a
& CLI_SESS_FILTER
)
3749 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3750 cli_session_actions
[s
].filter_in
,
3751 cli_session_actions
[s
].filter_out
);
3753 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3759 cluster_send_session(s
);
3762 // RADIUS interim accounting
3763 if (config
->radius_accounting
&& config
->radius_interim
> 0
3764 && session
[s
].ip
&& !session
[s
].walled_garden
3765 && !sess_local
[s
].radius
// RADIUS already in progress
3766 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3767 && session
[s
].flags
& SESSION_STARTED
)
3769 int rad
= radiusnew(s
);
3772 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3773 STAT(radius_overflow
);
3777 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3778 session
[s
].user
, session
[s
].unique_id
);
3780 radiussend(rad
, RADIUSINTERIM
);
3781 sess_local
[s
].last_interim
= time_now
;
3786 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3787 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3791 // Are we in the middle of a tunnel update, or radius
3794 static int still_busy(void)
3797 static clockt last_talked
= 0;
3798 static clockt start_busy_wait
= 0;
3801 static time_t stopped_bgp
= 0;
3806 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3808 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3809 if (bgp_peers
[i
].state
== Established
)
3810 bgp_stop(&bgp_peers
[i
]);
3812 stopped_bgp
= time_now
;
3814 if (!config
->cluster_iam_master
)
3816 // we don't want to become master
3817 cluster_send_ping(0);
3823 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3828 if (!config
->cluster_iam_master
)
3831 if (main_quit
== QUIT_SHUTDOWN
)
3833 static int dropped
= 0;
3838 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3839 for (i
= 1; i
< MAXTUNNEL
; i
++)
3840 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3841 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3847 if (start_busy_wait
== 0)
3848 start_busy_wait
= TIME
;
3850 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3852 if (!tunnel
[i
].controlc
)
3855 if (last_talked
!= TIME
)
3857 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3863 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3864 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3866 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3870 for (i
= 1; i
< MAXRADIUS
; i
++)
3872 if (radius
[i
].state
== RADIUSNULL
)
3874 if (radius
[i
].state
== RADIUSWAIT
)
3877 if (last_talked
!= TIME
)
3879 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3889 # include <sys/epoll.h>
3891 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3892 # include "fake_epoll.h"
3896 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink, udplac
3899 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3903 // additional polled fds
3905 # define EXTRA_FDS BGP_NUM_PEERS
3907 # define EXTRA_FDS 0
3910 // main loop - gets packets on tun or udp and processes them
3911 static void mainloop(void)
3915 uint8_t *p
= buf
+ 8; // for the hearder of the forwarded MPPP packet (see C_MPPP_FORWARD)
3916 int size_bufp
= sizeof(buf
) - 8;
3917 clockt next_cluster_ping
= 0; // send initial ping immediately
3918 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3919 int maxevent
= sizeof(events
)/sizeof(*events
);
3921 if ((epollfd
= epoll_create(maxevent
)) < 0)
3923 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3928 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\n",
3929 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
, udplacfd
);
3931 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3932 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3935 /* setup our fds to poll for input */
3937 static struct event_data d
[BASE_FDS
];
3938 struct epoll_event e
;
3945 d
[i
].type
= FD_TYPE_CLI
;
3946 e
.data
.ptr
= &d
[i
++];
3947 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3950 d
[i
].type
= FD_TYPE_CLUSTER
;
3951 e
.data
.ptr
= &d
[i
++];
3952 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3954 d
[i
].type
= FD_TYPE_TUN
;
3955 e
.data
.ptr
= &d
[i
++];
3956 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3958 d
[i
].type
= FD_TYPE_UDP
;
3959 e
.data
.ptr
= &d
[i
++];
3960 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3962 d
[i
].type
= FD_TYPE_CONTROL
;
3963 e
.data
.ptr
= &d
[i
++];
3964 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3966 d
[i
].type
= FD_TYPE_DAE
;
3967 e
.data
.ptr
= &d
[i
++];
3968 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3970 d
[i
].type
= FD_TYPE_NETLINK
;
3971 e
.data
.ptr
= &d
[i
++];
3972 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3975 d
[i
].type
= FD_TYPE_UDPLAC
;
3976 e
.data
.ptr
= &d
[i
++];
3977 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udplacfd
, &e
);
3982 signal(SIGPIPE
, SIG_IGN
);
3983 bgp_setup(config
->as_number
);
3984 if (config
->bind_address
)
3985 bgp_add_route(config
->bind_address
, 0xffffffff);
3987 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3989 if (config
->neighbour
[i
].name
[0])
3990 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3991 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3992 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
3993 0); /* 0 = routing disabled */
3997 while (!main_quit
|| still_busy())
4007 config
->reload_config
++;
4010 if (config
->reload_config
)
4012 config
->reload_config
= 0;
4020 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
4021 STAT(select_called
);
4026 if (errno
== EINTR
||
4027 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
4030 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
4036 struct sockaddr_in addr
;
4037 struct in_addr local
;
4042 int udplac_ready
= 0;
4043 int udplac_pkts
= 0;
4046 int cluster_ready
= 0;
4049 int cluster_pkts
= 0;
4051 uint32_t bgp_events
[BGP_NUM_PEERS
];
4052 memset(bgp_events
, 0, sizeof(bgp_events
));
4055 for (c
= n
, i
= 0; i
< c
; i
++)
4057 struct event_data
*d
= events
[i
].data
.ptr
;
4061 case FD_TYPE_CLI
: // CLI connections
4065 alen
= sizeof(addr
);
4066 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
4072 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
4078 // these are handled below, with multiple interleaved reads
4079 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
4080 case FD_TYPE_TUN
: tun_ready
++; break;
4081 case FD_TYPE_UDP
: udp_ready
++; break;
4083 case FD_TYPE_UDPLAC
: udplac_ready
++; break;
4085 case FD_TYPE_CONTROL
: // nsctl commands
4086 alen
= sizeof(addr
);
4087 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4088 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
4092 case FD_TYPE_DAE
: // DAE requests
4093 alen
= sizeof(addr
);
4094 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
4095 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
4099 case FD_TYPE_RADIUS
: // RADIUS response
4100 alen
= sizeof(addr
);
4101 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
4102 if (s
>= 0 && config
->cluster_iam_master
)
4104 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
4105 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
4106 processrad(buf
, s
, d
->index
);
4108 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
4109 fmtaddr(addr
.sin_addr
.s_addr
, 0));
4117 bgp_events
[d
->index
] = events
[i
].events
;
4122 case FD_TYPE_NETLINK
:
4124 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
4125 s
= netlink_recv(buf
, sizeof(buf
));
4126 if (nh
->nlmsg_type
== NLMSG_ERROR
)
4128 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
4131 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
4133 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
4138 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
4143 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
);
4149 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
4154 bgp_process(bgp_events
);
4157 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4162 alen
= sizeof(addr
);
4163 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
4165 processudp(buf
, s
, &addr
);
4178 alen
= sizeof(addr
);
4179 if ((s
= recvfrom(udplacfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
4181 if (!config
->disable_lac_func
)
4182 processudp(buf
, s
, &addr
);
4196 if ((s
= read(tunfd
, p
, size_bufp
)) > 0)
4211 alen
= sizeof(addr
);
4212 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4214 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
4225 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4226 STAT(multi_read_used
);
4228 if (c
>= config
->multi_read_count
)
4231 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster %d rmlns packets\n",
4232 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
, udplac_pkts
);
4234 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
4235 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
4237 STAT(multi_read_exceeded
);
4243 /* no event received, but timers could still have expired */
4244 bgp_process_peers_timers();
4249 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4251 // Log current traffic stats
4252 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4253 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4254 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4255 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4256 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4258 udp_tx
= udp_rx
= 0;
4259 udp_rx_pkt
= eth_rx_pkt
= 0;
4260 eth_tx
= eth_rx
= 0;
4263 if (config
->dump_speed
)
4264 printf("%s\n", config
->bandwidth
);
4266 // Update the internal time counter
4267 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4271 struct param_timer p
= { time_now
};
4272 run_plugins(PLUGIN_TIMER
, &p
);
4276 // Runs on every machine (master and slaves).
4277 if (next_cluster_ping
<= TIME
)
4279 // Check to see which of the cluster is still alive..
4281 cluster_send_ping(basetime
); // Only does anything if we're a slave
4282 cluster_check_master(); // ditto.
4284 cluster_heartbeat(); // Only does anything if we're a master.
4285 cluster_check_slaves(); // ditto.
4287 master_update_counts(); // If we're a slave, send our byte counters to our master.
4289 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4290 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4292 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4295 if (!config
->cluster_iam_master
)
4298 // Run token bucket filtering queue..
4299 // Only run it every 1/10th of a second.
4301 static clockt last_run
= 0;
4302 if (last_run
!= TIME
)
4309 // Handle timeouts, retries etc.
4311 static double last_clean
= 0;
4315 TIME
= now(&this_clean
);
4316 diff
= this_clean
- last_clean
;
4318 // Run during idle time (after we've handled
4319 // all incoming packets) or every 1/10th sec
4320 if (!more
|| diff
> 0.1)
4322 regular_cleanups(diff
);
4323 last_clean
= this_clean
;
4327 if (*config
->accounting_dir
)
4329 static clockt next_acct
= 0;
4330 static clockt next_shut_acct
= 0;
4332 if (next_acct
<= TIME
)
4334 // Dump accounting data
4335 next_acct
= TIME
+ ACCT_TIME
;
4336 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4339 else if (next_shut_acct
<= TIME
)
4341 // Dump accounting data for shutdown sessions
4342 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4349 // Are we the master and shutting down??
4350 if (config
->cluster_iam_master
)
4351 cluster_heartbeat(); // Flush any queued changes..
4353 // Ok. Notify everyone we're shutting down. If we're
4354 // the master, this will force an election.
4355 cluster_send_ping(0);
4358 // Important!!! We MUST not process any packets past this point!
4359 LOG(1, 0, 0, "Shutdown complete\n");
4362 static void stripdomain(char *host
)
4366 if ((p
= strchr(host
, '.')))
4372 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4378 while (fgets(buf
, sizeof(buf
), resolv
))
4380 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4383 if (!isspace(buf
[6]))
4387 while (isspace(*b
)) b
++;
4392 while (*b
&& !isspace(*b
)) b
++;
4394 if (buf
[0] == 'd') // domain is canonical
4400 // first search line
4403 // hold, may be subsequent domain line
4404 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4415 int hl
= strlen(host
);
4416 int dl
= strlen(domain
);
4417 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4418 host
[hl
-dl
- 1] = 0;
4422 *p
= 0; // everything after first dot
4427 // Init data structures
4428 static void initdata(int optdebug
, char *optconfig
)
4432 if (!(config
= shared_malloc(sizeof(configt
))))
4434 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4438 memset(config
, 0, sizeof(configt
));
4439 time(&config
->start_time
);
4440 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4441 config
->debug
= optdebug
;
4442 config
->num_tbfs
= MAXTBFS
;
4443 config
->rl_rate
= 28; // 28kbps
4444 config
->cluster_mcast_ttl
= 1;
4445 config
->cluster_master_min_adv
= 1;
4446 config
->ppp_restart_time
= 3;
4447 config
->ppp_max_configure
= 10;
4448 config
->ppp_max_failure
= 5;
4449 config
->kill_timedout_sessions
= 1;
4450 strcpy(config
->random_device
, RANDOMDEVICE
);
4451 // Set default value echo_timeout and idle_echo_timeout
4452 config
->echo_timeout
= ECHO_TIMEOUT
;
4453 config
->idle_echo_timeout
= IDLE_ECHO_TIMEOUT
;
4455 log_stream
= stderr
;
4458 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4460 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4463 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4466 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4468 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4471 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4473 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4476 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4478 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4481 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4483 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4486 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4488 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4492 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4494 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4498 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4500 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4504 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4506 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4510 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4512 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4515 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4517 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4519 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4522 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4524 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4526 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4529 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4531 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4532 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4533 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4534 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4535 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4537 // Put all the sessions on the free list marked as undefined.
4538 for (i
= 1; i
< MAXSESSION
; i
++)
4540 session
[i
].next
= i
+ 1;
4541 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4543 session
[MAXSESSION
- 1].next
= 0;
4546 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4547 for (i
= 1; i
< MAXTUNNEL
; i
++)
4548 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4550 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4551 bundle
[i
].state
= BUNDLEUNDEF
;
4556 // Grab my hostname unless it's been specified
4557 gethostname(hostname
, sizeof(hostname
));
4558 stripdomain(hostname
);
4561 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4564 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4566 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4572 lac_initremotelnsdata();
4576 static int assign_ip_address(sessionidt s
)
4580 time_t best_time
= time_now
;
4581 char *u
= session
[s
].user
;
4585 CSTAT(assign_ip_address
);
4587 for (i
= 1; i
< ip_pool_size
; i
++)
4589 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4592 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4599 if (ip_address_pool
[i
].last
< best_time
)
4602 if (!(best_time
= ip_address_pool
[i
].last
))
4603 break; // never used, grab this one
4609 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4613 session
[s
].ip
= ip_address_pool
[best
].address
;
4614 session
[s
].ip_pool_index
= best
;
4615 ip_address_pool
[best
].assigned
= 1;
4616 ip_address_pool
[best
].last
= time_now
;
4617 ip_address_pool
[best
].session
= s
;
4618 if (session
[s
].walled_garden
)
4619 /* Don't track addresses of users in walled garden (note: this
4620 means that their address isn't "sticky" even if they get
4622 ip_address_pool
[best
].user
[0] = 0;
4624 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4627 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4628 reuse
? "Reusing" : "Allocating", best
);
4633 static void free_ip_address(sessionidt s
)
4635 int i
= session
[s
].ip_pool_index
;
4638 CSTAT(free_ip_address
);
4641 return; // what the?
4643 if (i
< 0) // Is this actually part of the ip pool?
4647 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4649 ip_address_pool
[i
].assigned
= 0;
4650 ip_address_pool
[i
].session
= 0;
4651 ip_address_pool
[i
].last
= time_now
;
4655 // Fsck the address pool against the session table.
4656 // Normally only called when we become a master.
4658 // This isn't perfect: We aren't keep tracking of which
4659 // users used to have an IP address.
4661 void rebuild_address_pool(void)
4666 // Zero the IP pool allocation, and build
4667 // a map from IP address to pool index.
4668 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4670 ip_address_pool
[i
].assigned
= 0;
4671 ip_address_pool
[i
].session
= 0;
4672 if (!ip_address_pool
[i
].address
)
4675 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4678 for (i
= 0; i
< MAXSESSION
; ++i
)
4681 if (!(session
[i
].opened
&& session
[i
].ip
))
4684 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4686 if (session
[i
].ip_pool_index
< 0)
4688 // Not allocated out of the pool.
4689 if (ipid
< 1) // Not found in the pool either? good.
4692 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4693 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4695 // Fall through and process it as part of the pool.
4699 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4701 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4703 session
[i
].ip_pool_index
= ipid
;
4707 ip_address_pool
[ipid
].assigned
= 1;
4708 ip_address_pool
[ipid
].session
= i
;
4709 ip_address_pool
[ipid
].last
= time_now
;
4710 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4711 session
[i
].ip_pool_index
= ipid
;
4712 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4717 // Fix the address pool to match a changed session.
4718 // (usually when the master sends us an update).
4719 static void fix_address_pool(int sid
)
4723 ipid
= session
[sid
].ip_pool_index
;
4725 if (ipid
> ip_pool_size
)
4726 return; // Ignore it. rebuild_address_pool will fix it up.
4728 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4729 return; // Just ignore it. rebuild_address_pool will take care of it.
4731 ip_address_pool
[ipid
].assigned
= 1;
4732 ip_address_pool
[ipid
].session
= sid
;
4733 ip_address_pool
[ipid
].last
= time_now
;
4734 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4738 // Add a block of addresses to the IP pool to hand out.
4740 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4744 prefixlen
= 32; // Host route only.
4746 addr
&= 0xffffffff << (32 - prefixlen
);
4748 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4751 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4753 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4754 continue; // Skip 0 and broadcast addresses.
4756 ip_address_pool
[ip_pool_size
].address
= i
;
4757 ip_address_pool
[ip_pool_size
].assigned
= 0;
4759 if (ip_pool_size
>= MAXIPPOOL
)
4761 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4767 // Initialize the IP address pool
4768 static void initippool()
4773 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4775 if (!(f
= fopen(IPPOOLFILE
, "r")))
4777 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4781 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4784 buf
[4095] = 0; // Force it to be zero terminated/
4786 if (*buf
== '#' || *buf
== '\n')
4787 continue; // Skip comments / blank lines
4788 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4789 if ((p
= (char *)strchr(buf
, ':')))
4793 src
= inet_addr(buf
);
4794 if (src
== INADDR_NONE
)
4796 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4799 // This entry is for a specific IP only
4800 if (src
!= config
->bind_address
)
4805 if ((p
= (char *)strchr(pool
, '/')))
4809 in_addr_t start
= 0;
4811 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4813 if (!*p
|| !(numbits
= atoi(p
)))
4815 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4818 start
= ntohl(inet_addr(pool
));
4820 // Add a static route for this pool
4821 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4822 fmtaddr(htonl(start
), 0), numbits
);
4824 routeset(0, start
, numbits
, 0, 1);
4826 add_to_ip_pool(start
, numbits
);
4830 // It's a single ip address
4831 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4835 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4838 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4840 struct sockaddr_in snoop_addr
= {0};
4841 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4844 snoop_addr
.sin_family
= AF_INET
;
4845 snoop_addr
.sin_addr
.s_addr
= destination
;
4846 snoop_addr
.sin_port
= ntohs(port
);
4848 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4849 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4850 htons(snoop_addr
.sin_port
));
4852 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4853 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4855 STAT(packets_snooped
);
4858 static int dump_session(FILE **f
, sessiont
*s
)
4861 if (!s
->opened
|| (!s
->ip
&& !s
->forwardtosession
) || !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4863 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4869 char filename
[1024];
4871 time_t now
= time(NULL
);
4873 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4874 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4876 if (!(*f
= fopen(filename
, "w")))
4878 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4882 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4883 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4888 "# format: username ip qos uptxoctets downrxoctets\n",
4890 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4895 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4896 fprintf(*f
, "%s %s %d %u %u\n",
4897 s
->user
, // username
4898 fmtaddr(htonl(s
->ip
), 0), // ip
4899 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4900 (uint32_t) s
->cin_delta
, // uptxoctets
4901 (uint32_t) s
->cout_delta
); // downrxoctets
4903 s
->cin_delta
= s
->cout_delta
= 0;
4908 static void dump_acct_info(int all
)
4914 CSTAT(dump_acct_info
);
4918 for (i
= 0; i
< shut_acct_n
; i
++)
4919 dump_session(&f
, &shut_acct
[i
]);
4925 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4926 dump_session(&f
, &session
[i
]);
4933 int main(int argc
, char *argv
[])
4937 char *optconfig
= CONFIGFILE
;
4939 time(&basetime
); // start clock
4942 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4947 if (fork()) exit(0);
4949 freopen("/dev/null", "r", stdin
);
4950 freopen("/dev/null", "w", stdout
);
4951 freopen("/dev/null", "w", stderr
);
4960 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4963 printf("Args are:\n"
4964 "\t-d\t\tDetach from terminal\n"
4965 "\t-c <file>\tConfig file\n"
4966 "\t-h <hostname>\tForce hostname\n"
4974 // Start the timer routine off
4976 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4979 initdata(optdebug
, optconfig
);
4983 /* set hostname /after/ having read the config file */
4984 if (*config
->hostname
)
4985 strcpy(hostname
, config
->hostname
);
4986 cli_init_complete(hostname
);
4988 init_tbf(config
->num_tbfs
);
4990 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4991 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4992 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4995 rlim
.rlim_cur
= RLIM_INFINITY
;
4996 rlim
.rlim_max
= RLIM_INFINITY
;
4997 // Remove the maximum core size
4998 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4999 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
5001 // Make core dumps go to /tmp
5005 if (config
->scheduler_fifo
)
5008 struct sched_param params
= {0};
5009 params
.sched_priority
= 1;
5011 if (get_nprocs() < 2)
5013 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
5014 config
->scheduler_fifo
= 0;
5018 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
5020 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
5024 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
5025 config
->scheduler_fifo
= 0;
5032 /* Set up the cluster communications port. */
5033 if (cluster_init() < 0)
5037 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
5045 unsigned seed
= time_now
^ getpid();
5046 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
5050 signal(SIGHUP
, sighup_handler
);
5051 signal(SIGCHLD
, sigchild_handler
);
5052 signal(SIGTERM
, shutdown_handler
);
5053 signal(SIGINT
, shutdown_handler
);
5054 signal(SIGQUIT
, shutdown_handler
);
5056 // Prevent us from getting paged out
5057 if (config
->lock_pages
)
5059 if (!mlockall(MCL_CURRENT
))
5060 LOG(1, 0, 0, "Locking pages into memory\n");
5062 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
5067 /* remove plugins (so cleanup code gets run) */
5070 // Remove the PID file if we wrote it
5071 if (config
->wrote_pid
&& *config
->pid_file
== '/')
5072 unlink(config
->pid_file
);
5074 /* kill CLI children */
5075 signal(SIGTERM
, SIG_IGN
);
5080 static void sighup_handler(int sig
)
5085 static void shutdown_handler(int sig
)
5087 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
5090 static void sigchild_handler(int sig
)
5092 while (waitpid(-1, NULL
, WNOHANG
) > 0)
5096 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
5099 *challenge_response
= NULL
;
5101 if (!*config
->l2tp_secret
)
5103 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
5107 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
5109 *challenge_response
= calloc(17, 1);
5112 MD5_Update(&ctx
, &id
, 1);
5113 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5114 MD5_Update(&ctx
, challenge
, challenge_length
);
5115 MD5_Final(*challenge_response
, &ctx
);
5120 static int facility_value(char *name
)
5123 for (i
= 0; facilitynames
[i
].c_name
; i
++)
5125 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
5126 return facilitynames
[i
].c_val
;
5131 static void update_config()
5135 static int timeout
= 0;
5136 static int interval
= 0;
5143 if (log_stream
!= stderr
)
5149 if (*config
->log_filename
)
5151 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
5153 char *p
= config
->log_filename
+ 7;
5156 openlog("l2tpns", LOG_PID
, facility_value(p
));
5160 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
5162 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
5164 fseek(log_stream
, 0, SEEK_END
);
5165 setbuf(log_stream
, NULL
);
5169 log_stream
= stderr
;
5170 setbuf(log_stream
, NULL
);
5176 log_stream
= stderr
;
5177 setbuf(log_stream
, NULL
);
5180 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
5181 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
5183 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
5184 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
5185 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
5187 // reset MRU/MSS globals
5188 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
5189 if (MRU
> PPPoE_MRU
)
5192 MSS
= MRU
- TCP_HDRS
;
5195 config
->numradiusservers
= 0;
5196 for (i
= 0; i
< MAXRADSERVER
; i
++)
5197 if (config
->radiusserver
[i
])
5199 config
->numradiusservers
++;
5200 // Set radius port: if not set, take the port from the
5201 // first radius server. For the first radius server,
5202 // take the #defined default value from l2tpns.h
5204 // test twice, In case someone works with
5205 // a secondary radius server without defining
5206 // a primary one, this will work even then.
5207 if (i
> 0 && !config
->radiusport
[i
])
5208 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5209 if (!config
->radiusport
[i
])
5210 config
->radiusport
[i
] = RADPORT
;
5213 if (!config
->numradiusservers
)
5214 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5216 // parse radius_authtypes_s
5217 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5218 p
= config
->radius_authtypes_s
;
5221 char *s
= strpbrk(p
, " \t,");
5227 while (*s
== ' ' || *s
== '\t')
5234 if (!strncasecmp("chap", p
, strlen(p
)))
5236 else if (!strncasecmp("pap", p
, strlen(p
)))
5239 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5241 config
->radius_authtypes
|= type
;
5242 if (!config
->radius_authprefer
)
5243 config
->radius_authprefer
= type
;
5248 if (!config
->radius_authtypes
)
5250 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5251 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5254 // normalise radius_authtypes_s
5255 if (config
->radius_authprefer
== AUTHPAP
)
5257 strcpy(config
->radius_authtypes_s
, "pap");
5258 if (config
->radius_authtypes
& AUTHCHAP
)
5259 strcat(config
->radius_authtypes_s
, ", chap");
5263 strcpy(config
->radius_authtypes_s
, "chap");
5264 if (config
->radius_authtypes
& AUTHPAP
)
5265 strcat(config
->radius_authtypes_s
, ", pap");
5268 if (!config
->radius_dae_port
)
5269 config
->radius_dae_port
= DAEPORT
;
5272 if(!config
->bind_portremotelns
)
5273 config
->bind_portremotelns
= L2TPLACPORT
;
5276 // re-initialise the random number source
5277 initrandom(config
->random_device
);
5280 for (i
= 0; i
< MAXPLUGINS
; i
++)
5282 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5285 if (*config
->plugins
[i
])
5288 add_plugin(config
->plugins
[i
]);
5290 else if (*config
->old_plugins
[i
])
5293 remove_plugin(config
->old_plugins
[i
]);
5298 guest_accounts_num
= 0;
5299 char *p2
= config
->guest_user
;
5302 char *s
= strpbrk(p2
, " \t,");
5306 while (*s
== ' ' || *s
== '\t')
5313 strcpy(guest_users
[guest_accounts_num
], p2
);
5314 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5315 guest_accounts_num
++;
5318 // Rebuild the guest_user array
5319 strcpy(config
->guest_user
, "");
5321 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5323 strcat(config
->guest_user
, guest_users
[ui
]);
5324 if (ui
<guest_accounts_num
-1)
5326 strcat(config
->guest_user
, ",");
5331 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5332 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5333 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5334 if (!*config
->cluster_interface
)
5335 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5337 if (!config
->cluster_hb_interval
)
5338 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5340 if (!config
->cluster_hb_timeout
)
5341 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5343 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5345 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5346 // late, ensure we're sufficiently larger than that
5347 int t
= 4 * config
->cluster_hb_interval
+ 11;
5349 if (config
->cluster_hb_timeout
< t
)
5351 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5352 config
->cluster_hb_timeout
= t
;
5355 // Push timing changes to the slaves immediately if we're the master
5356 if (config
->cluster_iam_master
)
5357 cluster_heartbeat();
5359 interval
= config
->cluster_hb_interval
;
5360 timeout
= config
->cluster_hb_timeout
;
5364 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5367 if ((f
= fopen(config
->pid_file
, "w")))
5369 fprintf(f
, "%d\n", getpid());
5371 config
->wrote_pid
= 1;
5375 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5380 static void read_config_file()
5384 if (!config
->config_file
) return;
5385 if (!(f
= fopen(config
->config_file
, "r")))
5387 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5391 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5393 LOG(3, 0, 0, "Done reading config file\n");
5397 int sessionsetup(sessionidt s
, tunnelidt t
)
5399 // A session now exists, set it up
5405 CSTAT(sessionsetup
);
5407 LOG(3, s
, t
, "Doing session setup for session\n");
5409 // Join a bundle if the MRRU option is accepted
5410 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5412 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5413 if (join_bundle(s
) > 0)
5414 cluster_send_bundle(session
[s
].bundle
);
5417 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5418 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5425 assign_ip_address(s
);
5428 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5429 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5432 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5433 fmtaddr(htonl(session
[s
].ip
), 0));
5436 // Make sure this is right
5437 session
[s
].tunnel
= t
;
5439 // zap old sessions with same IP and/or username
5440 // Don't kill gardened sessions - doing so leads to a DoS
5441 // from someone who doesn't need to know the password
5444 user
= session
[s
].user
;
5445 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5447 if (i
== s
) continue;
5448 if (!session
[s
].opened
) break;
5449 // Allow duplicate sessions for multilink ones of the same bundle.
5450 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
) continue;
5452 if (ip
== session
[i
].ip
)
5454 sessionkill(i
, "Duplicate IP address");
5455 cluster_listinvert_session(s
, i
);
5459 if (config
->allow_duplicate_users
) continue;
5460 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5464 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5466 if (!strcasecmp(user
, guest_users
[gu
]))
5472 if (found
) continue;
5474 // Drop the new session in case of duplicate sessionss, not the old one.
5475 if (!strcasecmp(user
, session
[i
].user
))
5476 sessionkill(i
, "Duplicate session for users");
5480 // no need to set a route for the same IP address of the bundle
5481 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5485 // Add the route for this session.
5486 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5488 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5489 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5492 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5495 // Static IPs need to be routed if not already
5496 // convered by a Framed-Route. Anything else is part
5497 // of the IP address pool and is already routed, it
5498 // just needs to be added to the IP cache.
5499 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5500 if (session
[s
].ip_pool_index
== -1) // static ip
5502 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5505 cache_ipmap(session
[s
].ip
, s
);
5508 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5509 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5511 // Run the plugin's against this new session.
5513 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5514 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5517 // Allocate TBFs if throttled
5518 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5519 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5521 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5523 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5524 fmtaddr(htonl(session
[s
].ip
), 0),
5525 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5527 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5529 return 1; // RADIUS OK and IP allocated, done...
5533 // This session just got dropped on us by the master or something.
5534 // Make sure our tables up up to date...
5536 int load_session(sessionidt s
, sessiont
*new)
5542 if (new->ip_pool_index
>= MAXIPPOOL
||
5543 new->tunnel
>= MAXTUNNEL
)
5545 LOG(0, s
, 0, "Strange session update received!\n");
5546 // FIXME! What to do here?
5551 // Ok. All sanity checks passed. Now we're committed to
5552 // loading the new session.
5555 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5557 // See if routes/ip cache need updating
5558 if (new->ip
!= session
[s
].ip
)
5561 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5562 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5563 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5571 // remove old routes...
5572 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5574 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5575 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5578 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5584 if (session
[s
].ip_pool_index
== -1) // static IP
5586 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5588 else // It's part of the IP pool, remove it manually.
5589 uncache_ipmap(session
[s
].ip
);
5594 // add new routes...
5595 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5597 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5598 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5601 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5607 // If there's a new one, add it.
5608 if (new->ip_pool_index
== -1)
5610 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5613 cache_ipmap(new->ip
, s
);
5618 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5619 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5622 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5624 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5628 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5630 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5631 new->filter_out
= 0;
5634 if (new->filter_in
!= session
[s
].filter_in
)
5636 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5637 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5640 if (new->filter_out
!= session
[s
].filter_out
)
5642 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5643 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5646 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5647 // for walking the sessions to forward byte counts to the master.
5648 config
->cluster_highest_sessionid
= s
;
5650 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5652 // Do fixups into address pool.
5653 if (new->ip_pool_index
!= -1)
5654 fix_address_pool(s
);
5659 static void initplugins()
5663 loaded_plugins
= ll_init();
5664 // Initialize the plugins to nothing
5665 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5666 plugins
[i
] = ll_init();
5669 static void *open_plugin(char *plugin_name
, int load
)
5671 char path
[256] = "";
5673 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5674 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5675 return dlopen(path
, RTLD_NOW
);
5678 // plugin callback to get a config value
5679 static void *getconfig(char *key
, enum config_typet type
)
5683 for (i
= 0; config_values
[i
].key
; i
++)
5685 if (!strcmp(config_values
[i
].key
, key
))
5687 if (config_values
[i
].type
== type
)
5688 return ((void *) config
) + config_values
[i
].offset
;
5690 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5691 key
, type
, config_values
[i
].type
);
5697 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5701 static int add_plugin(char *plugin_name
)
5703 static struct pluginfuncs funcs
= {
5708 sessiontbysessionidt
,
5709 sessionidtbysessiont
,
5716 cluster_send_session
,
5719 void *p
= open_plugin(plugin_name
, 1);
5720 int (*initfunc
)(struct pluginfuncs
*);
5725 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5729 if (ll_contains(loaded_plugins
, p
))
5732 return 0; // already loaded
5736 int *v
= dlsym(p
, "plugin_api_version");
5737 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5739 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5745 if ((initfunc
= dlsym(p
, "plugin_init")))
5747 if (!initfunc(&funcs
))
5749 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5755 ll_push(loaded_plugins
, p
);
5757 for (i
= 0; i
< max_plugin_functions
; i
++)
5760 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5762 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5763 ll_push(plugins
[i
], x
);
5767 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5771 static void run_plugin_done(void *plugin
)
5773 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5779 static int remove_plugin(char *plugin_name
)
5781 void *p
= open_plugin(plugin_name
, 0);
5787 if (ll_contains(loaded_plugins
, p
))
5790 for (i
= 0; i
< max_plugin_functions
; i
++)
5793 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5794 ll_delete(plugins
[i
], x
);
5797 ll_delete(loaded_plugins
, p
);
5803 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5807 int run_plugins(int plugin_type
, void *data
)
5809 int (*func
)(void *data
);
5811 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5812 return PLUGIN_RET_ERROR
;
5814 ll_reset(plugins
[plugin_type
]);
5815 while ((func
= ll_next(plugins
[plugin_type
])))
5819 if (r
!= PLUGIN_RET_OK
)
5820 return r
; // stop here
5823 return PLUGIN_RET_OK
;
5826 static void plugins_done()
5830 ll_reset(loaded_plugins
);
5831 while ((p
= ll_next(loaded_plugins
)))
5835 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5837 struct nsctl request
;
5838 struct nsctl response
;
5839 int type
= unpack_control(&request
, buf
, len
);
5843 if (log_stream
&& config
->debug
>= 4)
5847 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5848 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5852 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5853 dump_control(&request
, log_stream
);
5859 case NSCTL_REQ_LOAD
:
5860 if (request
.argc
!= 1)
5862 response
.type
= NSCTL_RES_ERR
;
5864 response
.argv
[0] = "name of plugin required";
5866 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5868 response
.type
= NSCTL_RES_ERR
;
5870 response
.argv
[0] = !r
5871 ? "plugin already loaded"
5872 : "error loading plugin";
5876 response
.type
= NSCTL_RES_OK
;
5882 case NSCTL_REQ_UNLOAD
:
5883 if (request
.argc
!= 1)
5885 response
.type
= NSCTL_RES_ERR
;
5887 response
.argv
[0] = "name of plugin required";
5889 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5891 response
.type
= NSCTL_RES_ERR
;
5893 response
.argv
[0] = !r
5894 ? "plugin not loaded"
5895 : "plugin not found";
5899 response
.type
= NSCTL_RES_OK
;
5905 case NSCTL_REQ_HELP
:
5906 response
.type
= NSCTL_RES_OK
;
5909 ll_reset(loaded_plugins
);
5910 while ((p
= ll_next(loaded_plugins
)))
5912 char **help
= dlsym(p
, "plugin_control_help");
5913 while (response
.argc
< 0xff && help
&& *help
)
5914 response
.argv
[response
.argc
++] = *help
++;
5919 case NSCTL_REQ_CONTROL
:
5921 struct param_control param
= {
5922 config
->cluster_iam_master
,
5929 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5931 if (r
== PLUGIN_RET_ERROR
)
5933 response
.type
= NSCTL_RES_ERR
;
5935 response
.argv
[0] = param
.additional
5937 : "error returned by plugin";
5939 else if (r
== PLUGIN_RET_NOTMASTER
)
5941 static char msg
[] = "must be run on master: 000.000.000.000";
5943 response
.type
= NSCTL_RES_ERR
;
5945 if (config
->cluster_master_address
)
5947 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5948 response
.argv
[0] = msg
;
5952 response
.argv
[0] = "must be run on master: none elected";
5955 else if (!(param
.response
& NSCTL_RESPONSE
))
5957 response
.type
= NSCTL_RES_ERR
;
5959 response
.argv
[0] = param
.response
5960 ? "unrecognised response value from plugin"
5961 : "unhandled action";
5965 response
.type
= param
.response
;
5967 if (param
.additional
)
5970 response
.argv
[0] = param
.additional
;
5978 response
.type
= NSCTL_RES_ERR
;
5980 response
.argv
[0] = "error unpacking control packet";
5983 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5986 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5990 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5993 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5994 if (log_stream
&& config
->debug
>= 4)
5996 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5997 dump_control(&response
, log_stream
);
6001 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
6002 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
6007 static tunnelidt
new_tunnel()
6010 for (i
= 1; i
< MAXTUNNEL
; i
++)
6012 if (tunnel
[i
].state
== TUNNELFREE
)
6014 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
6015 if (i
> config
->cluster_highest_tunnelid
)
6016 config
->cluster_highest_tunnelid
= i
;
6020 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
6025 // We're becoming the master. Do any required setup..
6027 // This is principally telling all the plugins that we're
6028 // now a master, and telling them about all the sessions
6029 // that are active too..
6031 void become_master(void)
6034 static struct event_data d
[RADIUS_FDS
];
6035 struct epoll_event e
;
6037 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
6039 // running a bunch of iptables commands is slow and can cause
6040 // the master to drop tunnels on takeover--kludge around the
6041 // problem by forking for the moment (note: race)
6042 if (!fork_and_close())
6044 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6046 if (!session
[s
].opened
) // Not an in-use session.
6049 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
6056 for (i
= 0; i
< RADIUS_FDS
; i
++)
6058 d
[i
].type
= FD_TYPE_RADIUS
;
6062 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
6066 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6072 if (CLI_HELP_REQUESTED
)
6073 return CLI_HELP_NO_ARGS
;
6076 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6078 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6081 if (!session
[s
].opened
)
6084 idle
= time_now
- session
[s
].last_data
;
6085 idle
/= 5 ; // In multiples of 5 seconds.
6095 for (i
= 0; i
< 63; ++i
)
6097 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6099 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
6100 cli_print(cli
, "%d total sessions open.", count
);
6104 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
6110 if (CLI_HELP_REQUESTED
)
6111 return CLI_HELP_NO_ARGS
;
6114 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
6116 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
6119 if (!session
[s
].opened
)
6122 d
= time_now
- session
[s
].opened
;
6125 while (d
> 1 && open
< 32)
6135 for (i
= 0; i
< 30; ++i
)
6137 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
6140 cli_print(cli
, "%d total sessions open.", count
);
6146 * This unencodes the AVP using the L2TP secret and the previously
6147 * stored random vector. It overwrites the hidden data with the
6148 * unhidden AVP subformat.
6150 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
6156 uint16_t m
= htons(type
);
6158 // Compute initial pad
6160 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
6161 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6162 MD5_Update(&ctx
, vector
, vec_len
);
6163 MD5_Final(digest
, &ctx
);
6165 // pointer to last decoded 16 octets
6170 // calculate a new pad based on the last decoded block
6171 if (d
>= sizeof(digest
))
6174 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
6175 MD5_Update(&ctx
, last
, sizeof(digest
));
6176 MD5_Final(digest
, &ctx
);
6182 *value
++ ^= digest
[d
++];
6187 int find_filter(char const *name
, size_t len
)
6192 for (i
= 0; i
< MAXFILTER
; i
++)
6194 if (!*ip_filters
[i
].name
)
6202 if (strlen(ip_filters
[i
].name
) != len
)
6205 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6212 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6216 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6217 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6218 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6219 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6220 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6226 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6230 case FILTER_FLAG_OP_ANY
:
6231 return (flags
& sflags
) || (~flags
& cflags
);
6233 case FILTER_FLAG_OP_ALL
:
6234 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6236 case FILTER_FLAG_OP_EST
:
6237 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6243 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6245 uint16_t frag_offset
;
6249 uint16_t src_port
= 0;
6250 uint16_t dst_port
= 0;
6252 ip_filter_rulet
*rule
;
6254 if (len
< 20) // up to end of destination address
6257 if ((*buf
>> 4) != 4) // IPv4
6260 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6262 src_ip
= *(in_addr_t
*) (buf
+ 12);
6263 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6265 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6267 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6268 if (len
< l
+ 4) // ports
6271 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6272 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6273 if (proto
== IPPROTO_TCP
)
6275 if (len
< l
+ 14) // flags
6278 flags
= buf
[l
+ 13] & 0x3f;
6282 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6284 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6287 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6288 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6291 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6292 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6297 // layer 4 deny rules are skipped
6298 if (rule
->action
== FILTER_ACTION_DENY
&&
6299 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6307 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6309 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6312 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6315 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6316 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6323 return rule
->action
== FILTER_ACTION_PERMIT
;
6332 tunnelidt
lac_new_tunnel()
6334 return new_tunnel();
6337 void lac_tunnelclear(tunnelidt t
)
6342 void lac_send_SCCRQ(tunnelidt t
, uint8_t * auth
, unsigned int auth_len
)
6344 uint16_t version
= 0x0100; // protocol version
6346 tunnel
[t
].state
= TUNNELOPENING
;
6348 // Sent SCCRQ - Start Control Connection Request
6349 controlt
*c
= controlnew(1); // sending SCCRQ
6350 controls(c
, 7, hostname
, 1); // host name
6351 controls(c
, 8, Vendor_name
, 1); // Vendor name
6352 control16(c
, 2, version
, 1); // protocol version
6353 control32(c
, 3, 3, 1); // framing Capabilities
6354 control16(c
, 9, t
, 1); // assigned tunnel
6355 controlb(c
, 11, (uint8_t *) auth
, auth_len
, 1); // CHAP Challenge
6356 LOG(3, 0, t
, "Sent SCCRQ to REMOTE LNS\n");
6357 controladd(c
, 0, t
); // send
6360 void lac_send_ICRQ(tunnelidt t
, sessionidt s
)
6362 // Sent ICRQ Incoming-call-request
6363 controlt
*c
= controlnew(10); // ICRQ
6365 control16(c
, 14, s
, 1); // assigned sesion
6366 call_serial_number
++;
6367 control32(c
, 15, call_serial_number
, 1); // call serial number
6368 LOG(3, s
, t
, "Sent ICRQ to REMOTE LNS (far ID %u)\n", tunnel
[t
].far
);
6369 controladd(c
, 0, t
); // send
6372 void lac_tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
6374 tunnelshutdown(t
, reason
, result
, error
, msg
);