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"
57 configt
*config
= NULL
; // all configuration
58 int nlfd
= -1; // netlink socket
59 int tunfd
= -1; // tun interface file handle. (network device)
60 int udpfd
= -1; // UDP file handle
61 int controlfd
= -1; // Control signal handle
62 int clifd
= -1; // Socket listening for CLI connections.
63 int daefd
= -1; // Socket listening for DAE connections.
64 int snoopfd
= -1; // UDP file handle for sending out intercept data
65 int *radfds
= NULL
; // RADIUS requests file handles
66 int rand_fd
= -1; // Random data source
67 int cluster_sockfd
= -1; // Intra-cluster communications socket.
68 int epollfd
= -1; // event polling
69 time_t basetime
= 0; // base clock
70 char hostname
[MAXHOSTNAME
] = ""; // us.
71 static int tunidx
; // ifr_ifindex of tun device
72 int nlseqnum
= 0; // netlink sequence number
73 int min_initok_nlseqnum
= 0; // minimun seq number for messages after init is ok
74 static int syslog_log
= 0; // are we logging to syslog
75 static FILE *log_stream
= 0; // file handle for direct logging (i.e. direct into file, not via syslog).
76 uint32_t last_id
= 0; // Unique ID for radius accounting
78 char guest_users
[10][32]; // Array of guest users
79 int guest_accounts_num
= 0; // Number of guest users
81 // calculated from config->l2tp_mtu
82 uint16_t MRU
= 0; // PPP MRU
83 uint16_t MSS
= 0; // TCP MSS
85 struct cli_session_actions
*cli_session_actions
= NULL
; // Pending session changes requested by CLI
86 struct cli_tunnel_actions
*cli_tunnel_actions
= NULL
; // Pending tunnel changes required by CLI
91 } ip_hash
[256]; // Mapping from IP address to session structures.
95 struct ipv6radix
*branch
;
96 } ipv6_hash
[256]; // Mapping from IPv6 address to session structures.
99 static uint32_t udp_rx
= 0, udp_rx_pkt
= 0, udp_tx
= 0;
100 static uint32_t eth_rx
= 0, eth_rx_pkt
= 0;
103 static uint32_t ip_pool_size
= 1; // Size of the pool of addresses used for dynamic address allocation.
104 time_t time_now
= 0; // Current time in seconds since epoch.
105 uint64_t time_now_ms
= 0; // Current time in milliseconds since epoch.
106 static char time_now_string
[64] = {0}; // Current time as a string.
107 static int time_changed
= 0; // time_now changed
108 char main_quit
= 0; // True if we're in the process of exiting.
109 static char main_reload
= 0; // Re-load pending
110 linked_list
*loaded_plugins
;
111 linked_list
*plugins
[MAX_PLUGIN_TYPES
];
113 #define membersize(STRUCT, MEMBER) sizeof(((STRUCT *)0)->MEMBER)
114 #define CONFIG(NAME, MEMBER, TYPE) { NAME, offsetof(configt, MEMBER), membersize(configt, MEMBER), TYPE }
116 config_descriptt config_values
[] = {
117 CONFIG("debug", debug
, INT
),
118 CONFIG("log_file", log_filename
, STRING
),
119 CONFIG("pid_file", pid_file
, STRING
),
120 CONFIG("random_device", random_device
, STRING
),
121 CONFIG("l2tp_secret", l2tp_secret
, STRING
),
122 CONFIG("l2tp_mtu", l2tp_mtu
, INT
),
123 CONFIG("ppp_restart_time", ppp_restart_time
, INT
),
124 CONFIG("ppp_max_configure", ppp_max_configure
, INT
),
125 CONFIG("ppp_max_failure", ppp_max_failure
, INT
),
126 CONFIG("primary_dns", default_dns1
, IPv4
),
127 CONFIG("secondary_dns", default_dns2
, IPv4
),
128 CONFIG("primary_radius", radiusserver
[0], IPv4
),
129 CONFIG("secondary_radius", radiusserver
[1], IPv4
),
130 CONFIG("primary_radius_port", radiusport
[0], SHORT
),
131 CONFIG("secondary_radius_port", radiusport
[1], SHORT
),
132 CONFIG("radius_accounting", radius_accounting
, BOOL
),
133 CONFIG("radius_interim", radius_interim
, INT
),
134 CONFIG("radius_secret", radiussecret
, STRING
),
135 CONFIG("radius_authtypes", radius_authtypes_s
, STRING
),
136 CONFIG("radius_dae_port", radius_dae_port
, SHORT
),
137 CONFIG("radius_bind_min", radius_bind_min
, SHORT
),
138 CONFIG("radius_bind_max", radius_bind_max
, SHORT
),
139 CONFIG("allow_duplicate_users", allow_duplicate_users
, BOOL
),
140 CONFIG("kill_timedout_sessions", kill_timedout_sessions
, BOOL
),
141 CONFIG("guest_account", guest_user
, STRING
),
142 CONFIG("bind_address", bind_address
, IPv4
),
143 CONFIG("peer_address", peer_address
, IPv4
),
144 CONFIG("send_garp", send_garp
, BOOL
),
145 CONFIG("throttle_speed", rl_rate
, UNSIGNED_LONG
),
146 CONFIG("throttle_buckets", num_tbfs
, INT
),
147 CONFIG("accounting_dir", accounting_dir
, STRING
),
148 CONFIG("dump_speed", dump_speed
, BOOL
),
149 CONFIG("multi_read_count", multi_read_count
, INT
),
150 CONFIG("scheduler_fifo", scheduler_fifo
, BOOL
),
151 CONFIG("lock_pages", lock_pages
, BOOL
),
152 CONFIG("icmp_rate", icmp_rate
, INT
),
153 CONFIG("packet_limit", max_packets
, INT
),
154 CONFIG("cluster_address", cluster_address
, IPv4
),
155 CONFIG("cluster_interface", cluster_interface
, STRING
),
156 CONFIG("cluster_mcast_ttl", cluster_mcast_ttl
, INT
),
157 CONFIG("cluster_hb_interval", cluster_hb_interval
, INT
),
158 CONFIG("cluster_hb_timeout", cluster_hb_timeout
, INT
),
159 CONFIG("cluster_master_min_adv", cluster_master_min_adv
, INT
),
160 CONFIG("ipv6_prefix", ipv6_prefix
, IPv6
),
161 CONFIG("cli_bind_address", cli_bind_address
, IPv4
),
162 CONFIG("hostname", hostname
, STRING
),
163 CONFIG("nexthop_address", nexthop_address
, IPv4
),
164 CONFIG("nexthop6_address", nexthop6_address
, IPv6
),
168 static char *plugin_functions
[] = {
173 "plugin_new_session",
174 "plugin_kill_session",
176 "plugin_radius_response",
177 "plugin_radius_reset",
178 "plugin_radius_account",
179 "plugin_become_master",
180 "plugin_new_session_master",
183 #define max_plugin_functions (sizeof(plugin_functions) / sizeof(char *))
185 // Counters for shutdown sessions
186 static sessiont shut_acct
[8192];
187 static sessionidt shut_acct_n
= 0;
189 tunnelt
*tunnel
= NULL
; // Array of tunnel structures.
190 bundlet
*bundle
= NULL
; // Array of bundle structures.
191 fragmentationt
*frag
= NULL
; // Array of fragmentation structures.
192 sessiont
*session
= NULL
; // Array of session structures.
193 sessionlocalt
*sess_local
= NULL
; // Array of local per-session counters.
194 radiust
*radius
= NULL
; // Array of radius structures.
195 ippoolt
*ip_address_pool
= NULL
; // Array of dynamic IP addresses.
196 ip_filtert
*ip_filters
= NULL
; // Array of named filters.
197 static controlt
*controlfree
= 0;
198 struct Tstats
*_statistics
= NULL
;
200 struct Tringbuffer
*ringbuffer
= NULL
;
203 static ssize_t
netlink_send(struct nlmsghdr
*nh
);
204 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
);
205 static void cache_ipmap(in_addr_t ip
, sessionidt s
);
206 static void uncache_ipmap(in_addr_t ip
);
207 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
);
208 static void free_ip_address(sessionidt s
);
209 static void dump_acct_info(int all
);
210 static void sighup_handler(int sig
);
211 static void shutdown_handler(int sig
);
212 static void sigchild_handler(int sig
);
213 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
);
214 static void update_config(void);
215 static void read_config_file(void);
216 static void initplugins(void);
217 static int add_plugin(char *plugin_name
);
218 static int remove_plugin(char *plugin_name
);
219 static void plugins_done(void);
220 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
);
221 static tunnelidt
new_tunnel(void);
222 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
);
223 static void bundleclear(bundleidt b
);
225 // on slaves, alow BGP to withdraw cleanly before exiting
228 // quit actions (master)
229 #define QUIT_FAILOVER 1 // SIGTERM: exit when all control messages have been acked (for cluster failover)
230 #define QUIT_SHUTDOWN 2 // SIGQUIT: shutdown sessions/tunnels, reject new connections
232 // return internal time (10ths since process startup), set f if given
233 // as a side-effect sets time_now, and time_changed
234 static clockt
now(double *f
)
238 if (f
) *f
= t
.tv_sec
+ t
.tv_usec
/ 1000000.0;
239 if (t
.tv_sec
!= time_now
)
245 // Time in milliseconds
246 time_now_ms
= (t
.tv_sec
* 1000) + (t
.tv_usec
/1000);
248 return (t
.tv_sec
- basetime
) * 10 + t
.tv_usec
/ 100000 + 1;
251 // work out a retry time based on try number
252 // This is a straight bounded exponential backoff.
253 // Maximum re-try time is 32 seconds. (2^5).
254 clockt
backoff(uint8_t try)
256 if (try > 5) try = 5; // max backoff
257 return now(NULL
) + 10 * (1 << try);
262 // Log a debug message. Typically called via the LOG macro
264 void _log(int level
, sessionidt s
, tunnelidt t
, const char *format
, ...)
266 static char message
[65536] = {0};
272 if (++ringbuffer
->tail
>= RINGBUFFER_SIZE
)
273 ringbuffer
->tail
= 0;
274 if (ringbuffer
->tail
== ringbuffer
->head
)
275 if (++ringbuffer
->head
>= RINGBUFFER_SIZE
)
276 ringbuffer
->head
= 0;
278 ringbuffer
->buffer
[ringbuffer
->tail
].level
= level
;
279 ringbuffer
->buffer
[ringbuffer
->tail
].session
= s
;
280 ringbuffer
->buffer
[ringbuffer
->tail
].tunnel
= t
;
281 va_start(ap
, format
);
282 vsnprintf(ringbuffer
->buffer
[ringbuffer
->tail
].message
, 4095, format
, ap
);
287 if (config
->debug
< level
) return;
289 va_start(ap
, format
);
290 vsnprintf(message
, sizeof(message
), format
, ap
);
293 fprintf(log_stream
, "%s %02d/%02d %s", time_now_string
, t
, s
, message
);
295 syslog(level
+ 2, "%02d/%02d %s", t
, s
, message
); // We don't need LOG_EMERG or LOG_ALERT
300 void _log_hex(int level
, const char *title
, const uint8_t *data
, int maxsize
)
303 const uint8_t *d
= data
;
305 if (config
->debug
< level
) return;
307 // No support for _log_hex to syslog
310 _log(level
, 0, 0, "%s (%d bytes):\n", title
, maxsize
);
311 setvbuf(log_stream
, NULL
, _IOFBF
, 16384);
313 for (i
= 0; i
< maxsize
; )
315 fprintf(log_stream
, "%4X: ", i
);
316 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
318 fprintf(log_stream
, "%02X ", d
[j
]);
320 fputs(": ", log_stream
);
323 for (; j
< i
+ 16; j
++)
325 fputs(" ", log_stream
);
327 fputs(": ", log_stream
);
330 fputs(" ", log_stream
);
331 for (j
= i
; j
< maxsize
&& j
< (i
+ 16); j
++)
333 if (d
[j
] >= 0x20 && d
[j
] < 0x7f && d
[j
] != 0x20)
334 fputc(d
[j
], log_stream
);
336 fputc('.', log_stream
);
339 fputs(" ", log_stream
);
343 fputs("\n", log_stream
);
347 setbuf(log_stream
, NULL
);
351 // update a counter, accumulating 2^32 wraps
352 void increment_counter(uint32_t *counter
, uint32_t *wrap
, uint32_t delta
)
354 uint32_t new = *counter
+ delta
;
361 // initialise the random generator
362 static void initrandom(char *source
)
364 static char path
[sizeof(config
->random_device
)] = "*undefined*";
366 // reinitialise only if we are forced to do so or if the config has changed
367 if (source
&& !strncmp(path
, source
, sizeof(path
)))
370 // close previous source, if any
379 snprintf(path
, sizeof(path
), "%s", source
);
383 rand_fd
= open(path
, O_RDONLY
|O_NONBLOCK
);
385 LOG(0, 0, 0, "Error opening the random device %s: %s\n",
386 path
, strerror(errno
));
391 // fill buffer with random data
392 void random_data(uint8_t *buf
, int len
)
399 n
= read(rand_fd
, buf
, len
);
400 if (n
>= len
) return;
405 LOG(0, 0, 0, "Error reading from random source: %s\n",
408 // fall back to rand()
416 // append missing data
418 // not using the low order bits from the prng stream
419 buf
[n
++] = (rand() >> 4) & 0xff;
424 // This adds it to the routing table, advertises it
425 // via BGP if enabled, and stuffs it into the
426 // 'sessionbyip' cache.
428 // 'ip' must be in _host_ order.
430 static void routeset(sessionidt s
, in_addr_t ip
, int prefixlen
, in_addr_t gw
, int add
)
440 if (!prefixlen
) prefixlen
= 32;
442 ip
&= 0xffffffff << (32 - prefixlen
);; // Force the ip to be the first one in the route.
444 memset(&req
, 0, sizeof(req
));
448 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
449 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
453 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
454 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
457 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
459 req
.rt
.rtm_family
= AF_INET
;
460 req
.rt
.rtm_dst_len
= prefixlen
;
461 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
462 req
.rt
.rtm_protocol
= 42;
463 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
464 req
.rt
.rtm_type
= RTN_UNICAST
;
466 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
468 netlink_addattr(&req
.nh
, RTA_DST
, &n_ip
, sizeof(n_ip
));
472 netlink_addattr(&req
.nh
, RTA_GATEWAY
, &n_ip
, sizeof(n_ip
));
475 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d%s%s\n", add
? "add" : "del",
476 fmtaddr(htonl(ip
), 0), prefixlen
,
477 gw
? " via" : "", gw
? fmtaddr(htonl(gw
), 2) : "");
479 if (netlink_send(&req
.nh
) < 0)
480 LOG(0, 0, 0, "routeset() error in sending netlink message: %s\n", strerror(errno
));
484 bgp_add_route(htonl(ip
), prefixlen
);
486 bgp_del_route(htonl(ip
), prefixlen
);
489 // Add/Remove the IPs to the 'sessionbyip' cache.
490 // Note that we add the zero address in the case of
491 // a network route. Roll on CIDR.
493 // Note that 's == 0' implies this is the address pool.
494 // We still cache it here, because it will pre-fill
495 // the malloc'ed tree.
499 if (!add
) // Are we deleting a route?
500 s
= 0; // Caching the session as '0' is the same as uncaching.
502 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
507 void route6set(sessionidt s
, struct in6_addr ip
, int prefixlen
, int add
)
515 char ipv6addr
[INET6_ADDRSTRLEN
];
517 if (!config
->ipv6_prefix
.s6_addr
[0])
519 LOG(0, 0, 0, "Asked to set IPv6 route, but IPv6 not setup.\n");
523 memset(&req
, 0, sizeof(req
));
527 req
.nh
.nlmsg_type
= RTM_NEWROUTE
;
528 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
;
532 req
.nh
.nlmsg_type
= RTM_DELROUTE
;
533 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
;
536 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.rt
));
538 req
.rt
.rtm_family
= AF_INET6
;
539 req
.rt
.rtm_dst_len
= prefixlen
;
540 req
.rt
.rtm_table
= RT_TABLE_MAIN
;
541 req
.rt
.rtm_protocol
= 42;
542 req
.rt
.rtm_scope
= RT_SCOPE_LINK
;
543 req
.rt
.rtm_type
= RTN_UNICAST
;
545 netlink_addattr(&req
.nh
, RTA_OIF
, &tunidx
, sizeof(int));
546 netlink_addattr(&req
.nh
, RTA_DST
, &ip
, sizeof(ip
));
548 netlink_addattr(&req
.nh
, RTA_METRICS
, &metric
, sizeof(metric
));
550 LOG(1, s
, session
[s
].tunnel
, "Route %s %s/%d\n",
552 inet_ntop(AF_INET6
, &ip
, ipv6addr
, INET6_ADDRSTRLEN
),
555 if (netlink_send(&req
.nh
) < 0)
556 LOG(0, 0, 0, "route6set() error in sending netlink message: %s\n", strerror(errno
));
560 bgp_add_route6(ip
, prefixlen
);
562 bgp_del_route6(ip
, prefixlen
);
567 if (!add
) // Are we deleting a route?
568 s
= 0; // Caching the session as '0' is the same as uncaching.
570 cache_ipv6map(ip
, prefixlen
, s
);
577 // Set up netlink socket
578 static void initnetlink(void)
580 struct sockaddr_nl nladdr
;
582 nlfd
= socket(AF_NETLINK
, SOCK_RAW
, NETLINK_ROUTE
);
585 LOG(0, 0, 0, "Can't create netlink socket: %s\n", strerror(errno
));
589 memset(&nladdr
, 0, sizeof(nladdr
));
590 nladdr
.nl_family
= AF_NETLINK
;
591 nladdr
.nl_pid
= getpid();
593 if (bind(nlfd
, (struct sockaddr
*)&nladdr
, sizeof(nladdr
)) < 0)
595 LOG(0, 0, 0, "Can't bind netlink socket: %s\n", strerror(errno
));
600 static ssize_t
netlink_send(struct nlmsghdr
*nh
)
602 struct sockaddr_nl nladdr
;
606 nh
->nlmsg_pid
= getpid();
607 nh
->nlmsg_seq
= ++nlseqnum
;
609 // set kernel address
610 memset(&nladdr
, 0, sizeof(nladdr
));
611 nladdr
.nl_family
= AF_NETLINK
;
613 iov
= (struct iovec
){ (void *)nh
, nh
->nlmsg_len
};
614 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
616 return sendmsg(nlfd
, &msg
, 0);
619 static ssize_t
netlink_recv(void *buf
, ssize_t len
)
621 struct sockaddr_nl nladdr
;
625 // set kernel address
626 memset(&nladdr
, 0, sizeof(nladdr
));
627 nladdr
.nl_family
= AF_NETLINK
;
629 iov
= (struct iovec
){ buf
, len
};
630 msg
= (struct msghdr
){ (void *)&nladdr
, sizeof(nladdr
), &iov
, 1, NULL
, 0, 0 };
632 return recvmsg(nlfd
, &msg
, 0);
635 /* adapted from iproute2 */
636 static void netlink_addattr(struct nlmsghdr
*nh
, int type
, const void *data
, int alen
)
638 int len
= RTA_LENGTH(alen
);
641 rta
= (struct rtattr
*)(((void *)nh
) + NLMSG_ALIGN(nh
->nlmsg_len
));
642 rta
->rta_type
= type
;
644 memcpy(RTA_DATA(rta
), data
, alen
);
645 nh
->nlmsg_len
= NLMSG_ALIGN(nh
->nlmsg_len
) + RTA_ALIGN(len
);
648 // messages corresponding to different phases seq number
649 static char *tun_nl_phase_msg
[] = {
651 "getting tun interface index",
652 "setting tun interface parameters",
653 "setting tun IPv4 address",
654 "setting tun LL IPv6 address",
655 "setting tun global IPv6 address",
659 // Set up TUN interface
660 static void inittun(void)
664 memset(&ifr
, 0, sizeof(ifr
));
665 ifr
.ifr_flags
= IFF_TUN
;
667 tunfd
= open(TUNDEVICE
, O_RDWR
);
670 LOG(0, 0, 0, "Can't open %s: %s\n", TUNDEVICE
, strerror(errno
));
674 int flags
= fcntl(tunfd
, F_GETFL
, 0);
675 fcntl(tunfd
, F_SETFL
, flags
| O_NONBLOCK
);
677 if (ioctl(tunfd
, TUNSETIFF
, (void *) &ifr
) < 0)
679 LOG(0, 0, 0, "Can't set tun interface: %s\n", strerror(errno
));
682 assert(strlen(ifr
.ifr_name
) < sizeof(config
->tundevice
) - 1);
683 strncpy(config
->tundevice
, ifr
.ifr_name
, sizeof(config
->tundevice
));
685 tunidx
= if_nametoindex(config
->tundevice
);
688 LOG(0, 0, 0, "Can't get tun interface index\n");
697 struct ifinfomsg ifinfo
;
698 struct ifaddrmsg ifaddr
;
700 char rtdata
[32]; // 32 should be enough
702 uint32_t txqlen
, mtu
;
705 memset(&req
, 0, sizeof(req
));
707 req
.nh
.nlmsg_type
= RTM_NEWLINK
;
708 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_MULTI
;
709 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifinfo
));
711 req
.ifmsg
.ifinfo
.ifi_family
= AF_UNSPEC
;
712 req
.ifmsg
.ifinfo
.ifi_index
= tunidx
;
713 req
.ifmsg
.ifinfo
.ifi_flags
|= IFF_UP
; // set interface up
714 req
.ifmsg
.ifinfo
.ifi_change
= IFF_UP
; // only change this flag
716 /* Bump up the qlen to deal with bursts from the network */
718 netlink_addattr(&req
.nh
, IFLA_TXQLEN
, &txqlen
, sizeof(txqlen
));
719 /* set MTU to modem MRU */
721 netlink_addattr(&req
.nh
, IFLA_MTU
, &mtu
, sizeof(mtu
));
723 if (netlink_send(&req
.nh
) < 0)
726 memset(&req
, 0, sizeof(req
));
728 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
729 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
730 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
732 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET
;
733 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 32;
734 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
735 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
737 if (config
->bind_address
)
738 ip
= config
->bind_address
;
740 ip
= 0x01010101; // 1.1.1.1
741 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip
, sizeof(ip
));
743 if (netlink_send(&req
.nh
) < 0)
746 // Only setup IPv6 on the tun device if we have a configured prefix
747 if (config
->ipv6_prefix
.s6_addr
[0]) {
750 memset(&req
, 0, sizeof(req
));
752 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
753 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
754 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
756 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
757 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
758 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_LINK
;
759 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
761 // Link local address is FE80::1
762 memset(&ip6
, 0, sizeof(ip6
));
763 ip6
.s6_addr
[0] = 0xFE;
764 ip6
.s6_addr
[1] = 0x80;
766 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
768 if (netlink_send(&req
.nh
) < 0)
771 memset(&req
, 0, sizeof(req
));
773 req
.nh
.nlmsg_type
= RTM_NEWADDR
;
774 req
.nh
.nlmsg_flags
= NLM_F_REQUEST
| NLM_F_CREATE
| NLM_F_REPLACE
| NLM_F_MULTI
;
775 req
.nh
.nlmsg_len
= NLMSG_LENGTH(sizeof(req
.ifmsg
.ifaddr
));
777 req
.ifmsg
.ifaddr
.ifa_family
= AF_INET6
;
778 req
.ifmsg
.ifaddr
.ifa_prefixlen
= 64;
779 req
.ifmsg
.ifaddr
.ifa_scope
= RT_SCOPE_UNIVERSE
;
780 req
.ifmsg
.ifaddr
.ifa_index
= tunidx
;
782 // Global address is prefix::1
783 ip6
= config
->ipv6_prefix
;
785 netlink_addattr(&req
.nh
, IFA_LOCAL
, &ip6
, sizeof(ip6
));
787 if (netlink_send(&req
.nh
) < 0)
791 memset(&req
, 0, sizeof(req
));
793 req
.nh
.nlmsg_type
= NLMSG_DONE
;
794 req
.nh
.nlmsg_len
= NLMSG_LENGTH(0);
796 if (netlink_send(&req
.nh
) < 0)
799 // if we get an error for seqnum < min_initok_nlseqnum,
800 // we must exit as initialization went wrong
801 if (config
->ipv6_prefix
.s6_addr
[0])
802 min_initok_nlseqnum
= 5 + 1; // idx + if + addr + 2*addr6
804 min_initok_nlseqnum
= 3 + 1; // idx + if + addr
810 LOG(0, 0, 0, "Error while setting up tun device: %s\n", strerror(errno
));
815 static void initudp(void)
818 struct sockaddr_in addr
;
821 memset(&addr
, 0, sizeof(addr
));
822 addr
.sin_family
= AF_INET
;
823 addr
.sin_port
= htons(L2TPPORT
);
824 addr
.sin_addr
.s_addr
= config
->bind_address
;
825 udpfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
826 setsockopt(udpfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
828 int flags
= fcntl(udpfd
, F_GETFL
, 0);
829 fcntl(udpfd
, F_SETFL
, flags
| O_NONBLOCK
);
831 if (bind(udpfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
833 LOG(0, 0, 0, "Error in UDP bind: %s\n", strerror(errno
));
838 memset(&addr
, 0, sizeof(addr
));
839 addr
.sin_family
= AF_INET
;
840 addr
.sin_port
= htons(NSCTL_PORT
);
841 controlfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
842 setsockopt(controlfd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
843 setsockopt(controlfd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
844 if (bind(controlfd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
846 LOG(0, 0, 0, "Error in control bind: %s\n", strerror(errno
));
850 // Dynamic Authorization Extensions to RADIUS
851 memset(&addr
, 0, sizeof(addr
));
852 addr
.sin_family
= AF_INET
;
853 addr
.sin_port
= htons(config
->radius_dae_port
);
854 daefd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
855 setsockopt(daefd
, SOL_SOCKET
, SO_REUSEADDR
, &on
, sizeof(on
));
856 setsockopt(daefd
, SOL_IP
, IP_PKTINFO
, &on
, sizeof(on
)); // recvfromto
857 if (bind(daefd
, (struct sockaddr
*) &addr
, sizeof(addr
)) < 0)
859 LOG(0, 0, 0, "Error in DAE bind: %s\n", strerror(errno
));
864 snoopfd
= socket(AF_INET
, SOCK_DGRAM
, IPPROTO_UDP
);
868 // Find session by IP, < 1 for not found
870 // Confusingly enough, this 'ip' must be
871 // in _network_ order. This being the common
872 // case when looking it up from IP packet headers.
874 // We actually use this cache for two things.
875 // #1. For used IP addresses, this maps to the
876 // session ID that it's used by.
877 // #2. For un-used IP addresses, this maps to the
878 // index into the pool table that contains that
882 static sessionidt
lookup_ipmap(in_addr_t ip
)
884 uint8_t *a
= (uint8_t *) &ip
;
885 union iphash
*h
= ip_hash
;
887 if (!(h
= h
[*a
++].idx
)) return 0;
888 if (!(h
= h
[*a
++].idx
)) return 0;
889 if (!(h
= h
[*a
++].idx
)) return 0;
894 static sessionidt
lookup_ipv6map(struct in6_addr ip
)
896 struct ipv6radix
*curnode
;
899 char ipv6addr
[INET6_ADDRSTRLEN
];
901 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
905 while (s
== 0 && i
< 15 && curnode
->branch
!= NULL
)
907 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
912 LOG(4, s
, session
[s
].tunnel
, "Looking up address %s and got %d\n",
913 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
920 sessionidt
sessionbyip(in_addr_t ip
)
922 sessionidt s
= lookup_ipmap(ip
);
925 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
931 sessionidt
sessionbyipv6(struct in6_addr ip
)
934 CSTAT(sessionbyipv6
);
936 if (!memcmp(&config
->ipv6_prefix
, &ip
, 8) ||
937 (ip
.s6_addr
[0] == 0xFE &&
938 ip
.s6_addr
[1] == 0x80 &&
939 ip
.s6_addr16
[1] == 0 &&
940 ip
.s6_addr16
[2] == 0 &&
941 ip
.s6_addr16
[3] == 0)) {
942 s
= lookup_ipmap(*(in_addr_t
*) &ip
.s6_addr
[8]);
944 s
= lookup_ipv6map(ip
);
947 if (s
> 0 && s
< MAXSESSION
&& session
[s
].opened
)
954 // Take an IP address in HOST byte order and
955 // add it to the sessionid by IP cache.
957 // (It's actually cached in network order)
959 static void cache_ipmap(in_addr_t ip
, sessionidt s
)
961 in_addr_t nip
= htonl(ip
); // MUST be in network order. I.e. MSB must in be ((char *) (&ip))[0]
962 uint8_t *a
= (uint8_t *) &nip
;
963 union iphash
*h
= ip_hash
;
966 for (i
= 0; i
< 3; i
++)
968 if (!(h
[a
[i
]].idx
|| (h
[a
[i
]].idx
= calloc(256, sizeof(union iphash
)))))
977 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s\n", fmtaddr(nip
, 0));
980 LOG(4, 0, 0, "Un-caching ip address %s\n", fmtaddr(nip
, 0));
981 // else a map to an ip pool index.
984 static void uncache_ipmap(in_addr_t ip
)
986 cache_ipmap(ip
, 0); // Assign it to the NULL session.
989 static void cache_ipv6map(struct in6_addr ip
, int prefixlen
, sessionidt s
)
993 struct ipv6radix
*curnode
;
994 char ipv6addr
[INET6_ADDRSTRLEN
];
996 curnode
= &ipv6_hash
[ip
.s6_addr
[0]];
998 bytes
= prefixlen
>> 3;
1001 if (curnode
->branch
== NULL
)
1003 if (!(curnode
->branch
= calloc(256,
1004 sizeof (struct ipv6radix
))))
1007 curnode
= &curnode
->branch
[ip
.s6_addr
[i
]];
1014 LOG(4, s
, session
[s
].tunnel
, "Caching ip address %s/%d\n",
1015 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1019 LOG(4, 0, 0, "Un-caching ip address %s/%d\n",
1020 inet_ntop(AF_INET6
, &ip
, ipv6addr
,
1026 // CLI list to dump current ipcache.
1028 int cmd_show_ipcache(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
1030 union iphash
*d
= ip_hash
, *e
, *f
, *g
;
1034 if (CLI_HELP_REQUESTED
)
1035 return CLI_HELP_NO_ARGS
;
1037 cli_print(cli
, "%7s %s", "Sess#", "IP Address");
1039 for (i
= 0; i
< 256; ++i
)
1045 for (j
= 0; j
< 256; ++j
)
1051 for (k
= 0; k
< 256; ++k
)
1057 for (l
= 0; l
< 256; ++l
)
1062 cli_print(cli
, "%7d %d.%d.%d.%d", g
[l
].sess
, i
, j
, k
, l
);
1068 cli_print(cli
, "%d entries in cache", count
);
1073 // Find session by username, 0 for not found
1074 // walled garden users aren't authenticated, so the username is
1075 // reasonably useless. Ignore them to avoid incorrect actions
1077 // This is VERY inefficent. Don't call it often. :)
1079 sessionidt
sessionbyuser(char *username
)
1082 CSTAT(sessionbyuser
);
1084 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
1086 if (!session
[s
].opened
)
1089 if (session
[s
].walled_garden
)
1090 continue; // Skip walled garden users.
1092 if (!strncmp(session
[s
].user
, username
, 128))
1096 return 0; // Not found.
1099 void send_garp(in_addr_t ip
)
1105 s
= socket(PF_INET
, SOCK_DGRAM
, 0);
1108 LOG(0, 0, 0, "Error creating socket for GARP: %s\n", strerror(errno
));
1111 memset(&ifr
, 0, sizeof(ifr
));
1112 strncpy(ifr
.ifr_name
, "eth0", sizeof(ifr
.ifr_name
) - 1);
1113 if (ioctl(s
, SIOCGIFHWADDR
, &ifr
) < 0)
1115 LOG(0, 0, 0, "Error getting eth0 hardware address for GARP: %s\n", strerror(errno
));
1119 memcpy(mac
, &ifr
.ifr_hwaddr
.sa_data
, 6*sizeof(char));
1120 if (ioctl(s
, SIOCGIFINDEX
, &ifr
) < 0)
1122 LOG(0, 0, 0, "Error getting eth0 interface index for GARP: %s\n", strerror(errno
));
1127 sendarp(ifr
.ifr_ifindex
, mac
, ip
);
1130 static sessiont
*sessiontbysessionidt(sessionidt s
)
1132 if (!s
|| s
>= MAXSESSION
) return NULL
;
1136 static sessionidt
sessionidtbysessiont(sessiont
*s
)
1138 sessionidt val
= s
-session
;
1139 if (s
< session
|| val
>= MAXSESSION
) return 0;
1143 // actually send a control message for a specific tunnel
1144 void tunnelsend(uint8_t * buf
, uint16_t l
, tunnelidt t
)
1146 struct sockaddr_in addr
;
1152 LOG(0, 0, t
, "tunnelsend called with 0 as tunnel id\n");
1153 STAT(tunnel_tx_errors
);
1159 LOG(1, 0, t
, "Error sending data out tunnel: no remote endpoint (tunnel not set up)\n");
1160 STAT(tunnel_tx_errors
);
1164 memset(&addr
, 0, sizeof(addr
));
1165 addr
.sin_family
= AF_INET
;
1166 *(uint32_t *) & addr
.sin_addr
= htonl(tunnel
[t
].ip
);
1167 addr
.sin_port
= htons(tunnel
[t
].port
);
1169 // sequence expected, if sequence in message
1170 if (*buf
& 0x08) *(uint16_t *) (buf
+ ((*buf
& 0x40) ? 10 : 8)) = htons(tunnel
[t
].nr
);
1172 // If this is a control message, deal with retries
1175 tunnel
[t
].last
= time_now
; // control message sent
1176 tunnel
[t
].retry
= backoff(tunnel
[t
].try); // when to resend
1179 STAT(tunnel_retries
);
1180 LOG(3, 0, t
, "Control message resend try %d\n", tunnel
[t
].try);
1184 if (sendto(udpfd
, buf
, l
, 0, (void *) &addr
, sizeof(addr
)) < 0)
1186 LOG(0, ntohs((*(uint16_t *) (buf
+ 6))), t
, "Error sending data out tunnel: %s (udpfd=%d, buf=%p, len=%d, dest=%s)\n",
1187 strerror(errno
), udpfd
, buf
, l
, inet_ntoa(addr
.sin_addr
));
1188 STAT(tunnel_tx_errors
);
1192 LOG_HEX(5, "Send Tunnel Data", buf
, l
);
1193 STAT(tunnel_tx_packets
);
1194 INC_STAT(tunnel_tx_bytes
, l
);
1198 // Tiny helper function to write data to
1199 // the 'tun' device.
1201 int tun_write(uint8_t * data
, int size
)
1203 return write(tunfd
, data
, size
);
1206 // adjust tcp mss to avoid fragmentation (called only for tcp packets with syn set)
1207 void adjust_tcp_mss(sessionidt s
, tunnelidt t
, uint8_t *buf
, int len
, uint8_t *tcp
)
1209 int d
= (tcp
[12] >> 4) * 4;
1216 if ((tcp
[13] & 0x3f) & ~(TCP_FLAG_SYN
|TCP_FLAG_ACK
)) // only want SYN and SYN,ACK
1219 if (tcp
+ d
> buf
+ len
) // short?
1227 if (*opts
== 2 && opts
[1] == 4) // mss option (2), length 4
1230 if (mss
+ 2 > data
) return; // short?
1234 if (*opts
== 0) return; // end of options
1235 if (*opts
== 1 || !opts
[1]) // no op (one byte), or no length (prevent loop)
1238 opts
+= opts
[1]; // skip over option
1241 if (!mss
) return; // not found
1242 orig
= ntohs(*(uint16_t *) mss
);
1244 if (orig
<= MSS
) return; // mss OK
1246 LOG(5, s
, t
, "TCP: %s:%u -> %s:%u SYN%s: adjusted mss from %u to %u\n",
1247 fmtaddr(*(in_addr_t
*) (buf
+ 12), 0), ntohs(*(uint16_t *) tcp
),
1248 fmtaddr(*(in_addr_t
*) (buf
+ 16), 1), ntohs(*(uint16_t *) (tcp
+ 2)),
1249 (tcp
[13] & TCP_FLAG_ACK
) ? ",ACK" : "", orig
, MSS
);
1252 *(int16_t *) mss
= htons(MSS
);
1254 // adjust checksum (see rfc1141)
1255 sum
= orig
+ (~MSS
& 0xffff);
1256 sum
+= ntohs(*(uint16_t *) (tcp
+ 16));
1257 sum
= (sum
& 0xffff) + (sum
>> 16);
1258 *(uint16_t *) (tcp
+ 16) = htons(sum
+ (sum
>> 16));
1261 void processmpframe(sessionidt s
, tunnelidt t
, uint8_t *p
, uint16_t l
, uint8_t extra
)
1265 // Skip the four extra bytes
1277 proto
= ntohs(*(uint16_t *) p
);
1285 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1286 return; // closing session, PPP not processed
1288 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1289 processipin(s
, t
, p
, l
);
1291 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
1295 LOG(4, s
, t
, "MPPP: Session %d is closing. Don't process PPP packets\n", s
);
1296 return; // closing session, PPP not processed
1299 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1300 processipv6in(s
, t
, p
, l
);
1302 else if (proto
== PPPIPCP
)
1304 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1305 processipcp(s
, t
, p
, l
);
1307 else if (proto
== PPPCCP
)
1309 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
1310 processccp(s
, t
, p
, l
);
1314 LOG(2, s
, t
, "MPPP: Unsupported MP protocol 0x%04X received\n",proto
);
1318 static void update_session_out_stat(sessionidt s
, sessiont
*sp
, int len
)
1320 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1321 sp
->cout_delta
+= len
;
1323 sp
->last_data
= time_now
;
1325 sess_local
[s
].cout
+= len
; // To send to master..
1326 sess_local
[s
].pout
++;
1329 // process outgoing (to tunnel) IP
1331 static void processipout(uint8_t *buf
, int len
)
1338 uint8_t *data
= buf
; // Keep a copy of the originals.
1341 uint8_t fragbuf
[MAXETHER
+ 20];
1343 CSTAT(processipout
);
1345 if (len
< MIN_IP_SIZE
)
1347 LOG(1, 0, 0, "Short IP, %d bytes\n", len
);
1348 STAT(tun_rx_errors
);
1351 if (len
>= MAXETHER
)
1353 LOG(1, 0, 0, "Oversize IP packet %d bytes\n", len
);
1354 STAT(tun_rx_errors
);
1358 // Skip the tun header
1362 // Got an IP header now
1363 if (*(uint8_t *)(buf
) >> 4 != 4)
1365 LOG(1, 0, 0, "IP: Don't understand anything except IPv4\n");
1369 ip
= *(uint32_t *)(buf
+ 16);
1370 if (!(s
= sessionbyip(ip
)))
1372 // Is this a packet for a session that doesn't exist?
1373 static int rate
= 0; // Number of ICMP packets we've sent this second.
1374 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1376 if (last
!= time_now
)
1382 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1384 LOG(4, 0, 0, "IP: Sending ICMP host unreachable to %s\n", fmtaddr(*(in_addr_t
*)(buf
+ 12), 0));
1385 host_unreachable(*(in_addr_t
*)(buf
+ 12), *(uint16_t *)(buf
+ 4),
1386 config
->bind_address
? config
->bind_address
: my_address
, buf
, len
);
1391 t
= session
[s
].tunnel
;
1392 if (len
> session
[s
].mru
|| (session
[s
].mrru
&& len
> session
[s
].mrru
))
1394 LOG(3, s
, t
, "Packet size more than session MRU\n");
1400 // DoS prevention: enforce a maximum number of packets per 0.1s for a session
1401 if (config
->max_packets
> 0)
1403 if (sess_local
[s
].last_packet_out
== TIME
)
1405 int max
= config
->max_packets
;
1407 // All packets for throttled sessions are handled by the
1408 // master, so further limit by using the throttle rate.
1409 // A bit of a kludge, since throttle rate is in kbps,
1410 // but should still be generous given our average DSL
1411 // packet size is 200 bytes: a limit of 28kbps equates
1412 // to around 180 packets per second.
1413 if (!config
->cluster_iam_master
&& sp
->throttle_out
&& sp
->throttle_out
< max
)
1414 max
= sp
->throttle_out
;
1416 if (++sess_local
[s
].packets_out
> max
)
1418 sess_local
[s
].packets_dropped
++;
1424 if (sess_local
[s
].packets_dropped
)
1426 INC_STAT(tun_rx_dropped
, sess_local
[s
].packets_dropped
);
1427 LOG(3, s
, t
, "Dropped %u/%u packets to %s for %suser %s\n",
1428 sess_local
[s
].packets_dropped
, sess_local
[s
].packets_out
,
1429 fmtaddr(ip
, 0), sp
->throttle_out
? "throttled " : "",
1433 sess_local
[s
].last_packet_out
= TIME
;
1434 sess_local
[s
].packets_out
= 1;
1435 sess_local
[s
].packets_dropped
= 0;
1439 // run access-list if any
1440 if (session
[s
].filter_out
&& !ip_filter(buf
, len
, session
[s
].filter_out
- 1))
1443 // adjust MSS on SYN and SYN,ACK packets with options
1444 if ((ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff) == 0 && buf
[9] == IPPROTO_TCP
) // first tcp fragment
1446 int ihl
= (buf
[0] & 0xf) * 4; // length of IP header
1447 if (len
>= ihl
+ 20 && (buf
[ihl
+ 13] & TCP_FLAG_SYN
) && ((buf
[ihl
+ 12] >> 4) > 5))
1448 adjust_tcp_mss(s
, t
, buf
, len
, buf
+ ihl
);
1453 // Are we throttling this session?
1454 if (config
->cluster_iam_master
)
1455 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1457 master_throttle_packet(sp
->tbf_out
, data
, size
);
1461 if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1463 // We are walled-gardening this
1464 master_garden_packet(s
, data
, size
);
1468 if(session
[s
].bundle
!= 0 && bundle
[session
[s
].bundle
].num_of_links
> 1)
1470 // Add on L2TP header
1471 sessionidt members
[MAXBUNDLESES
];
1472 bundleidt bid
= session
[s
].bundle
;
1473 bundlet
*b
= &bundle
[bid
];
1474 uint32_t num_of_links
, nb_opened
;
1477 num_of_links
= b
->num_of_links
;
1479 for (i
= 0;i
< num_of_links
;i
++)
1482 if (session
[s
].ppp
.lcp
== Opened
)
1484 members
[nb_opened
] = s
;
1491 LOG(2, s
, t
, "MPPP: PROCESSIPOUT ERROR, no session opened in bundle:%d\n", bid
);
1495 num_of_links
= nb_opened
;
1496 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1497 s
= members
[b
->current_ses
];
1498 t
= session
[s
].tunnel
;
1500 LOG(4, s
, t
, "MPPP: (1)Session number becomes: %d\n", s
);
1502 if (num_of_links
> 1)
1504 if(len
> MINFRAGLEN
)
1506 //for rotate traffic among the member links
1507 uint32_t divisor
= num_of_links
;
1509 divisor
= divisor
/2 + (divisor
& 1);
1511 // Partition the packet to "num_of_links" fragments
1512 uint32_t fraglen
= len
/ divisor
;
1513 uint32_t last_fraglen
= fraglen
+ len
% divisor
;
1514 uint32_t remain
= len
;
1516 // send the first packet
1517 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, fraglen
, s
, t
, PPPIP
, 0, bid
, MP_BEGIN
);
1519 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1522 update_session_out_stat(s
, sp
, fraglen
);
1525 while (remain
> last_fraglen
)
1527 b
->current_ses
= (b
->current_ses
+ 1) % num_of_links
;
1528 s
= members
[b
->current_ses
];
1529 t
= session
[s
].tunnel
;
1531 LOG(4, s
, t
, "MPPP: (2)Session number becomes: %d\n", s
);
1532 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), fraglen
, s
, t
, PPPIP
, 0, bid
, 0);
1534 tunnelsend(fragbuf
, fraglen
+ (p
-fragbuf
), t
); // send it...
1535 update_session_out_stat(s
, sp
, fraglen
);
1538 // send the last fragment
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: (2)Session number becomes: %d\n", s
);
1544 p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
+(len
- remain
), remain
, s
, t
, PPPIP
, 0, bid
, MP_END
);
1546 tunnelsend(fragbuf
, remain
+ (p
-fragbuf
), t
); // send it...
1547 update_session_out_stat(s
, sp
, remain
);
1548 if (remain
!= last_fraglen
)
1549 LOG(3, s
, t
, "PROCESSIPOUT ERROR REMAIN != LAST_FRAGLEN, %d != %d\n", remain
, last_fraglen
);
1553 // Send it as one frame
1554 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, bid
, MP_BOTH_BITS
);
1556 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1557 LOG(4, s
, t
, "MPPP: packet sent as one frame\n");
1558 update_session_out_stat(s
, sp
, len
);
1563 // Send it as one frame (NO MPPP Frame)
1564 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1566 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1567 update_session_out_stat(s
, sp
, len
);
1572 uint8_t *p
= makeppp(fragbuf
, sizeof(fragbuf
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1574 tunnelsend(fragbuf
, len
+ (p
-fragbuf
), t
); // send it...
1575 update_session_out_stat(s
, sp
, len
);
1578 // Snooping this session, send it to intercept box
1579 if (sp
->snoop_ip
&& sp
->snoop_port
)
1580 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1585 // process outgoing (to tunnel) IPv6
1587 static void processipv6out(uint8_t * buf
, int len
)
1593 struct in6_addr ip6
;
1595 uint8_t *data
= buf
; // Keep a copy of the originals.
1598 uint8_t b
[MAXETHER
+ 20];
1600 CSTAT(processipv6out
);
1602 if (len
< MIN_IP_SIZE
)
1604 LOG(1, 0, 0, "Short IPv6, %d bytes\n", len
);
1605 STAT(tunnel_tx_errors
);
1608 if (len
>= MAXETHER
)
1610 LOG(1, 0, 0, "Oversize IPv6 packet %d bytes\n", len
);
1611 STAT(tunnel_tx_errors
);
1615 // Skip the tun header
1619 // Got an IP header now
1620 if (*(uint8_t *)(buf
) >> 4 != 6)
1622 LOG(1, 0, 0, "IP: Don't understand anything except IPv6\n");
1626 ip6
= *(struct in6_addr
*)(buf
+24);
1627 s
= sessionbyipv6(ip6
);
1631 ip
= *(uint32_t *)(buf
+ 32);
1632 s
= sessionbyip(ip
);
1637 // Is this a packet for a session that doesn't exist?
1638 static int rate
= 0; // Number of ICMP packets we've sent this second.
1639 static int last
= 0; // Last time we reset the ICMP packet counter 'rate'.
1641 if (last
!= time_now
)
1647 if (rate
++ < config
->icmp_rate
) // Only send a max of icmp_rate per second.
1649 // FIXME: Should send icmp6 host unreachable
1653 if (session
[s
].bundle
&& bundle
[session
[s
].bundle
].num_of_links
> 1)
1655 bundleidt bid
= session
[s
].bundle
;
1656 bundlet
*b
= &bundle
[bid
];
1658 b
->current_ses
= (b
->current_ses
+ 1) % b
->num_of_links
;
1659 s
= b
->members
[b
->current_ses
];
1660 LOG(3, s
, session
[s
].tunnel
, "MPPP: Session number becomes: %u\n", s
);
1662 t
= session
[s
].tunnel
;
1664 sp
->last_data
= time_now
;
1666 // FIXME: add DoS prevention/filters?
1670 // Are we throttling this session?
1671 if (config
->cluster_iam_master
)
1672 tbf_queue_packet(sp
->tbf_out
, data
, size
);
1674 master_throttle_packet(sp
->tbf_out
, data
, size
);
1677 else if (sp
->walled_garden
&& !config
->cluster_iam_master
)
1679 // We are walled-gardening this
1680 master_garden_packet(s
, data
, size
);
1684 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1686 // Add on L2TP header
1688 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIPV6
, 0, 0, 0);
1690 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1693 // Snooping this session, send it to intercept box
1694 if (sp
->snoop_ip
&& sp
->snoop_port
)
1695 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1697 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1698 sp
->cout_delta
+= len
;
1702 sess_local
[s
].cout
+= len
; // To send to master..
1703 sess_local
[s
].pout
++;
1707 // Helper routine for the TBF filters.
1708 // Used to send queued data in to the user!
1710 static void send_ipout(sessionidt s
, uint8_t *buf
, int len
)
1715 uint8_t b
[MAXETHER
+ 20];
1717 if (len
< 0 || len
> MAXETHER
)
1719 LOG(1, 0, 0, "Odd size IP packet: %d bytes\n", len
);
1723 // Skip the tun header
1730 t
= session
[s
].tunnel
;
1733 LOG(5, s
, t
, "Ethernet -> Tunnel (%d bytes)\n", len
);
1735 // Add on L2TP header
1737 uint8_t *p
= makeppp(b
, sizeof(b
), buf
, len
, s
, t
, PPPIP
, 0, 0, 0);
1739 tunnelsend(b
, len
+ (p
-b
), t
); // send it...
1742 // Snooping this session.
1743 if (sp
->snoop_ip
&& sp
->snoop_port
)
1744 snoop_send_packet(buf
, len
, sp
->snoop_ip
, sp
->snoop_port
);
1746 increment_counter(&sp
->cout
, &sp
->cout_wrap
, len
); // byte count
1747 sp
->cout_delta
+= len
;
1751 sess_local
[s
].cout
+= len
; // To send to master..
1752 sess_local
[s
].pout
++;
1755 // add an AVP (16 bit)
1756 static void control16(controlt
* c
, uint16_t avp
, uint16_t val
, uint8_t m
)
1758 uint16_t l
= (m
? 0x8008 : 0x0008);
1759 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1760 c
->buf16
[c
->length
/2 + 1] = htons(0);
1761 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1762 c
->buf16
[c
->length
/2 + 3] = htons(val
);
1766 // add an AVP (32 bit)
1767 static void control32(controlt
* c
, uint16_t avp
, uint32_t val
, uint8_t m
)
1769 uint16_t l
= (m
? 0x800A : 0x000A);
1770 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1771 c
->buf16
[c
->length
/2 + 1] = htons(0);
1772 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1773 *(uint32_t *) &c
->buf
[c
->length
+ 6] = htonl(val
);
1777 // add an AVP (string)
1778 static void controls(controlt
* c
, uint16_t avp
, char *val
, uint8_t m
)
1780 uint16_t l
= ((m
? 0x8000 : 0) + strlen(val
) + 6);
1781 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1782 c
->buf16
[c
->length
/2 + 1] = htons(0);
1783 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1784 memcpy(&c
->buf
[c
->length
+ 6], val
, strlen(val
));
1785 c
->length
+= 6 + strlen(val
);
1789 static void controlb(controlt
* c
, uint16_t avp
, uint8_t *val
, unsigned int len
, uint8_t m
)
1791 uint16_t l
= ((m
? 0x8000 : 0) + len
+ 6);
1792 c
->buf16
[c
->length
/2 + 0] = htons(l
);
1793 c
->buf16
[c
->length
/2 + 1] = htons(0);
1794 c
->buf16
[c
->length
/2 + 2] = htons(avp
);
1795 memcpy(&c
->buf
[c
->length
+ 6], val
, len
);
1796 c
->length
+= 6 + len
;
1799 // new control connection
1800 static controlt
*controlnew(uint16_t mtype
)
1804 c
= malloc(sizeof(controlt
));
1808 controlfree
= c
->next
;
1812 c
->buf16
[0] = htons(0xC802); // flags/ver
1814 control16(c
, 0, mtype
, 1);
1818 // send zero block if nothing is waiting
1820 static void controlnull(tunnelidt t
)
1823 if (tunnel
[t
].controlc
) // Messages queued; They will carry the ack.
1826 buf
[0] = htons(0xC802); // flags/ver
1827 buf
[1] = htons(12); // length
1828 buf
[2] = htons(tunnel
[t
].far
); // tunnel
1829 buf
[3] = htons(0); // session
1830 buf
[4] = htons(tunnel
[t
].ns
); // sequence
1831 buf
[5] = htons(tunnel
[t
].nr
); // sequence
1832 tunnelsend((uint8_t *)buf
, 12, t
);
1835 // add a control message to a tunnel, and send if within window
1836 static void controladd(controlt
*c
, sessionidt far
, tunnelidt t
)
1838 c
->buf16
[1] = htons(c
->length
); // length
1839 c
->buf16
[2] = htons(tunnel
[t
].far
); // tunnel
1840 c
->buf16
[3] = htons(far
); // session
1841 c
->buf16
[4] = htons(tunnel
[t
].ns
); // sequence
1842 tunnel
[t
].ns
++; // advance sequence
1843 // link in message in to queue
1844 if (tunnel
[t
].controlc
)
1845 tunnel
[t
].controle
->next
= c
;
1847 tunnel
[t
].controls
= c
;
1849 tunnel
[t
].controle
= c
;
1850 tunnel
[t
].controlc
++;
1852 // send now if space in window
1853 if (tunnel
[t
].controlc
<= tunnel
[t
].window
)
1855 tunnel
[t
].try = 0; // first send
1856 tunnelsend(c
->buf
, c
->length
, t
);
1861 // Throttle or Unthrottle a session
1863 // Throttle the data from/to through a session to no more than
1864 // 'rate_in' kbit/sec in (from user) or 'rate_out' kbit/sec out (to
1867 // If either value is -1, the current value is retained for that
1870 void throttle_session(sessionidt s
, int rate_in
, int rate_out
)
1872 if (!session
[s
].opened
)
1873 return; // No-one home.
1875 if (!*session
[s
].user
)
1876 return; // User not logged in
1880 int bytes
= rate_in
* 1024 / 8; // kbits to bytes
1881 if (session
[s
].tbf_in
)
1882 free_tbf(session
[s
].tbf_in
);
1885 session
[s
].tbf_in
= new_tbf(s
, bytes
* 2, bytes
, send_ipin
);
1887 session
[s
].tbf_in
= 0;
1889 session
[s
].throttle_in
= rate_in
;
1894 int bytes
= rate_out
* 1024 / 8;
1895 if (session
[s
].tbf_out
)
1896 free_tbf(session
[s
].tbf_out
);
1899 session
[s
].tbf_out
= new_tbf(s
, bytes
* 2, bytes
, send_ipout
);
1901 session
[s
].tbf_out
= 0;
1903 session
[s
].throttle_out
= rate_out
;
1907 // add/remove filters from session (-1 = no change)
1908 void filter_session(sessionidt s
, int filter_in
, int filter_out
)
1910 if (!session
[s
].opened
)
1911 return; // No-one home.
1913 if (!*session
[s
].user
)
1914 return; // User not logged in
1917 if (filter_in
> MAXFILTER
) filter_in
= -1;
1918 if (filter_out
> MAXFILTER
) filter_out
= -1;
1919 if (session
[s
].filter_in
> MAXFILTER
) session
[s
].filter_in
= 0;
1920 if (session
[s
].filter_out
> MAXFILTER
) session
[s
].filter_out
= 0;
1924 if (session
[s
].filter_in
)
1925 ip_filters
[session
[s
].filter_in
- 1].used
--;
1928 ip_filters
[filter_in
- 1].used
++;
1930 session
[s
].filter_in
= filter_in
;
1933 if (filter_out
>= 0)
1935 if (session
[s
].filter_out
)
1936 ip_filters
[session
[s
].filter_out
- 1].used
--;
1939 ip_filters
[filter_out
- 1].used
++;
1941 session
[s
].filter_out
= filter_out
;
1945 // start tidy shutdown of session
1946 void sessionshutdown(sessionidt s
, char const *reason
, int cdn_result
, int cdn_error
, int term_cause
)
1948 int walled_garden
= session
[s
].walled_garden
;
1949 bundleidt b
= session
[s
].bundle
;
1950 //delete routes only for last session in bundle (in case of MPPP)
1951 int del_routes
= !b
|| (bundle
[b
].num_of_links
== 1);
1953 CSTAT(sessionshutdown
);
1955 if (!session
[s
].opened
)
1957 LOG(3, s
, session
[s
].tunnel
, "Called sessionshutdown on an unopened session.\n");
1958 return; // not a live session
1961 if (!session
[s
].die
)
1963 struct param_kill_session data
= { &tunnel
[session
[s
].tunnel
], &session
[s
] };
1964 LOG(2, s
, session
[s
].tunnel
, "Shutting down session %u: %s\n", s
, reason
);
1965 run_plugins(PLUGIN_KILL_SESSION
, &data
);
1966 session
[s
].die
= TIME
+ 150; // Clean up in 15 seconds
1969 if (session
[s
].ip
&& !walled_garden
&& !session
[s
].die
)
1971 // RADIUS Stop message
1972 uint16_t r
= radiusnew(s
);
1975 // stop, if not already trying
1976 if (radius
[r
].state
!= RADIUSSTOP
)
1978 radius
[r
].term_cause
= term_cause
;
1979 radius
[r
].term_msg
= reason
;
1980 radiussend(r
, RADIUSSTOP
);
1984 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Stop message\n");
1986 // Save counters to dump to accounting file
1987 if (*config
->accounting_dir
&& shut_acct_n
< sizeof(shut_acct
) / sizeof(*shut_acct
))
1988 memcpy(&shut_acct
[shut_acct_n
++], &session
[s
], sizeof(session
[s
]));
1992 { // IP allocated, clear and unroute
1995 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
1997 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
1998 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
2001 if (del_routes
) routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 0);
2002 session
[s
].route
[r
].ip
= 0;
2005 if (session
[s
].ip_pool_index
== -1) // static ip
2007 if (!routed
&& del_routes
) routeset(s
, session
[s
].ip
, 0, 0, 0);
2013 // unroute IPv6, if setup
2014 if (session
[s
].ppp
.ipv6cp
== Opened
&& session
[s
].ipv6prefixlen
&& del_routes
)
2015 route6set(s
, session
[s
].ipv6route
, session
[s
].ipv6prefixlen
, 0);
2019 // This session was part of a bundle
2020 bundle
[b
].num_of_links
--;
2021 LOG(3, s
, session
[s
].tunnel
, "MPPP: Dropping member link: %d from bundle %d\n",s
,b
);
2022 if(bundle
[b
].num_of_links
== 0)
2025 LOG(3, s
, session
[s
].tunnel
, "MPPP: Kill bundle: %d (No remaing member links)\n",b
);
2029 // Adjust the members array to accomodate the new change
2030 uint8_t mem_num
= 0;
2031 // It should be here num_of_links instead of num_of_links-1 (previous instruction "num_of_links--")
2032 if(bundle
[b
].members
[bundle
[b
].num_of_links
] != s
)
2035 for(ml
= 0; ml
<bundle
[b
].num_of_links
; ml
++)
2036 if(bundle
[b
].members
[ml
] == s
)
2041 bundle
[b
].members
[mem_num
] = bundle
[b
].members
[bundle
[b
].num_of_links
];
2042 LOG(3, s
, session
[s
].tunnel
, "MPPP: Adjusted member links array\n");
2044 // If the killed session is the first of the bundle,
2045 // the new first session must be stored in the cache_ipmap
2046 // else the function sessionbyip return 0 and the sending not work any more (processipout).
2049 sessionidt new_s
= bundle
[b
].members
[0];
2052 // Add the route for this session.
2053 for (r
= 0; r
< MAXROUTE
&& session
[new_s
].route
[r
].ip
; r
++)
2058 prefixlen
= session
[new_s
].route
[r
].prefixlen
;
2059 ip
= session
[new_s
].route
[r
].ip
;
2061 if (!prefixlen
) prefixlen
= 32;
2062 ip
&= 0xffffffff << (32 - prefixlen
); // Force the ip to be the first one in the route.
2064 for (i
= ip
; i
< ip
+(1<<(32-prefixlen
)) ; ++i
)
2065 cache_ipmap(i
, new_s
);
2067 cache_ipmap(session
[new_s
].ip
, new_s
);
2070 if (session
[new_s
].ipv6prefixlen
)
2071 cache_ipv6map(session
[new_s
].ipv6route
, session
[new_s
].ipv6prefixlen
, new_s
);
2076 cluster_send_bundle(b
);
2080 if (session
[s
].throttle_in
|| session
[s
].throttle_out
) // Unthrottle if throttled.
2081 throttle_session(s
, 0, 0);
2085 controlt
*c
= controlnew(14); // sending CDN
2089 buf
[0] = htons(cdn_result
);
2090 buf
[1] = htons(cdn_error
);
2091 controlb(c
, 1, (uint8_t *)buf
, 4, 1);
2094 control16(c
, 1, cdn_result
, 1);
2096 control16(c
, 14, s
, 1); // assigned session (our end)
2097 controladd(c
, session
[s
].far
, session
[s
].tunnel
); // send the message
2100 // update filter refcounts
2101 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
2102 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
2105 memset(&session
[s
].ppp
, 0, sizeof(session
[s
].ppp
));
2106 sess_local
[s
].lcp
.restart
= 0;
2107 sess_local
[s
].ipcp
.restart
= 0;
2108 sess_local
[s
].ipv6cp
.restart
= 0;
2109 sess_local
[s
].ccp
.restart
= 0;
2111 cluster_send_session(s
);
2114 void sendipcp(sessionidt s
, tunnelidt t
)
2116 uint8_t buf
[MAXETHER
];
2120 LOG(3, s
, t
, "IPCP: send ConfigReq\n");
2122 if (!session
[s
].unique_id
)
2124 if (!++last_id
) ++last_id
; // skip zero
2125 session
[s
].unique_id
= last_id
;
2128 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPCP
, 0, 0, 0);
2132 q
[1] = session
[s
].unique_id
& 0xf; // ID, dont care, we only send one type of request
2133 *(uint16_t *) (q
+ 2) = htons(10); // packet length
2134 q
[4] = 3; // ip address option
2135 q
[5] = 6; // option length
2136 *(in_addr_t
*) (q
+ 6) = config
->peer_address
? config
->peer_address
:
2137 config
->bind_address
? config
->bind_address
:
2138 my_address
; // send my IP
2140 tunnelsend(buf
, 10 + (q
- buf
), t
); // send it
2141 restart_timer(s
, ipcp
);
2144 void sendipv6cp(sessionidt s
, tunnelidt t
)
2146 uint8_t buf
[MAXETHER
];
2150 LOG(3, s
, t
, "IPV6CP: send ConfigReq\n");
2152 q
= makeppp(buf
, sizeof(buf
), 0, 0, s
, t
, PPPIPV6CP
, 0, 0, 0);
2156 q
[1] = session
[s
].unique_id
& 0xf; // ID, don't care, we
2157 // only send one type
2159 *(uint16_t *) (q
+ 2) = htons(14);
2160 q
[4] = 1; // interface identifier option
2161 q
[5] = 10; // option length
2162 *(uint32_t *) (q
+ 6) = 0; // We'll be prefix::1
2163 *(uint32_t *) (q
+ 10) = 0;
2166 tunnelsend(buf
, 14 + (q
- buf
), t
); // send it
2167 restart_timer(s
, ipv6cp
);
2170 static void sessionclear(sessionidt s
)
2172 memset(&session
[s
], 0, sizeof(session
[s
]));
2173 memset(&sess_local
[s
], 0, sizeof(sess_local
[s
]));
2174 memset(&cli_session_actions
[s
], 0, sizeof(cli_session_actions
[s
]));
2176 session
[s
].tunnel
= T_FREE
; // Mark it as free.
2177 session
[s
].next
= sessionfree
;
2181 // kill a session now
2182 void sessionkill(sessionidt s
, char *reason
)
2186 if (!session
[s
].opened
) // not alive
2189 if (session
[s
].next
)
2191 LOG(0, s
, session
[s
].tunnel
, "Tried to kill a session with next pointer set (%u)\n", session
[s
].next
);
2195 if (!session
[s
].die
)
2196 sessionshutdown(s
, reason
, CDN_ADMIN_DISC
, TERM_ADMIN_RESET
); // close radius/routes, etc.
2198 if (sess_local
[s
].radius
)
2199 radiusclear(sess_local
[s
].radius
, s
); // cant send clean accounting data, session is killed
2201 LOG(2, s
, session
[s
].tunnel
, "Kill session %d (%s): %s\n", s
, session
[s
].user
, reason
);
2203 cluster_send_session(s
);
2206 static void tunnelclear(tunnelidt t
)
2209 memset(&tunnel
[t
], 0, sizeof(tunnel
[t
]));
2210 tunnel
[t
].state
= TUNNELFREE
;
2213 static void bundleclear(bundleidt b
)
2216 memset(&bundle
[b
], 0, sizeof(bundle
[b
]));
2217 bundle
[b
].state
= BUNDLEFREE
;
2220 // kill a tunnel now
2221 static void tunnelkill(tunnelidt t
, char *reason
)
2228 tunnel
[t
].state
= TUNNELDIE
;
2230 // free control messages
2231 while ((c
= tunnel
[t
].controls
))
2233 controlt
* n
= c
->next
;
2234 tunnel
[t
].controls
= n
;
2235 tunnel
[t
].controlc
--;
2236 c
->next
= controlfree
;
2240 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2241 if (session
[s
].tunnel
== t
)
2242 sessionkill(s
, reason
);
2246 LOG(1, 0, t
, "Kill tunnel %u: %s\n", t
, reason
);
2247 cli_tunnel_actions
[t
].action
= 0;
2248 cluster_send_tunnel(t
);
2251 // shut down a tunnel cleanly
2252 static void tunnelshutdown(tunnelidt t
, char *reason
, int result
, int error
, char *msg
)
2256 CSTAT(tunnelshutdown
);
2258 if (!tunnel
[t
].last
|| !tunnel
[t
].far
|| tunnel
[t
].state
== TUNNELFREE
)
2260 // never set up, can immediately kill
2261 tunnelkill(t
, reason
);
2264 LOG(1, 0, t
, "Shutting down tunnel %u (%s)\n", t
, reason
);
2267 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
2268 if (session
[s
].tunnel
== t
)
2269 sessionshutdown(s
, reason
, CDN_NONE
, TERM_ADMIN_RESET
);
2271 tunnel
[t
].state
= TUNNELDIE
;
2272 tunnel
[t
].die
= TIME
+ 700; // Clean up in 70 seconds
2273 cluster_send_tunnel(t
);
2274 // TBA - should we wait for sessions to stop?
2277 controlt
*c
= controlnew(4); // sending StopCCN
2282 buf
[0] = htons(result
);
2283 buf
[1] = htons(error
);
2286 int m
= strlen(msg
);
2287 if (m
+ 4 > sizeof(buf
))
2288 m
= sizeof(buf
) - 4;
2290 memcpy(buf
+2, msg
, m
);
2294 controlb(c
, 1, (uint8_t *)buf
, l
, 1);
2297 control16(c
, 1, result
, 1);
2299 control16(c
, 9, t
, 1); // assigned tunnel (our end)
2300 controladd(c
, 0, t
); // send the message
2304 // read and process packet on tunnel (UDP)
2305 void processudp(uint8_t *buf
, int len
, struct sockaddr_in
*addr
)
2307 uint8_t *chapresponse
= NULL
;
2308 uint16_t l
= len
, t
= 0, s
= 0, ns
= 0, nr
= 0;
2309 uint8_t *p
= buf
+ 2;
2316 LOG_HEX(5, "UDP Data", buf
, len
);
2317 STAT(tunnel_rx_packets
);
2318 INC_STAT(tunnel_rx_bytes
, len
);
2321 LOG(1, 0, 0, "Short UDP, %d bytes\n", len
);
2322 STAT(tunnel_rx_errors
);
2325 if ((buf
[1] & 0x0F) != 2)
2327 LOG(1, 0, 0, "Bad L2TP ver %d\n", buf
[1] & 0x0F);
2328 STAT(tunnel_rx_errors
);
2333 l
= ntohs(*(uint16_t *) p
);
2336 t
= ntohs(*(uint16_t *) p
);
2338 s
= ntohs(*(uint16_t *) p
);
2340 if (s
>= MAXSESSION
)
2342 LOG(1, s
, t
, "Received UDP packet with invalid session ID\n");
2343 STAT(tunnel_rx_errors
);
2348 LOG(1, s
, t
, "Received UDP packet with invalid tunnel ID\n");
2349 STAT(tunnel_rx_errors
);
2354 ns
= ntohs(*(uint16_t *) p
);
2356 nr
= ntohs(*(uint16_t *) p
);
2361 uint16_t o
= ntohs(*(uint16_t *) p
);
2366 LOG(1, s
, t
, "Bad length %d>%d\n", (int) (p
- buf
), l
);
2367 STAT(tunnel_rx_errors
);
2372 // used to time out old tunnels
2373 if (t
&& tunnel
[t
].state
== TUNNELOPEN
)
2374 tunnel
[t
].lastrec
= time_now
;
2378 uint16_t message
= 0xFFFF; // message type
2380 uint8_t mandatory
= 0;
2381 uint16_t asession
= 0; // assigned session
2382 uint32_t amagic
= 0; // magic number
2383 uint8_t aflags
= 0; // flags from last LCF
2384 uint16_t version
= 0x0100; // protocol version (we handle 0.0 as well and send that back just in case)
2385 char called
[MAXTEL
] = ""; // called number
2386 char calling
[MAXTEL
] = ""; // calling number
2388 if (!config
->cluster_iam_master
)
2390 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
2394 // control messages must have bits 0x80|0x40|0x08
2395 // (type, length and sequence) set, and bits 0x02|0x01
2396 // (offset and priority) clear
2397 if ((*buf
& 0xCB) != 0xC8)
2399 LOG(1, s
, t
, "Bad control header %02X\n", *buf
);
2400 STAT(tunnel_rx_errors
);
2404 // check for duplicate tunnel open message
2410 // Is this a duplicate of the first packet? (SCCRQ)
2412 for (i
= 1; i
<= config
->cluster_highest_tunnelid
; ++i
)
2414 if (tunnel
[i
].state
!= TUNNELOPENING
||
2415 tunnel
[i
].ip
!= ntohl(*(in_addr_t
*) & addr
->sin_addr
) ||
2416 tunnel
[i
].port
!= ntohs(addr
->sin_port
) )
2419 LOG(3, s
, t
, "Duplicate SCCRQ?\n");
2424 LOG(3, s
, t
, "Control message (%d bytes): (unacked %d) l-ns %u l-nr %u r-ns %u r-nr %u\n",
2425 l
, tunnel
[t
].controlc
, tunnel
[t
].ns
, tunnel
[t
].nr
, ns
, nr
);
2427 // if no tunnel specified, assign one
2430 if (!(t
= new_tunnel()))
2432 LOG(1, 0, 0, "No more tunnels\n");
2433 STAT(tunnel_overflow
);
2437 tunnel
[t
].ip
= ntohl(*(in_addr_t
*) & addr
->sin_addr
);
2438 tunnel
[t
].port
= ntohs(addr
->sin_port
);
2439 tunnel
[t
].window
= 4; // default window
2440 STAT(tunnel_created
);
2441 LOG(1, 0, t
, " New tunnel from %s:%u ID %u\n",
2442 fmtaddr(htonl(tunnel
[t
].ip
), 0), tunnel
[t
].port
, t
);
2445 // If the 'ns' just received is not the 'nr' we're
2446 // expecting, just send an ack and drop it.
2448 // if 'ns' is less, then we got a retransmitted packet.
2449 // if 'ns' is greater than missed a packet. Either way
2450 // we should ignore it.
2451 if (ns
!= tunnel
[t
].nr
)
2453 // is this the sequence we were expecting?
2454 STAT(tunnel_rx_errors
);
2455 LOG(1, 0, t
, " Out of sequence tunnel %u, (%u is not the expected %u)\n",
2456 t
, ns
, tunnel
[t
].nr
);
2458 if (l
) // Is this not a ZLB?
2463 // check sequence of this message
2465 int skip
= tunnel
[t
].window
; // track how many in-window packets are still in queue
2466 // some to clear maybe?
2467 while (tunnel
[t
].controlc
> 0 && (((tunnel
[t
].ns
- tunnel
[t
].controlc
) - nr
) & 0x8000))
2469 controlt
*c
= tunnel
[t
].controls
;
2470 tunnel
[t
].controls
= c
->next
;
2471 tunnel
[t
].controlc
--;
2472 c
->next
= controlfree
;
2475 tunnel
[t
].try = 0; // we have progress
2478 // receiver advance (do here so quoted correctly in any sends below)
2479 if (l
) tunnel
[t
].nr
= (ns
+ 1);
2480 if (skip
< 0) skip
= 0;
2481 if (skip
< tunnel
[t
].controlc
)
2483 // some control packets can now be sent that were previous stuck out of window
2484 int tosend
= tunnel
[t
].window
- skip
;
2485 controlt
*c
= tunnel
[t
].controls
;
2493 tunnel
[t
].try = 0; // first send
2494 tunnelsend(c
->buf
, c
->length
, t
);
2499 if (!tunnel
[t
].controlc
)
2500 tunnel
[t
].retry
= 0; // caught up
2503 { // if not a null message
2508 // Default disconnect cause/message on receipt of CDN. Set to
2509 // more specific value from attribute 1 (result code) or 46
2510 // (disconnect cause) if present below.
2511 int disc_cause_set
= 0;
2512 int disc_cause
= TERM_NAS_REQUEST
;
2513 char const *disc_reason
= "Closed (Received CDN).";
2516 while (l
&& !(fatal
& 0x80)) // 0x80 = mandatory AVP
2518 uint16_t n
= (ntohs(*(uint16_t *) p
) & 0x3FF);
2525 LOG(1, s
, t
, "Invalid length in AVP\n");
2526 STAT(tunnel_rx_errors
);
2531 if (flags
& 0x3C) // reserved bits, should be clear
2533 LOG(1, s
, t
, "Unrecognised AVP flags %02X\n", *b
);
2535 result
= 2; // general error
2536 error
= 3; // reserved field non-zero
2541 if (*(uint16_t *) (b
))
2543 LOG(2, s
, t
, "Unknown AVP vendor %u\n", ntohs(*(uint16_t *) (b
)));
2545 result
= 2; // general error
2546 error
= 6; // generic vendor-specific error
2547 msg
= "unsupported vendor-specific";
2551 mtype
= ntohs(*(uint16_t *) (b
));
2559 // handle hidden AVPs
2560 if (!*config
->l2tp_secret
)
2562 LOG(1, s
, t
, "Hidden AVP requested, but no L2TP secret.\n");
2564 result
= 2; // general error
2565 error
= 6; // generic vendor-specific error
2566 msg
= "secret not specified";
2569 if (!session
[s
].random_vector_length
)
2571 LOG(1, s
, t
, "Hidden AVP requested, but no random vector.\n");
2573 result
= 2; // general error
2574 error
= 6; // generic
2575 msg
= "no random vector";
2580 LOG(2, s
, t
, "Short hidden AVP.\n");
2582 result
= 2; // general error
2583 error
= 2; // length is wrong
2589 unhide_value(b
, n
, mtype
, session
[s
].random_vector
, session
[s
].random_vector_length
);
2591 orig_len
= ntohs(*(uint16_t *) b
);
2592 if (orig_len
> n
+ 2)
2594 LOG(1, s
, t
, "Original length %d too long in hidden AVP of length %d; wrong secret?\n",
2598 result
= 2; // general error
2599 error
= 2; // length is wrong
2608 LOG(4, s
, t
, " AVP %u (%s) len %d%s%s\n", mtype
, l2tp_avp_name(mtype
), n
,
2609 flags
& 0x40 ? ", hidden" : "", flags
& 0x80 ? ", mandatory" : "");
2613 case 0: // message type
2614 message
= ntohs(*(uint16_t *) b
);
2615 mandatory
= flags
& 0x80;
2616 LOG(4, s
, t
, " Message type = %u (%s)\n", *b
, l2tp_code(message
));
2618 case 1: // result code
2620 uint16_t rescode
= ntohs(*(uint16_t *) b
);
2621 char const *resdesc
= "(unknown)";
2622 char const *errdesc
= NULL
;
2627 resdesc
= l2tp_stopccn_result_code(rescode
);
2628 cause
= TERM_LOST_SERVICE
;
2630 else if (message
== 14)
2632 resdesc
= l2tp_cdn_result_code(rescode
);
2634 cause
= TERM_LOST_CARRIER
;
2636 cause
= TERM_ADMIN_RESET
;
2639 LOG(4, s
, t
, " Result Code %u: %s\n", rescode
, resdesc
);
2642 uint16_t errcode
= ntohs(*(uint16_t *)(b
+ 2));
2643 errdesc
= l2tp_error_code(errcode
);
2644 LOG(4, s
, t
, " Error Code %u: %s\n", errcode
, errdesc
);
2647 LOG(4, s
, t
, " Error String: %.*s\n", n
-4, b
+4);
2649 if (cause
&& disc_cause_set
< mtype
) // take cause from attrib 46 in preference
2651 disc_cause_set
= mtype
;
2652 disc_reason
= errdesc
? errdesc
: resdesc
;
2659 case 2: // protocol version
2661 version
= ntohs(*(uint16_t *) (b
));
2662 LOG(4, s
, t
, " Protocol version = %u\n", version
);
2663 if (version
&& version
!= 0x0100)
2664 { // allow 0.0 and 1.0
2665 LOG(1, s
, t
, " Bad protocol version %04X\n", version
);
2667 result
= 5; // unspported protocol version
2668 error
= 0x0100; // supported version
2674 case 3: // framing capabilities
2676 case 4: // bearer capabilities
2678 case 5: // tie breaker
2679 // We never open tunnels, so we don't care about tie breakers
2681 case 6: // firmware revision
2683 case 7: // host name
2684 memset(tunnel
[t
].hostname
, 0, sizeof(tunnel
[t
].hostname
));
2685 memcpy(tunnel
[t
].hostname
, b
, (n
< sizeof(tunnel
[t
].hostname
)) ? n
: sizeof(tunnel
[t
].hostname
) - 1);
2686 LOG(4, s
, t
, " Tunnel hostname = \"%s\"\n", tunnel
[t
].hostname
);
2687 // TBA - to send to RADIUS
2689 case 8: // vendor name
2690 memset(tunnel
[t
].vendor
, 0, sizeof(tunnel
[t
].vendor
));
2691 memcpy(tunnel
[t
].vendor
, b
, (n
< sizeof(tunnel
[t
].vendor
)) ? n
: sizeof(tunnel
[t
].vendor
) - 1);
2692 LOG(4, s
, t
, " Vendor name = \"%s\"\n", tunnel
[t
].vendor
);
2694 case 9: // assigned tunnel
2695 tunnel
[t
].far
= ntohs(*(uint16_t *) (b
));
2696 LOG(4, s
, t
, " Remote tunnel id = %u\n", tunnel
[t
].far
);
2698 case 10: // rx window
2699 tunnel
[t
].window
= ntohs(*(uint16_t *) (b
));
2700 if (!tunnel
[t
].window
)
2701 tunnel
[t
].window
= 1; // window of 0 is silly
2702 LOG(4, s
, t
, " rx window = %u\n", tunnel
[t
].window
);
2704 case 11: // Challenge
2706 LOG(4, s
, t
, " LAC requested CHAP authentication for tunnel\n");
2707 build_chap_response(b
, 2, n
, &chapresponse
);
2710 case 13: // Response
2711 // Why did they send a response? We never challenge.
2712 LOG(2, s
, t
, " received unexpected challenge response\n");
2715 case 14: // assigned session
2716 asession
= session
[s
].far
= ntohs(*(uint16_t *) (b
));
2717 LOG(4, s
, t
, " assigned session = %u\n", asession
);
2719 case 15: // call serial number
2720 LOG(4, s
, t
, " call serial number = %u\n", ntohl(*(uint32_t *)b
));
2722 case 18: // bearer type
2723 LOG(4, s
, t
, " bearer type = %u\n", ntohl(*(uint32_t *)b
));
2726 case 19: // framing type
2727 LOG(4, s
, t
, " framing type = %u\n", ntohl(*(uint32_t *)b
));
2730 case 21: // called number
2731 memset(called
, 0, sizeof(called
));
2732 memcpy(called
, b
, (n
< sizeof(called
)) ? n
: sizeof(called
) - 1);
2733 LOG(4, s
, t
, " Called <%s>\n", called
);
2735 case 22: // calling number
2736 memset(calling
, 0, sizeof(calling
));
2737 memcpy(calling
, b
, (n
< sizeof(calling
)) ? n
: sizeof(calling
) - 1);
2738 LOG(4, s
, t
, " Calling <%s>\n", calling
);
2742 case 24: // tx connect speed
2745 session
[s
].tx_connect_speed
= ntohl(*(uint32_t *)b
);
2749 // AS5300s send connect speed as a string
2751 memset(tmp
, 0, sizeof(tmp
));
2752 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2753 session
[s
].tx_connect_speed
= atol(tmp
);
2755 LOG(4, s
, t
, " TX connect speed <%u>\n", session
[s
].tx_connect_speed
);
2757 case 38: // rx connect speed
2760 session
[s
].rx_connect_speed
= ntohl(*(uint32_t *)b
);
2764 // AS5300s send connect speed as a string
2766 memset(tmp
, 0, sizeof(tmp
));
2767 memcpy(tmp
, b
, (n
< sizeof(tmp
)) ? n
: sizeof(tmp
) - 1);
2768 session
[s
].rx_connect_speed
= atol(tmp
);
2770 LOG(4, s
, t
, " RX connect speed <%u>\n", session
[s
].rx_connect_speed
);
2772 case 25: // Physical Channel ID
2774 uint32_t tmp
= ntohl(*(uint32_t *) b
);
2775 LOG(4, s
, t
, " Physical Channel ID <%X>\n", tmp
);
2778 case 29: // Proxy Authentication Type
2780 uint16_t atype
= ntohs(*(uint16_t *)b
);
2781 LOG(4, s
, t
, " Proxy Auth Type %u (%s)\n", atype
, ppp_auth_type(atype
));
2784 case 30: // Proxy Authentication Name
2787 memset(authname
, 0, sizeof(authname
));
2788 memcpy(authname
, b
, (n
< sizeof(authname
)) ? n
: sizeof(authname
) - 1);
2789 LOG(4, s
, t
, " Proxy Auth Name (%s)\n",
2793 case 31: // Proxy Authentication Challenge
2795 LOG(4, s
, t
, " Proxy Auth Challenge\n");
2798 case 32: // Proxy Authentication ID
2800 uint16_t authid
= ntohs(*(uint16_t *)(b
));
2801 LOG(4, s
, t
, " Proxy Auth ID (%u)\n", authid
);
2804 case 33: // Proxy Authentication Response
2805 LOG(4, s
, t
, " Proxy Auth Response\n");
2807 case 27: // last sent lcp
2808 { // find magic number
2809 uint8_t *p
= b
, *e
= p
+ n
;
2810 while (p
+ 1 < e
&& p
[1] && p
+ p
[1] <= e
)
2812 if (*p
== 5 && p
[1] == 6) // Magic-Number
2813 amagic
= ntohl(*(uint32_t *) (p
+ 2));
2814 else if (*p
== 7) // Protocol-Field-Compression
2815 aflags
|= SESSION_PFC
;
2816 else if (*p
== 8) // Address-and-Control-Field-Compression
2817 aflags
|= SESSION_ACFC
;
2822 case 28: // last recv lcp confreq
2824 case 26: // Initial Received LCP CONFREQ
2826 case 39: // seq required - we control it as an LNS anyway...
2828 case 36: // Random Vector
2829 LOG(4, s
, t
, " Random Vector received. Enabled AVP Hiding.\n");
2830 memset(session
[s
].random_vector
, 0, sizeof(session
[s
].random_vector
));
2831 if (n
> sizeof(session
[s
].random_vector
))
2832 n
= sizeof(session
[s
].random_vector
);
2833 memcpy(session
[s
].random_vector
, b
, n
);
2834 session
[s
].random_vector_length
= n
;
2836 case 46: // ppp disconnect cause
2839 uint16_t code
= ntohs(*(uint16_t *) b
);
2840 uint16_t proto
= ntohs(*(uint16_t *) (b
+ 2));
2841 uint8_t dir
= *(b
+ 4);
2843 LOG(4, s
, t
, " PPP disconnect cause "
2844 "(code=%u, proto=%04X, dir=%u, msg=\"%.*s\")\n",
2845 code
, proto
, dir
, n
- 5, b
+ 5);
2847 disc_cause_set
= mtype
;
2851 case 1: // admin disconnect
2852 disc_cause
= TERM_ADMIN_RESET
;
2853 disc_reason
= "Administrative disconnect";
2855 case 3: // lcp terminate
2856 if (dir
!= 2) break; // 1=peer (LNS), 2=local (LAC)
2857 disc_cause
= TERM_USER_REQUEST
;
2858 disc_reason
= "Normal disconnection";
2860 case 4: // compulsory encryption unavailable
2861 if (dir
!= 1) break; // 1=refused by peer, 2=local
2862 disc_cause
= TERM_USER_ERROR
;
2863 disc_reason
= "Compulsory encryption refused";
2865 case 5: // lcp: fsm timeout
2866 disc_cause
= TERM_PORT_ERROR
;
2867 disc_reason
= "LCP: FSM timeout";
2869 case 6: // lcp: no recognisable lcp packets received
2870 disc_cause
= TERM_PORT_ERROR
;
2871 disc_reason
= "LCP: no recognisable LCP packets";
2873 case 7: // lcp: magic-no error (possibly looped back)
2874 disc_cause
= TERM_PORT_ERROR
;
2875 disc_reason
= "LCP: magic-no error (possible loop)";
2877 case 8: // lcp: echo request timeout
2878 disc_cause
= TERM_PORT_ERROR
;
2879 disc_reason
= "LCP: echo request timeout";
2881 case 13: // auth: fsm timeout
2882 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2883 disc_reason
= "Authentication: FSM timeout";
2885 case 15: // auth: unacceptable auth protocol
2886 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2887 disc_reason
= "Unacceptable authentication protocol";
2889 case 16: // auth: authentication failed
2890 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2891 disc_reason
= "Authentication failed";
2893 case 17: // ncp: fsm timeout
2894 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2895 disc_reason
= "NCP: FSM timeout";
2897 case 18: // ncp: no ncps available
2898 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2899 disc_reason
= "NCP: no NCPs available";
2901 case 19: // ncp: failure to converge on acceptable address
2902 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2903 disc_reason
= (dir
== 1)
2904 ? "NCP: too many Configure-Naks received from peer"
2905 : "NCP: too many Configure-Naks sent to peer";
2907 case 20: // ncp: user not permitted to use any address
2908 disc_cause
= TERM_SERVICE_UNAVAILABLE
;
2909 disc_reason
= (dir
== 1)
2910 ? "NCP: local link address not acceptable to peer"
2911 : "NCP: remote link address not acceptable";
2918 static char e
[] = "unknown AVP 0xXXXX";
2919 LOG(2, s
, t
, " Unknown AVP type %u\n", mtype
);
2921 result
= 2; // general error
2922 error
= 8; // unknown mandatory AVP
2923 sprintf((msg
= e
) + 14, "%04x", mtype
);
2930 tunnelshutdown(t
, "Invalid mandatory AVP", result
, error
, msg
);
2934 case 1: // SCCRQ - Start Control Connection Request
2935 tunnel
[t
].state
= TUNNELOPENING
;
2936 if (main_quit
!= QUIT_SHUTDOWN
)
2938 controlt
*c
= controlnew(2); // sending SCCRP
2939 control16(c
, 2, version
, 1); // protocol version
2940 control32(c
, 3, 3, 1); // framing
2941 controls(c
, 7, hostname
, 1); // host name
2942 if (chapresponse
) controlb(c
, 13, chapresponse
, 16, 1); // Challenge response
2943 control16(c
, 9, t
, 1); // assigned tunnel
2944 controladd(c
, 0, t
); // send the resply
2948 tunnelshutdown(t
, "Shutting down", 6, 0, 0);
2952 tunnel
[t
].state
= TUNNELOPEN
;
2953 tunnel
[t
].lastrec
= time_now
;
2956 tunnel
[t
].state
= TUNNELOPEN
;
2957 tunnel
[t
].lastrec
= time_now
;
2958 controlnull(t
); // ack
2961 controlnull(t
); // ack
2962 tunnelshutdown(t
, "Stopped", 0, 0, 0); // Shut down cleanly
2965 controlnull(t
); // simply ACK
2977 if (sessionfree
&& main_quit
!= QUIT_SHUTDOWN
)
2979 controlt
*c
= controlnew(11); // ICRP
2982 sessionfree
= session
[s
].next
;
2983 memset(&session
[s
], 0, sizeof(session
[s
]));
2985 if (s
> config
->cluster_highest_sessionid
)
2986 config
->cluster_highest_sessionid
= s
;
2988 session
[s
].opened
= time_now
;
2989 session
[s
].tunnel
= t
;
2990 session
[s
].far
= asession
;
2991 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
2992 LOG(3, s
, t
, "New session (%u/%u)\n", tunnel
[t
].far
, session
[s
].far
);
2993 control16(c
, 14, s
, 1); // assigned session
2994 controladd(c
, asession
, t
); // send the reply
2996 strncpy(session
[s
].called
, called
, sizeof(session
[s
].called
) - 1);
2997 strncpy(session
[s
].calling
, calling
, sizeof(session
[s
].calling
) - 1);
2999 session
[s
].ppp
.phase
= Establish
;
3000 session
[s
].ppp
.lcp
= Starting
;
3002 STAT(session_created
);
3007 controlt
*c
= controlnew(14); // CDN
3010 STAT(session_overflow
);
3011 LOG(1, 0, t
, "No free sessions\n");
3012 control16(c
, 1, 4, 0); // temporary lack of resources
3015 control16(c
, 1, 2, 7); // shutting down, try another
3017 controladd(c
, asession
, t
); // send the message
3024 if (amagic
== 0) amagic
= time_now
;
3025 session
[s
].magic
= amagic
; // set magic number
3026 session
[s
].flags
= aflags
; // set flags received
3027 session
[s
].mru
= PPPoE_MRU
; // default
3028 controlnull(t
); // ack
3031 sess_local
[s
].lcp_authtype
= config
->radius_authprefer
;
3032 sess_local
[s
].ppp_mru
= MRU
;
3034 // Set multilink options before sending initial LCP packet
3035 sess_local
[s
].mp_mrru
= 1614;
3036 sess_local
[s
].mp_epdis
= ntohl(config
->bind_address
? config
->bind_address
: my_address
);
3039 change_state(s
, lcp
, RequestSent
);
3043 controlnull(t
); // ack
3044 sessionshutdown(s
, disc_reason
, CDN_NONE
, disc_cause
);
3047 LOG(1, s
, t
, "Missing message type\n");
3050 STAT(tunnel_rx_errors
);
3052 tunnelshutdown(t
, "Unknown message type", 2, 6, "unknown message type");
3054 LOG(1, s
, t
, "Unknown message type %u\n", message
);
3057 if (chapresponse
) free(chapresponse
);
3058 cluster_send_tunnel(t
);
3062 LOG(4, s
, t
, " Got a ZLB ack\n");
3069 LOG_HEX(5, "Receive Tunnel Data", p
, l
);
3070 if (l
> 2 && p
[0] == 0xFF && p
[1] == 0x03)
3071 { // HDLC address header, discard
3077 LOG(1, s
, t
, "Short ppp length %d\n", l
);
3078 STAT(tunnel_rx_errors
);
3088 proto
= ntohs(*(uint16_t *) p
);
3093 if (s
&& !session
[s
].opened
) // Is something wrong??
3095 if (!config
->cluster_iam_master
)
3097 // Pass it off to the master to deal with..
3098 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3103 LOG(1, s
, t
, "UDP packet contains session which is not opened. Dropping packet.\n");
3104 STAT(tunnel_rx_errors
);
3108 if (proto
== PPPPAP
)
3110 session
[s
].last_packet
= time_now
;
3111 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3112 processpap(s
, t
, p
, l
);
3114 else if (proto
== PPPCHAP
)
3116 session
[s
].last_packet
= time_now
;
3117 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3118 processchap(s
, t
, p
, l
);
3120 else if (proto
== PPPLCP
)
3122 session
[s
].last_packet
= time_now
;
3123 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3124 processlcp(s
, t
, p
, l
);
3126 else if (proto
== PPPIPCP
)
3128 session
[s
].last_packet
= time_now
;
3129 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3130 processipcp(s
, t
, p
, l
);
3132 else if (proto
== PPPIPV6CP
&& config
->ipv6_prefix
.s6_addr
[0])
3134 session
[s
].last_packet
= time_now
;
3135 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3136 processipv6cp(s
, t
, p
, l
);
3138 else if (proto
== PPPCCP
)
3140 session
[s
].last_packet
= time_now
;
3141 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3142 processccp(s
, t
, p
, l
);
3144 else if (proto
== PPPIP
)
3148 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3149 return; // closing session, PPP not processed
3152 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3153 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3155 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3159 processipin(s
, t
, p
, l
);
3161 else if (proto
== PPPMP
)
3165 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3166 return; // closing session, PPP not processed
3169 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3170 if (!config
->cluster_iam_master
)
3172 // The fragments reconstruction is managed by the Master.
3173 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3177 processmpin(s
, t
, p
, l
);
3179 else if (proto
== PPPIPV6
&& config
->ipv6_prefix
.s6_addr
[0])
3183 LOG(4, s
, t
, "Session %u is closing. Don't process PPP packets\n", s
);
3184 return; // closing session, PPP not processed
3187 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
3188 if (session
[s
].walled_garden
&& !config
->cluster_iam_master
)
3190 master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
);
3194 processipv6in(s
, t
, p
, l
);
3196 else if (session
[s
].ppp
.lcp
== Opened
)
3198 session
[s
].last_packet
= time_now
;
3199 if (!config
->cluster_iam_master
) { master_forward_packet(buf
, len
, addr
->sin_addr
.s_addr
, addr
->sin_port
); return; }
3200 protoreject(s
, t
, p
, l
, proto
);
3204 LOG(2, s
, t
, "Unknown PPP protocol 0x%04X received in LCP %s state\n",
3205 proto
, ppp_state(session
[s
].ppp
.lcp
));
3210 // read and process packet on tun
3211 static void processtun(uint8_t * buf
, int len
)
3213 LOG_HEX(5, "Receive TUN Data", buf
, len
);
3214 STAT(tun_rx_packets
);
3215 INC_STAT(tun_rx_bytes
, len
);
3223 LOG(1, 0, 0, "Short tun packet %d bytes\n", len
);
3224 STAT(tun_rx_errors
);
3228 if (*(uint16_t *) (buf
+ 2) == htons(PKTIP
)) // IPv4
3229 processipout(buf
, len
);
3230 else if (*(uint16_t *) (buf
+ 2) == htons(PKTIPV6
) // IPV6
3231 && config
->ipv6_prefix
.s6_addr
[0])
3232 processipv6out(buf
, len
);
3237 // Handle retries, timeouts. Runs every 1/10th sec, want to ensure
3238 // that we look at the whole of the tunnel, radius and session tables
3240 static void regular_cleanups(double period
)
3242 // Next tunnel, radius and session to check for actions on.
3243 static tunnelidt t
= 0;
3245 static sessionidt s
= 0;
3258 // divide up tables into slices based on the last run
3259 t_slice
= config
->cluster_highest_tunnelid
* period
;
3260 r_slice
= (MAXRADIUS
- 1) * period
;
3261 s_slice
= config
->cluster_highest_sessionid
* period
;
3265 else if (t_slice
> config
->cluster_highest_tunnelid
)
3266 t_slice
= config
->cluster_highest_tunnelid
;
3270 else if (r_slice
> (MAXRADIUS
- 1))
3271 r_slice
= MAXRADIUS
- 1;
3275 else if (s_slice
> config
->cluster_highest_sessionid
)
3276 s_slice
= config
->cluster_highest_sessionid
;
3278 LOG(4, 0, 0, "Begin regular cleanup (last %f seconds ago)\n", period
);
3280 for (i
= 0; i
< t_slice
; i
++)
3283 if (t
> config
->cluster_highest_tunnelid
)
3286 // check for expired tunnels
3287 if (tunnel
[t
].die
&& tunnel
[t
].die
<= TIME
)
3289 STAT(tunnel_timeout
);
3290 tunnelkill(t
, "Expired");
3294 // check for message resend
3295 if (tunnel
[t
].retry
&& tunnel
[t
].controlc
)
3297 // resend pending messages as timeout on reply
3298 if (tunnel
[t
].retry
<= TIME
)
3300 controlt
*c
= tunnel
[t
].controls
;
3301 uint16_t w
= tunnel
[t
].window
;
3302 tunnel
[t
].try++; // another try
3303 if (tunnel
[t
].try > 5)
3304 tunnelkill(t
, "Timeout on control message"); // game over
3308 tunnelsend(c
->buf
, c
->length
, t
);
3316 if (tunnel
[t
].state
== TUNNELOPEN
&& !tunnel
[t
].controlc
&& (time_now
- tunnel
[t
].lastrec
) > 60)
3318 controlt
*c
= controlnew(6); // sending HELLO
3319 controladd(c
, 0, t
); // send the message
3320 LOG(3, 0, t
, "Sending HELLO message\n");
3324 // Check for tunnel changes requested from the CLI
3325 if ((a
= cli_tunnel_actions
[t
].action
))
3327 cli_tunnel_actions
[t
].action
= 0;
3328 if (a
& CLI_TUN_KILL
)
3330 LOG(2, 0, t
, "Dropping tunnel by CLI\n");
3331 tunnelshutdown(t
, "Requested by administrator", 1, 0, 0);
3337 for (i
= 0; i
< r_slice
; i
++)
3343 if (!radius
[r
].state
)
3346 if (radius
[r
].retry
<= TIME
)
3353 for (i
= 0; i
< s_slice
; i
++)
3356 if (s
> config
->cluster_highest_sessionid
)
3359 if (!session
[s
].opened
) // Session isn't in use
3362 // check for expired sessions
3365 if (session
[s
].die
<= TIME
)
3367 sessionkill(s
, "Expired");
3374 if (sess_local
[s
].lcp
.restart
<= time_now
)
3376 int next_state
= session
[s
].ppp
.lcp
;
3377 switch (session
[s
].ppp
.lcp
)
3381 next_state
= RequestSent
;
3384 if (sess_local
[s
].lcp
.conf_sent
< config
->ppp_max_configure
)
3386 LOG(3, s
, session
[s
].tunnel
, "No ACK for LCP ConfigReq... resending\n");
3387 sendlcp(s
, session
[s
].tunnel
);
3388 change_state(s
, lcp
, next_state
);
3392 sessionshutdown(s
, "No response to LCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3393 STAT(session_timeout
);
3403 if (sess_local
[s
].ipcp
.restart
<= time_now
)
3405 int next_state
= session
[s
].ppp
.ipcp
;
3406 switch (session
[s
].ppp
.ipcp
)
3410 next_state
= RequestSent
;
3413 if (sess_local
[s
].ipcp
.conf_sent
< config
->ppp_max_configure
)
3415 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPCP ConfigReq... resending\n");
3416 sendipcp(s
, session
[s
].tunnel
);
3417 change_state(s
, ipcp
, next_state
);
3421 sessionshutdown(s
, "No response to IPCP ConfigReq.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3422 STAT(session_timeout
);
3432 if (sess_local
[s
].ipv6cp
.restart
<= time_now
)
3434 int next_state
= session
[s
].ppp
.ipv6cp
;
3435 switch (session
[s
].ppp
.ipv6cp
)
3439 next_state
= RequestSent
;
3442 if (sess_local
[s
].ipv6cp
.conf_sent
< config
->ppp_max_configure
)
3444 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq... resending\n");
3445 sendipv6cp(s
, session
[s
].tunnel
);
3446 change_state(s
, ipv6cp
, next_state
);
3450 LOG(3, s
, session
[s
].tunnel
, "No ACK for IPV6CP ConfigReq\n");
3451 change_state(s
, ipv6cp
, Stopped
);
3458 if (sess_local
[s
].ccp
.restart
<= time_now
)
3460 int next_state
= session
[s
].ppp
.ccp
;
3461 switch (session
[s
].ppp
.ccp
)
3465 next_state
= RequestSent
;
3468 if (sess_local
[s
].ccp
.conf_sent
< config
->ppp_max_configure
)
3470 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq... resending\n");
3471 sendccp(s
, session
[s
].tunnel
);
3472 change_state(s
, ccp
, next_state
);
3476 LOG(3, s
, session
[s
].tunnel
, "No ACK for CCP ConfigReq\n");
3477 change_state(s
, ccp
, Stopped
);
3484 // Drop sessions who have not responded within IDLE_TIMEOUT seconds
3485 if (session
[s
].last_packet
&& (time_now
- session
[s
].last_packet
>= IDLE_TIMEOUT
))
3487 sessionshutdown(s
, "No response to LCP ECHO requests.", CDN_ADMIN_DISC
, TERM_LOST_SERVICE
);
3488 STAT(session_timeout
);
3493 // No data in ECHO_TIMEOUT seconds, send LCP ECHO
3494 if (session
[s
].ppp
.phase
>= Establish
&& (time_now
- session
[s
].last_packet
>= ECHO_TIMEOUT
) &&
3495 (time_now
- sess_local
[s
].last_echo
>= ECHO_TIMEOUT
))
3497 uint8_t b
[MAXETHER
];
3499 uint8_t *q
= makeppp(b
, sizeof(b
), 0, 0, s
, session
[s
].tunnel
, PPPLCP
, 1, 0, 0);
3503 *(uint8_t *)(q
+ 1) = (time_now
% 255); // ID
3504 *(uint16_t *)(q
+ 2) = htons(8); // Length
3505 *(uint32_t *)(q
+ 4) = session
[s
].ppp
.lcp
== Opened
? htonl(session
[s
].magic
) : 0; // Magic Number
3507 LOG(4, s
, session
[s
].tunnel
, "No data in %d seconds, sending LCP ECHO\n",
3508 (int)(time_now
- session
[s
].last_packet
));
3509 tunnelsend(b
, 24, session
[s
].tunnel
); // send it
3510 sess_local
[s
].last_echo
= time_now
;
3514 // Drop sessions who have reached session_timeout seconds
3515 if (session
[s
].session_timeout
)
3517 bundleidt bid
= session
[s
].bundle
;
3520 if (time_now
- bundle
[bid
].last_check
>= 1)
3522 bundle
[bid
].online_time
+= (time_now
- bundle
[bid
].last_check
) * bundle
[bid
].num_of_links
;
3523 bundle
[bid
].last_check
= time_now
;
3524 if (bundle
[bid
].online_time
>= session
[s
].session_timeout
)
3527 for (ses
= bundle
[bid
].num_of_links
- 1; ses
>= 0; ses
--)
3529 sessionshutdown(bundle
[bid
].members
[ses
], "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3536 else if (time_now
- session
[s
].opened
>= session
[s
].session_timeout
)
3538 sessionshutdown(s
, "Session timeout", CDN_ADMIN_DISC
, TERM_SESSION_TIMEOUT
);
3544 // Drop sessions who have reached idle_timeout seconds
3545 if (session
[s
].last_data
&& session
[s
].idle_timeout
&& (time_now
- session
[s
].last_data
>= session
[s
].idle_timeout
))
3547 sessionshutdown(s
, "Idle Timeout Reached", CDN_ADMIN_DISC
, TERM_IDLE_TIMEOUT
);
3548 STAT(session_timeout
);
3553 // Check for actions requested from the CLI
3554 if ((a
= cli_session_actions
[s
].action
))
3558 cli_session_actions
[s
].action
= 0;
3559 if (a
& CLI_SESS_KILL
)
3561 LOG(2, s
, session
[s
].tunnel
, "Dropping session by CLI\n");
3562 sessionshutdown(s
, "Requested by administrator.", CDN_ADMIN_DISC
, TERM_ADMIN_RESET
);
3563 a
= 0; // dead, no need to check for other actions
3567 if (a
& CLI_SESS_NOSNOOP
)
3569 LOG(2, s
, session
[s
].tunnel
, "Unsnooping session by CLI\n");
3570 session
[s
].snoop_ip
= 0;
3571 session
[s
].snoop_port
= 0;
3575 else if (a
& CLI_SESS_SNOOP
)
3577 LOG(2, s
, session
[s
].tunnel
, "Snooping session by CLI (to %s:%u)\n",
3578 fmtaddr(cli_session_actions
[s
].snoop_ip
, 0),
3579 cli_session_actions
[s
].snoop_port
);
3581 session
[s
].snoop_ip
= cli_session_actions
[s
].snoop_ip
;
3582 session
[s
].snoop_port
= cli_session_actions
[s
].snoop_port
;
3587 if (a
& CLI_SESS_NOTHROTTLE
)
3589 LOG(2, s
, session
[s
].tunnel
, "Un-throttling session by CLI\n");
3590 throttle_session(s
, 0, 0);
3594 else if (a
& CLI_SESS_THROTTLE
)
3596 LOG(2, s
, session
[s
].tunnel
, "Throttling session by CLI (to %dkb/s up and %dkb/s down)\n",
3597 cli_session_actions
[s
].throttle_in
,
3598 cli_session_actions
[s
].throttle_out
);
3600 throttle_session(s
, cli_session_actions
[s
].throttle_in
, cli_session_actions
[s
].throttle_out
);
3605 if (a
& CLI_SESS_NOFILTER
)
3607 LOG(2, s
, session
[s
].tunnel
, "Un-filtering session by CLI\n");
3608 filter_session(s
, 0, 0);
3612 else if (a
& CLI_SESS_FILTER
)
3614 LOG(2, s
, session
[s
].tunnel
, "Filtering session by CLI (in=%d, out=%d)\n",
3615 cli_session_actions
[s
].filter_in
,
3616 cli_session_actions
[s
].filter_out
);
3618 filter_session(s
, cli_session_actions
[s
].filter_in
, cli_session_actions
[s
].filter_out
);
3624 cluster_send_session(s
);
3627 // RADIUS interim accounting
3628 if (config
->radius_accounting
&& config
->radius_interim
> 0
3629 && session
[s
].ip
&& !session
[s
].walled_garden
3630 && !sess_local
[s
].radius
// RADIUS already in progress
3631 && time_now
- sess_local
[s
].last_interim
>= config
->radius_interim
3632 && session
[s
].flags
& SESSION_STARTED
)
3634 int rad
= radiusnew(s
);
3637 LOG(1, s
, session
[s
].tunnel
, "No free RADIUS sessions for Interim message\n");
3638 STAT(radius_overflow
);
3642 LOG(3, s
, session
[s
].tunnel
, "Sending RADIUS Interim for %s (%u)\n",
3643 session
[s
].user
, session
[s
].unique_id
);
3645 radiussend(rad
, RADIUSINTERIM
);
3646 sess_local
[s
].last_interim
= time_now
;
3651 LOG(4, 0, 0, "End regular cleanup: checked %d/%d/%d tunnels/radius/sessions; %d/%d/%d actions\n",
3652 t_slice
, r_slice
, s_slice
, t_actions
, r_actions
, s_actions
);
3656 // Are we in the middle of a tunnel update, or radius
3659 static int still_busy(void)
3662 static clockt last_talked
= 0;
3663 static clockt start_busy_wait
= 0;
3666 static time_t stopped_bgp
= 0;
3671 LOG(1, 0, 0, "Shutting down in %d seconds, stopping BGP...\n", QUIT_DELAY
);
3673 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3674 if (bgp_peers
[i
].state
== Established
)
3675 bgp_stop(&bgp_peers
[i
]);
3677 stopped_bgp
= time_now
;
3679 if (!config
->cluster_iam_master
)
3681 // we don't want to become master
3682 cluster_send_ping(0);
3688 if (!config
->cluster_iam_master
&& time_now
< (stopped_bgp
+ QUIT_DELAY
))
3693 if (!config
->cluster_iam_master
)
3696 if (main_quit
== QUIT_SHUTDOWN
)
3698 static int dropped
= 0;
3703 LOG(1, 0, 0, "Dropping sessions and tunnels\n");
3704 for (i
= 1; i
< MAXTUNNEL
; i
++)
3705 if (tunnel
[i
].ip
|| tunnel
[i
].state
)
3706 tunnelshutdown(i
, "L2TPNS Closing", 6, 0, 0);
3712 if (start_busy_wait
== 0)
3713 start_busy_wait
= TIME
;
3715 for (i
= config
->cluster_highest_tunnelid
; i
> 0 ; --i
)
3717 if (!tunnel
[i
].controlc
)
3720 if (last_talked
!= TIME
)
3722 LOG(2, 0, 0, "Tunnel %u still has un-acked control messages.\n", i
);
3728 // We stop waiting for radius after BUSY_WAIT_TIME 1/10th seconds
3729 if (abs(TIME
- start_busy_wait
) > BUSY_WAIT_TIME
)
3731 LOG(1, 0, 0, "Giving up waiting for RADIUS to be empty. Shutting down anyway.\n");
3735 for (i
= 1; i
< MAXRADIUS
; i
++)
3737 if (radius
[i
].state
== RADIUSNULL
)
3739 if (radius
[i
].state
== RADIUSWAIT
)
3742 if (last_talked
!= TIME
)
3744 LOG(2, 0, 0, "Radius session %u is still busy (sid %u)\n", i
, radius
[i
].session
);
3754 # include <sys/epoll.h>
3756 # define FAKE_EPOLL_IMPLEMENTATION /* include the functions */
3757 # include "fake_epoll.h"
3760 // the base set of fds polled: cli, cluster, tun, udp, control, dae, netlink
3763 // additional polled fds
3765 # define EXTRA_FDS BGP_NUM_PEERS
3767 # define EXTRA_FDS 0
3770 // main loop - gets packets on tun or udp and processes them
3771 static void mainloop(void)
3775 clockt next_cluster_ping
= 0; // send initial ping immediately
3776 struct epoll_event events
[BASE_FDS
+ RADIUS_FDS
+ EXTRA_FDS
];
3777 int maxevent
= sizeof(events
)/sizeof(*events
);
3779 if ((epollfd
= epoll_create(maxevent
)) < 0)
3781 LOG(0, 0, 0, "epoll_create failed: %s\n", strerror(errno
));
3785 LOG(4, 0, 0, "Beginning of main loop. clifd=%d, cluster_sockfd=%d, tunfd=%d, udpfd=%d, controlfd=%d, daefd=%d, nlfd=%d\n",
3786 clifd
, cluster_sockfd
, tunfd
, udpfd
, controlfd
, daefd
, nlfd
);
3788 /* setup our fds to poll for input */
3790 static struct event_data d
[BASE_FDS
];
3791 struct epoll_event e
;
3798 d
[i
].type
= FD_TYPE_CLI
;
3799 e
.data
.ptr
= &d
[i
++];
3800 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, clifd
, &e
);
3803 d
[i
].type
= FD_TYPE_CLUSTER
;
3804 e
.data
.ptr
= &d
[i
++];
3805 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, cluster_sockfd
, &e
);
3807 d
[i
].type
= FD_TYPE_TUN
;
3808 e
.data
.ptr
= &d
[i
++];
3809 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, tunfd
, &e
);
3811 d
[i
].type
= FD_TYPE_UDP
;
3812 e
.data
.ptr
= &d
[i
++];
3813 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, udpfd
, &e
);
3815 d
[i
].type
= FD_TYPE_CONTROL
;
3816 e
.data
.ptr
= &d
[i
++];
3817 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, controlfd
, &e
);
3819 d
[i
].type
= FD_TYPE_DAE
;
3820 e
.data
.ptr
= &d
[i
++];
3821 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, daefd
, &e
);
3823 d
[i
].type
= FD_TYPE_NETLINK
;
3824 e
.data
.ptr
= &d
[i
++];
3825 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, nlfd
, &e
);
3829 signal(SIGPIPE
, SIG_IGN
);
3830 bgp_setup(config
->as_number
);
3831 if (config
->bind_address
)
3832 bgp_add_route(config
->bind_address
, 0xffffffff);
3834 for (i
= 0; i
< BGP_NUM_PEERS
; i
++)
3836 if (config
->neighbour
[i
].name
[0])
3837 bgp_start(&bgp_peers
[i
], config
->neighbour
[i
].name
,
3838 config
->neighbour
[i
].as
, config
->neighbour
[i
].keepalive
,
3839 config
->neighbour
[i
].hold
, config
->neighbour
[i
].update_source
,
3840 0); /* 0 = routing disabled */
3844 while (!main_quit
|| still_busy())
3854 config
->reload_config
++;
3857 if (config
->reload_config
)
3859 config
->reload_config
= 0;
3867 n
= epoll_wait(epollfd
, events
, maxevent
, 100); // timeout 100ms (1/10th sec)
3868 STAT(select_called
);
3873 if (errno
== EINTR
||
3874 errno
== ECHILD
) // EINTR was clobbered by sigchild_handler()
3877 LOG(0, 0, 0, "Error returned from select(): %s\n", strerror(errno
));
3883 struct sockaddr_in addr
;
3884 struct in_addr local
;
3889 int cluster_ready
= 0;
3892 int cluster_pkts
= 0;
3894 uint32_t bgp_events
[BGP_NUM_PEERS
];
3895 memset(bgp_events
, 0, sizeof(bgp_events
));
3898 for (c
= n
, i
= 0; i
< c
; i
++)
3900 struct event_data
*d
= events
[i
].data
.ptr
;
3904 case FD_TYPE_CLI
: // CLI connections
3908 alen
= sizeof(addr
);
3909 if ((cli
= accept(clifd
, (struct sockaddr
*)&addr
, &alen
)) >= 0)
3915 LOG(0, 0, 0, "accept error: %s\n", strerror(errno
));
3921 // these are handled below, with multiple interleaved reads
3922 case FD_TYPE_CLUSTER
: cluster_ready
++; break;
3923 case FD_TYPE_TUN
: tun_ready
++; break;
3924 case FD_TYPE_UDP
: udp_ready
++; break;
3926 case FD_TYPE_CONTROL
: // nsctl commands
3927 alen
= sizeof(addr
);
3928 s
= recvfromto(controlfd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3929 if (s
> 0) processcontrol(buf
, s
, &addr
, alen
, &local
);
3933 case FD_TYPE_DAE
: // DAE requests
3934 alen
= sizeof(addr
);
3935 s
= recvfromto(daefd
, buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
, &local
);
3936 if (s
> 0) processdae(buf
, s
, &addr
, alen
, &local
);
3940 case FD_TYPE_RADIUS
: // RADIUS response
3941 alen
= sizeof(addr
);
3942 s
= recvfrom(radfds
[d
->index
], buf
, sizeof(buf
), MSG_WAITALL
, (struct sockaddr
*) &addr
, &alen
);
3943 if (s
>= 0 && config
->cluster_iam_master
)
3945 if (addr
.sin_addr
.s_addr
== config
->radiusserver
[0] ||
3946 addr
.sin_addr
.s_addr
== config
->radiusserver
[1])
3947 processrad(buf
, s
, d
->index
);
3949 LOG(3, 0, 0, "Dropping RADIUS packet from unknown source %s\n",
3950 fmtaddr(addr
.sin_addr
.s_addr
, 0));
3958 bgp_events
[d
->index
] = events
[i
].events
;
3963 case FD_TYPE_NETLINK
:
3965 struct nlmsghdr
*nh
= (struct nlmsghdr
*)buf
;
3966 s
= netlink_recv(buf
, sizeof(buf
));
3967 if (nh
->nlmsg_type
== NLMSG_ERROR
)
3969 struct nlmsgerr
*errmsg
= NLMSG_DATA(nh
);
3972 if (errmsg
->msg
.nlmsg_seq
< min_initok_nlseqnum
)
3974 LOG(0, 0, 0, "Got a fatal netlink error (while %s): %s\n", tun_nl_phase_msg
[nh
->nlmsg_seq
], strerror(-errmsg
->error
));
3979 LOG(0, 0, 0, "Got a netlink error: %s\n", strerror(-errmsg
->error
));
3984 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
);
3990 LOG(0, 0, 0, "Unexpected fd type returned from epoll_wait: %d\n", d
->type
);
3995 bgp_process(bgp_events
);
3998 for (c
= 0; n
&& c
< config
->multi_read_count
; c
++)
4003 alen
= sizeof(addr
);
4004 if ((s
= recvfrom(udpfd
, buf
, sizeof(buf
), 0, (void *) &addr
, &alen
)) > 0)
4006 processudp(buf
, s
, &addr
);
4019 if ((s
= read(tunfd
, buf
, sizeof(buf
))) > 0)
4034 alen
= sizeof(addr
);
4035 if ((s
= recvfrom(cluster_sockfd
, buf
, sizeof(buf
), MSG_WAITALL
, (void *) &addr
, &alen
)) > 0)
4037 processcluster(buf
, s
, addr
.sin_addr
.s_addr
);
4048 if (udp_pkts
> 1 || tun_pkts
> 1 || cluster_pkts
> 1)
4049 STAT(multi_read_used
);
4051 if (c
>= config
->multi_read_count
)
4053 LOG(3, 0, 0, "Reached multi_read_count (%d); processed %d udp, %d tun and %d cluster packets\n",
4054 config
->multi_read_count
, udp_pkts
, tun_pkts
, cluster_pkts
);
4056 STAT(multi_read_exceeded
);
4062 /* no event received, but timers could still have expired */
4063 bgp_process_peers_timers();
4068 double Mbps
= 1024.0 * 1024.0 / 8 * time_changed
;
4070 // Log current traffic stats
4071 snprintf(config
->bandwidth
, sizeof(config
->bandwidth
),
4072 "UDP-ETH:%1.0f/%1.0f ETH-UDP:%1.0f/%1.0f TOTAL:%0.1f IN:%u OUT:%u",
4073 (udp_rx
/ Mbps
), (eth_tx
/ Mbps
), (eth_rx
/ Mbps
), (udp_tx
/ Mbps
),
4074 ((udp_tx
+ udp_rx
+ eth_tx
+ eth_rx
) / Mbps
),
4075 udp_rx_pkt
/ time_changed
, eth_rx_pkt
/ time_changed
);
4077 udp_tx
= udp_rx
= 0;
4078 udp_rx_pkt
= eth_rx_pkt
= 0;
4079 eth_tx
= eth_rx
= 0;
4082 if (config
->dump_speed
)
4083 printf("%s\n", config
->bandwidth
);
4085 // Update the internal time counter
4086 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4090 struct param_timer p
= { time_now
};
4091 run_plugins(PLUGIN_TIMER
, &p
);
4095 // Runs on every machine (master and slaves).
4096 if (next_cluster_ping
<= TIME
)
4098 // Check to see which of the cluster is still alive..
4100 cluster_send_ping(basetime
); // Only does anything if we're a slave
4101 cluster_check_master(); // ditto.
4103 cluster_heartbeat(); // Only does anything if we're a master.
4104 cluster_check_slaves(); // ditto.
4106 master_update_counts(); // If we're a slave, send our byte counters to our master.
4108 if (config
->cluster_iam_master
&& !config
->cluster_iam_uptodate
)
4109 next_cluster_ping
= TIME
+ 1; // out-of-date slaves, do fast updates
4111 next_cluster_ping
= TIME
+ config
->cluster_hb_interval
;
4114 if (!config
->cluster_iam_master
)
4117 // Run token bucket filtering queue..
4118 // Only run it every 1/10th of a second.
4120 static clockt last_run
= 0;
4121 if (last_run
!= TIME
)
4128 // Handle timeouts, retries etc.
4130 static double last_clean
= 0;
4134 TIME
= now(&this_clean
);
4135 diff
= this_clean
- last_clean
;
4137 // Run during idle time (after we've handled
4138 // all incoming packets) or every 1/10th sec
4139 if (!more
|| diff
> 0.1)
4141 regular_cleanups(diff
);
4142 last_clean
= this_clean
;
4146 if (*config
->accounting_dir
)
4148 static clockt next_acct
= 0;
4149 static clockt next_shut_acct
= 0;
4151 if (next_acct
<= TIME
)
4153 // Dump accounting data
4154 next_acct
= TIME
+ ACCT_TIME
;
4155 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4158 else if (next_shut_acct
<= TIME
)
4160 // Dump accounting data for shutdown sessions
4161 next_shut_acct
= TIME
+ ACCT_SHUT_TIME
;
4168 // Are we the master and shutting down??
4169 if (config
->cluster_iam_master
)
4170 cluster_heartbeat(); // Flush any queued changes..
4172 // Ok. Notify everyone we're shutting down. If we're
4173 // the master, this will force an election.
4174 cluster_send_ping(0);
4177 // Important!!! We MUST not process any packets past this point!
4178 LOG(1, 0, 0, "Shutdown complete\n");
4181 static void stripdomain(char *host
)
4185 if ((p
= strchr(host
, '.')))
4191 FILE *resolv
= fopen("/etc/resolv.conf", "r");
4197 while (fgets(buf
, sizeof(buf
), resolv
))
4199 if (strncmp(buf
, "domain", 6) && strncmp(buf
, "search", 6))
4202 if (!isspace(buf
[6]))
4206 while (isspace(*b
)) b
++;
4211 while (*b
&& !isspace(*b
)) b
++;
4213 if (buf
[0] == 'd') // domain is canonical
4219 // first search line
4222 // hold, may be subsequent domain line
4223 strncpy(_domain
, d
, sizeof(_domain
))[sizeof(_domain
)-1] = 0;
4234 int hl
= strlen(host
);
4235 int dl
= strlen(domain
);
4236 if (dl
< hl
&& host
[hl
- dl
- 1] == '.' && !strcmp(host
+ hl
- dl
, domain
))
4237 host
[hl
-dl
- 1] = 0;
4241 *p
= 0; // everything after first dot
4246 // Init data structures
4247 static void initdata(int optdebug
, char *optconfig
)
4251 if (!(config
= shared_malloc(sizeof(configt
))))
4253 fprintf(stderr
, "Error doing malloc for configuration: %s\n", strerror(errno
));
4257 memset(config
, 0, sizeof(configt
));
4258 time(&config
->start_time
);
4259 strncpy(config
->config_file
, optconfig
, strlen(optconfig
));
4260 config
->debug
= optdebug
;
4261 config
->num_tbfs
= MAXTBFS
;
4262 config
->rl_rate
= 28; // 28kbps
4263 config
->cluster_mcast_ttl
= 1;
4264 config
->cluster_master_min_adv
= 1;
4265 config
->ppp_restart_time
= 3;
4266 config
->ppp_max_configure
= 10;
4267 config
->ppp_max_failure
= 5;
4268 config
->kill_timedout_sessions
= 1;
4269 strcpy(config
->random_device
, RANDOMDEVICE
);
4271 log_stream
= stderr
;
4274 if (!(ringbuffer
= shared_malloc(sizeof(struct Tringbuffer
))))
4276 LOG(0, 0, 0, "Error doing malloc for ringbuffer: %s\n", strerror(errno
));
4279 memset(ringbuffer
, 0, sizeof(struct Tringbuffer
));
4282 if (!(_statistics
= shared_malloc(sizeof(struct Tstats
))))
4284 LOG(0, 0, 0, "Error doing malloc for _statistics: %s\n", strerror(errno
));
4287 if (!(tunnel
= shared_malloc(sizeof(tunnelt
) * MAXTUNNEL
)))
4289 LOG(0, 0, 0, "Error doing malloc for tunnels: %s\n", strerror(errno
));
4292 if (!(bundle
= shared_malloc(sizeof(bundlet
) * MAXBUNDLE
)))
4294 LOG(0, 0, 0, "Error doing malloc for bundles: %s\n", strerror(errno
));
4297 if (!(frag
= shared_malloc(sizeof(fragmentationt
) * MAXBUNDLE
)))
4299 LOG(0, 0, 0, "Error doing malloc for fragmentations: %s\n", strerror(errno
));
4302 if (!(session
= shared_malloc(sizeof(sessiont
) * MAXSESSION
)))
4304 LOG(0, 0, 0, "Error doing malloc for sessions: %s\n", strerror(errno
));
4308 if (!(sess_local
= shared_malloc(sizeof(sessionlocalt
) * MAXSESSION
)))
4310 LOG(0, 0, 0, "Error doing malloc for sess_local: %s\n", strerror(errno
));
4314 if (!(radius
= shared_malloc(sizeof(radiust
) * MAXRADIUS
)))
4316 LOG(0, 0, 0, "Error doing malloc for radius: %s\n", strerror(errno
));
4320 if (!(ip_address_pool
= shared_malloc(sizeof(ippoolt
) * MAXIPPOOL
)))
4322 LOG(0, 0, 0, "Error doing malloc for ip_address_pool: %s\n", strerror(errno
));
4326 if (!(ip_filters
= shared_malloc(sizeof(ip_filtert
) * MAXFILTER
)))
4328 LOG(0, 0, 0, "Error doing malloc for ip_filters: %s\n", strerror(errno
));
4331 memset(ip_filters
, 0, sizeof(ip_filtert
) * MAXFILTER
);
4333 if (!(cli_session_actions
= shared_malloc(sizeof(struct cli_session_actions
) * MAXSESSION
)))
4335 LOG(0, 0, 0, "Error doing malloc for cli session actions: %s\n", strerror(errno
));
4338 memset(cli_session_actions
, 0, sizeof(struct cli_session_actions
) * MAXSESSION
);
4340 if (!(cli_tunnel_actions
= shared_malloc(sizeof(struct cli_tunnel_actions
) * MAXSESSION
)))
4342 LOG(0, 0, 0, "Error doing malloc for cli tunnel actions: %s\n", strerror(errno
));
4345 memset(cli_tunnel_actions
, 0, sizeof(struct cli_tunnel_actions
) * MAXSESSION
);
4347 memset(tunnel
, 0, sizeof(tunnelt
) * MAXTUNNEL
);
4348 memset(bundle
, 0, sizeof(bundlet
) * MAXBUNDLE
);
4349 memset(session
, 0, sizeof(sessiont
) * MAXSESSION
);
4350 memset(radius
, 0, sizeof(radiust
) * MAXRADIUS
);
4351 memset(ip_address_pool
, 0, sizeof(ippoolt
) * MAXIPPOOL
);
4353 // Put all the sessions on the free list marked as undefined.
4354 for (i
= 1; i
< MAXSESSION
; i
++)
4356 session
[i
].next
= i
+ 1;
4357 session
[i
].tunnel
= T_UNDEF
; // mark it as not filled in.
4359 session
[MAXSESSION
- 1].next
= 0;
4362 // Mark all the tunnels as undefined (waiting to be filled in by a download).
4363 for (i
= 1; i
< MAXTUNNEL
; i
++)
4364 tunnel
[i
].state
= TUNNELUNDEF
; // mark it as not filled in.
4366 for (i
= 1; i
< MAXBUNDLE
; i
++) {
4367 bundle
[i
].state
= BUNDLEUNDEF
;
4372 // Grab my hostname unless it's been specified
4373 gethostname(hostname
, sizeof(hostname
));
4374 stripdomain(hostname
);
4377 _statistics
->start_time
= _statistics
->last_reset
= time(NULL
);
4380 if (!(bgp_peers
= shared_malloc(sizeof(struct bgp_peer
) * BGP_NUM_PEERS
)))
4382 LOG(0, 0, 0, "Error doing malloc for bgp: %s\n", strerror(errno
));
4388 static int assign_ip_address(sessionidt s
)
4392 time_t best_time
= time_now
;
4393 char *u
= session
[s
].user
;
4397 CSTAT(assign_ip_address
);
4399 for (i
= 1; i
< ip_pool_size
; i
++)
4401 if (!ip_address_pool
[i
].address
|| ip_address_pool
[i
].assigned
)
4404 if (!session
[s
].walled_garden
&& ip_address_pool
[i
].user
[0] && !strcmp(u
, ip_address_pool
[i
].user
))
4411 if (ip_address_pool
[i
].last
< best_time
)
4414 if (!(best_time
= ip_address_pool
[i
].last
))
4415 break; // never used, grab this one
4421 LOG(0, s
, session
[s
].tunnel
, "assign_ip_address(): out of addresses\n");
4425 session
[s
].ip
= ip_address_pool
[best
].address
;
4426 session
[s
].ip_pool_index
= best
;
4427 ip_address_pool
[best
].assigned
= 1;
4428 ip_address_pool
[best
].last
= time_now
;
4429 ip_address_pool
[best
].session
= s
;
4430 if (session
[s
].walled_garden
)
4431 /* Don't track addresses of users in walled garden (note: this
4432 means that their address isn't "sticky" even if they get
4434 ip_address_pool
[best
].user
[0] = 0;
4436 strncpy(ip_address_pool
[best
].user
, u
, sizeof(ip_address_pool
[best
].user
) - 1);
4439 LOG(4, s
, session
[s
].tunnel
, "assign_ip_address(): %s ip address %d from pool\n",
4440 reuse
? "Reusing" : "Allocating", best
);
4445 static void free_ip_address(sessionidt s
)
4447 int i
= session
[s
].ip_pool_index
;
4450 CSTAT(free_ip_address
);
4453 return; // what the?
4455 if (i
< 0) // Is this actually part of the ip pool?
4459 cache_ipmap(session
[s
].ip
, -i
); // Change the mapping to point back to the ip pool index.
4461 ip_address_pool
[i
].assigned
= 0;
4462 ip_address_pool
[i
].session
= 0;
4463 ip_address_pool
[i
].last
= time_now
;
4467 // Fsck the address pool against the session table.
4468 // Normally only called when we become a master.
4470 // This isn't perfect: We aren't keep tracking of which
4471 // users used to have an IP address.
4473 void rebuild_address_pool(void)
4478 // Zero the IP pool allocation, and build
4479 // a map from IP address to pool index.
4480 for (i
= 1; i
< MAXIPPOOL
; ++i
)
4482 ip_address_pool
[i
].assigned
= 0;
4483 ip_address_pool
[i
].session
= 0;
4484 if (!ip_address_pool
[i
].address
)
4487 cache_ipmap(ip_address_pool
[i
].address
, -i
); // Map pool IP to pool index.
4490 for (i
= 0; i
< MAXSESSION
; ++i
)
4493 if (!(session
[i
].opened
&& session
[i
].ip
))
4496 ipid
= - lookup_ipmap(htonl(session
[i
].ip
));
4498 if (session
[i
].ip_pool_index
< 0)
4500 // Not allocated out of the pool.
4501 if (ipid
< 1) // Not found in the pool either? good.
4504 LOG(0, i
, 0, "Session %u has an IP address (%s) that was marked static, but is in the pool (%d)!\n",
4505 i
, fmtaddr(session
[i
].ip
, 0), ipid
);
4507 // Fall through and process it as part of the pool.
4511 if (ipid
> MAXIPPOOL
|| ipid
< 0)
4513 LOG(0, i
, 0, "Session %u has a pool IP that's not found in the pool! (%d)\n", i
, ipid
);
4515 session
[i
].ip_pool_index
= ipid
;
4519 ip_address_pool
[ipid
].assigned
= 1;
4520 ip_address_pool
[ipid
].session
= i
;
4521 ip_address_pool
[ipid
].last
= time_now
;
4522 strncpy(ip_address_pool
[ipid
].user
, session
[i
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4523 session
[i
].ip_pool_index
= ipid
;
4524 cache_ipmap(session
[i
].ip
, i
); // Fix the ip map.
4529 // Fix the address pool to match a changed session.
4530 // (usually when the master sends us an update).
4531 static void fix_address_pool(int sid
)
4535 ipid
= session
[sid
].ip_pool_index
;
4537 if (ipid
> ip_pool_size
)
4538 return; // Ignore it. rebuild_address_pool will fix it up.
4540 if (ip_address_pool
[ipid
].address
!= session
[sid
].ip
)
4541 return; // Just ignore it. rebuild_address_pool will take care of it.
4543 ip_address_pool
[ipid
].assigned
= 1;
4544 ip_address_pool
[ipid
].session
= sid
;
4545 ip_address_pool
[ipid
].last
= time_now
;
4546 strncpy(ip_address_pool
[ipid
].user
, session
[sid
].user
, sizeof(ip_address_pool
[ipid
].user
) - 1);
4550 // Add a block of addresses to the IP pool to hand out.
4552 static void add_to_ip_pool(in_addr_t addr
, int prefixlen
)
4556 prefixlen
= 32; // Host route only.
4558 addr
&= 0xffffffff << (32 - prefixlen
);
4560 if (ip_pool_size
>= MAXIPPOOL
) // Pool is full!
4563 for (i
= addr
; i
< addr
+(1<<(32-prefixlen
)); ++i
)
4565 if ((i
& 0xff) == 0 || (i
&0xff) == 255)
4566 continue; // Skip 0 and broadcast addresses.
4568 ip_address_pool
[ip_pool_size
].address
= i
;
4569 ip_address_pool
[ip_pool_size
].assigned
= 0;
4571 if (ip_pool_size
>= MAXIPPOOL
)
4573 LOG(0, 0, 0, "Overflowed IP pool adding %s\n", fmtaddr(htonl(addr
), 0));
4579 // Initialize the IP address pool
4580 static void initippool()
4585 memset(ip_address_pool
, 0, sizeof(ip_address_pool
));
4587 if (!(f
= fopen(IPPOOLFILE
, "r")))
4589 LOG(0, 0, 0, "Can't load pool file " IPPOOLFILE
": %s\n", strerror(errno
));
4593 while (ip_pool_size
< MAXIPPOOL
&& fgets(buf
, 4096, f
))
4596 buf
[4095] = 0; // Force it to be zero terminated/
4598 if (*buf
== '#' || *buf
== '\n')
4599 continue; // Skip comments / blank lines
4600 if ((p
= (char *)strrchr(buf
, '\n'))) *p
= 0;
4601 if ((p
= (char *)strchr(buf
, ':')))
4605 src
= inet_addr(buf
);
4606 if (src
== INADDR_NONE
)
4608 LOG(0, 0, 0, "Invalid address pool IP %s\n", buf
);
4611 // This entry is for a specific IP only
4612 if (src
!= config
->bind_address
)
4617 if ((p
= (char *)strchr(pool
, '/')))
4621 in_addr_t start
= 0;
4623 LOG(2, 0, 0, "Adding IP address range %s\n", buf
);
4625 if (!*p
|| !(numbits
= atoi(p
)))
4627 LOG(0, 0, 0, "Invalid pool range %s\n", buf
);
4630 start
= ntohl(inet_addr(pool
));
4632 // Add a static route for this pool
4633 LOG(5, 0, 0, "Adding route for address pool %s/%d\n",
4634 fmtaddr(htonl(start
), 0), numbits
);
4636 routeset(0, start
, numbits
, 0, 1);
4638 add_to_ip_pool(start
, numbits
);
4642 // It's a single ip address
4643 add_to_ip_pool(ntohl(inet_addr(pool
)), 0);
4647 LOG(1, 0, 0, "IP address pool is %d addresses\n", ip_pool_size
- 1);
4650 void snoop_send_packet(uint8_t *packet
, uint16_t size
, in_addr_t destination
, uint16_t port
)
4652 struct sockaddr_in snoop_addr
= {0};
4653 if (!destination
|| !port
|| snoopfd
<= 0 || size
<= 0 || !packet
)
4656 snoop_addr
.sin_family
= AF_INET
;
4657 snoop_addr
.sin_addr
.s_addr
= destination
;
4658 snoop_addr
.sin_port
= ntohs(port
);
4660 LOG(5, 0, 0, "Snooping %d byte packet to %s:%u\n", size
,
4661 fmtaddr(snoop_addr
.sin_addr
.s_addr
, 0),
4662 htons(snoop_addr
.sin_port
));
4664 if (sendto(snoopfd
, packet
, size
, MSG_DONTWAIT
| MSG_NOSIGNAL
, (void *) &snoop_addr
, sizeof(snoop_addr
)) < 0)
4665 LOG(0, 0, 0, "Error sending intercept packet: %s\n", strerror(errno
));
4667 STAT(packets_snooped
);
4670 static int dump_session(FILE **f
, sessiont
*s
)
4672 if (!s
->opened
|| !s
->ip
|| !(s
->cin_delta
|| s
->cout_delta
) || !*s
->user
|| s
->walled_garden
)
4677 char filename
[1024];
4679 time_t now
= time(NULL
);
4681 strftime(timestr
, sizeof(timestr
), "%Y%m%d%H%M%S", localtime(&now
));
4682 snprintf(filename
, sizeof(filename
), "%s/%s", config
->accounting_dir
, timestr
);
4684 if (!(*f
= fopen(filename
, "w")))
4686 LOG(0, 0, 0, "Can't write accounting info to %s: %s\n", filename
, strerror(errno
));
4690 LOG(3, 0, 0, "Dumping accounting information to %s\n", filename
);
4691 fprintf(*f
, "# dslwatch.pl dump file V1.01\n"
4696 "# format: username ip qos uptxoctets downrxoctets\n",
4698 fmtaddr(config
->bind_address
? config
->bind_address
: my_address
, 0),
4703 LOG(4, 0, 0, "Dumping accounting information for %s\n", s
->user
);
4704 fprintf(*f
, "%s %s %d %u %u\n",
4705 s
->user
, // username
4706 fmtaddr(htonl(s
->ip
), 0), // ip
4707 (s
->throttle_in
|| s
->throttle_out
) ? 2 : 1, // qos
4708 (uint32_t) s
->cin_delta
, // uptxoctets
4709 (uint32_t) s
->cout_delta
); // downrxoctets
4711 s
->cin_delta
= s
->cout_delta
= 0;
4716 static void dump_acct_info(int all
)
4722 CSTAT(dump_acct_info
);
4726 for (i
= 0; i
< shut_acct_n
; i
++)
4727 dump_session(&f
, &shut_acct
[i
]);
4733 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
4734 dump_session(&f
, &session
[i
]);
4741 int main(int argc
, char *argv
[])
4745 char *optconfig
= CONFIGFILE
;
4747 time(&basetime
); // start clock
4750 while ((i
= getopt(argc
, argv
, "dvc:h:")) >= 0)
4755 if (fork()) exit(0);
4757 freopen("/dev/null", "r", stdin
);
4758 freopen("/dev/null", "w", stdout
);
4759 freopen("/dev/null", "w", stderr
);
4768 snprintf(hostname
, sizeof(hostname
), "%s", optarg
);
4771 printf("Args are:\n"
4772 "\t-d\t\tDetach from terminal\n"
4773 "\t-c <file>\tConfig file\n"
4774 "\t-h <hostname>\tForce hostname\n"
4782 // Start the timer routine off
4784 strftime(time_now_string
, sizeof(time_now_string
), "%Y-%m-%d %H:%M:%S", localtime(&time_now
));
4787 initdata(optdebug
, optconfig
);
4791 /* set hostname /after/ having read the config file */
4792 if (*config
->hostname
)
4793 strcpy(hostname
, config
->hostname
);
4794 cli_init_complete(hostname
);
4796 init_tbf(config
->num_tbfs
);
4798 LOG(0, 0, 0, "L2TPNS version " VERSION
"\n");
4799 LOG(0, 0, 0, "Copyright (c) 2003, 2004, 2005, 2006 Optus Internet Engineering\n");
4800 LOG(0, 0, 0, "Copyright (c) 2002 FireBrick (Andrews & Arnold Ltd / Watchfront Ltd) - GPL licenced\n");
4803 rlim
.rlim_cur
= RLIM_INFINITY
;
4804 rlim
.rlim_max
= RLIM_INFINITY
;
4805 // Remove the maximum core size
4806 if (setrlimit(RLIMIT_CORE
, &rlim
) < 0)
4807 LOG(0, 0, 0, "Can't set ulimit: %s\n", strerror(errno
));
4809 // Make core dumps go to /tmp
4813 if (config
->scheduler_fifo
)
4816 struct sched_param params
= {0};
4817 params
.sched_priority
= 1;
4819 if (get_nprocs() < 2)
4821 LOG(0, 0, 0, "Not using FIFO scheduler, there is only 1 processor in the system.\n");
4822 config
->scheduler_fifo
= 0;
4826 if ((ret
= sched_setscheduler(0, SCHED_FIFO
, ¶ms
)) == 0)
4828 LOG(1, 0, 0, "Using FIFO scheduler. Say goodbye to any other processes running\n");
4832 LOG(0, 0, 0, "Error setting scheduler to FIFO: %s\n", strerror(errno
));
4833 config
->scheduler_fifo
= 0;
4840 /* Set up the cluster communications port. */
4841 if (cluster_init() < 0)
4845 LOG(1, 0, 0, "Set up on interface %s\n", config
->tundevice
);
4853 unsigned seed
= time_now
^ getpid();
4854 LOG(4, 0, 0, "Seeding the pseudo random generator: %u\n", seed
);
4858 signal(SIGHUP
, sighup_handler
);
4859 signal(SIGCHLD
, sigchild_handler
);
4860 signal(SIGTERM
, shutdown_handler
);
4861 signal(SIGINT
, shutdown_handler
);
4862 signal(SIGQUIT
, shutdown_handler
);
4864 // Prevent us from getting paged out
4865 if (config
->lock_pages
)
4867 if (!mlockall(MCL_CURRENT
))
4868 LOG(1, 0, 0, "Locking pages into memory\n");
4870 LOG(0, 0, 0, "Can't lock pages: %s\n", strerror(errno
));
4875 /* remove plugins (so cleanup code gets run) */
4878 // Remove the PID file if we wrote it
4879 if (config
->wrote_pid
&& *config
->pid_file
== '/')
4880 unlink(config
->pid_file
);
4882 /* kill CLI children */
4883 signal(SIGTERM
, SIG_IGN
);
4888 static void sighup_handler(int sig
)
4893 static void shutdown_handler(int sig
)
4895 main_quit
= (sig
== SIGQUIT
) ? QUIT_SHUTDOWN
: QUIT_FAILOVER
;
4898 static void sigchild_handler(int sig
)
4900 while (waitpid(-1, NULL
, WNOHANG
) > 0)
4904 static void build_chap_response(uint8_t *challenge
, uint8_t id
, uint16_t challenge_length
, uint8_t **challenge_response
)
4907 *challenge_response
= NULL
;
4909 if (!*config
->l2tp_secret
)
4911 LOG(0, 0, 0, "LNS requested CHAP authentication, but no l2tp secret is defined\n");
4915 LOG(4, 0, 0, " Building challenge response for CHAP request\n");
4917 *challenge_response
= calloc(17, 1);
4920 MD5_Update(&ctx
, &id
, 1);
4921 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
4922 MD5_Update(&ctx
, challenge
, challenge_length
);
4923 MD5_Final(*challenge_response
, &ctx
);
4928 static int facility_value(char *name
)
4931 for (i
= 0; facilitynames
[i
].c_name
; i
++)
4933 if (strcmp(facilitynames
[i
].c_name
, name
) == 0)
4934 return facilitynames
[i
].c_val
;
4939 static void update_config()
4943 static int timeout
= 0;
4944 static int interval
= 0;
4951 if (log_stream
!= stderr
)
4957 if (*config
->log_filename
)
4959 if (strstr(config
->log_filename
, "syslog:") == config
->log_filename
)
4961 char *p
= config
->log_filename
+ 7;
4964 openlog("l2tpns", LOG_PID
, facility_value(p
));
4968 else if (strchr(config
->log_filename
, '/') == config
->log_filename
)
4970 if ((log_stream
= fopen((char *)(config
->log_filename
), "a")))
4972 fseek(log_stream
, 0, SEEK_END
);
4973 setbuf(log_stream
, NULL
);
4977 log_stream
= stderr
;
4978 setbuf(log_stream
, NULL
);
4984 log_stream
= stderr
;
4985 setbuf(log_stream
, NULL
);
4988 #define L2TP_HDRS (20+8+6+4) // L2TP data encaptulation: ip + udp + l2tp (data) + ppp (inc hdlc)
4989 #define TCP_HDRS (20+20) // TCP encapsulation: ip + tcp
4991 if (config
->l2tp_mtu
<= 0) config
->l2tp_mtu
= 1500; // ethernet default
4992 else if (config
->l2tp_mtu
< MINMTU
) config
->l2tp_mtu
= MINMTU
;
4993 else if (config
->l2tp_mtu
> MAXMTU
) config
->l2tp_mtu
= MAXMTU
;
4995 // reset MRU/MSS globals
4996 MRU
= config
->l2tp_mtu
- L2TP_HDRS
;
4997 if (MRU
> PPPoE_MRU
)
5000 MSS
= MRU
- TCP_HDRS
;
5003 config
->numradiusservers
= 0;
5004 for (i
= 0; i
< MAXRADSERVER
; i
++)
5005 if (config
->radiusserver
[i
])
5007 config
->numradiusservers
++;
5008 // Set radius port: if not set, take the port from the
5009 // first radius server. For the first radius server,
5010 // take the #defined default value from l2tpns.h
5012 // test twice, In case someone works with
5013 // a secondary radius server without defining
5014 // a primary one, this will work even then.
5015 if (i
> 0 && !config
->radiusport
[i
])
5016 config
->radiusport
[i
] = config
->radiusport
[i
-1];
5017 if (!config
->radiusport
[i
])
5018 config
->radiusport
[i
] = RADPORT
;
5021 if (!config
->numradiusservers
)
5022 LOG(0, 0, 0, "No RADIUS servers defined!\n");
5024 // parse radius_authtypes_s
5025 config
->radius_authtypes
= config
->radius_authprefer
= 0;
5026 p
= config
->radius_authtypes_s
;
5029 char *s
= strpbrk(p
, " \t,");
5035 while (*s
== ' ' || *s
== '\t')
5042 if (!strncasecmp("chap", p
, strlen(p
)))
5044 else if (!strncasecmp("pap", p
, strlen(p
)))
5047 LOG(0, 0, 0, "Invalid RADIUS authentication type \"%s\"\n", p
);
5049 config
->radius_authtypes
|= type
;
5050 if (!config
->radius_authprefer
)
5051 config
->radius_authprefer
= type
;
5056 if (!config
->radius_authtypes
)
5058 LOG(0, 0, 0, "Defaulting to PAP authentication\n");
5059 config
->radius_authtypes
= config
->radius_authprefer
= AUTHPAP
;
5062 // normalise radius_authtypes_s
5063 if (config
->radius_authprefer
== AUTHPAP
)
5065 strcpy(config
->radius_authtypes_s
, "pap");
5066 if (config
->radius_authtypes
& AUTHCHAP
)
5067 strcat(config
->radius_authtypes_s
, ", chap");
5071 strcpy(config
->radius_authtypes_s
, "chap");
5072 if (config
->radius_authtypes
& AUTHPAP
)
5073 strcat(config
->radius_authtypes_s
, ", pap");
5076 if (!config
->radius_dae_port
)
5077 config
->radius_dae_port
= DAEPORT
;
5079 // re-initialise the random number source
5080 initrandom(config
->random_device
);
5083 for (i
= 0; i
< MAXPLUGINS
; i
++)
5085 if (strcmp(config
->plugins
[i
], config
->old_plugins
[i
]) == 0)
5088 if (*config
->plugins
[i
])
5091 add_plugin(config
->plugins
[i
]);
5093 else if (*config
->old_plugins
[i
])
5096 remove_plugin(config
->old_plugins
[i
]);
5101 guest_accounts_num
= 0;
5102 char *p2
= config
->guest_user
;
5105 char *s
= strpbrk(p2
, " \t,");
5109 while (*s
== ' ' || *s
== '\t')
5116 strcpy(guest_users
[guest_accounts_num
], p2
);
5117 LOG(1, 0, 0, "Guest account[%d]: %s\n", guest_accounts_num
, guest_users
[guest_accounts_num
]);
5118 guest_accounts_num
++;
5121 // Rebuild the guest_user array
5122 strcpy(config
->guest_user
, "");
5124 for (ui
=0; ui
<guest_accounts_num
; ui
++)
5126 strcat(config
->guest_user
, guest_users
[ui
]);
5127 if (ui
<guest_accounts_num
-1)
5129 strcat(config
->guest_user
, ",");
5134 memcpy(config
->old_plugins
, config
->plugins
, sizeof(config
->plugins
));
5135 if (!config
->multi_read_count
) config
->multi_read_count
= 10;
5136 if (!config
->cluster_address
) config
->cluster_address
= inet_addr(DEFAULT_MCAST_ADDR
);
5137 if (!*config
->cluster_interface
)
5138 strncpy(config
->cluster_interface
, DEFAULT_MCAST_INTERFACE
, sizeof(config
->cluster_interface
) - 1);
5140 if (!config
->cluster_hb_interval
)
5141 config
->cluster_hb_interval
= PING_INTERVAL
; // Heartbeat every 0.5 seconds.
5143 if (!config
->cluster_hb_timeout
)
5144 config
->cluster_hb_timeout
= HB_TIMEOUT
; // 10 missed heartbeat triggers an election.
5146 if (interval
!= config
->cluster_hb_interval
|| timeout
!= config
->cluster_hb_timeout
)
5148 // Paranoia: cluster_check_master() treats 2 x interval + 1 sec as
5149 // late, ensure we're sufficiently larger than that
5150 int t
= 4 * config
->cluster_hb_interval
+ 11;
5152 if (config
->cluster_hb_timeout
< t
)
5154 LOG(0, 0, 0, "Heartbeat timeout %d too low, adjusting to %d\n", config
->cluster_hb_timeout
, t
);
5155 config
->cluster_hb_timeout
= t
;
5158 // Push timing changes to the slaves immediately if we're the master
5159 if (config
->cluster_iam_master
)
5160 cluster_heartbeat();
5162 interval
= config
->cluster_hb_interval
;
5163 timeout
= config
->cluster_hb_timeout
;
5167 if (*config
->pid_file
== '/' && !config
->wrote_pid
)
5170 if ((f
= fopen(config
->pid_file
, "w")))
5172 fprintf(f
, "%d\n", getpid());
5174 config
->wrote_pid
= 1;
5178 LOG(0, 0, 0, "Can't write to PID file %s: %s\n", config
->pid_file
, strerror(errno
));
5183 static void read_config_file()
5187 if (!config
->config_file
) return;
5188 if (!(f
= fopen(config
->config_file
, "r")))
5190 fprintf(stderr
, "Can't open config file %s: %s\n", config
->config_file
, strerror(errno
));
5194 LOG(3, 0, 0, "Reading config file %s\n", config
->config_file
);
5196 LOG(3, 0, 0, "Done reading config file\n");
5200 int sessionsetup(sessionidt s
, tunnelidt t
)
5202 // A session now exists, set it up
5208 CSTAT(sessionsetup
);
5210 LOG(3, s
, t
, "Doing session setup for session\n");
5212 // Join a bundle if the MRRU option is accepted
5213 if(session
[s
].mrru
> 0 && session
[s
].bundle
== 0)
5215 LOG(3, s
, t
, "This session can be part of multilink bundle\n");
5216 if (join_bundle(s
) > 0)
5217 cluster_send_bundle(session
[s
].bundle
);
5220 LOG(0, s
, t
, "MPPP: Mismaching mssf option with other sessions in bundle\n");
5221 sessionshutdown(s
, "Mismaching mssf option.", CDN_NONE
, TERM_SERVICE_UNAVAILABLE
);
5228 assign_ip_address(s
);
5231 LOG(0, s
, t
, " No IP allocated. The IP address pool is FULL!\n");
5232 sessionshutdown(s
, "No IP addresses available.", CDN_TRY_ANOTHER
, TERM_SERVICE_UNAVAILABLE
);
5235 LOG(3, s
, t
, " No IP allocated. Assigned %s from pool\n",
5236 fmtaddr(htonl(session
[s
].ip
), 0));
5240 // Make sure this is right
5241 session
[s
].tunnel
= t
;
5243 // zap old sessions with same IP and/or username
5244 // Don't kill gardened sessions - doing so leads to a DoS
5245 // from someone who doesn't need to know the password
5248 user
= session
[s
].user
;
5249 for (i
= 1; i
<= config
->cluster_highest_sessionid
; i
++)
5251 if (i
== s
) continue;
5252 if (!session
[s
].opened
) continue;
5253 // Allow duplicate sessions for multilink ones of the same bundle.
5254 if (session
[s
].bundle
&& session
[i
].bundle
&& session
[s
].bundle
== session
[i
].bundle
)
5256 if (ip
== session
[i
].ip
)
5258 sessionkill(i
, "Duplicate IP address");
5262 if (config
->allow_duplicate_users
) continue;
5263 if (session
[s
].walled_garden
|| session
[i
].walled_garden
) continue;
5267 for (gu
= 0; gu
< guest_accounts_num
; gu
++)
5269 if (!strcasecmp(user
, guest_users
[gu
]))
5275 if (found
) continue;
5277 // Drop the new session in case of duplicate sessionss, not the old one.
5278 if (!strcasecmp(user
, session
[i
].user
))
5279 sessionkill(i
, "Duplicate session for users");
5283 // no need to set a route for the same IP address of the bundle
5284 if (!session
[s
].bundle
|| (bundle
[session
[s
].bundle
].num_of_links
== 1))
5288 // Add the route for this session.
5289 for (r
= 0; r
< MAXROUTE
&& session
[s
].route
[r
].ip
; r
++)
5291 if ((session
[s
].ip
>> (32-session
[s
].route
[r
].prefixlen
)) ==
5292 (session
[s
].route
[r
].ip
>> (32-session
[s
].route
[r
].prefixlen
)))
5295 routeset(s
, session
[s
].route
[r
].ip
, session
[s
].route
[r
].prefixlen
, 0, 1);
5298 // Static IPs need to be routed if not already
5299 // convered by a Framed-Route. Anything else is part
5300 // of the IP address pool and is already routed, it
5301 // just needs to be added to the IP cache.
5302 // IPv6 route setup is done in ppp.c, when IPV6CP is acked.
5303 if (session
[s
].ip_pool_index
== -1) // static ip
5305 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 1);
5308 cache_ipmap(session
[s
].ip
, s
);
5311 sess_local
[s
].lcp_authtype
= 0; // RADIUS authentication complete
5312 lcp_open(s
, t
); // transition to Network phase and send initial IPCP
5314 // Run the plugin's against this new session.
5316 struct param_new_session data
= { &tunnel
[t
], &session
[s
] };
5317 run_plugins(PLUGIN_NEW_SESSION
, &data
);
5320 // Allocate TBFs if throttled
5321 if (session
[s
].throttle_in
|| session
[s
].throttle_out
)
5322 throttle_session(s
, session
[s
].throttle_in
, session
[s
].throttle_out
);
5324 session
[s
].last_packet
= session
[s
].last_data
= time_now
;
5326 LOG(2, s
, t
, "Login by %s at %s from %s (%s)\n", session
[s
].user
,
5327 fmtaddr(htonl(session
[s
].ip
), 0),
5328 fmtaddr(htonl(tunnel
[t
].ip
), 1), tunnel
[t
].hostname
);
5330 cluster_send_session(s
); // Mark it as dirty, and needing to the flooded to the cluster.
5332 return 1; // RADIUS OK and IP allocated, done...
5336 // This session just got dropped on us by the master or something.
5337 // Make sure our tables up up to date...
5339 int load_session(sessionidt s
, sessiont
*new)
5345 if (new->ip_pool_index
>= MAXIPPOOL
||
5346 new->tunnel
>= MAXTUNNEL
)
5348 LOG(0, s
, 0, "Strange session update received!\n");
5349 // FIXME! What to do here?
5354 // Ok. All sanity checks passed. Now we're committed to
5355 // loading the new session.
5358 session
[s
].tunnel
= new->tunnel
; // For logging in cache_ipmap
5360 // See if routes/ip cache need updating
5361 if (new->ip
!= session
[s
].ip
)
5364 for (i
= 0; !newip
&& i
< MAXROUTE
&& (session
[s
].route
[i
].ip
|| new->route
[i
].ip
); i
++)
5365 if (new->route
[i
].ip
!= session
[s
].route
[i
].ip
||
5366 new->route
[i
].prefixlen
!= session
[s
].route
[i
].prefixlen
)
5374 // remove old routes...
5375 for (i
= 0; i
< MAXROUTE
&& session
[s
].route
[i
].ip
; i
++)
5377 if ((session
[s
].ip
>> (32-session
[s
].route
[i
].prefixlen
)) ==
5378 (session
[s
].route
[i
].ip
>> (32-session
[s
].route
[i
].prefixlen
)))
5381 routeset(s
, session
[s
].route
[i
].ip
, session
[s
].route
[i
].prefixlen
, 0, 0);
5387 if (session
[s
].ip_pool_index
== -1) // static IP
5389 if (!routed
) routeset(s
, session
[s
].ip
, 0, 0, 0);
5391 else // It's part of the IP pool, remove it manually.
5392 uncache_ipmap(session
[s
].ip
);
5397 // add new routes...
5398 for (i
= 0; i
< MAXROUTE
&& new->route
[i
].ip
; i
++)
5400 if ((new->ip
>> (32-new->route
[i
].prefixlen
)) ==
5401 (new->route
[i
].ip
>> (32-new->route
[i
].prefixlen
)))
5404 routeset(s
, new->route
[i
].ip
, new->route
[i
].prefixlen
, 0, 1);
5410 // If there's a new one, add it.
5411 if (new->ip_pool_index
== -1)
5413 if (!routed
) routeset(s
, new->ip
, 0, 0, 1);
5416 cache_ipmap(new->ip
, s
);
5421 if (new->ipv6prefixlen
&& new->ppp
.ipv6cp
== Opened
&& session
[s
].ppp
.ipv6cp
!= Opened
)
5422 route6set(s
, new->ipv6route
, new->ipv6prefixlen
, 1);
5425 if (new->filter_in
&& (new->filter_in
> MAXFILTER
|| !ip_filters
[new->filter_in
- 1].name
[0]))
5427 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid input filter %u\n", (int) new->filter_in
);
5431 if (new->filter_out
&& (new->filter_out
> MAXFILTER
|| !ip_filters
[new->filter_out
- 1].name
[0]))
5433 LOG(2, s
, session
[s
].tunnel
, "Dropping invalid output filter %u\n", (int) new->filter_out
);
5434 new->filter_out
= 0;
5437 if (new->filter_in
!= session
[s
].filter_in
)
5439 if (session
[s
].filter_in
) ip_filters
[session
[s
].filter_in
- 1].used
--;
5440 if (new->filter_in
) ip_filters
[new->filter_in
- 1].used
++;
5443 if (new->filter_out
!= session
[s
].filter_out
)
5445 if (session
[s
].filter_out
) ip_filters
[session
[s
].filter_out
- 1].used
--;
5446 if (new->filter_out
) ip_filters
[new->filter_out
- 1].used
++;
5449 if (new->tunnel
&& s
> config
->cluster_highest_sessionid
) // Maintain this in the slave. It's used
5450 // for walking the sessions to forward byte counts to the master.
5451 config
->cluster_highest_sessionid
= s
;
5453 memcpy(&session
[s
], new, sizeof(session
[s
])); // Copy over..
5455 // Do fixups into address pool.
5456 if (new->ip_pool_index
!= -1)
5457 fix_address_pool(s
);
5462 static void initplugins()
5466 loaded_plugins
= ll_init();
5467 // Initialize the plugins to nothing
5468 for (i
= 0; i
< MAX_PLUGIN_TYPES
; i
++)
5469 plugins
[i
] = ll_init();
5472 static void *open_plugin(char *plugin_name
, int load
)
5474 char path
[256] = "";
5476 snprintf(path
, 256, PLUGINDIR
"/%s.so", plugin_name
);
5477 LOG(2, 0, 0, "%soading plugin from %s\n", load
? "L" : "Un-l", path
);
5478 return dlopen(path
, RTLD_NOW
);
5481 // plugin callback to get a config value
5482 static void *getconfig(char *key
, enum config_typet type
)
5486 for (i
= 0; config_values
[i
].key
; i
++)
5488 if (!strcmp(config_values
[i
].key
, key
))
5490 if (config_values
[i
].type
== type
)
5491 return ((void *) config
) + config_values
[i
].offset
;
5493 LOG(1, 0, 0, "plugin requested config item \"%s\" expecting type %d, have type %d\n",
5494 key
, type
, config_values
[i
].type
);
5500 LOG(1, 0, 0, "plugin requested unknown config item \"%s\"\n", key
);
5504 static int add_plugin(char *plugin_name
)
5506 static struct pluginfuncs funcs
= {
5511 sessiontbysessionidt
,
5512 sessionidtbysessiont
,
5519 cluster_send_session
,
5522 void *p
= open_plugin(plugin_name
, 1);
5523 int (*initfunc
)(struct pluginfuncs
*);
5528 LOG(1, 0, 0, " Plugin load failed: %s\n", dlerror());
5532 if (ll_contains(loaded_plugins
, p
))
5535 return 0; // already loaded
5539 int *v
= dlsym(p
, "plugin_api_version");
5540 if (!v
|| *v
!= PLUGIN_API_VERSION
)
5542 LOG(1, 0, 0, " Plugin load failed: API version mismatch: %s\n", dlerror());
5548 if ((initfunc
= dlsym(p
, "plugin_init")))
5550 if (!initfunc(&funcs
))
5552 LOG(1, 0, 0, " Plugin load failed: plugin_init() returned FALSE: %s\n", dlerror());
5558 ll_push(loaded_plugins
, p
);
5560 for (i
= 0; i
< max_plugin_functions
; i
++)
5563 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5565 LOG(3, 0, 0, " Supports function \"%s\"\n", plugin_functions
[i
]);
5566 ll_push(plugins
[i
], x
);
5570 LOG(2, 0, 0, " Loaded plugin %s\n", plugin_name
);
5574 static void run_plugin_done(void *plugin
)
5576 int (*donefunc
)(void) = dlsym(plugin
, "plugin_done");
5582 static int remove_plugin(char *plugin_name
)
5584 void *p
= open_plugin(plugin_name
, 0);
5590 if (ll_contains(loaded_plugins
, p
))
5593 for (i
= 0; i
< max_plugin_functions
; i
++)
5596 if (plugin_functions
[i
] && (x
= dlsym(p
, plugin_functions
[i
])))
5597 ll_delete(plugins
[i
], x
);
5600 ll_delete(loaded_plugins
, p
);
5606 LOG(2, 0, 0, "Removed plugin %s\n", plugin_name
);
5610 int run_plugins(int plugin_type
, void *data
)
5612 int (*func
)(void *data
);
5614 if (!plugins
[plugin_type
] || plugin_type
> max_plugin_functions
)
5615 return PLUGIN_RET_ERROR
;
5617 ll_reset(plugins
[plugin_type
]);
5618 while ((func
= ll_next(plugins
[plugin_type
])))
5622 if (r
!= PLUGIN_RET_OK
)
5623 return r
; // stop here
5626 return PLUGIN_RET_OK
;
5629 static void plugins_done()
5633 ll_reset(loaded_plugins
);
5634 while ((p
= ll_next(loaded_plugins
)))
5638 static void processcontrol(uint8_t *buf
, int len
, struct sockaddr_in
*addr
, int alen
, struct in_addr
*local
)
5640 struct nsctl request
;
5641 struct nsctl response
;
5642 int type
= unpack_control(&request
, buf
, len
);
5646 if (log_stream
&& config
->debug
>= 4)
5650 LOG(4, 0, 0, "Bogus control message from %s (%d)\n",
5651 fmtaddr(addr
->sin_addr
.s_addr
, 0), type
);
5655 LOG(4, 0, 0, "Received [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5656 dump_control(&request
, log_stream
);
5662 case NSCTL_REQ_LOAD
:
5663 if (request
.argc
!= 1)
5665 response
.type
= NSCTL_RES_ERR
;
5667 response
.argv
[0] = "name of plugin required";
5669 else if ((r
= add_plugin(request
.argv
[0])) < 1)
5671 response
.type
= NSCTL_RES_ERR
;
5673 response
.argv
[0] = !r
5674 ? "plugin already loaded"
5675 : "error loading plugin";
5679 response
.type
= NSCTL_RES_OK
;
5685 case NSCTL_REQ_UNLOAD
:
5686 if (request
.argc
!= 1)
5688 response
.type
= NSCTL_RES_ERR
;
5690 response
.argv
[0] = "name of plugin required";
5692 else if ((r
= remove_plugin(request
.argv
[0])) < 1)
5694 response
.type
= NSCTL_RES_ERR
;
5696 response
.argv
[0] = !r
5697 ? "plugin not loaded"
5698 : "plugin not found";
5702 response
.type
= NSCTL_RES_OK
;
5708 case NSCTL_REQ_HELP
:
5709 response
.type
= NSCTL_RES_OK
;
5712 ll_reset(loaded_plugins
);
5713 while ((p
= ll_next(loaded_plugins
)))
5715 char **help
= dlsym(p
, "plugin_control_help");
5716 while (response
.argc
< 0xff && help
&& *help
)
5717 response
.argv
[response
.argc
++] = *help
++;
5722 case NSCTL_REQ_CONTROL
:
5724 struct param_control param
= {
5725 config
->cluster_iam_master
,
5732 int r
= run_plugins(PLUGIN_CONTROL
, ¶m
);
5734 if (r
== PLUGIN_RET_ERROR
)
5736 response
.type
= NSCTL_RES_ERR
;
5738 response
.argv
[0] = param
.additional
5740 : "error returned by plugin";
5742 else if (r
== PLUGIN_RET_NOTMASTER
)
5744 static char msg
[] = "must be run on master: 000.000.000.000";
5746 response
.type
= NSCTL_RES_ERR
;
5748 if (config
->cluster_master_address
)
5750 strcpy(msg
+ 23, fmtaddr(config
->cluster_master_address
, 0));
5751 response
.argv
[0] = msg
;
5755 response
.argv
[0] = "must be run on master: none elected";
5758 else if (!(param
.response
& NSCTL_RESPONSE
))
5760 response
.type
= NSCTL_RES_ERR
;
5762 response
.argv
[0] = param
.response
5763 ? "unrecognised response value from plugin"
5764 : "unhandled action";
5768 response
.type
= param
.response
;
5770 if (param
.additional
)
5773 response
.argv
[0] = param
.additional
;
5781 response
.type
= NSCTL_RES_ERR
;
5783 response
.argv
[0] = "error unpacking control packet";
5786 buf
= calloc(NSCTL_MAX_PKT_SZ
, 1);
5789 LOG(2, 0, 0, "Failed to allocate nsctl response\n");
5793 r
= pack_control(buf
, NSCTL_MAX_PKT_SZ
, response
.type
, response
.argc
, response
.argv
);
5796 sendtofrom(controlfd
, buf
, r
, 0, (const struct sockaddr
*) addr
, alen
, local
);
5797 if (log_stream
&& config
->debug
>= 4)
5799 LOG(4, 0, 0, "Sent [%s] ", fmtaddr(addr
->sin_addr
.s_addr
, 0));
5800 dump_control(&response
, log_stream
);
5804 LOG(2, 0, 0, "Failed to pack nsctl response for %s (%d)\n",
5805 fmtaddr(addr
->sin_addr
.s_addr
, 0), r
);
5810 static tunnelidt
new_tunnel()
5813 for (i
= 1; i
< MAXTUNNEL
; i
++)
5815 if (tunnel
[i
].state
== TUNNELFREE
)
5817 LOG(4, 0, i
, "Assigning tunnel ID %u\n", i
);
5818 if (i
> config
->cluster_highest_tunnelid
)
5819 config
->cluster_highest_tunnelid
= i
;
5823 LOG(0, 0, 0, "Can't find a free tunnel! There shouldn't be this many in use!\n");
5828 // We're becoming the master. Do any required setup..
5830 // This is principally telling all the plugins that we're
5831 // now a master, and telling them about all the sessions
5832 // that are active too..
5834 void become_master(void)
5837 static struct event_data d
[RADIUS_FDS
];
5838 struct epoll_event e
;
5840 run_plugins(PLUGIN_BECOME_MASTER
, NULL
);
5842 // running a bunch of iptables commands is slow and can cause
5843 // the master to drop tunnels on takeover--kludge around the
5844 // problem by forking for the moment (note: race)
5845 if (!fork_and_close())
5847 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5849 if (!session
[s
].opened
) // Not an in-use session.
5852 run_plugins(PLUGIN_NEW_SESSION_MASTER
, &session
[s
]);
5859 for (i
= 0; i
< RADIUS_FDS
; i
++)
5861 d
[i
].type
= FD_TYPE_RADIUS
;
5865 epoll_ctl(epollfd
, EPOLL_CTL_ADD
, radfds
[i
], &e
);
5869 int cmd_show_hist_idle(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5875 if (CLI_HELP_REQUESTED
)
5876 return CLI_HELP_NO_ARGS
;
5879 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5881 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5884 if (!session
[s
].opened
)
5887 idle
= time_now
- session
[s
].last_data
;
5888 idle
/= 5 ; // In multiples of 5 seconds.
5898 for (i
= 0; i
< 63; ++i
)
5900 cli_print(cli
, "%3d seconds : %7.2f%% (%6d)", i
* 5, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5902 cli_print(cli
, "lots of secs : %7.2f%% (%6d)", (double) buckets
[63] * 100.0 / count
, buckets
[i
]);
5903 cli_print(cli
, "%d total sessions open.", count
);
5907 int cmd_show_hist_open(struct cli_def
*cli
, char *command
, char **argv
, int argc
)
5913 if (CLI_HELP_REQUESTED
)
5914 return CLI_HELP_NO_ARGS
;
5917 for (i
= 0; i
< 64;++i
) buckets
[i
] = 0;
5919 for (s
= 1; s
<= config
->cluster_highest_sessionid
; ++s
)
5922 if (!session
[s
].opened
)
5925 d
= time_now
- session
[s
].opened
;
5928 while (d
> 1 && open
< 32)
5938 for (i
= 0; i
< 30; ++i
)
5940 cli_print(cli
, " < %8d seconds : %7.2f%% (%6d)", s
, (double) buckets
[i
] * 100.0 / count
, buckets
[i
]);
5943 cli_print(cli
, "%d total sessions open.", count
);
5949 * This unencodes the AVP using the L2TP secret and the previously
5950 * stored random vector. It overwrites the hidden data with the
5951 * unhidden AVP subformat.
5953 static void unhide_value(uint8_t *value
, size_t len
, uint16_t type
, uint8_t *vector
, size_t vec_len
)
5959 uint16_t m
= htons(type
);
5961 // Compute initial pad
5963 MD5_Update(&ctx
, (unsigned char *) &m
, 2);
5964 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5965 MD5_Update(&ctx
, vector
, vec_len
);
5966 MD5_Final(digest
, &ctx
);
5968 // pointer to last decoded 16 octets
5973 // calculate a new pad based on the last decoded block
5974 if (d
>= sizeof(digest
))
5977 MD5_Update(&ctx
, config
->l2tp_secret
, strlen(config
->l2tp_secret
));
5978 MD5_Update(&ctx
, last
, sizeof(digest
));
5979 MD5_Final(digest
, &ctx
);
5985 *value
++ ^= digest
[d
++];
5990 int find_filter(char const *name
, size_t len
)
5995 for (i
= 0; i
< MAXFILTER
; i
++)
5997 if (!*ip_filters
[i
].name
)
6005 if (strlen(ip_filters
[i
].name
) != len
)
6008 if (!strncmp(ip_filters
[i
].name
, name
, len
))
6015 static int ip_filter_port(ip_filter_portt
*p
, uint16_t port
)
6019 case FILTER_PORT_OP_EQ
: return port
== p
->port
;
6020 case FILTER_PORT_OP_NEQ
: return port
!= p
->port
;
6021 case FILTER_PORT_OP_GT
: return port
> p
->port
;
6022 case FILTER_PORT_OP_LT
: return port
< p
->port
;
6023 case FILTER_PORT_OP_RANGE
: return port
>= p
->port
&& port
<= p
->port2
;
6029 static int ip_filter_flag(uint8_t op
, uint8_t sflags
, uint8_t cflags
, uint8_t flags
)
6033 case FILTER_FLAG_OP_ANY
:
6034 return (flags
& sflags
) || (~flags
& cflags
);
6036 case FILTER_FLAG_OP_ALL
:
6037 return (flags
& sflags
) == sflags
&& (~flags
& cflags
) == cflags
;
6039 case FILTER_FLAG_OP_EST
:
6040 return (flags
& (TCP_FLAG_ACK
|TCP_FLAG_RST
)) && (~flags
& TCP_FLAG_SYN
);
6046 int ip_filter(uint8_t *buf
, int len
, uint8_t filter
)
6048 uint16_t frag_offset
;
6052 uint16_t src_port
= 0;
6053 uint16_t dst_port
= 0;
6055 ip_filter_rulet
*rule
;
6057 if (len
< 20) // up to end of destination address
6060 if ((*buf
>> 4) != 4) // IPv4
6063 frag_offset
= ntohs(*(uint16_t *) (buf
+ 6)) & 0x1fff;
6065 src_ip
= *(in_addr_t
*) (buf
+ 12);
6066 dst_ip
= *(in_addr_t
*) (buf
+ 16);
6068 if (frag_offset
== 0 && (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
))
6070 int l
= (buf
[0] & 0xf) * 4; // length of IP header
6071 if (len
< l
+ 4) // ports
6074 src_port
= ntohs(*(uint16_t *) (buf
+ l
));
6075 dst_port
= ntohs(*(uint16_t *) (buf
+ l
+ 2));
6076 if (proto
== IPPROTO_TCP
)
6078 if (len
< l
+ 14) // flags
6081 flags
= buf
[l
+ 13] & 0x3f;
6085 for (rule
= ip_filters
[filter
].rules
; rule
->action
; rule
++)
6087 if (rule
->proto
!= IPPROTO_IP
&& proto
!= rule
->proto
)
6090 if (rule
->src_wild
!= INADDR_BROADCAST
&&
6091 (src_ip
& ~rule
->src_wild
) != (rule
->src_ip
& ~rule
->src_wild
))
6094 if (rule
->dst_wild
!= INADDR_BROADCAST
&&
6095 (dst_ip
& ~rule
->dst_wild
) != (rule
->dst_ip
& ~rule
->dst_wild
))
6100 // layer 4 deny rules are skipped
6101 if (rule
->action
== FILTER_ACTION_DENY
&&
6102 (rule
->src_ports
.op
|| rule
->dst_ports
.op
|| rule
->tcp_flag_op
))
6110 if (proto
== IPPROTO_TCP
|| proto
== IPPROTO_UDP
)
6112 if (rule
->src_ports
.op
&& !ip_filter_port(&rule
->src_ports
, src_port
))
6115 if (rule
->dst_ports
.op
&& !ip_filter_port(&rule
->dst_ports
, dst_port
))
6118 if (proto
== IPPROTO_TCP
&& rule
->tcp_flag_op
&&
6119 !ip_filter_flag(rule
->tcp_flag_op
, rule
->tcp_sflags
, rule
->tcp_cflags
, flags
))
6126 return rule
->action
== FILTER_ACTION_PERMIT
;